public ICollection <IImageFile> GetImageFiles(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath))
            {
                throw new ArgumentException("Folder path cannot be empty.", nameof(folderPath));
            }

            ICollection <FileInfo> filesInformation;

            try
            {
                filesInformation = new DirectoryInfo(folderPath)
                                   .GetFiles("*", SearchOption.TopDirectoryOnly)
                                   .ToArray();
            }
            catch
            {
                return(EmptyImageFileCollection);
            }

            var imageFiles = filesInformation
                             .Where(aFileInfo =>
                                    ImageFileExtensions.Contains(aFileInfo.Extension))
                             .OrderBy(aFileInfo => aFileInfo.Name)
                             .Select(aFileInfo => _imageFileFactory.GetImageFile(_imageResizer, aFileInfo.FullName))
                             .OrderBy(aFileInfo => aFileInfo.FileName, _fileSystemEntryComparer)
                             .ToArray();

            return(imageFiles);
        }
Ejemplo n.º 2
0
        public static FileType CheckFileType(string extension)
        {
            if (!string.IsNullOrEmpty(extension))
            {
                FileExtension file = new FileExtension(extension.ToUpper(), FileType.UnKnow, "");

                if (VideoFileExtensions.Contains(file))
                {
                    return(FileType.Video);
                }
                else if (SubTitleFileExtensions.Contains(file))
                {
                    return(FileType.SubTitle);
                }
                else if (AudioFileExtensions.Contains(file))
                {
                    return(FileType.Audio);
                }
                else if (ImageFileExtensions.Contains(file))
                {
                    return(FileType.Image);
                }
            }

            return(FileType.UnKnow);
        }
Ejemplo n.º 3
0
        private Option <string> LocateArtwork(Movie movie, ArtworkKind artworkKind)
        {
            string segment = artworkKind switch
            {
                ArtworkKind.Poster => "poster",
                ArtworkKind.FanArt => "fanart",
                _ => throw new ArgumentOutOfRangeException(nameof(artworkKind))
            };

            string path   = movie.MediaVersions.Head().MediaFiles.Head().Path;
            string folder = Path.GetDirectoryName(path) ?? string.Empty;
            IEnumerable <string> possibleMoviePosters = ImageFileExtensions.Collect(
                ext => new[] { $"{segment}.{ext}", Path.GetFileNameWithoutExtension(path) + $"-{segment}.{ext}" })
                                                        .Map(f => Path.Combine(folder, f));
            Option <string> result = possibleMoviePosters.Filter(p => _localFileSystem.FileExists(p)).HeadOrNone();

            if (result.IsNone && artworkKind == ArtworkKind.Poster)
            {
                IEnumerable <string> possibleFolderPosters = ImageFileExtensions.Collect(
                    ext => new[] { $"folder.{ext}" })
                                                             .Map(f => Path.Combine(folder, f));
                result = possibleFolderPosters.Filter(p => _localFileSystem.FileExists(p)).HeadOrNone();
            }

            return(result);
        }
    }
Ejemplo n.º 4
0
 public static bool IsImageExtension(this string ext)
 {
     if (ext.Contains('.'))
     {
         ext = Path.GetExtension(ext);
     }
     return(ImageFileExtensions.Contains(ext.ToLower()));
 }
Ejemplo n.º 5
0
    private Option <string> LocatePoster(Season season, string seasonFolder)
    {
        string folder = Path.GetDirectoryName(seasonFolder) ?? string.Empty;

        return(ImageFileExtensions
               .Map(ext => Path.Combine(folder, $"season{season.SeasonNumber:00}-poster.{ext}"))
               .Filter(s => _localFileSystem.FileExists(s))
               .HeadOrNone());
    }
Ejemplo n.º 6
0
    private Option <string> LocateThumbnail(MusicVideo musicVideo)
    {
        string path = musicVideo.MediaVersions.Head().MediaFiles.Head().Path;

        return(ImageFileExtensions
               .Map(ext => Path.ChangeExtension(path, ext))
               .Filter(f => _localFileSystem.FileExists(f))
               .HeadOrNone());
    }
