FanartMovieImageProvider.cs 16 KB

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