public void TestFanArtExtractAlbumArtistFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid albumId = Guid.NewGuid();

            Guid artist1Id = Guid.NewGuid();
            Guid artist2Id = Guid.NewGuid();
            IList <Tuple <Guid, string> > artists = new List <Tuple <Guid, string> >
            {
                new Tuple <Guid, string>(artist1Id, "Album Artist1"),
                new Tuple <Guid, string>(artist2Id, "Album Artist2")
            };

            AudioFanArtHandlerForTests fh = new AudioFanArtHandlerForTests();

            //Act
            fh.TestExtractAlbumFolderFanArt(albumId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Audio/TestArtist/TestAlbum/"), artists).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(artist1Id, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/.artists/album_artist1-thumb.png");

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(artist2Id, out fanart));
            fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();
            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/.artists/album_artist2-thumb.png");
        }
        public void TestFanArtExtractSeasonActorFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid seasonId = Guid.NewGuid();

            Guid actor1Id = Guid.NewGuid();
            Guid actor2Id = Guid.NewGuid();
            IList <Tuple <Guid, string> > actors = new List <Tuple <Guid, string> >
            {
                new Tuple <Guid, string>(actor1Id, "Season Actor1"),
                new Tuple <Guid, string>(actor2Id, "Season Actor2")
            };

            SeriesFanArtHandlerForTests fh = new SeriesFanArtHandlerForTests();

            //Act
            fh.TestExtractSeasonFolderFanArt(seasonId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Series/TestSeries/Season 1/episode1.mkv"), 1, actors).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(actor1Id, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Series/TestSeries/Season 1/.actors/season_actor1-thumb.png");

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(actor2Id, out fanart));
            fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();
            CollectionAssert.Contains(fanartBasePaths, "Series/TestSeries/Season 1/.actors/season_actor2-thumb.png");
        }
        protected bool BuildBaseUrl()
        {
            IServerConnectionManager scm = ServiceRegistration.Get <IServerConnectionManager>();

            // In case we lost the connection clear the url so it can be looked up later again
            if (!scm.IsHomeServerConnected)
            {
                _baseUrl = null;
                return(false);
            }
            if (!string.IsNullOrWhiteSpace(_baseUrl))
            {
                return(true);
            }

            // We need to know the base url of the server's remote access service, so we can use the IP and port number.
            try
            {
                IRemoteResourceInformationService rris = ServiceRegistration.Get <IRemoteResourceInformationService>();
                string    resourceUrl;
                IPAddress localIpAddress;
                if (!rris.GetFileHttpUrl(scm.HomeServerSystemId, ResourcePath.BuildBaseProviderPath(Guid.Empty, string.Empty), out resourceUrl, out localIpAddress))
                {
                    return(false);
                }

                Uri uri = new Uri(resourceUrl);
                _baseUrl = uri.Authority;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #4
0
        public void AddDirectory(string directory, IEnumerable <string> files)
        {
            directory = StringUtils.RemoveSuffixIfPresent(directory, "/");
            ResourcePath directoryPath = ResourcePath.BuildBaseProviderPath(PROVIDER_ID, directory);
            IEnumerable <IFileSystemResourceAccessor> fileAccessors = files.Select(f => new MockFileSystemAccessor(ResourcePathHelper.Combine(directoryPath, f), this, null));

            _accessors.Add(directory, new MockFileSystemAccessor(directoryPath, this, fileAccessors.ToList()));
        }
 private static bool BuildLogoResourceLocatorAndReturn(ref IList <IResourceLocator> result, string logoFileName)
 {
     if (!File.Exists(logoFileName))
     {
         return(false);
     }
     result = new List <IResourceLocator> {
         new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, logoFileName))
     };
     return(true);
 }
        public void TestFanArtGetAdditionalSeasonFolderFanArt(string[] paths, int seasonNumber, int expectedCount)
        {
            //Arrange
            List <ResourcePath>         resourcePaths = paths.Select(p => ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, p)).ToList();
            SeriesFanArtHandlerForTests fh            = new SeriesFanArtHandlerForTests();

            //Act
            FanArtPathCollection fanart = fh.TestGetAdditionalSeasonFolderFanArt(resourcePaths, seasonNumber);

            //Assert
            Assert.AreEqual(expectedCount, fanart.Sum(kvp => kvp.Value.Count));
        }
        public void TestFanArtGetAllNamedFolderFanArt(string[] paths, int expectedCount)
        {
            //Arrange
            List <ResourcePath>       resourcePaths = paths.Select(p => ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, p)).ToList();
            BaseFanArtHandlerForTests fh            = new BaseFanArtHandlerForTests();

            //Act
            var fanart = fh.TestGetAllFolderFanArt(resourcePaths, "Name");

            //Assert
            Assert.AreEqual(expectedCount, fanart.Sum(kvp => kvp.Value.Count));
        }
