using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace MediaBrowser.Providers.Movies { /// /// Class MovieDbImagesProvider /// public class MovieDbImagesProvider : BaseMetadataProvider { /// /// The get images /// private const string GetImages = @"http://api.themoviedb.org/3/{2}/{0}/images?api_key={1}"; /// /// The _provider manager /// private readonly IProviderManager _providerManager; /// /// The _json serializer /// private readonly IJsonSerializer _jsonSerializer; /// /// Initializes a new instance of the class. /// /// The log manager. /// The configuration manager. /// The provider manager. /// The json serializer. public MovieDbImagesProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager, IJsonSerializer jsonSerializer) : base(logManager, configurationManager) { _providerManager = providerManager; _jsonSerializer = jsonSerializer; } /// /// Gets the priority. /// /// The priority. public override MetadataProviderPriority Priority { get { return MetadataProviderPriority.Fourth; } } /// /// Supports the specified item. /// /// The item. /// true if XXXX, false otherwise public override bool Supports(BaseItem item) { var trailer = item as Trailer; if (trailer != null) { return !trailer.IsLocalTrailer; } // Don't support local trailers return item is Movie || item is BoxSet || item is MusicVideo; } public override ItemUpdateType ItemUpdateType { get { return ItemUpdateType.ImageUpdate; } } /// /// Gets a value indicating whether [requires internet]. /// /// true if [requires internet]; otherwise, false. public override bool RequiresInternet { get { return true; } } /// /// Gets a value indicating whether [refresh on version change]. /// /// true if [refresh on version change]; otherwise, false. protected override bool RefreshOnVersionChange { get { return true; } } /// /// Gets the provider version. /// /// The provider version. protected override string ProviderVersion { get { return "3"; } } /// /// Needses the refresh internal. /// /// The item. /// The provider info. /// true if XXXX, false otherwise protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo) { if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb))) { return false; } // Don't refresh if we already have both poster and backdrop and we're not refreshing images if (item.HasImage(ImageType.Primary) && item.BackdropImagePaths.Count >= ConfigurationManager.Configuration.MaxBackdrops) { return false; } return base.NeedsRefreshInternal(item, providerInfo); } protected override bool NeedsRefreshBasedOnCompareDate(BaseItem item, BaseProviderInfo providerInfo) { if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb))) { return false; } var path = MovieDbProvider.Current.GetDataFilePath(item, "default"); if (!string.IsNullOrEmpty(path)) { var fileInfo = new FileInfo(path); if (fileInfo.Exists) { return fileInfo.LastWriteTimeUtc > providerInfo.LastRefreshed; } } return false; } /// /// Fetches metadata and returns true or false indicating if any work that requires persistence was done /// /// The item. /// if set to true [force]. /// The cancellation token /// Task{System.Boolean}. public override async Task FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken) { var id = item.GetProviderId(MetadataProviders.Tmdb); var status = ProviderRefreshStatus.Success; if (!string.IsNullOrEmpty(id)) { var images = FetchImages(item); if (images != null) { status = await ProcessImages(item, images, cancellationToken).ConfigureAwait(false); } } SetLastRefreshed(item, DateTime.UtcNow, status); return true; } /// /// Fetches the images. /// /// The item. /// Task{MovieImages}. private MovieDbProvider.Images FetchImages(BaseItem item) { var path = MovieDbProvider.Current.GetDataFilePath(item, "default"); if (!string.IsNullOrEmpty(path)) { var fileInfo = new FileInfo(path); if (fileInfo.Exists) { return _jsonSerializer.DeserializeFromFile(path).images; } } return null; } /// /// Processes the images. /// /// The item. /// The images. /// The cancellation token /// Task. private async Task ProcessImages(BaseItem item, MovieDbProvider.Images images, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var status = ProviderRefreshStatus.Success; var eligiblePosters = images.posters == null ? new List() : images.posters.Where(i => i.width >= ConfigurationManager.Configuration.MinMoviePosterWidth) .ToList(); eligiblePosters = eligiblePosters.OrderByDescending(i => i.vote_average).ToList(); // poster if (eligiblePosters.Count > 0 && !item.HasImage(ImageType.Primary)) { var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false); var tmdbImageUrl = tmdbSettings.images.base_url + "original"; // get highest rated poster for our language var poster = eligiblePosters.FirstOrDefault(p => string.Equals(p.iso_639_1, ConfigurationManager.Configuration.PreferredMetadataLanguage, StringComparison.OrdinalIgnoreCase)); if (poster == null) { // couldn't find our specific language, find english poster = eligiblePosters.FirstOrDefault(p => string.Equals(p.iso_639_1, "en", StringComparison.OrdinalIgnoreCase)); } if (poster == null) { //still couldn't find it - try highest rated null one poster = eligiblePosters.FirstOrDefault(p => p.iso_639_1 == null); } if (poster == null) { //finally - just get the highest rated one poster = eligiblePosters.FirstOrDefault(); } if (poster != null) { var url = tmdbImageUrl + poster.file_path; var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken }).ConfigureAwait(false); await _providerManager.SaveImage(item, img, MimeTypes.GetMimeType(poster.file_path), ImageType.Primary, null, url, cancellationToken) .ConfigureAwait(false); } } cancellationToken.ThrowIfCancellationRequested(); var eligibleBackdrops = images.backdrops == null ? new List() : images.backdrops.Where(i => i.width >= ConfigurationManager.Configuration.MinMovieBackdropWidth) .ToList(); var backdropLimit = ConfigurationManager.Configuration.MaxBackdrops; // backdrops - only download if earlier providers didn't find any (fanart) if (eligibleBackdrops.Count > 0 && ConfigurationManager.Configuration.DownloadMovieImages.Backdrops && item.BackdropImagePaths.Count < backdropLimit) { var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false); var tmdbImageUrl = tmdbSettings.images.base_url + "original"; for (var i = 0; i < eligibleBackdrops.Count; i++) { var url = tmdbImageUrl + eligibleBackdrops[i].file_path; if (!item.ContainsImageWithSourceUrl(url)) { var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions { Url = url, CancellationToken = cancellationToken }).ConfigureAwait(false); await _providerManager.SaveImage(item, img, MimeTypes.GetMimeType(eligibleBackdrops[i].file_path), ImageType.Backdrop, item.BackdropImagePaths.Count, url, cancellationToken) .ConfigureAwait(false); } if (item.BackdropImagePaths.Count >= backdropLimit) { break; } } } return status; } } }