/// <summary>
        /// Gets a <see cref="FanArtPathCollection"/> containing all matching series fanart paths in the specified <see cref="ResourcePath"/>.
        /// </summary>
        /// <param name="seriesDirectory"><see cref="IFileSystemResourceAccessor"/> that points to the series directory.</param>
        /// <returns><see cref="FanArtPathCollection"/> containing all matching paths.</returns>
        protected FanArtPathCollection GetSeriesFolderFanArt(IFileSystemResourceAccessor seriesDirectory)
        {
            FanArtPathCollection paths = new FanArtPathCollection();

            if (seriesDirectory == null)
            {
                return(paths);
            }

            if (seriesDirectory != null)
            {
                List <ResourcePath> potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(seriesDirectory);
                ExtractAllFanArtImages(potentialFanArtFiles, paths);

                if (seriesDirectory.ResourceExists("ExtraFanArt/"))
                {
                    using (IFileSystemResourceAccessor extraFanArtDirectory = seriesDirectory.GetResource("ExtraFanArt/"))
                        paths.AddRange(FanArtTypes.FanArt, LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectory));
                }
            }

            return(paths);
        }
        /// <summary>
        /// Gets a <see cref="FanArtPathCollection"/> containing all matching fanart paths in the specified <see cref="ResourcePath"/>.
        /// </summary>
        /// <param name="videoDirectory"><see cref="IFileSystemResourceAccessor"/> that points to the episode directory.</param>
        /// <param name="filename">The file name of the media item to extract images for.</param>
        /// <returns><see cref="FanArtPathCollection"/> containing all matching paths.</returns>
        protected FanArtPathCollection GetFolderFanArt(IFileSystemResourceAccessor videoDirectory, string filename, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            FanArtPathCollection paths = new FanArtPathCollection();

            if (videoDirectory == null)
            {
                return(paths);
            }

            //Get all fanart in the current directory
            List <ResourcePath> potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(videoDirectory);

            ExtractAllFanArtImages(potentialFanArtFiles, paths, filename);

            //Add extra backdrops in ExtraFanArt directory
            if (videoDirectory.ResourceExists("ExtraFanArt/"))
            {
                using (IFileSystemResourceAccessor extraFanArtDirectory = videoDirectory.GetResource("ExtraFanArt/"))
                    paths.AddRange(FanArtTypes.FanArt, LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectory));
            }

            return(paths);
        }
        /// <summary>
        /// Gets a <see cref="FanArtPathCollection"/> containing all matching fanart paths in the specified <see cref="ResourcePath"/>.
        /// </summary>
        /// <param name="artistDirectory"><see cref="IFileSystemResourceAccessor"/> that points to the artist directory.</param>
        /// <returns><see cref="FanArtPathCollection"/> containing all matching paths.</returns>
        protected FanArtPathCollection GetArtistFolderFanArt(IFileSystemResourceAccessor artistDirectory)
        {
            FanArtPathCollection paths = new FanArtPathCollection();

            if (artistDirectory == null)
            {
                return(paths);
            }

            //Get all fanart in the current directory
            List <ResourcePath> potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(artistDirectory);

            ExtractAllFanArtImages(potentialFanArtFiles, paths);

            //Add extra backdrops in ExtraFanArt directory
            if (artistDirectory.ResourceExists("ExtraFanArt/"))
            {
                using (IFileSystemResourceAccessor extraFanArtDirectory = artistDirectory.GetResource("ExtraFanArt/"))
                    paths.AddRange(FanArtTypes.FanArt, LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectory));
            }

            return(paths);
        }
예제 #4
0
        /// <summary>
        /// Gets all movie folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="mediaItemLocator"><see cref="IResourceLocator>"/> that points to the file.</param>
        /// <param name="movieMediaItemId">Id of the media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractMovieFolderFanArt(IResourceLocator mediaItemLocator, Guid movieMediaItemId, string title, IList <Tuple <Guid, string> > actors)
        {
            //Get the file's directory
            var movieDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../");

            try
            {
                var mediaItemFileName      = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemLocator.NativeResourcePath.ToString()).ToLowerInvariant();
                FanArtPathCollection paths = null;
                IList <ResourcePath> potentialActorImages = null;
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, movieDirectory).CreateAccessor())
                    if (accessor is IFileSystemResourceAccessor fsra)
                    {
                        paths = GetMovieFolderFanArt(fsra, mediaItemFileName);
                        //See if there's an actor fanart directory and try and get any actor fanart
                        if (actors != null && actors.Count > 0 && fsra.ResourceExists(".actors"))
                        {
                            using (IFileSystemResourceAccessor actorsDirectory = fsra.GetResource(".actors"))
                                potentialActorImages = LocalFanartHelper.GetPotentialFanArtFiles(actorsDirectory);
                        }
                    }

                if (paths != null)
                {
                    await SaveFolderImagesToCache(mediaItemLocator.NativeSystemId, paths, movieMediaItemId, title).ConfigureAwait(false);
                }
                if (potentialActorImages != null)
                {
                    await SavePersonFolderImages(mediaItemLocator.NativeSystemId, potentialActorImages, actors).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("MovieFanArtHandler: Exception while reading folder images for '{0}'", ex, movieDirectory);
            }
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.MovieCollection)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter     = new RelationshipFilter(MovieAspect.ROLE_MOVIE, MovieCollectionAspect.ROLE_MOVIE_COLLECTION, mediaItemId);
            MediaItemQuery    movieQuery = new MediaItemQuery(NECESSARY_MIAS, filter);
            IList <MediaItem> items      = mediaLibrary.Search(movieQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            var files = new List <IResourceLocator>();

            foreach (MediaItem mediaItem in items)
            {
                // Virtual resources won't have any local fanart
                if (mediaItem.IsVirtual)
                {
                    continue;
                }
                var mediaIteamLocator = mediaItem.GetResourceLocator();
                var fanArtPaths       = new List <ResourcePath>();

                // File based access
                try
                {
                    var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                    var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                    var mediaItemCollectionDirectoryPath  = ResourcePathHelper.Combine(mediaItemPath, "../../");
                    var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-poster"
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-banner"
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "movieset-fanart"
                                                                                  select potentialFanArtFile);
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemCollectionDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" || potentialFanArtFileNameWithoutExtension == "movieset-poster" ||
                                                                                  potentialFanArtFileNameWithoutExtension.EndsWith("-poster")
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "banner" || potentialFanArtFileNameWithoutExtension == "movieset-banner" || potentialFanArtFileNameWithoutExtension.EndsWith("-banner")
                                                                                  select potentialFanArtFile);
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart" || potentialFanArtFileNameWithoutExtension == "movieset-fanart" ||
                                                                                  potentialFanArtFileNameWithoutExtension.EndsWith("-fanart")
                                                                                  select potentialFanArtFile);

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                }

                if (files.Count > 0)
                {
                    break;
                }
            }
            if (files.Count == 0)
            {
                foreach (MediaItem mediaItem in items)
                {
                    // Virtual resources won't have any local fanart
                    if (mediaItem.IsVirtual)
                    {
                        continue;
                    }
                    var mediaIteamLocator = mediaItem.GetResourceLocator();
                    var fanArtPaths       = new List <ResourcePath>();

                    // File based access
                    try
                    {
                        var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                        var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                        var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                        using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                        {
                            var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                            if (directoryFsra != null)
                            {
                                var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                                if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-poster")
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtType == FanArtTypes.Banner)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "banner" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-banner")
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtType == FanArtTypes.FanArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-fanart")
                                                                                      select potentialFanArtFile);

                                    if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                    {
                                        using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                            fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                    }
                                }

                                files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                    }

                    if (files.Count > 0)
                    {
                        break;
                    }
                }
            }
            result = files;
            return(files.Count > 0);
        }