Ejemplo n.º 7
0
 private void AddImageExtension()
 {
     IsAddingImageExtension = false;
     if (!string.IsNullOrWhiteSpace(_newExtensionText) &&
         _extensionValidater.IsValid(_newExtensionText) &&
         !ImageFileExtensions.Contains(_newExtensionText))
     {
         ImageFileExtensions.Add(_newExtensionText);
     }
 }
Ejemplo n.º 8
0
        public ActionResult ShowFileData(int fileid)
        {
            try
            {
                if (!db.Files.Any(m => m.fileid == fileid))
                {
                    return(RedirectToAction("Partial_Toast", "Toast", NoSuchFile()));
                }

                string fileExt = db.Files.Include(m => m.FileExtension).FirstOrDefault(m => m.fileid == fileid)?.FileExtension?.displayname;

                if (ImageFileExtensions.Any(fileExt.Contains))
                {
                    var file = db.Files.Include(m => m.FileExtension).FirstOrDefault(m => m.fileid == fileid);
                    return(PartialView("_PartialShowFileImage", new FileEditModel(file)));
                }

                if (TextFileExtensions.Any(fileExt.Contains))
                {
                    var file = db.Files.Include(m => m.FileExtension).FirstOrDefault(m => m.fileid == fileid);
                    file.FileContentAsString = file.file_content != null?Encoding.UTF8.GetString(file.file_content) : "";

                    return(PartialView("_PartialShowFileData", new FileEditModel(file)));
                }

                // загрузка данных файла без контента файла
                File fileWithoutData = db.Files.AsEnumerable().Where(m => m.fileid == fileid).Select(m => new File
                {
                    fileid        = m.fileid,
                    FileExtension = m.FileExtension,
                    description   = m.description,
                    displayname   = m.displayname,
                    folderid      = m.folderid
                }).FirstOrDefault();

                string extName      = fileWithoutData.FileExtension?.icon_filename ?? fileWithoutData.FileExtension.displayname + ".svg";
                string relativePath = "/Content/FileIcons/" + extName;
                string fullpath     = HttpContext.Server.MapPath(relativePath);

                if (System.IO.File.Exists(fullpath))
                {
                    fileWithoutData.IconFileName = extName;
                }
                else
                {
                    fileWithoutData.IconFileName = "unknown.svg";
                }

                return(PartialView("_PartialShowFileExtension", new FileEditModel(fileWithoutData)));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("Partial_UnknownErrorToast", "Toast"));
            }
        }
Ejemplo n.º 9
0
    private Option <string> LocateThumbnail(Episode episode)
    {
        string path   = episode.MediaVersions.Head().MediaFiles.Head().Path;
        string folder = Path.GetDirectoryName(path) ?? string.Empty;

        return(ImageFileExtensions
               .Map(ext => Path.GetFileNameWithoutExtension(path) + $"-thumb.{ext}")
               .Map(f => Path.Combine(folder, f))
               .Filter(f => _localFileSystem.FileExists(f))
               .HeadOrNone());
    }
