FanartMovieImageProvider.cs 13 KB

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