예제 #6
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Artist && mediaType != FanArtMediaTypes.Album && mediaType != FanArtMediaTypes.Audio)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = null;
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);

            if (mediaType == FanArtMediaTypes.Artist)
            {
                necessaryMias.Add(AudioAspect.ASPECT_ID);
                necessaryMias.Add(RelationshipAspect.ASPECT_ID);
                filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, PersonAspect.ROLE_ALBUMARTIST, mediaItemId);
            }
            else if (fanArtType == FanArtTypes.FanArt)
            {
                if (mediaType == FanArtMediaTypes.Album)
                {
                    //Might be a request for album FanArt which doesn't exist. Artist FanArt is used instead.
                    filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, AudioAlbumAspect.ROLE_ALBUM, mediaItemId);
                }
                else if (mediaType == FanArtMediaTypes.Audio)
                {
                    //Might be a request for track FanArt which doesn't exist. Artist FanArt is used instead.
                    necessaryMias.Add(AudioAspect.ASPECT_ID);
                    filter = new MediaItemIdFilter(mediaItemId);
                }
            }
            else
            {
                return(false);
            }

            MediaItemQuery mediaQuery = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            string artistName    = null;
            var    mediaItemPath = mediaIteamLocator.NativeResourcePath;
            var    albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
            var    artistMediaItemPath         = ResourcePathHelper.Combine(mediaItemPath, "../../");
            string album = null;

            if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, AudioAspect.ATTR_ALBUM, out album) && LocalFanartHelper.IsDiscFolder(album, albumMediaItemDirectoryPath.FileName))
            {
                //Probably a CD folder so try next parent
                albumMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");
                artistMediaItemPath         = ResourcePathHelper.Combine(mediaItemPath, "../../../");
            }
            if (mediaType == FanArtMediaTypes.Artist)
            {
                SingleMediaItemAspect audioAspect;
                List <string>         artists = new List <string>();
                if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, AudioAspect.Metadata, out audioAspect))
                {
                    IEnumerable <object> artistObjects = audioAspect.GetCollectionAttribute <object>(AudioAspect.ATTR_ALBUMARTISTS);
                    if (artistObjects != null)
                    {
                        artists.AddRange(artistObjects.Cast <string>());
                    }
                }

                IList <MultipleMediaItemAspect> relationAspects;
                if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                {
                    foreach (MultipleMediaItemAspect relation in relationAspects)
                    {
                        if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ALBUMARTIST && (Guid?)relation[RelationshipAspect.ATTR_LINKED_ID] == mediaItemId)
                        {
                            int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                            if (index.HasValue && artists.Count > index.Value && index.Value >= 0)
                            {
                                artistName = artists[index.Value];
                            }
                            break;
                        }
                    }
                }
            }

            // File based access
            try
            {
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, artistMediaItemPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Undefined || fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                        }


                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }

                if (!string.IsNullOrEmpty(artistName)) //Only one artist was found
                {
                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, albumMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get Artists thumbs
                            IFileSystemResourceAccessor alternateArtistMediaItemDirectory = directoryFsra.GetResource(".artists");
                            if (alternateArtistMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(alternateArtistMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString())
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(artistName.Replace(" ", "_"), StringComparison.InvariantCultureIgnoreCase)
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }

                    //Find central artist information folder
                    ResourcePath centralArtistFolderPath = LocalFanartHelper.GetCentralPersonFolder(artistMediaItemPath, CentralPersonFolderType.AudioArtists);
                    if (centralArtistFolderPath != null)
                    {
                        // First get the ResourcePath of the central directory
                        var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(artistName)}/");

                        // Then try to create an IFileSystemResourceAccessor for this directory
                        artistFolderPath.TryCreateLocalResourceAccessor(out var artistNfoDirectoryRa);
                        var directoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Logo)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.ClearArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalArtistFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