Beispiel #8
0
        protected MultimediaDriveHandler(DriveInfo driveInfo, IEnumerable <Guid> necessaryMIATypeIds, IEnumerable <Guid> optionalMIATypeIds, MultiMediaType mediaType) : base(driveInfo)
        {
            _mediaType = mediaType;
            string drive = driveInfo.Name;

            drive = drive.Substring(0, 2); // Clip potential '\\' at the end
            string directory = "/" + drive + "/";

            _mediaItemsSubViewSpecification = new LocalDirectoryViewSpecification(driveInfo.VolumeLabel + " (" + DriveUtils.GetDriveNameWithoutRootDirectory(driveInfo) + ")",
                                                                                  ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, directory),
                                                                                  necessaryMIATypeIds, optionalMIATypeIds);
        }
Beispiel #9
0
        /// <summary>
        /// Updates the data for the resource provider path tree.
        /// </summary>
        public void UpdateResourceProviderPathTree()
        {
            ResourceProviderMetadata rpm = BaseResourceProvider;

            if (rpm == null)
            { // This happens when the WF-Manager navigates back to the overview screen - all properties have been cleared before
                _resourceProviderPathsTree.Clear();
                _resourceProviderPathsTree.FireChange();
                return;
            }
            RefreshResourceProviderPathList(_resourceProviderPathsTree, ResourcePath.BuildBaseProviderPath(rpm.ResourceProviderId, "/"));
            UpdateIsChoosenPathValid();
        }
