FanartMovieImageProvider.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Channels;
  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.Channels;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Providers;
  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;
  20. using System.Threading;
  21. using System.Threading.Tasks;
  22. using System.Xml;
  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 const string FanArtBaseUrl = "http://api.fanart.tv/webservice/movie/{0}/{1}/xml/all/1/1";
  32. internal static FanartMovieImageProvider Current;
  33. public FanartMovieImageProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem)
  34. {
  35. _config = config;
  36. _httpClient = httpClient;
  37. _fileSystem = fileSystem;
  38. Current = this;
  39. }
  40. public string Name
  41. {
  42. get { return ProviderName; }
  43. }
  44. public static string ProviderName
  45. {
  46. get { return "FanArt"; }
  47. }
  48. public bool Supports(IHasImages item)
  49. {
  50. var trailer = item as Trailer;
  51. if (trailer != null)
  52. {
  53. return !trailer.IsLocalTrailer;
  54. }
  55. return item is Movie || item is BoxSet || item is MusicVideo;
  56. }
  57. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  58. {
  59. return new List<ImageType>
  60. {
  61. ImageType.Primary,
  62. ImageType.Thumb,
  63. ImageType.Art,
  64. ImageType.Logo,
  65. ImageType.Disc,
  66. ImageType.Banner,
  67. ImageType.Backdrop
  68. };
  69. }
  70. public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
  71. {
  72. var baseItem = (BaseItem)item;
  73. var list = new List<RemoteImageInfo>();
  74. var movieId = baseItem.GetProviderId(MetadataProviders.Tmdb);
  75. if (!string.IsNullOrEmpty(movieId))
  76. {
  77. await EnsureMovieXml(movieId, cancellationToken).ConfigureAwait(false);
  78. var xmlPath = GetFanartXmlPath(movieId);
  79. try
  80. {
  81. AddImages(list, xmlPath, cancellationToken);
  82. }
  83. catch (FileNotFoundException)
  84. {
  85. // No biggie. Don't blow up
  86. }
  87. }
  88. var language = item.GetPreferredMetadataLanguage();
  89. var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  90. // Sort first by width to prioritize HD versions
  91. return list.OrderByDescending(i => i.Width ?? 0)
  92. .ThenByDescending(i =>
  93. {
  94. if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  95. {
  96. return 3;
  97. }
  98. if (!isLanguageEn)
  99. {
  100. if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  101. {
  102. return 2;
  103. }
  104. }
  105. if (string.IsNullOrEmpty(i.Language))
  106. {
  107. return isLanguageEn ? 3 : 2;
  108. }
  109. return 0;
  110. })
  111. .ThenByDescending(i => i.CommunityRating ?? 0);
  112. }
  113. private void AddImages(List<RemoteImageInfo> list, string xmlPath, CancellationToken cancellationToken)
  114. {
  115. using (var streamReader = new StreamReader(xmlPath, Encoding.UTF8))
  116. {
  117. // Use XmlReader for best performance
  118. using (var reader = XmlReader.Create(streamReader, new XmlReaderSettings
  119. {
  120. CheckCharacters = false,
  121. IgnoreProcessingInstructions = true,
  122. IgnoreComments = true,
  123. ValidationType = ValidationType.None
  124. }))
  125. {
  126. reader.MoveToContent();
  127. // Loop through each element
  128. while (reader.Read())
  129. {
  130. cancellationToken.ThrowIfCancellationRequested();
  131. if (reader.NodeType == XmlNodeType.Element)
  132. {
  133. switch (reader.Name)
  134. {
  135. case "movie":
  136. {
  137. using (var subReader = reader.ReadSubtree())
  138. {
  139. AddImages(list, subReader, cancellationToken);
  140. }
  141. break;
  142. }
  143. default:
  144. reader.Skip();
  145. break;
  146. }
  147. }
  148. }
  149. }
  150. }
  151. }
  152. private void AddImages(List<RemoteImageInfo> list, XmlReader reader, CancellationToken cancellationToken)
  153. {
  154. reader.MoveToContent();
  155. while (reader.Read())
  156. {
  157. if (reader.NodeType == XmlNodeType.Element)
  158. {
  159. switch (reader.Name)
  160. {
  161. case "hdmoviecleararts":
  162. {
  163. using (var subReader = reader.ReadSubtree())
  164. {
  165. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Art, 1000, 562);
  166. }
  167. break;
  168. }
  169. case "hdmovielogos":
  170. {
  171. using (var subReader = reader.ReadSubtree())
  172. {
  173. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Logo, 800, 310);
  174. }
  175. break;
  176. }
  177. case "moviediscs":
  178. {
  179. using (var subReader = reader.ReadSubtree())
  180. {
  181. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Disc, 1000, 1000);
  182. }
  183. break;
  184. }
  185. case "movieposters":
  186. {
  187. using (var subReader = reader.ReadSubtree())
  188. {
  189. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Primary, 1000, 1426);
  190. }
  191. break;
  192. }
  193. case "movielogos":
  194. {
  195. using (var subReader = reader.ReadSubtree())
  196. {
  197. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Logo, 400, 155);
  198. }
  199. break;
  200. }
  201. case "moviearts":
  202. {
  203. using (var subReader = reader.ReadSubtree())
  204. {
  205. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Art, 500, 281);
  206. }
  207. break;
  208. }
  209. case "moviethumbs":
  210. {
  211. using (var subReader = reader.ReadSubtree())
  212. {
  213. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Thumb, 1000, 562);
  214. }
  215. break;
  216. }
  217. case "moviebanners":
  218. {
  219. using (var subReader = reader.ReadSubtree())
  220. {
  221. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Banner, 1000, 185);
  222. }
  223. break;
  224. }
  225. case "moviebackgrounds":
  226. {
  227. using (var subReader = reader.ReadSubtree())
  228. {
  229. PopulateImageCategory(list, subReader, cancellationToken, ImageType.Backdrop, 1920, 1080);
  230. }
  231. break;
  232. }
  233. default:
  234. {
  235. using (reader.ReadSubtree())
  236. {
  237. }
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. private void PopulateImageCategory(List<RemoteImageInfo> list, XmlReader reader, CancellationToken cancellationToken, ImageType type, int width, int height)
  245. {
  246. reader.MoveToContent();
  247. while (reader.Read())
  248. {
  249. cancellationToken.ThrowIfCancellationRequested();
  250. if (reader.NodeType == XmlNodeType.Element)
  251. {
  252. switch (reader.Name)
  253. {
  254. case "hdmovielogo":
  255. case "moviedisc":
  256. case "hdmovieclearart":
  257. case "movieposter":
  258. case "movielogo":
  259. case "movieart":
  260. case "moviethumb":
  261. case "moviebanner":
  262. case "moviebackground":
  263. {
  264. var url = reader.GetAttribute("url");
  265. if (!string.IsNullOrEmpty(url))
  266. {
  267. var likesString = reader.GetAttribute("likes");
  268. int likes;
  269. var info = new RemoteImageInfo
  270. {
  271. RatingType = RatingType.Likes,
  272. Type = type,
  273. Width = width,
  274. Height = height,
  275. ProviderName = Name,
  276. Url = url,
  277. Language = reader.GetAttribute("lang")
  278. };
  279. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
  280. {
  281. info.CommunityRating = likes;
  282. }
  283. list.Add(info);
  284. }
  285. break;
  286. }
  287. default:
  288. reader.Skip();
  289. break;
  290. }
  291. }
  292. }
  293. }
  294. public int Order
  295. {
  296. get { return 1; }
  297. }
  298. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  299. {
  300. return _httpClient.GetResponse(new HttpRequestOptions
  301. {
  302. CancellationToken = cancellationToken,
  303. Url = url,
  304. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  305. });
  306. }
  307. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  308. {
  309. if (!_config.Configuration.EnableFanArtUpdates)
  310. {
  311. return false;
  312. }
  313. var id = item.GetProviderId(MetadataProviders.Tmdb);
  314. if (!string.IsNullOrEmpty(id))
  315. {
  316. // Process images
  317. var xmlPath = GetFanartXmlPath(id);
  318. var fileInfo = new FileInfo(xmlPath);
  319. return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
  320. }
  321. return false;
  322. }
  323. /// <summary>
  324. /// Gets the movie data path.
  325. /// </summary>
  326. /// <param name="appPaths">The app paths.</param>
  327. /// <param name="tmdbId">The TMDB id.</param>
  328. /// <returns>System.String.</returns>
  329. internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
  330. {
  331. var dataPath = Path.Combine(GetMoviesDataPath(appPaths), tmdbId);
  332. return dataPath;
  333. }
  334. /// <summary>
  335. /// Gets the movie data path.
  336. /// </summary>
  337. /// <param name="appPaths">The app paths.</param>
  338. /// <returns>System.String.</returns>
  339. internal static string GetMoviesDataPath(IApplicationPaths appPaths)
  340. {
  341. var dataPath = Path.Combine(appPaths.CachePath, "fanart-movies");
  342. return dataPath;
  343. }
  344. public string GetFanartXmlPath(string tmdbId)
  345. {
  346. var movieDataPath = GetMovieDataPath(_config.ApplicationPaths, tmdbId);
  347. return Path.Combine(movieDataPath, "fanart.xml");
  348. }
  349. /// <summary>
  350. /// Downloads the movie XML.
  351. /// </summary>
  352. /// <param name="tmdbId">The TMDB id.</param>
  353. /// <param name="cancellationToken">The cancellation token.</param>
  354. /// <returns>Task.</returns>
  355. internal async Task DownloadMovieXml(string tmdbId, CancellationToken cancellationToken)
  356. {
  357. cancellationToken.ThrowIfCancellationRequested();
  358. var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, tmdbId);
  359. var xmlPath = GetFanartXmlPath(tmdbId);
  360. Directory.CreateDirectory(Path.GetDirectoryName(xmlPath));
  361. using (var response = await _httpClient.Get(new HttpRequestOptions
  362. {
  363. Url = url,
  364. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool,
  365. CancellationToken = cancellationToken
  366. }).ConfigureAwait(false))
  367. {
  368. using (var xmlFileStream = _fileSystem.GetFileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  369. {
  370. await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
  371. }
  372. }
  373. }
  374. private readonly Task _cachedTask = Task.FromResult(true);
  375. internal Task EnsureMovieXml(string tmdbId, CancellationToken cancellationToken)
  376. {
  377. var path = GetFanartXmlPath(tmdbId);
  378. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  379. if (fileInfo.Exists)
  380. {
  381. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  382. {
  383. return _cachedTask;
  384. }
  385. }
  386. return DownloadMovieXml(tmdbId, cancellationToken);
  387. }
  388. }
  389. }