예제 #7
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Actor || (fanArtType != FanArtTypes.Undefined && fanArtType != FanArtTypes.Thumbnail))
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = new RelationshipFilter(MovieAspect.ROLE_MOVIE, PersonAspect.ROLE_ACTOR, mediaItemId);
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);
            MediaItemQuery    mediaQuery    = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            string actorName = null;
            SingleMediaItemAspect videoAspect;
            List <string>         actors = new List <string>();

            if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, VideoAspect.Metadata, out videoAspect))
            {
                IEnumerable <object> actorObjects = videoAspect.GetCollectionAttribute <object>(VideoAspect.ATTR_ACTORS);
                if (actorObjects != null)
                {
                    actors.AddRange(actorObjects.Cast <string>());
                }
            }

            IList <MultipleMediaItemAspect> relationAspects;

            if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
            {
                foreach (MultipleMediaItemAspect relation in relationAspects)
                {
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ACTOR && (Guid?)relation[RelationshipAspect.ATTR_LINKED_ID] == mediaItemId)
                    {
                        int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                        if (index.HasValue && actors.Count > index.Value && index.Value >= 0)
                        {
                            actorName = actors[index.Value];
                        }
                    }
                }
            }

            // File based access
            try
            {
                var mediaItemPath          = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");

                if (!string.IsNullOrEmpty(actorName))
                {
                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get Artists thumbs
                            IFileSystemResourceAccessor actorMediaItemDirectory = directoryFsra.GetResource(".actors");
                            if (actorMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(actorMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString())
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(actorName.Replace(" ", "_"), StringComparison.InvariantCultureIgnoreCase)
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalMovieActorFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Gets all season folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="mediaItemLocator"><see cref="IResourceLocator>"/> that points to the file.</param>
        /// <param name="seasonMediaItemId">Id of the season media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <param name="seasonNumber">Season number.</param>
        /// <param name="actors">Collection of actor ids and names.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractSeasonFolderFanArt(IResourceLocator mediaItemLocator, Guid seasonMediaItemId, string title, int?seasonNumber, IList <Tuple <Guid, string> > actors)
        {
            var seasonDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../");

            try
            {
                bool isSeriesFolder  = false;
                var  seriesDirectory = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../../");
                using (IResourceAccessor seasonAccessor = new ResourceLocator(mediaItemLocator.NativeSystemId, seasonDirectory).CreateAccessor())
                    using (IResourceAccessor seriesAccessor = new ResourceLocator(mediaItemLocator.NativeSystemId, seriesDirectory).CreateAccessor())
                    {
                        if (!LocalFanartHelper.IsSeriesFolder(seriesAccessor as IFileSystemResourceAccessor, seasonNumber) && LocalFanartHelper.IsSeriesFolder(seasonAccessor as IFileSystemResourceAccessor, seasonNumber))
                        {
                            isSeriesFolder = true;
                        }
                    }

                FanArtPathCollection paths = null;
                IList <ResourcePath> potentialActorImages = null;
                using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, seasonDirectory).CreateAccessor())
                {
                    if (accessor is IFileSystemResourceAccessor fsra)
                    {
                        paths = GetSeasonFolderFanArt(fsra, seasonNumber, isSeriesFolder);
                        //See if there's an actor fanart directory and try and get any actor fanart
                        if (actors != null && actors.Count > 0 && fsra.ResourceExists(".actors"))
                        {
                            using (IFileSystemResourceAccessor actorsDirectory = fsra.GetResource(".actors"))
                                potentialActorImages = LocalFanartHelper.GetPotentialFanArtFiles(actorsDirectory);
                        }
                    }
                }

                if (paths != null)
                {
                    await SaveFolderImagesToCache(mediaItemLocator.NativeSystemId, paths, seasonMediaItemId, title).ConfigureAwait(false);
                }
                if (potentialActorImages != null)
                {
                    await SavePersonFolderImages(mediaItemLocator.NativeSystemId, potentialActorImages, actors).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("SeriesFanArtHandler: Exception while reading folder images for '{0}'", ex, seasonDirectory);
            }
        }
예제 #9
0
        /// <summary>
        /// Gets all artist folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="nativeSystemId">The native system id of the media item.</param>
        /// <param name="albumDirectory"><see cref="ResourcePath>"/> that points to the album directory.</param>
        /// <param name="albumMediaItemId">Id of the media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <param name="artists">List of artists.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractArtistFolderFanArt(string nativeSystemId, ResourcePath albumDirectory, IList <Tuple <Guid, string> > artists)
        {
            if (artists == null || artists.Count == 0)
            {
                return;
            }

            //Get the file's directory
            var artistDirectory = ResourcePathHelper.Combine(albumDirectory, "../");

            try
            {
                var artist = artists.FirstOrDefault(a => string.Compare(a.Item2, artistDirectory.FileName, StringComparison.OrdinalIgnoreCase) == 0);
                if (artist == null)
                {
                    artist = artists[0];
                }

                //See if we've already processed this artist
                if (!AddToCache(artist.Item1))
                {
                    return;
                }

                //Get all fanart paths in the current directory
                FanArtPathCollection paths = new FanArtPathCollection();
                using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, artistDirectory).CreateAccessor())
                {
                    foreach (var path in GetArtistFolderFanArt(accessor as IFileSystemResourceAccessor))
                    {
                        paths.AddRange(path.Key, path.Value);
                    }
                }

                //Find central artist information folder
                ResourcePath centralArtistFolderPath = LocalFanartHelper.GetCentralPersonFolder(artistDirectory, CentralPersonFolderType.AudioArtists);
                if (centralArtistFolderPath != null)
                {
                    // First get the ResourcePath of the central directory
                    var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(artist.Item2)}/");
                    using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, artistFolderPath).CreateAccessor())
                    {
                        foreach (var path in GetArtistFolderFanArt(accessor as IFileSystemResourceAccessor))
                        {
                            paths.AddRange(path.Key, path.Value);
                        }
                    }
                }

                //Save the fanart to the IFanArtCache service
                await SaveFolderImagesToCache(nativeSystemId, paths, artist.Item1, artist.Item2).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Warn("AudioFanArtHandler: Exception while reading folder images for '{0}'", ex, artistDirectory);
            }
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Series && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.Series)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeriesAspect.ROLE_SERIES, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Poster)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Tries to find a artist nfo-file for the given <param name="mediaFsra"></param>
        /// </summary>
        /// <param name="miNumber">Unique number for logging purposes</param>
        /// <param name="mediaFsra">FileSystemResourceAccessor for which we search a artist nfo-file</param>
        /// <param name="artistNfoFsra">FileSystemResourceAccessor of the artist nfo-file or <c>null</c> if no artist nfo-file was found</param>
        /// <returns><c>true</c> if a artist nfo-file was found, otherwise <c>false</c></returns>
        protected bool TryGetArtistNfoSResourceAccessor(long miNumber, IFileSystemResourceAccessor mediaFsra, string artistName, out IFileSystemResourceAccessor artistNfoFsra)
        {
            artistNfoFsra = null;

            #region First Directory
            // Determine the first directory, in which we look for the artist nfo-file
            // We cannot use mediaFsra.GetResource, because for ChainedResourceProviders the parent directory
            // may be located in the ParentResourceProvider. For details see the comments for the ResourcePathHelper class.

            // First get the ResourcePath of the parent directory
            // The parent directory is
            // - for an IFilesystemResourceAcessor pointing to a file:
            //   the directory in which the file is located;
            // - for an IFilesystemResourceAcessor pointing to a root directory of a ChainedResourceProvider (e.g. in case of a DVD iso-file):
            //   the directory in which the file that was unfolded by the ChainedResourceProvider is located;
            // - for an IFilesystemResourceAcessor pointing to any other directory (e.g. DVD directories):
            //   the parent directory of such directory.
            var firstArtistNfoDirectoryResourcePath = ResourcePathHelper.Combine(mediaFsra.CanonicalLocalResourcePath, "../");
            _debugLogger.Info("[#{0}]: first artist nfo-directory: '{1}'", miNumber, firstArtistNfoDirectoryResourcePath);

            // Then try to create an IFileSystemResourceAccessor for this directory
            IResourceAccessor artistNfoDirectoryRa;
            firstArtistNfoDirectoryResourcePath.TryCreateLocalResourceAccessor(out artistNfoDirectoryRa);
            var artistNfoDirectoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
            if (artistNfoDirectoryFsra == null)
            {
                _debugLogger.Info("[#{0}]: first artist nfo-directory not accessible'", miNumber, firstArtistNfoDirectoryResourcePath);
                if (artistNfoDirectoryRa != null)
                {
                    artistNfoDirectoryRa.Dispose();
                }
            }
            else
            {
                // Try to find a artist nfo-file in the that directory
                using (artistNfoDirectoryFsra)
                {
                    var artistNfoFileNames = GetArtistNfoFileNames();
                    foreach (var artistNfoFileName in artistNfoFileNames)
                    {
                        if (artistNfoDirectoryFsra.ResourceExists(artistNfoFileName))
                        {
                            _debugLogger.Info("[#{0}]: artist nfo-file found: '{1}'", miNumber, artistNfoFileName);
                            artistNfoFsra = artistNfoDirectoryFsra.GetResource(artistNfoFileName);
                            return(true);
                        }
                        else
                        {
                            _debugLogger.Info("[#{0}]: artist nfo-file '{1}' not found; checking next possible file...", miNumber, artistNfoFileName);
                        }
                    }
                }
            }
            #endregion

            #region Second directory
            // Determine the second directory, in which we look for the series nfo-file

            // First get the ResourcePath of the parent directory's parent directory
            var secondArtistNfoDirectoryResourcePath = ResourcePathHelper.Combine(firstArtistNfoDirectoryResourcePath, "../");
            _debugLogger.Info("[#{0}]: second artist nfo-directory: '{1}'", miNumber, secondArtistNfoDirectoryResourcePath);

            // Then try to create an IFileSystemResourceAccessor for this directory
            secondArtistNfoDirectoryResourcePath.TryCreateLocalResourceAccessor(out artistNfoDirectoryRa);
            artistNfoDirectoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
            if (artistNfoDirectoryFsra == null)
            {
                _debugLogger.Info("[#{0}]: second artist nfo-directory not accessible'", miNumber, secondArtistNfoDirectoryResourcePath);
                if (artistNfoDirectoryRa != null)
                {
                    artistNfoDirectoryRa.Dispose();
                }
                return(false);
            }

            // Finally try to find a artist nfo-file in the that second directory
            using (artistNfoDirectoryFsra)
            {
                var artistNfoFileNames = GetArtistNfoFileNames();
                foreach (var artistNfoFileName in artistNfoFileNames)
                {
                    if (artistNfoDirectoryFsra.ResourceExists(artistNfoFileName))
                    {
                        _debugLogger.Info("[#{0}]: artist nfo-file found: '{1}'", miNumber, artistNfoFileName);
                        artistNfoFsra = artistNfoDirectoryFsra.GetResource(artistNfoFileName);
                        return(true);
                    }
                    else
                    {
                        _debugLogger.Info("[#{0}]: artist nfo-file '{1}' not found; checking next possible file...", miNumber, artistNfoFileName);
                    }
                }
            }
            #endregion

            if (!string.IsNullOrEmpty(artistName))
            {
                //Find cached central artist information folder
                ResourcePath centralArtistFolderPath = LocalFanartHelper.GetCentralPersonFolder(mediaFsra.CanonicalLocalResourcePath, CentralPersonFolderType.AudioArtists);
                if (centralArtistFolderPath == null)
                {
                    _debugLogger.Info("[#{0}]: No artist nfo-file found", miNumber);
                    return(false);
                }

                #region Look for central artist directory

                // First get the ResourcePath of the central directory
                var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(artistName)}/");
                _debugLogger.Info("[#{0}]: Central artist nfo-directory: '{1}'", miNumber, artistFolderPath);

                // Then try to create an IFileSystemResourceAccessor for this directory
                artistFolderPath.TryCreateLocalResourceAccessor(out artistNfoDirectoryRa);
                artistNfoDirectoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                if (artistNfoDirectoryFsra == null)
                {
                    _debugLogger.Info("[#{0}]: Central artist nfo-directory not accessible'", miNumber, artistFolderPath);
                }
                else
                {
                    // Finally try to find a artist nfo-file in the central directory
                    using (artistNfoDirectoryFsra)
                    {
                        var artistNfoFileNames = GetArtistNfoFileNames();
                        foreach (var artistNfoFileName in artistNfoFileNames)
                        {
                            if (artistNfoDirectoryFsra.ResourceExists(artistNfoFileName))
                            {
                                _debugLogger.Info("[#{0}]: Central artist nfo-file found: '{1}'", miNumber, artistNfoFileName);
                                artistNfoFsra = artistNfoDirectoryFsra.GetResource(artistNfoFileName);
                                return(true);
                            }
                        }
                    }
                }
                #endregion
            }

            _debugLogger.Info("[#{0}]: No artist nfo-file found", miNumber);
            return(false);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Undefined)
            {
                return(false);
            }

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = new MediaItemIdFilter(mediaItemId);
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);

            MediaItemQuery mediaQuery = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemDirectoryPath = mediaIteamLocator.NativeResourcePath;
                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalContainerFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