Beispiel #10
0
        public void TestNfoMovieReaderReadMetadata()
        {
            //Arrange
            var resourceProviders = new Dictionary <Guid, IResourceProvider>();

            resourceProviders.Add(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, new LocalFsResourceProvider());
            var mockMediaAccessor = new Mock <IMediaAccessor>();

            ServiceRegistration.Set <IMediaAccessor>(mockMediaAccessor.Object);
            mockMediaAccessor.Setup(x => x.LocalResourceProviders).Returns(resourceProviders);

            Mock <IFileSystemResourceAccessor> mockRA = new Mock <IFileSystemResourceAccessor>();

            mockRA.Setup(r => r.OpenReadAsync()).Returns(Task.FromResult(
                                                             Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Server.NfoMetadataExtractor.TestData.MovieNfo.movie.nfo")));
            mockRA.SetupGet(t => t.CanonicalLocalResourcePath).Returns(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, @"TestData\MovieNfo\movie.nfo"));
            NfoMovieReader reader = new NfoMovieReader(new ConsoleLogger(LogLevel.All, true), 1, false, false, false, null, new NfoMovieMetadataExtractorSettings());

            //Act
            reader.TryReadMetadataAsync(mockRA.Object).Wait();
            var stubs = reader.GetMovieStubs();

            //Assert
            Assert.NotNull(stubs);
            Assert.AreEqual(1, stubs.Count);
            var stub = stubs[0];

            Assert.NotNull(stub);
            Assert.AreEqual("The Lego Batman Movie", stub.Title);
            Assert.AreEqual("The Lego Batman Movie", stub.OriginalTitle);
            Assert.AreEqual(7.2m, stub.Rating);
            Assert.AreEqual(new DateTime(2017, 1, 1), stub.Year);
            Assert.AreEqual(1853, stub.Votes);
            Assert.AreEqual("In the irreverent spirit of fun that made “The Lego Movie” a worldwide phenomenon, the self-described leading man of that ensemble—Lego Batman—stars in his own big-screen adventure. But there are big changes...", stub.Outline);
            Assert.AreEqual("In the irreverent spirit of fun that made “The Lego Movie” a worldwide phenomenon, the self-described leading man of that ensemble—Lego Batman—stars in his own big-screen adventure. But there are big changes brewing in Gotham, and if he wants to save the city from The Joker’s hostile takeover, Batman may have to drop the lone vigilante thing, try to work with others and maybe, just maybe, learn to lighten up.", stub.Plot);
            Assert.AreEqual("Always be yourself. Unless you can be Batman.", stub.Tagline);
            Assert.AreEqual(TimeSpan.FromMinutes(104), stub.Runtime);
            CollectionAssert.AreEqual(new[] { "UK:U" }, stub.Mpaa);
            CollectionAssert.AreEqual(new[] { "UK:U" }, stub.Certification);
            Assert.AreEqual("tt4116284", stub.Id);
            Assert.AreEqual(324849, stub.TmdbId);
            CollectionAssert.AreEqual(new[] { "Denmark", "United States" }, stub.Countries);
            Assert.AreEqual(false, stub.Watched);
            Assert.AreEqual(0, stub.PlayCount);
            CollectionAssert.AreEqual(new[] { "Action", "Animation", "Comedy", "Family", "Fantasy" }, stub.Genres);
            CollectionAssert.AreEqual(new[] { "Lin Pictures", "Warner Bros. Animation", "Warner Bros.", "Animal Logic", "DC Entertainment", "Lord Miller", "LEGO System A", "S" }, stub.Studios);
            CollectionAssert.AreEqual(new[] { "Chris McKenna", "Erik Sommers", "Seth Grahame-Smith", "Jared Stern", "John Whittington" }, stub.Credits);
            Assert.AreEqual("Chris McKay", stub.Director);
            CollectionAssert.AreEqual(new[] { "English" }, stub.Languages);
        }
Beispiel #11
0
        /// <summary>
        /// Main process method for the InnerBlock
        /// </summary>
        /// <remarks>
        /// - SingleResources are just passed to the next DataflowBlock
        /// - If it's not a SingleResource
        ///   - it finds all the files in the current directory,
        ///   - in case of a RefreshImport
        ///     - it deletes all the files in the MediaLibrary that do not exist anymore in the filesystem,
        ///     - it stores the DateOfLastImport of all the files in the <see cref="PendingImportResourceNewGen"/>
        /// </remarks>
        /// <param name="importResource"><see cref="PendingImportResourceNewGen"/> to be processed</param>
        /// <returns>
        /// a HashSet of <see cref="PendingImportResourceNewGen"/>s containing the current <see cref="PendingImportResource"/>
        /// after processing as well as <see cref="PendingImportResourceNewGen"/>s for all files in the current directory
        /// </returns>
        private async Task <IEnumerable <PendingImportResourceNewGen> > ProcessChanges(PendingImportResourceNewGen importResource)
        {
            var result = new HashSet <PendingImportResourceNewGen> {
                importResource
            };

            try
            {
                if (ImportJobInformation.JobType == ImportJobType.Refresh)
                {
                    // ReSharper disable once PossibleInvalidOperationException
                    IEnumerable <MediaItem> mediaItems = await GetUpdatableMediaItems(PROVIDERRESOURCE_IMPORTER_MIA_ID_ENUMERATION, null);

                    if (mediaItems != null)
                    {
                        foreach (MediaItem mi in mediaItems)
                        {
                            IList <MultipleMediaItemAspect> providerAspects = null;
                            if (MediaItemAspect.TryGetAspects(mi.Aspects, ProviderResourceAspect.Metadata, out providerAspects))
                            {
                                ResourcePath      path        = ResourcePath.Deserialize(providerAspects[0].GetAttributeValue <String>(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH));
                                Guid?             directoryId = providerAspects[0].GetAttributeValue <Guid?>(ProviderResourceAspect.ATTR_PARENT_DIRECTORY_ID);
                                IResourceAccessor ra;
                                if (path.TryCreateLocalResourceAccessor(out ra) && ra is IFileSystemResourceAccessor)
                                {
                                    IFileSystemResourceAccessor f   = ra as IFileSystemResourceAccessor;
                                    string       dirPath            = ResourcePathHelper.GetDirectoryName(ra.Path);
                                    ResourcePath dirRa              = ResourcePath.BuildBaseProviderPath(ra.ParentProvider.Metadata.ResourceProviderId, dirPath);
                                    PendingImportResourceNewGen pir = new PendingImportResourceNewGen(dirRa, f, ToString(), ParentImportJobController, directoryId, mi.MediaItemId);
                                    pir.DateOfLastImport = DateTime.MinValue; //Force update
                                    result.Add(pir);
                                }
                            }
                        }
                    }
                }
                return(result);
            }
            catch (TaskCanceledException)
            {
                return(result);
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Warn("ImporterWorker.{0}.{1}: Error while processing {2}", ex, ParentImportJobController, ToString(), importResource);
                importResource.IsValid = false;
                return(result);
            }
        }
        public void TestFanArtExtractEpisodeFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid episodeId = Guid.NewGuid();
            SeriesFanArtHandlerForTests fh = new SeriesFanArtHandlerForTests();

            //Act
            fh.TestExtractEpisodeFolderFanArt(episodeId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Series/TestSeries/Season 1/episode1.mkv")).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(episodeId, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Series/TestSeries/Season 1/episode1-thumb.png");
        }