Ejemplo n.º 10
0
        public void Image_Valid()
        {
            //Arrange
            string test     = "test.jpg";
            bool   expected = true;

            //Act
            IFileExtensions extension = new ImageFileExtensions();
            FileValidation  validate  = new FileValidation();
            bool            result    = validate.IsExtension(test, extension);

            //Assert
            Assert.AreEqual(expected, result);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> Create(CreateTeamViewModel formModel)
        {
            var userId = this.userManager.GetUserId(User);

            if (await this.teams.ContainsNameAsync(formModel.Name))
            {
                ModelState.AddModelError("Name",
                                         string.Format(ErrorMessages.TeamNameExists, formModel.Name));
                return(View(formModel));
            }

            if (await this.teams.ContainsTagAsync(formModel.Tag))
            {
                ModelState.AddModelError("Tag",
                                         string.Format(ErrorMessages.TeamTagExists, formModel.Tag));
                return(View(formModel));
            }

            var fileName      = formModel.Image.FileName;
            var imageModelKey = nameof(formModel.Image);

            // Checks if image file extensions is valid.
            if (!ImageFileExtensions.FileExtensionValidation(formModel.Image.FileName))
            {
                ModelState.AddModelError(imageModelKey, ErrorMessages.InvalidImageFileExtension);
                return(View(formModel));
            }

            // Checks if image file signature is valid
            if (!ImageFileExtensions.FileSignatureValidation(fileName, formModel.Image.OpenReadStream()))
            {
                ModelState.AddModelError(imageModelKey, ErrorMessages.InvalidImageFileSignature);
                return(View(formModel));
            }

            // Uploads image to root folder and returns generated image file name.
            var imageName = await ImageFileExtensions.UploadFileAsync(formModel.Image, webHostEnvironment.WebRootPath);


            await this.teams.CreateAsync(
                formModel.Name,
                formModel.Tag,
                imageName,
                userId);

            TempData.AddSuccessMessage(string.Format(SuccessMessages.CreateTeam, formModel.Name));

            return(RedirectToAction(nameof(HomeController.Index), "Home", new { area = string.Empty }));
        }
Ejemplo n.º 12
0
    private Option <string> LocateThumbnail(Song song)
    {
        string path = song.MediaVersions.Head().MediaFiles.Head().Path;
        Option <DirectoryInfo> parent = Optional(Directory.GetParent(path));

        return(parent.Map(
                   di =>
        {
            string coverPath = Path.Combine(di.FullName, "cover.jpg");
            return ImageFileExtensions
            .Map(ext => Path.ChangeExtension(coverPath, ext))
            .Filter(f => _localFileSystem.FileExists(f))
            .HeadOrNone();
        }).Flatten());
    }
Ejemplo n.º 13
0
    private Option <string> LocateArtworkForArtist(string artistFolder, ArtworkKind artworkKind)
    {
        string segment = artworkKind switch
        {
            ArtworkKind.Thumbnail => "thumb",
            ArtworkKind.FanArt => "fanart",
            _ => throw new ArgumentOutOfRangeException(nameof(artworkKind))
        };

        return(ImageFileExtensions
               .Map(ext => $"{segment}.{ext}")
               .Map(f => Path.Combine(artistFolder, f))
               .Filter(s => _localFileSystem.FileExists(s))
               .HeadOrNone());
    }
Ejemplo n.º 14
0
        private Option <string> LocateArtworkForShow(string showFolder, ArtworkKind artworkKind)
        {
            string[] segments = artworkKind switch
            {
                ArtworkKind.Poster => new[] { "poster", "folder" },
                ArtworkKind.FanArt => new[] { "fanart" },
                _ => throw new ArgumentOutOfRangeException(nameof(artworkKind))
            };

            return(ImageFileExtensions
                   .Map(ext => segments.Map(segment => $"{segment}.{ext}"))
                   .Flatten()
                   .Map(f => Path.Combine(showFolder, f))
                   .Filter(s => _localFileSystem.FileExists(s))
                   .HeadOrNone());
        }
Ejemplo n.º 15
0
 private void SaveSettings()
 {
     _appSettings.UploadDelay      = Delay;
     _appSettings.CheckForUpdates  = CheckForUpdates;
     _appSettings.ImageExtensions  = ImageFileExtensions.ToString();
     _appSettings.FollowUploadFile = FollowUploadFile;
     if (SelectedColorTheme != null)
     {
         _appSettings.Theme = SelectedColorTheme.Id;
     }
     if (SelectedLanguage != null)
     {
         _appSettings.Language = SelectedLanguage.Code;
     }
     _appSettings.Save();
     _navigatorService.LeaveSettingsPage();
 }
        public async Task <IActionResult> Add(AddGameFormModel formModel)
        {
            if (await this.games.ContainsAsync(formModel.Name))
            {
                ModelState.AddModelError(nameof(formModel.Name),
                                         string.Format(ErrorMessages.GameExists, formModel.Name));
                return(RedirectToAction(nameof(Add)));
            }

            var fileName      = formModel.Image.FileName;
            var imageModelKey = nameof(formModel.Image);

            // Checks if image file extensions is valid.
            if (!ImageFileExtensions.FileExtensionValidation(formModel.Image.FileName))
            {
                ModelState.AddModelError(imageModelKey, ErrorMessages.InvalidImageFileExtension);
                return(View(formModel));
            }

            // Checks if image file signature is valid
            if (!ImageFileExtensions.FileSignatureValidation(fileName, formModel.Image.OpenReadStream()))
            {
                ModelState.AddModelError(imageModelKey, ErrorMessages.InvalidImageFileSignature);
                return(View(formModel));
            }

            // Uploads image to root folder and returns generated image file name.
            var imageName = await ImageFileExtensions.UploadFileAsync(formModel.Image, webHostEnvironment.WebRootPath);



            await this.adminGames.AddAsync(
                formModel.Name,
                formModel.Developer,
                imageName);

            TempData.AddSuccessMessage(string.Format(SuccessMessages.AddedGame, formModel.Name));

            return(RedirectToAction(
                       nameof(Web.Controllers.GamesController.Index),
                       "Home", new { area = string.Empty }));
        }
Ejemplo n.º 17
0
 private MediaItem GetMediaItem(string file)
 {
     if (MovieFileExtensions.Any(ex =>
                                 file.ToLower().EndsWith(ex, StringComparison.Ordinal)) &&
         _mediaTypes.HasFlag(MediaType.Video))
     {
         return new MediaItem
                {
                    MediaType = MediaType.Video,
                    Path      = "file://" + file
                }
     }
     ;
     if (ImageFileExtensions.Any(ex =>
                                 file.ToLower().EndsWith(ex, StringComparison.Ordinal)) &&
         _mediaTypes.HasFlag(MediaType.Image))
     {
         return new MediaItem {
                    MediaType = MediaType.Image, Path = file
         }
     }
     ;
     return(null);
 }
        public static SaveImageThumbnailResult SaveImageThumbnail(idCatalogItem catalogItem, ref IDImagerDB db, ref IDImagerDB dbThumbs,
            List<String> types, Boolean keepAspectRatio, Boolean setGenericVideoThumbnailOnError)
        {
            SaveImageThumbnailResult result = new SaveImageThumbnailResult();
            Stream imageStream = null;
            String filePath = null;

            try
            {          
                filePath = GetImageFilePath(catalogItem);
                BitmapFrame bitmapFrame;

                if (ImageFileExtensions.Contains(catalogItem.idFileType))
                {
                    imageStream = GetImageFileStream(filePath);
                    bitmapFrame = GetBitmapFrameFromImageStream(imageStream, catalogItem.idFileType);
                }
                else if (VideoFileExtensions.Contains(catalogItem.idFileType))
                {
                    try
                    {
                        bitmapFrame = BitmapFrame.Create((BitmapSource)GenerateVideoThumbnail(filePath, new TimeSpan(0, 0, 0)));
                    }
                    catch (Exception ex)
                    {
                        if (setGenericVideoThumbnailOnError)
                        {
                            result.Exceptions.Add(new Exception(String.Format("Video thumbnail generation for imageGUID {0} file {1} failed. Generic thumbnails has been set.", catalogItem.GUID, filePath), ex));
                            
                            Assembly assembly = Assembly.GetExecutingAssembly();
                            Stream genericVideoThumbnailStream = assembly.GetManifestResourceStream(@"IDBrowserServiceCode.Images.image_ph2.png");
                            bitmapFrame = BitmapFrame.Create(genericVideoThumbnailStream);
                        }
                        else
                        {
                            result.Exceptions.Add(new Exception(String.Format("Video thumbnail generation for imageGUID {0} file {1} failed.", catalogItem.GUID, filePath), ex));
                            return result;
                        }
                    }
                }
                else
                {
                    throw new Exception(String.Format("File type {0} not supported", catalogItem.idFileType));
                }           

                foreach (String type in types)
                {
                    int imageWidth;
                    int imageHeight;

                    if (type.Equals("T"))
                    {
                        imageWidth = 160;
                        imageHeight = 120;
                    }
                    else
                    {
                        imageWidth = Int32.Parse(ConfigurationManager.AppSettings["MThumbmailWidth"]);
                        imageHeight = Int32.Parse(ConfigurationManager.AppSettings["MThumbnailHeight"]);
                    }

                    XDocument recipeXDocument = null;
                    if (type.Equals("T") || type.Equals("R"))
                    {
                        if (catalogItem.idHasRecipe > 0)
                            recipeXDocument = GetRecipeXDocument(db, catalogItem);
                    }
                                        
                    TransformGroup transformGroup = new TransformGroup();
                    
                    if (bitmapFrame.PixelWidth > imageWidth && bitmapFrame.PixelHeight > imageHeight)
                    {
                        double scaleX;
                        double scaleY;
                        
                        foreach (ScaleTransform existingScaleTransform in transformGroup.Children.OfType<ScaleTransform>().ToList())
                            transformGroup.Children.Remove(existingScaleTransform);

                        if (bitmapFrame.PixelWidth > bitmapFrame.PixelHeight)
                        {
                            scaleX = (double)imageWidth / (double)bitmapFrame.PixelWidth;
                            scaleY = (double)imageHeight / (double)bitmapFrame.PixelHeight;
                        }
                        else
                        {
                            scaleX = (double)imageHeight / (double)bitmapFrame.PixelHeight;
                            scaleY = (double)imageWidth / (double)bitmapFrame.PixelWidth;
                        }

                        ScaleTransform scaleTransform = new ScaleTransform(scaleX, scaleY, 0, 0);
                        transformGroup.Children.Add(scaleTransform);
                    }

                    Rotation rotation = StaticFunctions.GetRotation(bitmapFrame);
                    if (rotation != Rotation.Rotate0)
                    {
                        RotateTransform rotateTransform = new RotateTransform();

                        switch (rotation)
                        {
                            case Rotation.Rotate90:
                                rotateTransform.Angle = 90;
                                break;
                            case Rotation.Rotate180:
                                rotateTransform.Angle = 180;
                                break;
                            case Rotation.Rotate270:
                                rotateTransform.Angle = 270;
                                break;
                        }

                        transformGroup.Children.Add(rotateTransform);
                    }

                    Stream resizedImageStream = imageStream;
                    BitmapSource bitmapSource = bitmapFrame;

                    if (Recipe.ApplyXmpRecipe(recipeXDocument, ref bitmapSource, transformGroup))
                    {
                        BitmapFrame transformedBitmapFrame = BitmapFrame.Create(bitmapSource);

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.Frames.Add(transformedBitmapFrame);
                        resizedImageStream = new System.IO.MemoryStream();
                        encoder.Save(resizedImageStream);
                        resizedImageStream.Position = 0;
                    }

                    lock (dbThumbs)
                    {
                        idThumbs newThumb = new idThumbs();
                        newThumb.GUID = Guid.NewGuid().ToString().ToUpper();
                        newThumb.ImageGUID = catalogItem.GUID;
                        newThumb.idThumb = StreamToByteArray(resizedImageStream);
                        newThumb.idType = type;

                        dbThumbs.idThumbs.Add(newThumb);
                    }

                    result.ImageStreams.Add(resizedImageStream);
                }

                if (imageStream != null) { imageStream.Close(); }
                dbThumbs.SaveChanges(); 
            }
            catch (Exception ex)
            {
                if (imageStream != null) { imageStream.Close(); }
                result.Exceptions.Add(new Exception(String.Format("Error generating thumbnail for imageGUID {0} file {1}", catalogItem.GUID, filePath), ex));
            }

            return result;
        }
Ejemplo n.º 19
0
        public SettingsViewModel(
            IAppSettings appSettings,
            INavigatorService navigatorService,
            IUpdateCheck updateCheck,
            IWindowManager windowManager,
            IHelpers helpers) : base()
        {
            _extensionValidater = new ExtensionValidater();
            _navigatorService   = navigatorService;
            _helpers            = helpers;
            _appSettings        = appSettings;
            _windowManager      = windowManager;
            _updateCheck        = updateCheck;

            SetPropeertiesFromAppSettings();

            SelectedLanguage   = Languages.Where(x => x.Code == _appSettings.Language).FirstOrDefault();
            SelectedColorTheme = ColorThemes.Where(x => x.Id == _appSettings.Theme).FirstOrDefault();

            CancelSettingsCommand               = new RelayCommand(CancelSettings);
            SaveSettingsCommand                 = new RelayCommand(SaveSettings);
            CheckForUpdatesNowCommand           = new RelayCommand(CheckForUpdatesNow);
            RestoreDefaultsCommand              = new RelayCommand(RestoreDefaults);
            RemoveImageExtensionCommand         = new RelayParameterizedCommand(item => ImageFileExtensions.Remove((string)item));
            OpenAddImageExtensionCommand        = new RelayCommand(() => IsAddingImageExtension = true);
            AddImageEtensionCommand             = new RelayCommand(AddImageExtension);
            CloseImageFileExtensopnPopupCommand = new RelayCommand(() => IsAddingImageExtension = false);
        }