예제 #13
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            if (mediaType == FanArtMediaTypes.Image && fanArtType != FanArtTypes.FanArt)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter = new MediaItemIdFilter(mediaItemId);
            IList <MediaItem> items  = mediaLibrary.Search(new MediaItemQuery(NECESSARY_MIAS, filter), false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();

            if (mediaIteamLocator == null)
            {
                return(false);
            }
            var fanArtPaths = new List <ResourcePath>();
            var files       = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where /* Allow same file name only for non-images, otherwise each image would be its own thumbnail */
                                                                              potentialFanArtFileNameWithoutExtension == mediaItemFileNameWithoutExtension && !LocalFanartHelper.EXTENSIONS.Contains(mediaItemExtension) ||
                                                                              potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-thumb") ||
                                                                              potentialFanArtFileNameWithoutExtension == "thumb"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Poster)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where /* Allow same file name only for non-images, otherwise each image would be its own thumbnail */
                                                                              potentialFanArtFileNameWithoutExtension == mediaItemFileNameWithoutExtension && !LocalFanartHelper.EXTENSIONS.Contains(mediaItemExtension) ||
                                                                              potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-poster") ||
                                                                              potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" || potentialFanArtFileNameWithoutExtension == "cover"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "logo" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-logo")
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "clearart" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-clearart")
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.DiscArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "discart" || potentialFanArtFileNameWithoutExtension == "disc" ||
                                                                              potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-discart")
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "banner" || potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-banner")
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            if (mediaType == FanArtMediaTypes.Image)
                            {
                                fanArtPaths.Add(mediaIteamLocator.NativeResourcePath);
                            }
                            else
                            {
                                fanArtPaths.AddRange(
                                    from potentialFanArtFile in potentialFanArtFiles
                                    let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                  where potentialFanArtFileNameWithoutExtension == "backdrop" ||
                                                                                  potentialFanArtFileNameWithoutExtension == "fanart" ||
                                                                                  potentialFanArtFileNameWithoutExtension.StartsWith(mediaItemFileNameWithoutExtension + "-fanart")
                                                                                  select potentialFanArtFile);

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Actor || (fanArtType != FanArtTypes.Undefined && fanArtType != FanArtTypes.Thumbnail))
            {
                return(false);
            }

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, PersonAspect.ROLE_ACTOR, mediaItemId);
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);
            MediaItemQuery    mediaQuery    = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            string actorName = null;
            SingleMediaItemAspect videoAspect;
            List <string>         actors = new List <string>();

            if (MediaItemAspect.TryGetAspect(mediaItem.Aspects, VideoAspect.Metadata, out videoAspect))
            {
                IEnumerable <object> actorObjects = videoAspect.GetCollectionAttribute <object>(VideoAspect.ATTR_ACTORS);
                if (actorObjects != null)
                {
                    actors.AddRange(actorObjects.Cast <string>());
                }
            }

            IList <MultipleMediaItemAspect> relationAspects;

            if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
            {
                foreach (MultipleMediaItemAspect relation in relationAspects)
                {
                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ACTOR && (Guid?)relation[RelationshipAspect.ATTR_LINKED_ID] == mediaItemId)
                    {
                        int?index = (int?)relation[RelationshipAspect.ATTR_RELATIONSHIP_INDEX];
                        if (index.HasValue && actors.Count > index.Value && index.Value >= 0)
                        {
                            actorName = actors[index.Value];
                        }
                        break;
                    }
                }
            }

            // File based access
            try
            {
                var mediaItemPath = mediaIteamLocator.NativeResourcePath;
                var seasonMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
                var seriesMediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");

                if (!string.IsNullOrEmpty(actorName))
                {
                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, seriesMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get series actor thumbs
                            IFileSystemResourceAccessor actorMediaItemDirectory = directoryFsra.GetResource(".actors");
                            if (actorMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(actorMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString())
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(actorName.Replace(" ", "_"), StringComparison.InvariantCultureIgnoreCase)
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, seasonMediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            //Get season actor thumbs
                            IFileSystemResourceAccessor actorMediaItemDirectory = directoryFsra.GetResource(".actors");
                            if (actorMediaItemDirectory != null)
                            {
                                var potentialArtistFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(actorMediaItemDirectory);

                                foreach (ResourcePath thumbPath in
                                         from potentialFanArtFile in potentialArtistFanArtFiles
                                         let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                       where potentialFanArtFileNameWithoutExtension.StartsWith(actorName.Replace(" ", "_"))
                                                                                       select potentialFanArtFile)
                                {
                                    files.Add(new ResourceLocator(mediaIteamLocator.NativeSystemId, thumbPath));
                                }
                            }
                        }
                    }

                    //Find central actor information folder
                    ResourcePath centralActorFolderPath = LocalFanartHelper.GetCentralPersonFolder(seriesMediaItemDirectoryPath, CentralPersonFolderType.SeriesActors);
                    if (centralActorFolderPath != null)
                    {
                        // First get the ResourcePath of the central directory
                        var actorFolderPath = ResourcePathHelper.Combine(centralActorFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(actorName)}/");

                        // Then try to create an IFileSystemResourceAccessor for this directory
                        actorFolderPath.TryCreateLocalResourceAccessor(out var artistNfoDirectoryRa);
                        var directoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.Logo)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.ClearArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeriesActorFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.SeriesSeason && mediaType != FanArtMediaTypes.Episode)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter filter = null;

            if (mediaType == FanArtMediaTypes.SeriesSeason)
            {
                filter = new RelationshipFilter(EpisodeAspect.ROLE_EPISODE, SeasonAspect.ROLE_SEASON, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Episode)
            {
                filter = new MediaItemIdFilter(mediaItemId);
            }
            MediaItemQuery episodeQuery = new MediaItemQuery(NECESSARY_MIAS, filter);

            episodeQuery.Limit = 1;
            IList <MediaItem> items = mediaLibrary.Search(episodeQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                var mediaItemParentDirectoryPath      = ResourcePathHelper.Combine(mediaItemPath, "../../");
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension                = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "thumb"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Poster)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Logo)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "logo"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.ClearArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "clearart"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.Banner)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "banner"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart"
                                                                              select potentialFanArtFile);

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemParentDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        int?season = null;
                        MediaItemAspect.TryGetAttribute(mediaItem.Aspects, EpisodeAspect.ATTR_SEASON, out season);

                        if (season.HasValue)
                        {
                            List <string> prefixes = new List <string>();
                            prefixes.Add(string.Format("season{0:00}-", season.Value));
                            if (season.Value == 0)
                            {
                                prefixes.Add("season-specials-");
                            }
                            else
                            {
                                prefixes.Add("season-all-");
                            }
                            prefixes.Add(""); //For finding series fallback

                            foreach (string prefix in prefixes)
                            {
                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Thumbnail)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "thumb"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Poster)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "poster"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Logo)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "logo"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.ClearArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "clearart"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.Banner)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "banner"
                                                                                      select potentialFanArtFile);
                                }

                                if (fanArtPaths.Count == 0 && fanArtType == FanArtTypes.FanArt)
                                {
                                    fanArtPaths.AddRange(
                                        from potentialFanArtFile in potentialFanArtFiles
                                        let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                                      where potentialFanArtFileNameWithoutExtension == prefix + "fanart"
                                                                                      select potentialFanArtFile);
                                }

                                files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalSeasonFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