Beispiel #13
0
        public ICollection <Share> CreateDefaultShares()
        {
            List <Share> result = new List <Share>();
            Guid         localFsResourceProviderId = LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID;

            if (LocalResourceProviders.ContainsKey(localFsResourceProviderId))
            {
                string folderPath;
                if (WindowsAPI.GetSpecialFolder(WindowsAPI.SpecialFolder.MyMusic, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Audio.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_MUSIC_SHARE_NAME_RESOURE, mediaCategories);
                    result.Add(sd);
                }

                if (WindowsAPI.GetSpecialFolder(WindowsAPI.SpecialFolder.MyVideos, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Video.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_VIDEOS_SHARE_NAME_RESOURCE, mediaCategories);
                    result.Add(sd);
                }

                if (WindowsAPI.GetSpecialFolder(WindowsAPI.SpecialFolder.MyPictures, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Image.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_PICTURES_SHARE_NAME_RESOURCE, mediaCategories);
                    result.Add(sd);
                }
            }
            if (result.Count > 0)
            {
                return(result);
            }
            // Fallback: If no share was added for the defaults above, use the provider's root folders
            result.AddRange(LocalBaseResourceProviders.Select(resourceProvider => resourceProvider.Metadata).Select(
                                metadata => Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(metadata.ResourceProviderId, "/"), metadata.Name, null)));
            return(result);
        }
        public void TestFanArtExtractAlbumFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid albumId = Guid.NewGuid();
            AudioFanArtHandlerForTests fh = new AudioFanArtHandlerForTests();

            //Act
            fh.TestExtractAlbumFolderFanArt(albumId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Audio/TestArtist/TestAlbum/")).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(albumId, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/cover.png");
            CollectionAssert.Contains(fanartBasePaths, "Audio/TestArtist/TestAlbum/ExtraFanArt/fanart.png");
        }
Beispiel #15
0
        public void TestFanArtExtractMovieFolderFanArt()
        {
            //Arrange
            _fanArtCache.Clear();
            Guid movieId = Guid.NewGuid();
            MovieFanArtHandlerForTests fh = new MovieFanArtHandlerForTests();

            //Act
            fh.TestExtractMovieFolderFanArt(movieId, ResourcePath.BuildBaseProviderPath(MockResourceProvider.PROVIDER_ID, "Movies/TestCollection/TestMovie/movie.mkv")).Wait();

            //Assert
            List <string> fanart;

            Assert.IsTrue(_fanArtCache.FanArt.TryGetValue(movieId, out fanart));
            ICollection <string> fanartBasePaths = fanart.Select(p => ResourcePath.Deserialize(p).BasePathSegment.Path).ToList();

            CollectionAssert.Contains(fanartBasePaths, "Movies/TestCollection/TestMovie/poster.png");
            CollectionAssert.Contains(fanartBasePaths, "Movies/TestCollection/TestMovie/ExtraFanArt/fanart.png");
        }
Beispiel #16
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;
            if (mediaType != FanArtMediaTypes.Movie && mediaType != FanArtMediaTypes.MovieCollection &&
                mediaType != FanArtMediaTypes.Undefined && fanArtType == FanArtTypes.Thumbnail)
            {
                return(false);
            }

            Guid mediaItemId;

            string[] patterns;

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

            List <IResourceLocator> files = new List <IResourceLocator>();

            foreach (var pattern in patterns)
            {
                try
                {
                    var           pathPart      = Path.GetDirectoryName(pattern);
                    var           filePart      = Path.GetFileName(pattern);
                    DirectoryInfo directoryInfo = new DirectoryInfo(pathPart);
                    if (directoryInfo.Exists)
                    {
                        files.AddRange(directoryInfo.GetFiles(filePart)
                                       .Select(f => f.FullName)
                                       .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                                       );
                    }
                }
                catch
                {
                }
            }
            result = files;
            return(files.Count > 0);
        }
        /// <summary>
        /// Helper method to create a valid <see cref="ResourcePath"/> from the given path. This method supports both local and UNC paths and will use the right ResourceProviderId.
        /// </summary>
        /// <param name="path">Path or file name</param>
        /// <returns></returns>
        protected static ResourcePath BuildResourcePath(string path)
        {
            Guid providerId;

            if (path.StartsWith("\\\\"))
            {
                // NetworkNeighborhoodResourceProvider
                providerId = new Guid("{03DD2DA6-4DA8-4D3E-9E55-80E3165729A3}");
                // Cut-off the first \
                path = path.Substring(1);
            }
            else
            {
                providerId = LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID;
            }

            string folderPath   = LocalFsResourceProviderBase.ToProviderPath(path);
            var    resourcePath = ResourcePath.BuildBaseProviderPath(providerId, folderPath);

            return(resourcePath);
        }
        public bool TryGetFanArt(string mediaType, string fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            if (mediaType != GameFanartTypes.MEDIA_TYPE_GAME && mediaType != FanArtMediaTypes.Undefined && fanArtType == FanArtTypes.Thumbnail)
            {
                return(false);
            }
            string path;

            if (!TryGetImagePath(name, fanArtType, out path))
            {
                return(false);
            }

            List <IResourceLocator> files = new List <IResourceLocator>();

            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                if (directoryInfo.Exists)
                {
                    foreach (string pattern in IMAGE_PATTERNS)
                    {
                        files.AddRange(directoryInfo.GetFiles(pattern)
                                       .Select(f => f.FullName)
                                       .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                                       );
                        result = files;
                        if (result.Count > 0)
                        {
                            return(true);
                        }
                    }
                }
            }
            catch (Exception) { }
            return(false);
        }
        public ICollection <Share> CreateDefaultShares()
        {
            List <Share> result = new List <Share>();
            Guid         localFsResourceProviderId = LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID;

            if (LocalResourceProviders.ContainsKey(localFsResourceProviderId))
            {
                string folderPath;
                if (WindowsAPI.GetSpecialFolder(Environment.SpecialFolder.MyMusic, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Audio.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_MUSIC_SHARE_NAME_RESOURE, true, mediaCategories);
                    result.Add(sd);
                }

                if (WindowsAPI.GetSpecialFolder(Environment.SpecialFolder.MyVideos, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Video.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_VIDEOS_SHARE_NAME_RESOURCE, true, mediaCategories);
                    result.Add(sd);
                }

                if (WindowsAPI.GetSpecialFolder(Environment.SpecialFolder.MyPictures, out folderPath))
                {
                    folderPath = LocalFsResourceProviderBase.ToProviderPath(folderPath);
                    string[] mediaCategories = new[] { DefaultMediaCategories.Image.ToString() };
                    Share    sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(localFsResourceProviderId, folderPath),
                                                            MY_PICTURES_SHARE_NAME_RESOURCE, true, mediaCategories);
                    result.Add(sd);
                }
            }
            return(result);
        }
