protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value is HttpPostedFileBase)
            {
                HttpPostedFileBase file          = (HttpPostedFileBase)value;
                string             fileName      = file.FileName;
                string             fileExtension = fileName.Substring(fileName.LastIndexOf(".")).ToLower();
                int fileSize = file.ContentLength;

                if (AllowedExtensions.Contains(fileExtension))
                {
                    if (fileSize <= ContentLength)
                    {
                        return(ValidationResult.Success);
                    }
                    else
                    {
                        return(new ValidationResult("The Uploaded file must be less than or equal " + ContentLength / 1024 / 1024 + "MB."));
                    }
                }
                else
                {
                    //var extensions = AllowedExtensions.ToString();
                    return(new ValidationResult("The Uploaded file must be of one these extensions (" + string.Join(",", AllowedExtensions) + ")."));
                }
            }
            else
            {
                return(new ValidationResult("You Should Upload File."));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Normalize a path to a name, e.g. remove relative bases, and ensure there is an extension.
        /// </summary>
        ///
        /// <param name="virtualPath">
        /// Full pathname of the virtual file.
        /// </param>
        ///
        /// <returns>
        /// A normalized name like "folder/script.js"
        /// </returns>

        public static string NormalizeName(string virtualPath)
        {
            int offset = 0, length = 0;

            if (virtualPath.StartsWith("~/"))
            {
                offset += 2;
            }
            if (virtualPath.Substring(offset, 1) == "/")
            {
                offset += 1;
            }

            // strip off querystrings
            //
            int pos = virtualPath.IndexOf("?");

            length = (pos >= 0 ?
                      pos :
                      virtualPath.Length) - offset;



            string output = virtualPath.Substring(offset, length);
            string suffix = output.AfterLast(".").ToLower();

            return(output +
                   (!AllowedExtensions.Contains(suffix) ? ".js" : ""));
        }
Ejemplo n.º 3
0
        public async Task CreateFile(FileContent file)
        {
            var cloudPath        = new CloudPath(file.Path, file.Filename);
            var fileAbsolutePath = GetAbsolutePath(cloudPath.TargetPath);

            var extension = Path.GetExtension(file.Filename);

            if (!AllowedExtensions.Contains(extension) && !file.ContentType.Contains("image"))
            {
                throw new StorageException("Invalid file(s). Note that allowed type files are all image types, video type mp4, webm, ogg, audio types mp3, ogg, wav, pdf, xlsx, xls, docx, ppt, pptx, zip, xml, html, css, js, json, woff and dicos files.");
            }

            var folderKey = GetAbsolutePath(cloudPath.Path);

            var response = await ListContainerObjects(folderKey);

            var newFileKey = GetNewFilePathIfExists(response.S3Objects.Select(x => x.Key), fileAbsolutePath, fileAbsolutePath);

            var putRequest = new PutObjectRequest
            {
                BucketName  = _amazonS3Config.Bucket,
                Key         = newFileKey,
                InputStream = new MemoryStream(file.FileBytes)
            };

            await _amazonS3.PutObjectAsync(putRequest);
        }
        public void PopulateBookList(string paramDir, Models.Item rootItem)
        {
            if (rootItem == null)
            {
                throw new ArgumentNullException();
            }

            rootItem.FullName = paramDir;
            rootItem.ItemType = Models.ItemType.Folder;

            DirectoryInfo dir = new DirectoryInfo(paramDir);

            foreach (DirectoryInfo dirInfo in dir.GetDirectories())
            {
                var item = new Models.Item();
                item.Name = dirInfo.Name;

                rootItem.Children.Add(item);

                PopulateBookList(dirInfo.FullName, item);
            }
            foreach (FileInfo fleInfo in dir.GetFiles().Where(x => AllowedExtensions.Contains(x.Extension)).ToList())
            {
                var item = new Models.Item();
                item.Name = fleInfo.Name;

                item.FullName = fleInfo.FullName;
                item.ItemType = (Models.ItemType)Enum.Parse(typeof(Extention), fleInfo.Extension.TrimStart('.'), true);

                rootItem.Children.Add(item);
            }
        }
Ejemplo n.º 5
0
        public IActionResult UploadCoverPhoto(int playlistId, [FromForm] CoverFile file)
        {
            var photo  = file.Photo;
            var sizeMB = photo.Length / 1024 / 1000;

            if (sizeMB > 10)
            {
                return(StatusCode(400, new ErrorDetails()
                {
                    errorId = ErrorList.WrongSize.Id,
                    errorMessage = ErrorList.WrongSize.Description
                }));
            }

            int userId = int.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == claimTypes.Id.ToString()).Value);

            if (!db.CheckPlaylistExists(playlistId, userId))
            {
                return(StatusCode(403, new ErrorDetails()
                {
                    errorId = ErrorList.UnauthorizedAction.Id, errorMessage = ErrorList.UnauthorizedAction.Description
                }.ToString()));
            }

            var extension = Path.GetExtension(photo.FileName).Replace(".", "");

            if (!AllowedExtensions.Contains(extension))
            {
                return(BadRequest(new ErrorDetails()
                {
                    errorId = ErrorList.InputDataError.Id, errorMessage = ErrorList.InputDataError.Description
                }.ToString()));
            }
            ;

            var imageName = Guid.NewGuid().ToString().Replace("-", "");
            var thumbName = $"{imageName}_cover.{extension}";

            var additionalPath = $"/{userId}";
            var newThumbPath   = $"{additionalPath}/{thumbName}";

            db.AddPlaylistCover(playlistId, userId, newThumbPath);

            var thumbPath = COVER_STORAGE + newThumbPath;

            var resizedThumb = helper.ResizeImage(Image.FromStream(photo.OpenReadStream()));

            if (!Directory.Exists(Path.GetDirectoryName(thumbPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(thumbPath));
            }

            helper.SaveImage(resizedThumb, thumbPath);

            var base64Photo = Convert.ToBase64String(System.IO.File.ReadAllBytes(thumbPath));

            return(Ok(new { response = new { coverPhoto = base64Photo } }));
        }
