FanartMovieImageProvider.cs 12 KB

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