예제 #1
0
        /// <summary>
        /// gets the number of pages of the cbz/cbr archive
        /// </summary>
        private int ReadPageCount(string archivePath)
        {
            if (File.Exists(archivePath))
            {
                //direct the program to the dependency: 7z.dll (7z64.dll for 64-bit ver.)
                SevenZipBase.SetLibraryPath(Path.Combine(Environment.CurrentDirectory, "7z.dll"));

                using (var extractor = new SevenZipExtractor(archivePath))
                {
                    //get the sorted archive file list to get the first image
                    //verify that the cover page is an image
                    var fileNames = extractor.ArchiveFileData
                                    .Where(
                        file => ImageChecker.IsImageExtension(
                            Path.GetExtension(file.FileName)
                            )
                        );
                    fileNames = fileNames.OrderBy(file => file.FileName);

                    //this is the page count
                    return(fileNames.Count());
                }
            }
            else
            {
                Trace.WriteLine("Set Path = " + "<" + filePath + ">" + " is invalid, cannot proceed with page counting process.");
                FileNotFoundException exc = new FileNotFoundException
                                            (
                    "Set Path = " + "<" + filePath + ">" + " cannot proceed with comic book records access."
                                            );
                throw exc;
            }
        }
        public override bool BindProperty(ControllerContext controllerContext,
                                          ModelBindingContext bindingContext,
                                          PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.PropertyType == typeof(Image))
            {
                HttpFileCollectionBase files = controllerContext.HttpContext.Request.Files;

                if (files.Count != 1)
                {
                    bindingContext.ModelState.AddModelError(propertyDescriptor.DisplayName, "Choose photo for uploading");
                    return(true);
                }

                HttpPostedFileBase uploadedFile = files[0];
                byte[]             data         = uploadedFile.ReadData();
                if (!ImageChecker.IsImage(data))
                {
                    bindingContext.ModelState.AddModelError(propertyDescriptor.DisplayName, "Choose photo for uploading");
                    return(true);
                }

                Image image = Image.Create(data, uploadedFile.ContentType);
                propertyDescriptor.SetValue(bindingContext.Model, image);
                return(true);
            }

            return(false);
        }
예제 #3
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var httpFiles = ExtractHttpFileCollection(validationContext);

            if (httpFiles == null || !httpFiles.All(httpFile => ImageChecker.IsImage(httpFile.Data)))
            {
                return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
            }

            return(null);
        }
예제 #4
0
        public void CheckValidExtension()
        {
            var dir   = "Data";
            var files = Directory.EnumerateFiles(dir);

            ImageChecker imageChecker = new ImageChecker();
            StreamUtil   utils        = new StreamUtil();

            foreach (var file in files)
            {
                string fileName = file.Substring(dir.Length + 1);
                using var stream = new FileStream(file, FileMode.Open, FileAccess.Read);

                FileInformation fileInformation = new FileInformation()
                {
                    data = utils.FileStreamToBytes(stream), fileName = fileName
                };

                //assert
                imageChecker.CheckForExtension(fileInformation);
            }
        }