예제 #16
0
        /// <summary>
        /// Gets all album folder images and caches them in the <see cref="IFanArtCache"/> service.
        /// </summary>
        /// <param name="nativeSystemId">The native system id of the media item.</param>
        /// <param name="albumDirectory"><see cref="ResourcePath>"/> that points to the album directory.</param>
        /// <param name="albumMediaItemId">Id of the media item.</param>
        /// <param name="title">Title of the media item.</param>
        /// <param name="artists">List of artists.</param>
        /// <returns><see cref="Task"/> that completes when the images have been cached.</returns>
        protected async Task ExtractAlbumFolderFanArt(string nativeSystemId, ResourcePath albumDirectory, Guid albumMediaItemId, string title, IList <Tuple <Guid, string> > artists)
        {
            try
            {
                FanArtPathCollection paths = null;
                IList <ResourcePath> potentialArtistImages = null;
                using (IResourceAccessor accessor = new ResourceLocator(nativeSystemId, albumDirectory).CreateAccessor())
                    if (accessor is IFileSystemResourceAccessor fsra)
                    {
                        paths = GetAlbumFolderFanArt(fsra);
                        //See if there's an actor fanart directory and try and get any actor fanart
                        if (artists != null && artists.Count > 0 && fsra.ResourceExists(".artists"))
                        {
                            using (IFileSystemResourceAccessor actorsDirectory = fsra.GetResource(".artists"))
                                potentialArtistImages = LocalFanartHelper.GetPotentialFanArtFiles(actorsDirectory);
                        }
                    }

                if (paths != null)
                {
                    await SaveFolderImagesToCache(nativeSystemId, paths, albumMediaItemId, title).ConfigureAwait(false);
                }
                if (potentialArtistImages != null)
                {
                    await SavePersonFolderImages(nativeSystemId, potentialArtistImages, artists).ConfigureAwait(false);
                }

                if (artists != null && artists.Count > 0)
                {
                    //Find central artist information folder
                    ResourcePath centralArtistFolderPath = null;
                    for (int level = 1; level <= 3; level++) //Look for central artist folder
                    {
                        // First get the ResourcePath of the central directory for the current level
                        var centralArtistNfoDirectoryResourcePath = albumDirectory;
                        for (int addLevel = 0; addLevel < level; addLevel++)
                        {
                            centralArtistNfoDirectoryResourcePath = ResourcePathHelper.Combine(centralArtistNfoDirectoryResourcePath, "../");
                        }
                        if (centralArtistNfoDirectoryResourcePath.BasePathSegment.Path.Length < 3)
                        {
                            break; //Path no longer valid
                        }
                        centralArtistNfoDirectoryResourcePath = ResourcePathHelper.Combine(centralArtistNfoDirectoryResourcePath, $"{ARTIST_INFO_FOLDER}/");

                        // Then try to create an IFileSystemResourceAccessor for this directory
                        centralArtistNfoDirectoryResourcePath.TryCreateLocalResourceAccessor(out var artistNfoDirectoryRa);
                        var artistNfoDirectoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                        if (artistNfoDirectoryFsra != null)
                        {
                            using (artistNfoDirectoryFsra)
                            {
                                centralArtistFolderPath = centralArtistNfoDirectoryResourcePath;
                                break;
                            }
                        }
                    }

                    if (centralArtistFolderPath != null)
                    {
                        foreach (var artist in artists)
                        {
                            var artistName = artist.Item2;
                            FanArtPathCollection artistsPaths = new FanArtPathCollection();

                            // First get the ResourcePath of the central directory
                            var artistFolderPath = ResourcePathHelper.Combine(centralArtistFolderPath, $"{FileUtils.GetSafeFilename(artistName, '¤').Replace("¤", "")}/");

                            // Then try to create an IFileSystemResourceAccessor for this directory
                            artistFolderPath.TryCreateLocalResourceAccessor(out var artistNfoDirectoryRa);
                            var directoryFsra = artistNfoDirectoryRa as IFileSystemResourceAccessor;
                            if (directoryFsra != null)
                            {
                                var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                                artistsPaths.AddRange(FanArtTypes.Thumbnail, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.ARTIST_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.Poster, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.Thumbnail, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.Banner, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.Logo, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.LOGO_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.ClearArt, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.CLEARART_FILENAMES));
                                artistsPaths.AddRange(FanArtTypes.FanArt, LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                                if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                {
                                    using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                        artistsPaths.AddRange(FanArtTypes.FanArt, LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                }
                            }

                            await SaveFolderImagesToCache(nativeSystemId, paths, artist.Item1, title).ConfigureAwait(false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Warn("AudioFanArtHandler: Exception while reading folder images for '{0}'", ex, albumDirectory);
            }
        }
예제 #17
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.MovieCollection)
            {
                return(false);
            }

            if (!Guid.TryParse(name, out mediaItemId))
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter     = new RelationshipFilter(MovieAspect.ROLE_MOVIE, MovieCollectionAspect.ROLE_MOVIE_COLLECTION, mediaItemId);
            MediaItemQuery    movieQuery = new MediaItemQuery(NECESSARY_MIAS, filter);
            IList <MediaItem> items      = mediaLibrary.Search(movieQuery, false, null, false);

            if (items == null || items.Count == 0)
            {
                return(false);
            }

            var files = new List <IResourceLocator>();

            foreach (MediaItem mediaItem in items)
            {
                // Virtual resources won't have any local fanart
                if (mediaItem.IsVirtual)
                {
                    continue;
                }
                var mediaIteamLocator = mediaItem.GetResourceLocator();
                var fanArtPaths       = new List <ResourcePath>();

                // File based access
                try
                {
                    var mediaItemPath                            = mediaIteamLocator.NativeResourcePath;
                    var mediaItemDirectoryPath                   = ResourcePathHelper.Combine(mediaItemPath, "../");
                    var mediaItemCollectionDirectoryPath         = ResourcePathHelper.Combine(mediaItemPath, "../../");
                    var mediaItemCentralCollectionDirectoryPath  = ResourcePathHelper.Combine(mediaItemPath, "../../" + MOVIESET_FANART_FOLDER);
                    var mediaItemCentralCollectionDirectoryPath2 = ResourcePathHelper.Combine(mediaItemPath, "../../../" + MOVIESET_FANART_FOLDER);
                    var mediaItemFileNameWithoutExtension        = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                    {
                        var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                        if (directoryFsra != null)
                        {
                            var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                            if (fanArtType == FanArtTypes.Undefined || fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES.Select(f => "movieset-" + f)));
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES.Select(f => "movieset-" + f)));
                            }

                            if (fanArtType == FanArtTypes.Banner)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByName(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES.Select(f => "movieset-" + f)));
                            }

                            if (fanArtType == FanArtTypes.FanArt)
                            {
                                fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES.Select(f => "movieset-" + f)));
                            }

                            files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                        }
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemCollectionDirectoryPath).CreateAccessor())
                    {
                        fanArtPaths.AddRange(GetCollectionFanart(fanArtType, directoryRa as IFileSystemResourceAccessor));
                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemCentralCollectionDirectoryPath).CreateAccessor())
                    {
                        fanArtPaths.AddRange(GetCollectionFanart(fanArtType, directoryRa as IFileSystemResourceAccessor));
                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }

                    using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemCentralCollectionDirectoryPath2).CreateAccessor())
                    {
                        fanArtPaths.AddRange(GetCollectionFanart(fanArtType, directoryRa as IFileSystemResourceAccessor));
                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
                catch (Exception ex)
                {
#if DEBUG
                    ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                }

                if (files.Count > 0)
                {
                    break;
                }
            }
            if (files.Count == 0)
            {
                foreach (MediaItem mediaItem in items)
                {
                    // Virtual resources won't have any local fanart
                    if (mediaItem.IsVirtual)
                    {
                        continue;
                    }
                    var mediaIteamLocator = mediaItem.GetResourceLocator();
                    var fanArtPaths       = new List <ResourcePath>();

                    // File based access
                    try
                    {
                        var mediaItemPath                     = mediaIteamLocator.NativeResourcePath;
                        var mediaItemDirectoryPath            = ResourcePathHelper.Combine(mediaItemPath, "../");
                        var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();

                        using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                        {
                            var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                            if (directoryFsra != null)
                            {
                                var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                                if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Thumbnail)
                                {
                                    fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByNameOrPrefix(potentialFanArtFiles, LocalFanartHelper.POSTER_FILENAMES,
                                                                                                                    LocalFanartHelper.POSTER_FILENAMES.Select(f => mediaItemFileNameWithoutExtension + "-" + f)));
                                    fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByNameOrPrefix(potentialFanArtFiles, LocalFanartHelper.THUMB_FILENAMES,
                                                                                                                    LocalFanartHelper.THUMB_FILENAMES.Select(f => mediaItemFileNameWithoutExtension + "-" + f)));
                                }

                                if (fanArtType == FanArtTypes.Banner)
                                {
                                    fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByNameOrPrefix(potentialFanArtFiles, LocalFanartHelper.BANNER_FILENAMES,
                                                                                                                    LocalFanartHelper.BANNER_FILENAMES.Select(f => mediaItemFileNameWithoutExtension + "-" + f)));
                                }

                                if (fanArtType == FanArtTypes.FanArt)
                                {
                                    fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByNameOrPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES,
                                                                                                                    LocalFanartHelper.BACKDROP_FILENAMES.Select(f => mediaItemFileNameWithoutExtension + "-" + f)));
                                    fanArtPaths.AddRange(LocalFanartHelper.FilterPotentialFanArtFilesByPrefix(potentialFanArtFiles, LocalFanartHelper.BACKDROP_FILENAMES));

                                    if (directoryFsra.ResourceExists("ExtraFanArt/"))
                                    {
                                        using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                            fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                                    }
                                }

                                files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        ServiceRegistration.Get <ILogger>().Warn("LocalMovieCollectionFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
                    }

                    if (files.Count > 0)
                    {
                        break;
                    }
                }
            }
            result = files;
            return(files.Count > 0);
        }