Ejemplo n.º 6
0
        public async Task CreateFiles(IEnumerable <FileContent> files)
        {
            foreach (var file in files)
            {
                var cloudPath = new CloudPath(file.Path, file.Filename);

                if (IsZip(file.FileBytes, file.Filename))
                {
                    var filenamePart = file.Filename.Split('.');
                    var newParts     = filenamePart.Take(filenamePart.Count() - 1).ToList();
                    var zipFolder    = string.Join(".", newParts);

                    var newFolderKey = string.IsNullOrWhiteSpace(cloudPath.Path) ? zipFolder : $"{cloudPath.Path}/{zipFolder}";
                    var folder       = await CreateFolder(newFolderKey);

                    using (var stream = new MemoryStream(file.FileBytes))
                    {
                        using (var archive = new ZipArchive(stream))
                        {
                            foreach (var entry in archive.Entries)
                            {
                                if (entry.Length > 0)
                                {
                                    var fileContent = new FileContent
                                    {
                                        ContentLength = (int)entry.Length,
                                        FileBytes     = ZipEntryToByteArray(entry),
                                        Filename      = entry.Name,
                                        ContentType   = GetContentType(entry.Name),
                                        Path          = $"{folder.Path}/{folder.Name}"
                                    };

                                    var extension = Path.GetExtension(fileContent.Filename);

                                    if (!AllowedExtensions.Contains(extension) && !fileContent.ContentType.Contains("image"))
                                    {
                                        throw new StorageException("Invalid file(s). Note that allowed type files are all image types, video type mp4, webm, ogg, audio types mp3, ogg, wav, pdf, xlsx, xls, docx, ppt, pptx, zip, xml, html, css, js, json, woff and dicos files.");
                                    }

                                    if (entry.FullName.Length > entry.Name.Length)
                                    {
                                        fileContent.Path = $"{folder.Path}/{folder.Name}/{entry.FullName.Substring(0, entry.FullName.Length - entry.Name.Length)}";
                                    }

                                    await CreateFile(fileContent);
                                }
                            }
                        }
                    }
                }
                else
                {
                    await CreateFile(file);
                }
            }
        }
