jellyfin/MediaBrowser.Providers/Movies/FanartMovieImageProvider.cs

371 lines
13 KiB
C#
Raw Normal View History

2014-10-25 11:32:58 -07:00
using System.Net;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
2014-01-30 21:50:09 -07:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
2014-01-30 14:23:54 -07:00
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
2014-10-25 11:32:58 -07:00
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
2014-10-22 21:26:01 -07:00
using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Music;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2015-01-17 22:45:10 -07:00
using MediaBrowser.Providers.TV;
namespace MediaBrowser.Providers.Movies
{
public class FanartMovieImageProvider : IRemoteImageProvider, IHasChangeMonitor, IHasOrder
{
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IServerConfigurationManager _config;
private readonly IHttpClient _httpClient;
2014-01-30 21:50:09 -07:00
private readonly IFileSystem _fileSystem;
2014-10-22 21:26:01 -07:00
private readonly IJsonSerializer _json;
2014-10-22 21:26:01 -07:00
private const string FanArtBaseUrl = "http://webservice.fanart.tv/v3/movies/{1}?api_key={0}";
// &client_key=52c813aa7b8c8b3bb87f4797532a2f8c
internal static FanartMovieImageProvider Current;
2014-10-22 21:26:01 -07:00
public FanartMovieImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
{
_config = config;
_httpClient = httpClient;
2014-01-30 21:50:09 -07:00
_fileSystem = fileSystem;
2014-10-22 21:26:01 -07:00
_json = json;
Current = this;
}
public string Name
{
get { return ProviderName; }
}
public static string ProviderName
{
get { return "FanArt"; }
}
2013-12-21 11:37:34 -07:00
public bool Supports(IHasImages item)
{
2014-01-30 14:23:54 -07:00
return item is Movie || item is BoxSet || item is MusicVideo;
}
public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
{
return new List<ImageType>
{
ImageType.Primary,
ImageType.Thumb,
ImageType.Art,
ImageType.Logo,
ImageType.Disc,
ImageType.Banner,
ImageType.Backdrop
};
}
2014-02-12 22:11:54 -07:00
public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
{
2013-12-21 11:37:34 -07:00
var baseItem = (BaseItem)item;
var list = new List<RemoteImageInfo>();
2013-12-21 11:37:34 -07:00
var movieId = baseItem.GetProviderId(MetadataProviders.Tmdb);
if (!string.IsNullOrEmpty(movieId))
{
2014-10-25 11:32:58 -07:00
// Bad id entered
try
{
await EnsureMovieJson(movieId, cancellationToken).ConfigureAwait(false);
}
catch (HttpException ex)
{
if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
{
throw;
}
}
2014-01-30 14:23:54 -07:00
2014-10-22 21:26:01 -07:00
var path = GetFanartJsonPath(movieId);
try
{
2014-10-22 21:26:01 -07:00
AddImages(list, path, cancellationToken);
}
catch (FileNotFoundException)
{
// No biggie. Don't blow up
}
2014-12-22 20:58:14 -07:00
catch (DirectoryNotFoundException)
{
// No biggie. Don't blow up
}
}
var language = item.GetPreferredMetadataLanguage();
var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
2013-12-21 11:37:34 -07:00
// Sort first by width to prioritize HD versions
2014-01-30 14:23:54 -07:00
return list.OrderByDescending(i => i.Width ?? 0)
.ThenByDescending(i =>
{
if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
{
return 3;
}
if (!isLanguageEn)
{
if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
{
return 2;
}
}
if (string.IsNullOrEmpty(i.Language))
{
return isLanguageEn ? 3 : 2;
}
return 0;
})
2014-01-30 14:23:54 -07:00
.ThenByDescending(i => i.CommunityRating ?? 0);
}
2014-10-22 21:26:01 -07:00
private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
{
2014-10-22 21:26:01 -07:00
var root = _json.DeserializeFromFile<RootObject>(path);
2014-10-22 21:26:01 -07:00
AddImages(list, root, cancellationToken);
}
2014-10-22 21:26:01 -07:00
private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
{
2014-10-22 21:26:01 -07:00
PopulateImages(list, obj.hdmovieclearart, ImageType.Art, 1000, 562);
PopulateImages(list, obj.hdmovielogo, ImageType.Logo, 800, 310);
PopulateImages(list, obj.moviedisc, ImageType.Disc, 1000, 1000);
PopulateImages(list, obj.movieposter, ImageType.Primary, 1000, 1426);
PopulateImages(list, obj.movielogo, ImageType.Logo, 400, 155);
PopulateImages(list, obj.movieart, ImageType.Art, 500, 281);
PopulateImages(list, obj.moviethumb, ImageType.Thumb, 1000, 562);
PopulateImages(list, obj.moviebanner, ImageType.Banner, 1000, 185);
PopulateImages(list, obj.moviebackground, ImageType.Backdrop, 1920, 1080);
}
2014-10-22 21:26:01 -07:00
private void PopulateImages(List<RemoteImageInfo> list, List<Image> images, ImageType type, int width, int height)
{
2014-10-22 21:26:01 -07:00
if (images == null)
{
return;
}
2014-10-22 21:26:01 -07:00
list.AddRange(images.Select(i =>
{
2014-10-22 21:26:01 -07:00
var url = i.url;
2014-10-22 21:26:01 -07:00
if (!string.IsNullOrEmpty(url))
{
2014-10-22 21:26:01 -07:00
var likesString = i.likes;
int likes;
var info = new RemoteImageInfo
{
RatingType = RatingType.Likes,
Type = type,
Width = width,
Height = height,
ProviderName = Name,
Url = url,
Language = i.lang
};
if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
{
2014-10-22 21:26:01 -07:00
info.CommunityRating = likes;
}
2014-10-22 21:26:01 -07:00
return info;
}
2014-10-22 21:26:01 -07:00
return null;
}).Where(i => i != null));
}
public int Order
{
get { return 1; }
}
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url,
ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
});
}
2014-01-30 21:50:09 -07:00
2014-02-10 11:39:41 -07:00
public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
2014-01-30 21:50:09 -07:00
{
2015-01-17 22:45:10 -07:00
var options = FanartSeriesProvider.Current.GetFanartOptions();
if (!options.EnableAutomaticUpdates)
{
return false;
}
2014-01-30 21:50:09 -07:00
var id = item.GetProviderId(MetadataProviders.Tmdb);
2014-10-22 21:26:01 -07:00
if (string.IsNullOrEmpty(id))
{
id = item.GetProviderId(MetadataProviders.Imdb);
}
2014-01-30 21:50:09 -07:00
if (!string.IsNullOrEmpty(id))
{
// Process images
2014-10-22 21:26:01 -07:00
var path = GetFanartJsonPath(id);
2014-01-30 21:50:09 -07:00
2014-10-22 21:26:01 -07:00
var fileInfo = new FileInfo(path);
2014-01-30 21:50:09 -07:00
return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
2014-01-30 21:50:09 -07:00
}
return false;
}
/// <summary>
/// Gets the movie data path.
/// </summary>
2014-10-22 21:26:01 -07:00
/// <param name="appPaths">The application paths.</param>
/// <param name="id">The identifier.</param>
/// <returns>System.String.</returns>
2014-10-22 21:26:01 -07:00
internal static string GetMovieDataPath(IApplicationPaths appPaths, string id)
{
2014-10-22 21:26:01 -07:00
var dataPath = Path.Combine(GetMoviesDataPath(appPaths), id);
return dataPath;
}
/// <summary>
/// Gets the movie data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <returns>System.String.</returns>
internal static string GetMoviesDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.CachePath, "fanart-movies");
return dataPath;
}
2014-10-22 21:26:01 -07:00
public string GetFanartJsonPath(string id)
{
2014-10-22 21:26:01 -07:00
var movieDataPath = GetMovieDataPath(_config.ApplicationPaths, id);
return Path.Combine(movieDataPath, "fanart.json");
}
/// <summary>
2014-10-22 21:26:01 -07:00
/// Downloads the movie json.
/// </summary>
2014-10-22 21:26:01 -07:00
/// <param name="id">The identifier.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2014-10-22 21:26:01 -07:00
internal async Task DownloadMovieJson(string id, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
2014-10-22 21:26:01 -07:00
var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, id);
2015-01-17 22:45:10 -07:00
var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
if (!string.IsNullOrWhiteSpace(clientKey))
{
2015-01-17 22:45:10 -07:00
url += "&client_key=" + clientKey;
}
2014-10-22 21:26:01 -07:00
var path = GetFanartJsonPath(id);
2014-10-22 21:26:01 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2014-11-28 19:40:46 -07:00
try
{
2014-11-28 19:40:46 -07:00
using (var response = await _httpClient.Get(new HttpRequestOptions
{
Url = url,
ResourcePool = FanartArtistProvider.Current.FanArtResourcePool,
CancellationToken = cancellationToken
2014-11-28 19:40:46 -07:00
}).ConfigureAwait(false))
{
using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
{
await response.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
}
catch (HttpException exception)
{
2014-11-28 19:40:46 -07:00
if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
{
2014-11-28 19:40:46 -07:00
// If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
_json.SerializeToFile(new RootObject(), path);
return;
}
2014-11-28 19:40:46 -07:00
throw;
}
}
private readonly Task _cachedTask = Task.FromResult(true);
2014-10-22 21:26:01 -07:00
internal Task EnsureMovieJson(string id, CancellationToken cancellationToken)
{
2014-10-22 21:26:01 -07:00
var path = GetFanartJsonPath(id);
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
{
2014-10-06 16:58:46 -07:00
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
{
return _cachedTask;
}
}
2014-10-22 21:26:01 -07:00
return DownloadMovieJson(id, cancellationToken);
}
public class Image
{
public string id { get; set; }
public string url { get; set; }
public string lang { get; set; }
public string likes { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string tmdb_id { get; set; }
public string imdb_id { get; set; }
public List<Image> hdmovielogo { get; set; }
public List<Image> moviedisc { get; set; }
public List<Image> movielogo { get; set; }
public List<Image> movieposter { get; set; }
public List<Image> hdmovieclearart { get; set; }
public List<Image> movieart { get; set; }
public List<Image> moviebackground { get; set; }
public List<Image> moviebanner { get; set; }
public List<Image> moviethumb { get; set; }
}
}
}