Beispiel #20
0
 public static ResourcePath ToResourcePath(Guid virtualId)
 {
     return(ResourcePath.BuildBaseProviderPath(VIRTUAL_RESOURCE_PROVIDER_ID, BuildProviderPath(virtualId)));
 }
Beispiel #21
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;

            if (!VALID_MEDIA_TYPES.Contains(mediaType) || !VALID_FANART_TYPES.Contains(fanArtType))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            Guid mediaItemId;

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

            IFanArtCache fanArtCache = ServiceRegistration.Get <IFanArtCache>();

            List <string> fanArtFiles = new List <string>();

            fanArtFiles.AddRange(fanArtCache.GetFanArtFiles(mediaItemId, fanArtType));
            if (fanArtFiles.Count == 0 && fanArtType == FanArtTypes.Poster)
            {
                fanArtFiles.AddRange(fanArtCache.GetFanArtFiles(mediaItemId, FanArtTypes.Cover));
            }

            // Try fallback
            if (fanArtFiles.Count == 0 && (mediaType == FanArtMediaTypes.Audio || mediaType == FanArtMediaTypes.Album))
            {
                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, OPTIONAL_MIAS, filter), false, null, true);
                if (items == null || items.Count == 0)
                {
                    return(false);
                }

                MediaItem mediaItem = items.First();

                IList <MultipleMediaItemAspect> relationAspects;
                if (mediaType == FanArtMediaTypes.Audio && fanArtType == FanArtTypes.FanArt)
                {
                    //No FanArt exists for Audio so use Artists
                    if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                    {
                        //Artist fallback
                        foreach (MultipleMediaItemAspect relation in relationAspects)
                        {
                            if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ARTIST)
                            {
                                fanArtFiles.AddRange(fanArtCache.GetFanArtFiles((Guid)relation[RelationshipAspect.ATTR_LINKED_ID], fanArtType));
                                if (fanArtFiles.Count > 0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (mediaType == FanArtMediaTypes.Album && fanArtType == FanArtTypes.FanArt)
                {
                    //No FanArt exists for Album so use Artists
                    if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                    {
                        //Album artist fallback
                        foreach (MultipleMediaItemAspect relation in relationAspects)
                        {
                            if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == PersonAspect.ROLE_ALBUMARTIST)
                            {
                                fanArtFiles.AddRange(fanArtCache.GetFanArtFiles((Guid)relation[RelationshipAspect.ATTR_LINKED_ID], fanArtType));
                                if (fanArtFiles.Count > 0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                else if (mediaItem.Aspects.ContainsKey(AudioAspect.ASPECT_ID))
                {
                    if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                    {
                        //Album fallback
                        foreach (MultipleMediaItemAspect relation in relationAspects)
                        {
                            if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == AudioAlbumAspect.ROLE_ALBUM)
                            {
                                fanArtFiles.AddRange(fanArtCache.GetFanArtFiles((Guid)relation[RelationshipAspect.ATTR_LINKED_ID], fanArtType));
                                if (fanArtFiles.Count > 0)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            List <IResourceLocator> files = new List <IResourceLocator>();

            try
            {
                files.AddRange(fanArtFiles
                               .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                               );
                result = files;
                return(result.Count > 0);
            }
            catch (Exception) { }
            return(false);
        }
 public static ResourcePath ToResourcePath(char drive, byte trackNo)
 {
     return(ResourcePath.BuildBaseProviderPath(AUDIO_CD_RESOURCE_PROVIDER_ID, BuildProviderPath(drive, trackNo)));
 }
        protected void PrepareMediaSources()
        {
            Dictionary <string, ICollection <MediaCategory> > checkFolders = new Dictionary <string, ICollection <MediaCategory> >();
            List <string> recordingFolders;
            string        singlePattern;
            string        seriesPattern;

            if (!GetRecordingConfiguration(out recordingFolders, out singlePattern, out seriesPattern))
            {
                ServiceRegistration.Get <ILogger>().Warn("SlimTvService: Unable to configure MediaSource for recordings, probably TV configuration wasn't run yet.");
                return;
            }

            string movieSubfolder  = GetFixedFolderPart(singlePattern);
            string seriesSubfolder = GetFixedFolderPart(seriesPattern);

            foreach (var recordingFolder in recordingFolders)
            {
                if (!string.IsNullOrEmpty(movieSubfolder) && !string.IsNullOrEmpty(seriesSubfolder))
                {
                    // If there are different target folders defined, register the media sources with specialized Series/Movie types
                    checkFolders.Add(FileUtils.CheckTrailingPathDelimiter(Path.Combine(recordingFolder, movieSubfolder)), new HashSet <MediaCategory> {
                        DefaultMediaCategories.Video, Movie
                    });
                    checkFolders.Add(FileUtils.CheckTrailingPathDelimiter(Path.Combine(recordingFolder, seriesSubfolder)), new HashSet <MediaCategory> {
                        DefaultMediaCategories.Video, Series
                    });
                }
                else
                {
                    checkFolders.Add(FileUtils.CheckTrailingPathDelimiter(recordingFolder), new HashSet <MediaCategory> {
                        DefaultMediaCategories.Video
                    });
                }
            }

            IMediaLibrary mediaLibrary = ServiceRegistration.Get <IMediaLibrary>();
            int           cnt          = 1;

            foreach (var folderTypes in checkFolders)
            {
                try
                {
                    List <Share> shares;
                    // Check if there are already share(s) for the folder
                    if (GetSharesForPath(folderTypes.Key, out shares))
                    {
                        continue;
                    }

                    var   folderPath      = LocalFsResourceProviderBase.ToProviderPath(folderTypes.Key);
                    var   mediaCategories = folderTypes.Value.Select(mc => mc.CategoryName);
                    Share sd = Share.CreateNewLocalShare(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, folderPath),
                                                         string.Format("Recordings ({0})", cnt), mediaCategories);

                    mediaLibrary.RegisterShare(sd);
                    cnt++;
                }
                catch (Exception ex)
                {
                    ServiceRegistration.Get <ILogger>().Error("SlimTvService: Error registering new MediaSource.", ex);
                }
            }
        }
Beispiel #24
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;

            if (!VALID_MEDIA_TYPES.Contains(mediaType) || !VALID_FANART_TYPES.Contains(fanArtType))
            {
                return(false);
            }

            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            Guid mediaItemId;

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

            List <string> fanArtFiles = new List <string>();

            fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(mediaItemId.ToString().ToUpperInvariant(), fanArtType));

            // Try fallback
            if (fanArtFiles.Count == 0 &&
                (mediaType == FanArtMediaTypes.SeriesSeason ||
                 mediaType == FanArtMediaTypes.Character ||
                 (mediaType == FanArtMediaTypes.Episode && fanArtType == FanArtTypes.FanArt)))
            {
                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, OPTIONAL_MIAS, filter), false, null, true);
                if (items == null || items.Count == 0)
                {
                    return(false);
                }

                MediaItem mediaItem = items.First();

                if (mediaType == FanArtMediaTypes.Episode && fanArtType == FanArtTypes.FanArt)
                {
                    if (mediaItem.Aspects.ContainsKey(EpisodeAspect.ASPECT_ID))
                    {
                        IList <MultipleMediaItemAspect> relationAspects;
                        if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                        {
                            //Season fallback
                            foreach (MultipleMediaItemAspect relation in relationAspects)
                            {
                                if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeasonAspect.ROLE_SEASON)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }

                            //Series fallback
                            if (fanArtFiles.Count == 0)
                            {
                                foreach (MultipleMediaItemAspect relation in relationAspects)
                                {
                                    if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeriesAspect.ROLE_SERIES)
                                    {
                                        fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                        if (fanArtFiles.Count > 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else if (mediaType == FanArtMediaTypes.SeriesSeason)
                {
                    if (mediaItem.Aspects.ContainsKey(SeasonAspect.ASPECT_ID))
                    {
                        IList <MultipleMediaItemAspect> relationAspects;
                        if (MediaItemAspect.TryGetAspects(mediaItem.Aspects, RelationshipAspect.Metadata, out relationAspects))
                        {
                            foreach (MultipleMediaItemAspect relation in relationAspects)
                            {
                                if ((Guid?)relation[RelationshipAspect.ATTR_LINKED_ROLE] == SeriesAspect.ROLE_SERIES)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                else if (mediaType == FanArtMediaTypes.Character)
                {
                    if (mediaItem.Aspects.ContainsKey(CharacterAspect.ASPECT_ID))
                    {
                        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)
                                {
                                    fanArtFiles.AddRange(FanArtCache.GetFanArtFiles(relation[RelationshipAspect.ATTR_LINKED_ID].ToString().ToUpperInvariant(), fanArtType));
                                    if (fanArtFiles.Count > 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            List <IResourceLocator> files = new List <IResourceLocator>();

            try
            {
                files.AddRange(fanArtFiles
                               .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                               );
                result = files;
                return(result.Count > 0);
            }
            catch (Exception) { }
            return(false);
        }
        private bool TryCreateInsertVideoMediaMediaItem(MediaItem origMi, out MediaItem subMi)
        {
            subMi = null;
            IPathManager pathManager       = ServiceRegistration.Get <IPathManager>();
            string       resourceDirectory = pathManager.GetPath(@"<DATA>\Resources\");

            string[] files = Directory.GetFiles(resourceDirectory, "InsertVideoMedia.*");
            if (files == null || files.Length == 0)
            {
                return(false);
            }

            IDictionary <Guid, IList <MediaItemAspect> > aspects = new Dictionary <Guid, IList <MediaItemAspect> >();

            foreach (var aspect in origMi.Aspects)
            {
                if (aspect.Key != ProviderResourceAspect.ASPECT_ID)
                {
                    aspects.Add(aspect.Key, aspect.Value);
                }
            }

            MediaItemAspect providerResourceAspect = MediaItemAspect.CreateAspect(aspects, ProviderResourceAspect.Metadata);

            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_INDEX, 0);
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_TYPE, ProviderResourceAspect.TYPE_PRIMARY);
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_RESOURCE_ACCESSOR_PATH, ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, files[0]).Serialize());
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_MIME_TYPE, MimeTypeDetector.GetMimeType(files[0], "video/unknown"));
            providerResourceAspect.SetAttribute(ProviderResourceAspect.ATTR_SYSTEM_ID, ServiceRegistration.Get <ISystemResolver>().LocalSystemId);

            subMi = new MediaItem(Guid.Empty, aspects);
            return(true);
        }
Beispiel #26
0
 protected internal static bool IsResource(string path)
 {
     if (IsRootPath(path))
     {
         return(true);
     }
     using (ServiceRegistration.Get <IImpersonationService>().CheckImpersonationFor(ResourcePath.BuildBaseProviderPath(NetworkNeighborhoodResourceProvider.NETWORK_NEIGHBORHOOD_RESOURCE_PROVIDER_ID, path)))
         return(IsServerPath(path) || LocalFsResourceProvider.Instance.IsResource("/" + path));
 }
        /// <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;
            if (mediaType != FanArtMediaTypes.ChannelTv && mediaType != FanArtMediaTypes.ChannelRadio)
            {
                return(false);
            }

            try
            {
                string designsFolder = FileUtils.BuildAssemblyRelativePath("Designs");

                ChannelType  logoChannelType = mediaType == FanArtMediaTypes.ChannelTv ? ChannelType.Tv : ChannelType.Radio;
                ThemeHandler themeHandler    = new ThemeHandler();
                Theme        theme           = themeHandler.Load(Path.Combine(designsFolder, _settings.LogoTheme));

                string logoFolder   = Path.Combine(_dataFolder, string.Format("{0}-{1}-{2}", logoChannelType, theme.DesignName, theme.ThemeName));
                string logoFileName = Path.Combine(logoFolder, FileUtils.GetSafeFilename(string.Format("{0}.png", name)));

                if (!Directory.Exists(logoFolder))
                {
                    Directory.CreateDirectory(logoFolder);
                }

                if (File.Exists(logoFileName))
                {
                    result = new List <IResourceLocator> {
                        new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, logoFileName))
                    };
                    return(true);
                }

                LogoProcessor processor = new LogoProcessor {
                    DesignsFolder = designsFolder
                };

                // From repository
                using (var repo = new LogoRepository {
                    RepositoryUrl = _settings.RepositoryUrl
                })
                {
                    var stream = repo.Download(name, logoChannelType, _country.TwoLetterISORegionName);
                    if (stream == null)
                    {
                        return(false);
                    }
                    using (stream)
                        if (processor.CreateLogo(theme, stream, logoFileName))
                        {
                            result = new List <IResourceLocator> {
                                new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, logoFileName))
                            };
                            return(true);
                        }
                }
            }
            catch (Exception ex)
            {
                ServiceRegistration.Get <ILogger>().Error("SlimTv Logos: Error processing logo image.", ex);
            }
            return(false);
        }
Beispiel #28
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(FanArtConstants.FanArtMediaType mediaType, FanArtConstants.FanArtType fanArtType, string name, int maxWidth, int maxHeight, bool singleRandom, out IList <IResourceLocator> result)
        {
            result = null;
            Guid mediaItemId;

            // Don't try to load "fanart" for images
            if (!Guid.TryParse(name, out mediaItemId) || mediaType == FanArtConstants.FanArtMediaType.Image)
            {
                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(_necessarryMIAs, filter), false);

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

            MediaItem               mediaItem      = items.First();
            string                  fileSystemPath = null;
            List <string>           localPatterns  = new List <string>();
            List <IResourceLocator> files          = new List <IResourceLocator>();

            // File based access
            try
            {
                var resourceLocator = mediaItem.GetResourceLocator();
                using (var accessor = resourceLocator.CreateAccessor())
                {
                    ILocalFsResourceAccessor fsra = accessor as ILocalFsResourceAccessor;
                    if (fsra != null)
                    {
                        fileSystemPath = fsra.LocalFileSystemPath;
                        var path = Path.GetDirectoryName(fileSystemPath);
                        var file = Path.GetFileNameWithoutExtension(fileSystemPath);

                        if (fanArtType == FanArtConstants.FanArtType.Poster || fanArtType == FanArtConstants.FanArtType.Thumbnail)
                        {
                            localPatterns.Add(Path.ChangeExtension(fileSystemPath, ".jpg"));
                            localPatterns.Add(Path.Combine(path, file + "-poster.jpg"));
                            localPatterns.Add(Path.Combine(path, "folder.jpg"));
                        }
                        if (fanArtType == FanArtConstants.FanArtType.FanArt)
                        {
                            localPatterns.Add(Path.Combine(path, "backdrop.jpg"));
                            localPatterns.Add(Path.Combine(path, file + "-fanart*.jpg"));
                            localPatterns.Add(Path.Combine(path, "ExtraFanArt\\*.jpg"));
                        }

                        // Copy all patterns for .jpg -> .png + .tbn
                        localPatterns.AddRange(new List <string>(localPatterns).Select(p => p.Replace(".jpg", ".png")));
                        localPatterns.AddRange(new List <string>(localPatterns).Select(p => p.Replace(".jpg", ".tbn")));

                        foreach (var pattern in localPatterns)
                        {
                            try
                            {
                                var           pathPart      = Path.GetDirectoryName(pattern);
                                var           filePart      = Path.GetFileName(pattern);
                                DirectoryInfo directoryInfo = new DirectoryInfo(pathPart);
                                if (directoryInfo.Exists)
                                {
                                    files.AddRange(directoryInfo.GetFiles(filePart)
                                                   .Select(f => f.FullName)
                                                   .Select(fileName => new ResourceLocator(resourceLocator.NativeSystemId, ResourcePath.BuildBaseProviderPath(resourceLocator.NativeResourcePath.LastPathSegment.ProviderId, fileName))));
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ServiceRegistration.Get <ILogger>().Warn("Error while search fanart of type '{0}' for path '{1}'", ex, fanArtType, fileSystemPath);
#endif
            }
            result = files;
            return(files.Count > 0);
        }
 public static ResourcePath ToProviderResourcePath(string path)
 {
     return(ResourcePath.BuildBaseProviderPath(RAW_URL_RESOURCE_PROVIDER_ID, path));
 }
        /// <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;
            if (string.IsNullOrWhiteSpace(name))
            {
                return(false);
            }

            int tvDbId;
            int seasonNum = 0;

            if (mediaType == FanArtMediaTypes.SeriesSeason)
            {
                int index = name.LastIndexOf(" S");
                if (!int.TryParse(name.Substring(index + 2), out seasonNum))
                {
                    return(false);
                }
                name = name.Substring(0, index);
            }

            string baseFolder = GetBaseFolder(mediaType, name, out tvDbId);

            // No known series
            if (baseFolder == null || !Directory.Exists(baseFolder))
            {
                return(false);
            }

            string[] patterns = GetPatterns(mediaType, fanArtType, name, tvDbId, seasonNum);
            if (patterns == null)
            {
                return(false);
            }

            List <IResourceLocator> files = new List <IResourceLocator>();

            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(baseFolder);
                if (directoryInfo.Exists)
                {
                    // Try each name pattern first.
                    foreach (string pattern in patterns)
                    {
                        files.AddRange(directoryInfo.GetFiles(pattern)
                                       .Select(f => f.FullName)
                                       .Select(fileName => new ResourceLocator(ResourcePath.BuildBaseProviderPath(LocalFsResourceProviderBase.LOCAL_FS_RESOURCE_PROVIDER_ID, fileName)))
                                       );
                        result = files;
                        if (result.Count > 0)
                        {
                            return(true);
                        }
                    }

                    // If we tried to load season banners and did not find any, fallback to series banners
                    if (mediaType == FanArtMediaTypes.SeriesSeason)
                    {
                        return(TryGetFanArt(FanArtMediaTypes.Series, fanArtType, name, maxWidth, maxHeight, singleRandom, out result));
                    }

                    return(false);
                }
            }
            catch (Exception) { }
            return(false);
        }