Ejemplo n.º 7
0
        public override void RepackFile(string inputPath, string outputFile, bool compress)
        {
            var fileName  = Path.GetFileName(outputFile);
            var extension = Path.GetExtension(outputFile);

            if (AllowedExtensions.Contains(extension))
            {
                Unity3DFile.Repack(inputPath, outputFile, compress);
            }
        }
Ejemplo n.º 8
0
        public override void ExtractFile(string inputFile, string outputPath)
        {
            var fileName  = Path.GetFileName(inputFile);
            var extension = Path.GetExtension(inputFile);

            if (AllowedExtensions.Contains(extension))
            {
                Unity3DFile.Extract(inputFile, outputPath);
            }
        }
Ejemplo n.º 9
0
        private IReadOnlyCollection <FilePath> FilterOutSearchedPaths(IEnumerable <FilePath> filePaths)
        {
            if (AllowedExtensions != null)
            {
                filePaths = filePaths.Where(path => AllowedExtensions.Contains(path.GetExtension()));
            }

            var includedPatternsString = RequiredPatterns != null?string.Join(';', RequiredPatterns) : "*";

            var excludedPatternsString = ExcludedPatterns != null?string.Join(';', ExcludedPatterns) : null;

            filePaths = FilesystemPathsMatcher.MatchSearchResult(includedPatternsString, excludedPatternsString, filePaths);

            return(filePaths.ToList());
        }