예제 #18
0
        /// <summary>
        /// Gets a list of <see cref="FanArtImage"/>s for a requested <paramref name="mediaType"/>, <paramref name="fanArtType"/> and <paramref name="name"/>.
        /// The name can be: Series name, Actor name, Artist name depending on the <paramref name="mediaType"/>.
        /// </summary>
        /// <param name="mediaType">Requested FanArtMediaType</param>
        /// <param name="fanArtType">Requested FanArtType</param>
        /// <param name="name">Requested name of Series, Actor, Artist...</param>
        /// <param name="maxWidth">Maximum width for image. <c>0</c> returns image in original size.</param>
        /// <param name="maxHeight">Maximum height for image. <c>0</c> returns image in original size.</param>
        /// <param name="singleRandom">If <c>true</c> only one random image URI will be returned</param>
        /// <param name="result">Result if return code is <c>true</c>.</param>
        /// <returns><c>true</c> if at least one match was found.</returns>
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            if (mediaType != FanArtMediaTypes.Album && mediaType != FanArtMediaTypes.Audio)
            {
                return(false);
            }

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtMediaTypes.Image)
            {
                return(false);
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>(false);

            if (mediaLibrary == null)
            {
                return(false);
            }

            IFilter           filter        = null;
            IList <MediaItem> items         = null;
            List <Guid>       necessaryMias = new List <Guid>(NECESSARY_MIAS);

            if (mediaType == FanArtMediaTypes.Album)
            {
                filter = new RelationshipFilter(AudioAspect.ROLE_TRACK, AudioAlbumAspect.ROLE_ALBUM, mediaItemId);
            }
            else if (mediaType == FanArtMediaTypes.Audio)
            {
                //Might be a request for track cover which doesn't exist. Album cover is used instead.
                filter = new MediaItemIdFilter(mediaItemId);
            }
            else
            {
                return(false);
            }

            MediaItemQuery mediaQuery = new MediaItemQuery(necessaryMias, filter);

            mediaQuery.Limit = 1;
            items            = mediaLibrary.Search(mediaQuery, false, null, false);
            if (items == null || items.Count == 0)
            {
                return(false);
            }

            MediaItem mediaItem = items.First();

            // Virtual resources won't have any local fanart
            if (mediaItem.IsVirtual)
            {
                return(false);
            }
            var mediaIteamLocator = mediaItem.GetResourceLocator();
            var fanArtPaths       = new List <ResourcePath>();
            var files             = new List <IResourceLocator>();

            // File based access
            try
            {
                var    mediaItemPath          = mediaIteamLocator.NativeResourcePath;
                var    mediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../");
                string album = null;
                if (MediaItemAspect.TryGetAttribute(mediaItem.Aspects, AudioAspect.ATTR_ALBUM, out album) && LocalFanartHelper.IsDiscFolder(album, mediaItemDirectoryPath.FileName))
                {
                    //Probably a CD folder so try next parent
                    mediaItemDirectoryPath = ResourcePathHelper.Combine(mediaItemPath, "../../");
                }
                var mediaItemFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(mediaItemPath.ToString()).ToLowerInvariant();
                var mediaItemExtension = ResourcePathHelper.GetExtension(mediaItemPath.ToString());

                using (var directoryRa = new ResourceLocator(mediaIteamLocator.NativeSystemId, mediaItemDirectoryPath).CreateAccessor())
                {
                    var directoryFsra = directoryRa as IFileSystemResourceAccessor;
                    if (directoryFsra != null)
                    {
                        var potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryFsra);

                        if (fanArtType == FanArtTypes.Poster || fanArtType == FanArtTypes.Cover || fanArtType == FanArtTypes.Thumbnail)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "poster" || potentialFanArtFileNameWithoutExtension == "folder" ||
                                                                              potentialFanArtFileNameWithoutExtension == "cover"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.DiscArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "discart" || potentialFanArtFileNameWithoutExtension == "disc"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.DiscArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "cdart"
                                                                              select potentialFanArtFile);
                        }

                        if (fanArtType == FanArtTypes.FanArt)
                        {
                            fanArtPaths.AddRange(
                                from potentialFanArtFile in potentialFanArtFiles
                                let potentialFanArtFileNameWithoutExtension = ResourcePathHelper.GetFileNameWithoutExtension(potentialFanArtFile.ToString()).ToLowerInvariant()
                                                                              where potentialFanArtFileNameWithoutExtension == "backdrop" || potentialFanArtFileNameWithoutExtension == "fanart"
                                                                              select potentialFanArtFile);

                            if (directoryFsra.ResourceExists("ExtraFanArt/"))
                            {
                                using (var extraFanArtDirectoryFsra = directoryFsra.GetResource("ExtraFanArt/"))
                                    fanArtPaths.AddRange(LocalFanartHelper.GetPotentialFanArtFiles(extraFanArtDirectoryFsra));
                            }
                        }

                        files.AddRange(fanArtPaths.Select(path => new ResourceLocator(mediaIteamLocator.NativeSystemId, path)));
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("LocalAlbumFanArtProvider: Error while searching fanart of type '{0}' for '{1}'", ex, fanArtType, mediaIteamLocator);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
        protected async Task ExtractEpisodeFanArt(Guid mediaItemId, IDictionary <Guid, IList <MediaItemAspect> > aspects)
        {
            bool             shouldCacheLocal = false;
            IResourceLocator mediaItemLocator = null;

            if (!BaseInfo.IsVirtualResource(aspects))
            {
                mediaItemLocator = GetResourceLocator(aspects);

                //Whether local fanart should be stored in the fanart cache
                shouldCacheLocal = ShouldCacheLocalFanArt(mediaItemLocator.NativeResourcePath,
                                                          SeriesMetadataExtractor.CacheLocalFanArt, SeriesMetadataExtractor.CacheOfflineFanArt);
            }

            if (mediaItemLocator == null)
            {
                return;
            }

            if (!shouldCacheLocal && SeriesMetadataExtractor.SkipFanArtDownload)
            {
                return; //Nothing to do
            }
            EpisodeInfo episodeInfo = new EpisodeInfo();

            episodeInfo.FromMetadata(aspects);

            //Episode fanart
            if (AddToCache(mediaItemId))
            {
                if (shouldCacheLocal)
                {
                    await ExtractEpisodeFolderFanArt(mediaItemLocator, mediaItemId, episodeInfo.ToString()).ConfigureAwait(false);
                }
                if (!SeriesMetadataExtractor.SkipFanArtDownload)
                {
                    await OnlineMatcherService.Instance.DownloadSeriesFanArtAsync(mediaItemId, episodeInfo).ConfigureAwait(false);
                }
            }

            //Actor fanart may be stored in the season or series directory, so get the actors now
            IList <Tuple <Guid, string> > actors = null;

            if (MediaItemAspect.TryGetAspect(aspects, VideoAspect.Metadata, out SingleMediaItemAspect videoAspect))
            {
                var actorNames = videoAspect.GetCollectionAttribute <string>(VideoAspect.ATTR_ACTORS);
                if (actorNames != null)
                {
                    RelationshipExtractorUtils.TryGetMappedLinkedIds(PersonAspect.ROLE_ACTOR, aspects, actorNames.ToList(), out actors);
                }
            }

            //Take advantage of the audio language being known and download season and series too

            //Season fanart
            if (RelationshipExtractorUtils.TryGetLinkedId(SeasonAspect.ROLE_SEASON, aspects, out Guid seasonMediaItemId) &&
                AddToCache(seasonMediaItemId))
            {
                SeasonInfo seasonInfo = episodeInfo.CloneBasicInstance <SeasonInfo>();
                if (shouldCacheLocal)
                {
                    await ExtractSeasonFolderFanArt(mediaItemLocator, seasonMediaItemId, seasonInfo.ToString(), seasonInfo.SeasonNumber, actors).ConfigureAwait(false);
                }
                if (!SeriesMetadataExtractor.SkipFanArtDownload)
                {
                    await OnlineMatcherService.Instance.DownloadSeriesFanArtAsync(seasonMediaItemId, seasonInfo).ConfigureAwait(false);
                }
            }

            //Series fanart
            if (RelationshipExtractorUtils.TryGetLinkedId(SeriesAspect.ROLE_SERIES, aspects, out Guid seriesMediaItemId) &&
                AddToCache(seriesMediaItemId))
            {
                SeriesInfo seriesInfo = episodeInfo.CloneBasicInstance <SeriesInfo>();
                if (shouldCacheLocal)
                {
                    await ExtractSeriesFolderFanArt(mediaItemLocator, seriesMediaItemId, seriesInfo.ToString(), episodeInfo.SeasonNumber, actors).ConfigureAwait(false);
                }
                if (!SeriesMetadataExtractor.SkipFanArtDownload)
                {
                    await OnlineMatcherService.Instance.DownloadSeriesFanArtAsync(seriesMediaItemId, seriesInfo).ConfigureAwait(false);
                }
            }

            //Find central actor information folder
            var          seriesDirectory        = ResourcePathHelper.Combine(mediaItemLocator.NativeResourcePath, "../../");
            ResourcePath centralActorFolderPath = LocalFanartHelper.GetCentralPersonFolder(seriesDirectory, CentralPersonFolderType.SeriesActors);

            if (shouldCacheLocal && centralActorFolderPath != null && actors != null)
            {
                foreach (var actor in actors)
                {
                    // Check if we already processed this actor
                    if (!AddToCache(actor.Item1))
                    {
                        continue;
                    }

                    // First get the ResourcePath of the central directory
                    var artistFolderPath = ResourcePathHelper.Combine(centralActorFolderPath, $"{LocalFanartHelper.GetSafePersonFolderName(actor.Item2)}/");
                    using (IResourceAccessor accessor = new ResourceLocator(mediaItemLocator.NativeSystemId, artistFolderPath).CreateAccessor())
                    {
                        if (accessor is IFileSystemResourceAccessor directoryAccessor)
                        {
                            FanArtPathCollection paths = new FanArtPathCollection();
                            List <ResourcePath>  potentialFanArtFiles = LocalFanartHelper.GetPotentialFanArtFiles(directoryAccessor);
                            ExtractAllFanArtImages(potentialFanArtFiles, paths);
                            await SaveFolderImagesToCache(mediaItemLocator.NativeSystemId, paths, actor.Item1, actor.Item2).ConfigureAwait(false);
                        }
                    }
                }
            }
        }