FanartMovieImageProvider.cs 12 KB

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