Ejemplo n.º 10
0
        public async Task CreateFile(FileContent file)
        {
            var path             = new CloudPath(file.Path, file.Filename);
            var fileAbsolutePath = GetAbsolutePath(path.TargetPath);

            var extension = Path.GetExtension(file.Filename);

            if (!AllowedExtensions.Contains(extension) && !file.ContentType.Contains("image"))
            {
                throw new StorageException("Invalid file(s). Note that allowed type files are all image types, video type mp4, webm, ogg, audio types mp3, ogg, wav, pdf, xlsx, xls, docx, ppt, pptx, zip, xml, html, css, js, json, woff and dicos files.");
            }

            var newFilePath = GetNewFilePathIfExists(fileAbsolutePath, fileAbsolutePath);
            await Task.Run(() =>
            {
                System.IO.File.WriteAllBytes(newFilePath, file.FileBytes);
            });
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            List <HttpPostedFileBase> _files = new List <HttpPostedFileBase>();

            if (HasMultiple)
            {
                _files.AddRange(value as List <HttpPostedFileBase>);
            }
            else
            {
                _files.Add(value as HttpPostedFileBase);
            }

            foreach (HttpPostedFileBase _file in _files)
            {
                if (_file != null)
                {
                    if (AllowedExtensions.Contains(Path.GetExtension(_file.FileName.ToLower())))
                    {
                        if (MaxFileSize >= ((_file.InputStream.Length / 1024f) / 1024f))
                        {
                            return(null);
                        }
                        else
                        {
                            return(new ValidationResult(string.Format("Invalid file. File should be less than {0} Mb", MaxFileSize)));
                        }
                    }
                    else
                    {
                        return(new ValidationResult(string.Format("Invalid file. Only {0} are supported", string.Join(", ", AllowedExtensions))));
                    }
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Validates that a required binary data have been send on the request
        /// </summary>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (AllowedBlobMaxLength <= 0)
            {
                throw new ArgumentException("The AllowedBlobMaxLength can't be zero or less.");
            }
            if (AllowedMinimunFiles <= 0)
            {
                throw new ArgumentException("The AllowedMinimunFiles can't be zero or less.");
            }
            if (AllowedMaximunFiles <= 0)
            {
                throw new ArgumentException("The AllowedMaximunFiles can't be zero or less.");
            }
            var formFiles = filterContext.HttpContext.Request.Form.Files;
            var blobs     = string.IsNullOrWhiteSpace(FormFieldName) ? formFiles : formFiles.Where(w => w.Name == FormFieldName);

            if (!blobs.Any())
            {
                filterContext.Result = new ApiResponse <string>()
                {
                    Status = ApiResponseStatus.Failed, Message = "FileUploadRequired"
                }.ToJson();
            }
            else
            {
                if (blobs.Count() < AllowedMinimunFiles)
                {
                    filterContext.Result = new ApiResponse <string>()
                    {
                        Status = ApiResponseStatus.Failed, Message = "TheCountOfFilesUploadedHasExceededTheMaximunAllowedFiles"
                    }.ToJson();
                }
                if (blobs.Count() > AllowedMaximunFiles)
                {
                    filterContext.Result = new ApiResponse <string>()
                    {
                        Status = ApiResponseStatus.Failed, Message = "TheCountOfFilesUploadedIsLessThanTheMinimunAllowedFiles"
                    }.ToJson();
                }
                foreach (var blob in blobs)
                {
                    if (blob == null || blob.Length == 0)
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "FileUploadRequired", Data = blob.Name
                        }.ToJson();
                    }
                    else if (blob.Length > AllowedBlobMaxLength)
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileHasExceededTheLargestSizeAllowed", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedContentTypes != null && AllowedContentTypes.Any() && !AllowedContentTypes.Contains(blob.ContentType))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedContentType", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedExtensions != null && AllowedExtensions.Any() && !AllowedExtensions.Contains(Path.GetExtension(blob.FileName)))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedExtension", Data = blob.Name
                        }.ToJson();
                    }
                    else if (AllowedContentDispositions != null && AllowedContentDispositions.Any() && !AllowedContentDispositions.Contains(blob.ContentDisposition))
                    {
                        filterContext.Result = new ApiResponse <string>()
                        {
                            Status = ApiResponseStatus.Failed, Message = "TheFileDoesNotHaveTheExpectedContentDisposition", Data = blob.Name
                        }.ToJson();
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> UploadPhoto([FromForm] PhotoFile file)
        {
            var photo  = file.Photo;
            var sizeMB = photo.Length / 1024 / 1000;

            if (sizeMB > 10)
            {
                return(StatusCode(400, new ErrorDetails()
                {
                    errorId = ErrorList.WrongSize.Id,
                    errorMessage = ErrorList.WrongSize.Description
                }));
            }

            int userId  = int.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type == claimTypes.Id.ToString()).Value);
            int?albumId = file.AlbumId;

            if (albumId > 0)
            {
                if (!db.CheckAlbumExists((int)albumId, userId))
                {
                    return(StatusCode(403, new ErrorDetails()
                    {
                        errorId = ErrorList.UnauthorizedAction.Id, errorMessage = ErrorList.UnauthorizedAction.Description
                    }.ToString()));
                }
            }

            var extension = Path.GetExtension(photo.FileName).Replace(".", "");

            if (!AllowedExtensions.Contains(extension))
            {
                return(BadRequest(new ErrorDetails()
                {
                    errorId = ErrorList.InputDataError.Id, errorMessage = ErrorList.InputDataError.Description
                }.ToString()));
            }
            ;

            var imageName   = Guid.NewGuid().ToString().Replace("-", "");
            var newFilename = $"{imageName}.{extension}";
            var thumbName   = $"{imageName}_thumb.{extension}";

            var additionalPath = $"/{userId}";
            var newImagePath   = $"{additionalPath}/{newFilename}";
            var newThumbPath   = $"{additionalPath}/{thumbName}";

            db.AddPhoto(newFilename, userId, albumId, newImagePath, newThumbPath, thumbName);

            var path      = storage + newImagePath;
            var thumbPath = storage + newThumbPath;

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                await photo.CopyToAsync(fileStream);
            }

            var resizedThumb = helper.ResizeImage(Image.FromStream(photo.OpenReadStream()));

            if (!Directory.Exists(Path.GetDirectoryName(thumbPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(thumbPath));
            }

            helper.SaveImage(resizedThumb, thumbPath);

            return(Ok(new { response = new { fileName = newFilename } }));
        }