예제 #5
0
        public static void CheckUploadedImageAndCreateThumbs(ImageUploadEditorAttribute attr, ref string temporaryFile)
        {
            ImageCheckResult[] supportedFormats = null;

            if (!attr.AllowNonImage)
            {
                supportedFormats = new ImageCheckResult[] {
                    ImageCheckResult.JPEGImage,
                    ImageCheckResult.GIFImage,
                    ImageCheckResult.PNGImage
                }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = attr.MinWidth;
            checker.MaxWidth    = attr.MaxWidth;
            checker.MinHeight   = attr.MinHeight;
            checker.MaxHeight   = attr.MaxHeight;
            checker.MaxDataSize = attr.MaxSize;

            Image image = null;

            try
            {
                var temporaryPath = UploadHelper.DbFilePath(temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (attr.MinSize != 0 && fs.Length < attr.MinSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooSmall,
                                                                UploadHelper.FileSizeDisplay(attr.MinSize)));
                    }

                    if (attr.MaxSize != 0 && fs.Length > attr.MaxSize)
                    {
                        throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooBig,
                                                                UploadHelper.FileSizeDisplay(attr.MaxSize)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result == ImageCheckResult.InvalidImage &&
                        attr.AllowNonImage)
                    {
                        return;
                    }

                    if (result > ImageCheckResult.UnsupportedFormat ||
                        (supportedFormats != null && Array.IndexOf(supportedFormats, result) < 0))
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result >= ImageCheckResult.FlashMovie)
                    {
                        return;
                    }

                    string basePath = UploadHelper.TemporaryPath;
                    string baseFile = Path.GetFileNameWithoutExtension(Path.GetFileName(temporaryPath));

                    TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                    if ((attr.ScaleWidth > 0 || attr.ScaleHeight > 0) &&
                        ((attr.ScaleWidth > 0 && (attr.ScaleSmaller || checker.Width > attr.ScaleWidth)) ||
                         (attr.ScaleHeight > 0 && (attr.ScaleSmaller || checker.Height > attr.ScaleHeight))))
                    {
                        using (Image scaledImage = ThumbnailGenerator.Generate(
                                   image, attr.ScaleWidth, attr.ScaleHeight, attr.ScaleMode, Color.Empty))
                        {
                            temporaryFile = baseFile + ".jpg";
                            fs.Close();
                            scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            temporaryFile = "temporary/" + temporaryFile;
                        }
                    }

                    var thumbSizes = attr.ThumbSizes.TrimToNull();
                    if (thumbSizes == null)
                    {
                        return;
                    }

                    foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                    {
                        var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                        int w, h;
                        if (dims.Length != 2 ||
                            !Int32.TryParse(dims[0], out w) ||
                            !Int32.TryParse(dims[1], out h) ||
                            w < 0 ||
                            h < 0 ||
                            (w == 0 && h == 0))
                        {
                            throw new ArgumentOutOfRangeException("thumbSizes");
                        }

                        using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, attr.ThumbMode, Color.Empty))
                        {
                            string thumbFile = Path.Combine(basePath,
                                                            baseFile + "_t" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                            thumbImage.Save(thumbFile);
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
예제 #6
0
        public void CheckUploadedImageAndCreateThumbs(ref string temporaryFile,
                                                      params ImageCheckResult[] supportedFormats)
        {
            if (supportedFormats == null ||
                supportedFormats.Length == 0)
            {
                supportedFormats = new ImageCheckResult[] { ImageCheckResult.JPEGImage, ImageCheckResult.GIFImage, ImageCheckResult.PNGImage }
            }
            ;

            UploadHelper.CheckFileNameSecurity(temporaryFile);

            var checker = new ImageChecker();

            checker.MinWidth    = this.MinWidth;
            checker.MaxWidth    = this.MaxWidth;
            checker.MinHeight   = this.MinHeight;
            checker.MaxHeight   = this.MaxHeight;
            checker.MaxDataSize = this.MaxBytes;

            Image image = null;

            try
            {
                var temporaryPath = Path.Combine(UploadHelper.TemporaryPath, temporaryFile);
                using (var fs = new FileStream(temporaryPath, FileMode.Open))
                {
                    if (this.MinBytes != 0 && fs.Length < this.MinBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en az {0} boyutunda olmalı!",
                                                                UploadHelper.FileSizeDisplay(this.MinBytes)));
                    }

                    if (this.MaxBytes != 0 && fs.Length > this.MaxBytes)
                    {
                        throw new ValidationError(String.Format("Yükleyeceğiniz dosya en çok {0} boyutunda olabilir!",
                                                                UploadHelper.FileSizeDisplay(this.MaxBytes)));
                    }

                    ImageCheckResult result;
                    if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf")
                    {
                        result = ImageCheckResult.FlashMovie;
                        // validate swf file somehow!
                    }
                    else
                    {
                        result = checker.CheckStream(fs, true, out image);
                    }

                    if (result > ImageCheckResult.FlashMovie ||
                        Array.IndexOf(supportedFormats, result) < 0)
                    {
                        string error = checker.FormatErrorMessage(result);
                        throw new ValidationError(error);
                    }

                    if (result != ImageCheckResult.FlashMovie)
                    {
                        string basePath = UploadHelper.TemporaryPath;
                        string baseFile = Path.GetFileNameWithoutExtension(temporaryFile);

                        TemporaryFileHelper.PurgeDirectoryDefault(basePath);

                        if ((this.ScaleWidth > 0 || this.ScaleHeight > 0) &&
                            ((this.ScaleWidth > 0 && (this.ScaleSmaller || checker.Width > this.ScaleWidth)) ||
                             (this.ScaleHeight > 0 && (this.ScaleSmaller || checker.Height > this.ScaleHeight))))
                        {
                            using (Image scaledImage = ThumbnailGenerator.Generate(
                                       image, this.ScaleWidth, this.ScaleHeight, this.ScaleMode, Color.Empty))
                            {
                                temporaryFile = baseFile + ".jpg";
                                fs.Close();
                                scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }

                        var thumbSizes = this.ThumbSizes.TrimToNull();
                        if (thumbSizes != null)
                        {
                            foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' }))
                            {
                                var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' });
                                int w, h;
                                if (dims.Length != 2 ||
                                    !Int32.TryParse(dims[0], out w) ||
                                    !Int32.TryParse(dims[1], out h) ||
                                    w < 0 ||
                                    h < 0 ||
                                    (w == 0 && h == 0))
                                {
                                    throw new ArgumentOutOfRangeException("thumbSizes");
                                }

                                using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, this.ThumbMode, Color.Empty))
                                {
                                    string thumbFile = Path.Combine(basePath,
                                                                    baseFile + "t_" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg");

                                    if (this.ThumbQuality != 0)
                                    {
                                        var p = new System.Drawing.Imaging.EncoderParameters(1);
                                        p.Param[0] = new EncoderParameter(Encoder.Quality, 80L);

                                        ImageCodecInfo   jpegCodec = null;
                                        ImageCodecInfo[] codecs    = ImageCodecInfo.GetImageEncoders();
                                        // Find the correct image codec
                                        for (int i = 0; i < codecs.Length; i++)
                                        {
                                            if (codecs[i].MimeType == "image/jpeg")
                                            {
                                                jpegCodec = codecs[i];
                                            }
                                        }
                                        thumbImage.Save(thumbFile, jpegCodec, p);
                                    }
                                    else
                                    {
                                        thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
    }
예제 #7
0
        /// <summary>
        /// extracts the first page of the comics in the list to cache
        /// </summary>
        private void ExtractCoversToCache()
        {
            //direct the program to the dependency: 7z.dll (7z64.dll for 64-bit ver.)
            SevenZipBase.SetLibraryPath(Path.Combine(Environment.CurrentDirectory, "7z.dll"));

            //extract cover pages of all comic books in the list
            foreach (var comicBook in comicBookList)
            {
                string archivePath = comicBook.GetArchivePath();
                //check if cover has been cached already
                bool fileExists = false;
                try
                {
                    string fileName = Directory.GetFiles(tempPath, Path.GetFileNameWithoutExtension(archivePath) + ".*").Single();
                    fileExists = true;
                }
                catch (InvalidOperationException exc)
                {
                    Trace.WriteLine("File pertaining to <" + Path.GetFileNameWithoutExtension(archivePath) + "> does not exist. Proceeding to extract.");
                }
                //skip if cover page has already been extracted
                if (fileExists)
                {
                    continue;
                }

                //else,
                //extract archive to temporary folder
                using (var extractor = new SevenZipExtractor(archivePath))
                {
                    //get the sorted archive file list to get the first image
                    //verify that the cover page is an image
                    var fileNames = extractor.ArchiveFileData
                                    .Where(
                        file => ImageChecker.IsImageExtension(
                            Path.GetExtension(file.FileName)
                            )
                        );
                    fileNames = fileNames.OrderBy(file => file.FileName);

                    //set the page count
                    comicBook.Override_SetPageCount(fileNames.Count());

                    //extract first image only
                    extractor.ExtractFiles(tempPath, fileNames.First().Index);
                    string newFileName = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(archivePath)
                                                      + Path.GetExtension(fileNames.First().FileName));
                    //rename file to name of archive file
                    File.Move(Path.Combine(tempPath, fileNames.First().FileName), newFileName);

                    //have to make sure the image is not within another directory
                    string[] dirs = Directory.GetDirectories(tempPath);

                    if (dirs.Length != 0)
                    {
                        string[] fileList;
                        foreach (var dir in dirs)
                        {
                            //get files in directory
                            fileList = Directory.GetFiles(dir);

                            //bring them to tempPath
                            foreach (var file in fileList)
                            {
                                string newFilePath = Path.Combine(tempPath, Path.GetFileName(file));
                                File.Move(file, newFilePath);
                            }
                            //delete the directory
                            Directory.Delete(dir);
                        }
                    }
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Open the comic based on archivePath, this closes the current one
        /// </summary>
        public void OpenComicBook(string archivePath)
        {
            //get the comic book from the archivePath using ComicAccess
            ComicAccess comAcc = new ComicAccess();

            comicBook = comAcc.GetComicBook(archivePath);

            //set extract folder in temporary folder pertaining to comic, and make it the new tempPath
            //this will be the cache for the comic book
            tempPath = Path.Combine(tempPath,
                                    Path.GetFileNameWithoutExtension(archivePath));

            //check if comic book has already been cached to temp folder
            if (Directory.Exists(tempPath) && Directory.GetFiles(tempPath).Length != 0)
            {
                //don't extract anymore, load the comic book from cache
                comicBook.SetComicPath(tempPath);
                //set current page as cover page(first page)
                currentPage = 1;
                //nothing to report
                ReportProgress?.Invoke(this, new ProgressArgs
                {
                    TotalProcessed   = 100,
                    TotalRecords     = 100,
                    Description      = "Done!",
                    IsDoneProcessing = true
                });
            }
            //comic book has not been cached yet, perform archive extraction
            else
            {
                //create extract folder in temporary folder pertaining to comic
                Directory.CreateDirectory(tempPath);

                //direct the program to the dependency: 7z.dll (7z64.dll for 64-bit)
                SevenZipBase.SetLibraryPath(Path.Combine(Environment.CurrentDirectory, "7z.dll"));

                //extract archive to temporary folder
                using (var extractor = new SevenZipExtractor(archivePath))
                {
                    //extract all images in temporary folder
                    for (var i = 0; i < extractor.ArchiveFileData.Count; i++)
                    {
                        //check if file to be extracted is an image
                        string fileToBeExtractedExtension = Path.GetExtension(extractor.ArchiveFileData[i].FileName);
                        if (ImageChecker.IsImageExtension(fileToBeExtractedExtension))
                        {
                            //extract the file
                            extractor.ExtractFiles(tempPath, extractor.ArchiveFileData[i].Index);
                        }

                        //report progress that a file has been processed
                        ReportProgress?.Invoke(this, new ProgressArgs
                        {
                            TotalProcessed   = i + 1,
                            TotalRecords     = extractor.ArchiveFileData.Count,
                            Description      = "Extracting comic book to cache.",
                            IsDoneProcessing = false
                        });
                    }
                }

                //move images outside the directories, if there are any
                string[] comicDirs = Directory.GetDirectories(tempPath);
                if (comicDirs.Length != 0)
                {
                    string[] fileList;
                    foreach (var dir in comicDirs)
                    {
                        //get files in directory
                        fileList = Directory.GetFiles(dir);
                        //start a new report
                        //report progress that a file has been processed
                        ReportProgress?.Invoke(this, new ProgressArgs
                        {
                            TotalProcessed   = 0,
                            TotalRecords     = fileList.Length,
                            Description      = "Rearranging comic book.",
                            IsDoneProcessing = false
                        });

                        int filesProcessed = 0;
                        //bring them to tempPath
                        foreach (var file in fileList)
                        {
                            string newFilePath = Path.Combine(tempPath, Path.GetFileName(file));
                            File.Move(file, newFilePath);
                            ReportProgress?.Invoke(this, new ProgressArgs
                            {
                                TotalProcessed   = filesProcessed,
                                TotalRecords     = fileList.Length,
                                Description      = "Rearranging comic book.",
                                IsDoneProcessing = false
                            });
                            filesProcessed++;
                        }
                        //delete the directory
                        Directory.Delete(dir);
                    }
                }

                //set the comic book path
                comicBook.SetComicPath(tempPath);

                //set current page as cover page(first page)
                currentPage = 1;

                //end reporting
                ReportProgress?.Invoke(this, new ProgressArgs
                {
                    TotalProcessed   = 100,
                    TotalRecords     = 100,
                    Description      = "Done!",
                    IsDoneProcessing = true
                });
                //go back to temp directory
                tempPath = Path.Combine(tempPath, @"..\");
            }
        }
        public async Task <IHttpActionResult> TemporaryLargeFileUpload()
        {
            var token = Request.Headers.Contains("X-File-Token") ? Request.Headers.GetValues("X-File-Token").FirstOrDefault() : null;

            if (string.IsNullOrWhiteSpace(token))
            {
                return(InternalServerError(new Exception("File Token not provided.")));
            }


            try
            {
                var uploadFileService = new UploadFileService();
                UploadProcessingResult uploadResult = await uploadFileService.HandleRequest(Request);

                if (uploadResult.IsComplete)
                {
                    var baseFileName = Guid.NewGuid().ToString("N");
                    var saveFileName = $"{baseFileName}{Path.GetExtension(uploadResult.FileName)}";
                    var saveFilePath = Path.Combine(Path.GetDirectoryName(uploadResult.LocalFilePath), saveFileName);
                    if (File.Exists(saveFilePath))
                    {
                        File.Delete(saveFilePath);
                    }

                    File.Move(uploadResult.LocalFilePath, saveFilePath);

                    using (var sw = new StreamWriter(Path.ChangeExtension(saveFilePath, ".orig")))
                        sw.WriteLine(uploadResult.FileName);

                    //create thumb for image
                    var  isImage = false;
                    var  height  = 0;
                    var  width   = 0;
                    long size    = 0;
                    if (IsImageExtension(saveFileName))
                    {
                        isImage = true;

                        using (var fileContent = new FileStream(saveFilePath, FileMode.Open))
                        {
                            var imageChecker = new ImageChecker();
                            var checkResult  = imageChecker.CheckStream(fileContent, true, out var image);
                            height = imageChecker.Height;
                            width  = imageChecker.Width;
                            size   = imageChecker.DataSize;
                            if (checkResult != ImageCheckResult.JPEGImage &&
                                checkResult != ImageCheckResult.GIFImage &&
                                checkResult != ImageCheckResult.PNGImage)
                            {
                                throw new Exception(imageChecker.FormatErrorMessage(checkResult));
                            }
                            else
                            {
                                using (var thumbImage = ThumbnailGenerator.Generate(image, 128, 96, ImageScaleMode.CropSourceImage, Color.Empty))
                                {
                                    var thumbFile = Path.Combine(Path.GetDirectoryName(uploadResult.LocalFilePath), baseFileName + "_t.jpg");
                                    thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg);

                                    //height = thumbImage.Width;
                                    //width = thumbImage.Height;
                                }
                            }
                        }
                    }

                    return(Ok(new UploadResponse()
                    {
                        TemporaryFile = UrlCombine(UploadFileService.TempFolder, saveFileName),
                        IsImage = isImage,
                        Width = width,
                        Height = height,
                        Size = size
                    }));
                }

                return(Ok(HttpStatusCode.Continue));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }