FanartMovieImageProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. using System.Net;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.Movies;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Providers;
  12. using MediaBrowser.Model.Serialization;
  13. using MediaBrowser.Providers.Music;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using CommonIO;
  22. using MediaBrowser.Providers.TV;
  23. namespace MediaBrowser.Providers.Movies
  24. {
  25. public class FanartMovieImageProvider : IRemoteImageProvider, IHasChangeMonitor, IHasOrder
  26. {
  27. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  28. private readonly IServerConfigurationManager _config;
  29. private readonly IHttpClient _httpClient;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IJsonSerializer _json;
  32. private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3/movies/{1}?api_key={0}";
  33. // &client_key=52c813aa7b8c8b3bb87f4797532a2f8c
  34. internal static FanartMovieImageProvider Current;
  35. public FanartMovieImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
  36. {
  37. _config = config;
  38. _httpClient = httpClient;
  39. _fileSystem = fileSystem;
  40. _json = json;
  41. Current = this;
  42. }
  43. public string Name
  44. {
  45. get { return ProviderName; }
  46. }
  47. public static string ProviderName
  48. {
  49. get { return "FanArt"; }
  50. }
  51. public bool Supports(IHasImages item)
  52. {
  53. //var channelItem = item as IChannelMediaItem;
  54. //if (channelItem != null)
  55. //{
  56. // if (channelItem.ContentType == ChannelMediaContentType.Movie)
  57. // {
  58. // return true;
  59. // }
  60. // if (channelItem.ContentType == ChannelMediaContentType.MovieExtra)
  61. // {
  62. // if (channelItem.ExtraType == ExtraType.Trailer)
  63. // {
  64. // return true;
  65. // }
  66. // }
  67. //}
  68. // Supports images for tv movies
  69. //var tvProgram = item as LiveTvProgram;
  70. //if (tvProgram != null && tvProgram.IsMovie)
  71. //{
  72. // return true;
  73. //}
  74. return item is Movie || item is BoxSet || item is MusicVideo;
  75. }
  76. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  77. {
  78. return new List<ImageType>
  79. {
  80. ImageType.Primary,
  81. ImageType.Thumb,
  82. ImageType.Art,
  83. ImageType.Logo,
  84. ImageType.Disc,
  85. ImageType.Banner,
  86. ImageType.Backdrop
  87. };
  88. }
  89. public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
  90. {
  91. var baseItem = (BaseItem)item;
  92. var list = new List<RemoteImageInfo>();
  93. var movieId = baseItem.GetProviderId(MetadataProviders.Tmdb);
  94. if (!string.IsNullOrEmpty(movieId))
  95. {
  96. // Bad id entered
  97. try
  98. {
  99. await EnsureMovieJson(movieId, cancellationToken).ConfigureAwait(false);
  100. }
  101. catch (HttpException ex)
  102. {
  103. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  104. {
  105. throw;
  106. }
  107. }
  108. var path = GetFanartJsonPath(movieId);
  109. try
  110. {
  111. AddImages(list, path, cancellationToken);
  112. }
  113. catch (FileNotFoundException)
  114. {
  115. // No biggie. Don't blow up
  116. }
  117. catch (DirectoryNotFoundException)
  118. {
  119. // No biggie. Don't blow up
  120. }
  121. }
  122. var language = item.GetPreferredMetadataLanguage();
  123. var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  124. // Sort first by width to prioritize HD versions
  125. return list.OrderByDescending(i => i.Width ?? 0)
  126. .ThenByDescending(i =>
  127. {
  128. if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  129. {
  130. return 3;
  131. }
  132. if (!isLanguageEn)
  133. {
  134. if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  135. {
  136. return 2;
  137. }
  138. }
  139. if (string.IsNullOrEmpty(i.Language))
  140. {
  141. return isLanguageEn ? 3 : 2;
  142. }
  143. return 0;
  144. })
  145. .ThenByDescending(i => i.CommunityRating ?? 0);
  146. }
  147. private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
  148. {
  149. var root = _json.DeserializeFromFile<RootObject>(path);
  150. AddImages(list, root, cancellationToken);
  151. }
  152. private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
  153. {
  154. PopulateImages(list, obj.hdmovieclearart, ImageType.Art, 1000, 562);
  155. PopulateImages(list, obj.hdmovielogo, ImageType.Logo, 800, 310);
  156. PopulateImages(list, obj.moviedisc, ImageType.Disc, 1000, 1000);
  157. PopulateImages(list, obj.movieposter, ImageType.Primary, 1000, 1426);
  158. PopulateImages(list, obj.movielogo, ImageType.Logo, 400, 155);
  159. PopulateImages(list, obj.movieart, ImageType.Art, 500, 281);
  160. PopulateImages(list, obj.moviethumb, ImageType.Thumb, 1000, 562);
  161. PopulateImages(list, obj.moviebanner, ImageType.Banner, 1000, 185);
  162. PopulateImages(list, obj.moviebackground, ImageType.Backdrop, 1920, 1080);
  163. }
  164. private void PopulateImages(List<RemoteImageInfo> list, List<Image> images, ImageType type, int width, int height)
  165. {
  166. if (images == null)
  167. {
  168. return;
  169. }
  170. list.AddRange(images.Select(i =>
  171. {
  172. var url = i.url;
  173. if (!string.IsNullOrEmpty(url))
  174. {
  175. var likesString = i.likes;
  176. int likes;
  177. var info = new RemoteImageInfo
  178. {
  179. RatingType = RatingType.Likes,
  180. Type = type,
  181. Width = width,
  182. Height = height,
  183. ProviderName = Name,
  184. Url = url,
  185. Language = i.lang
  186. };
  187. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
  188. {
  189. info.CommunityRating = likes;
  190. }
  191. return info;
  192. }
  193. return null;
  194. }).Where(i => i != null));
  195. }
  196. public int Order
  197. {
  198. get { return 1; }
  199. }
  200. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  201. {
  202. return _httpClient.GetResponse(new HttpRequestOptions
  203. {
  204. CancellationToken = cancellationToken,
  205. Url = url,
  206. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  207. });
  208. }
  209. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  210. {
  211. var options = FanartSeriesProvider.Current.GetFanartOptions();
  212. if (!options.EnableAutomaticUpdates)
  213. {
  214. return false;
  215. }
  216. var id = item.GetProviderId(MetadataProviders.Tmdb);
  217. if (string.IsNullOrEmpty(id))
  218. {
  219. id = item.GetProviderId(MetadataProviders.Imdb);
  220. }
  221. if (!string.IsNullOrEmpty(id))
  222. {
  223. // Process images
  224. var path = GetFanartJsonPath(id);
  225. var fileInfo = _fileSystem.GetFileInfo(path);
  226. return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
  227. }
  228. return false;
  229. }
  230. /// <summary>
  231. /// Gets the movie data path.
  232. /// </summary>
  233. /// <param name="appPaths">The application paths.</param>
  234. /// <param name="id">The identifier.</param>
  235. /// <returns>System.String.</returns>
  236. internal static string GetMovieDataPath(IApplicationPaths appPaths, string id)
  237. {
  238. var dataPath = Path.Combine(GetMoviesDataPath(appPaths), id);
  239. return dataPath;
  240. }
  241. /// <summary>
  242. /// Gets the movie data path.
  243. /// </summary>
  244. /// <param name="appPaths">The app paths.</param>
  245. /// <returns>System.String.</returns>
  246. internal static string GetMoviesDataPath(IApplicationPaths appPaths)
  247. {
  248. var dataPath = Path.Combine(appPaths.CachePath, "fanart-movies");
  249. return dataPath;
  250. }
  251. public string GetFanartJsonPath(string id)
  252. {
  253. var movieDataPath = GetMovieDataPath(_config.ApplicationPaths, id);
  254. return Path.Combine(movieDataPath, "fanart.json");
  255. }
  256. /// <summary>
  257. /// Downloads the movie json.
  258. /// </summary>
  259. /// <param name="id">The identifier.</param>
  260. /// <param name="cancellationToken">The cancellation token.</param>
  261. /// <returns>Task.</returns>
  262. internal async Task DownloadMovieJson(string id, CancellationToken cancellationToken)
  263. {
  264. cancellationToken.ThrowIfCancellationRequested();
  265. var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, id);
  266. var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
  267. if (!string.IsNullOrWhiteSpace(clientKey))
  268. {
  269. url += "&client_key=" + clientKey;
  270. }
  271. var path = GetFanartJsonPath(id);
  272. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  273. try
  274. {
  275. using (var response = await _httpClient.Get(new HttpRequestOptions
  276. {
  277. Url = url,
  278. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool,
  279. CancellationToken = cancellationToken
  280. }).ConfigureAwait(false))
  281. {
  282. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  283. {
  284. await response.CopyToAsync(fileStream).ConfigureAwait(false);
  285. }
  286. }
  287. }
  288. catch (HttpException exception)
  289. {
  290. if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
  291. {
  292. // If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
  293. _json.SerializeToFile(new RootObject(), path);
  294. return;
  295. }
  296. throw;
  297. }
  298. }
  299. private readonly Task _cachedTask = Task.FromResult(true);
  300. internal Task EnsureMovieJson(string id, CancellationToken cancellationToken)
  301. {
  302. var path = GetFanartJsonPath(id);
  303. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  304. if (fileInfo.Exists)
  305. {
  306. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  307. {
  308. return _cachedTask;
  309. }
  310. }
  311. return DownloadMovieJson(id, cancellationToken);
  312. }
  313. public class Image
  314. {
  315. public string id { get; set; }
  316. public string url { get; set; }
  317. public string lang { get; set; }
  318. public string likes { get; set; }
  319. }
  320. public class RootObject
  321. {
  322. public string name { get; set; }
  323. public string tmdb_id { get; set; }
  324. public string imdb_id { get; set; }
  325. public List<Image> hdmovielogo { get; set; }
  326. public List<Image> moviedisc { get; set; }
  327. public List<Image> movielogo { get; set; }
  328. public List<Image> movieposter { get; set; }
  329. public List<Image> hdmovieclearart { get; set; }
  330. public List<Image> movieart { get; set; }
  331. public List<Image> moviebackground { get; set; }
  332. public List<Image> moviebanner { get; set; }
  333. public List<Image> moviethumb { get; set; }
  334. }
  335. }
  336. }