Ejemplo n.º 14
0
        private void UploadFolderToAlbum(DirectoryInfo directory, bool reupload = false)
        {
            try
            {
                Logger.Info($"Uploading folder {directory.Name}");

                // looking in journal
                var alreadyUploadedJournalItem = _uploadedJournal.Directory(directory.FullName);
                if (alreadyUploadedJournalItem != null)
                {
                    if (reupload)
                    {
                        Logger.Warning($"Reuploading folder {directory.FullName} with id {alreadyUploadedJournalItem.AlbumId}");
                    }
                    else
                    {
                        Logger.Warning($"Folder {directory.FullName} is already uploaded with id {alreadyUploadedJournalItem.AlbumId}");
                        return;
                    }
                }

                // https://stackoverflow.com/questions/7039580/multiple-file-extensions-searchpattern-for-system-io-directory-getfiles/7039649
                var files = Directory.GetFiles(directory.FullName, "*.*", SearchOption.TopDirectoryOnly)
                            .Where(f => AllowedExtensions.Contains(Path.GetExtension(f).ToLower())).ToList();

                Logger.Info($"Files found: {files.Count}");

                if (files.Count == 0)
                {
                    return;
                }

                files.Sort();

                string albumId;

                if (alreadyUploadedJournalItem != null)
                {
                    // album is already created
                    albumId = alreadyUploadedJournalItem.AlbumId;
                }
                else
                {
                    //  creating album
                    var alb = GAPIAlbum.CreateAlbum(_accountConnection, directory.Name);
                    albumId = alb.id;

                    AddToJournal(directory.FullName, albumId);
                }

                // batch upload
                var batchCount = 20;

                var fileTokensBatch = new List <Dictionary <string, string> >();

                var actualBatch = new Dictionary <string, string>();

                var fIndex = 0;
                foreach (var f in files)
                {
                    var fi = new FileInfo(f);
                    if (fi.Length == 0)
                    {
                        Logger.Warning($"Skipping empty file ({f})");
                        continue;
                    }

                    //  uploading file

                    var uploadToken = _accountConnection.UploadFile(f);

                    if (string.IsNullOrEmpty(uploadToken))
                    {
                        Logger.Warning($"Empty upload file token for file ({f})");
                        continue;
                    }

                    actualBatch.Add(uploadToken, Path.GetFileName(f));

                    fIndex++;
                    if (fIndex > batchCount)
                    {
                        if (actualBatch.Count > 0)
                        {
                            fileTokensBatch.Add(actualBatch);
                            actualBatch = new Dictionary <string, string>();
                        }
                        fIndex = 0;
                    }
                }

                if (actualBatch.Count > 0)
                {
                    fileTokensBatch.Add(actualBatch);
                }

                if (fileTokensBatch.Count > 0)
                {
                    foreach (var batch in fileTokensBatch)
                    {
                        var uploadedItems = GAPIAlbum.AddMediaItemsToAlbum(_accountConnection, albumId, batch);
                    }
                }
                else
                {
                    Logger.Info($"No file uploaded");
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
Ejemplo n.º 15
0
        //public string RootFolder
        //{
        //    get;
        //    set;
        //}

        //public string DisplayFolder
        //{
        //    get;
        //    set;
        //}

        public bool IsExtAllowed(string extension)
        {
            return(AllowedExtensions.Contains(extension.ToLower()));
        }
Ejemplo n.º 16
0
 public bool IsExtensionAllowed(string ext)
 {
     return(AllowedExtensions.Contains("*") || AllowedExtensions.Contains(ext));
 }