FanArtMovieProvider.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  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.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using System;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Xml;
  18. namespace MediaBrowser.Providers.Movies
  19. {
  20. /// <summary>
  21. /// Class FanArtMovieProvider
  22. /// </summary>
  23. class FanArtMovieProvider : FanartBaseProvider
  24. {
  25. /// <summary>
  26. /// Gets the HTTP client.
  27. /// </summary>
  28. /// <value>The HTTP client.</value>
  29. protected IHttpClient HttpClient { get; private set; }
  30. /// <summary>
  31. /// The _provider manager
  32. /// </summary>
  33. private readonly IProviderManager _providerManager;
  34. /// <summary>
  35. /// The us culture
  36. /// </summary>
  37. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  38. internal static FanArtMovieProvider Current { get; private set; }
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="FanArtMovieProvider" /> class.
  41. /// </summary>
  42. /// <param name="httpClient">The HTTP client.</param>
  43. /// <param name="logManager">The log manager.</param>
  44. /// <param name="configurationManager">The configuration manager.</param>
  45. /// <param name="providerManager">The provider manager.</param>
  46. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  47. public FanArtMovieProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  48. : base(logManager, configurationManager)
  49. {
  50. if (httpClient == null)
  51. {
  52. throw new ArgumentNullException("httpClient");
  53. }
  54. HttpClient = httpClient;
  55. _providerManager = providerManager;
  56. Current = this;
  57. }
  58. /// <summary>
  59. /// Gets a value indicating whether [refresh on version change].
  60. /// </summary>
  61. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  62. protected override bool RefreshOnVersionChange
  63. {
  64. get
  65. {
  66. return true;
  67. }
  68. }
  69. /// <summary>
  70. /// Gets the provider version.
  71. /// </summary>
  72. /// <value>The provider version.</value>
  73. protected override string ProviderVersion
  74. {
  75. get
  76. {
  77. return "13";
  78. }
  79. }
  80. public override MetadataProviderPriority Priority
  81. {
  82. get
  83. {
  84. return MetadataProviderPriority.Fourth;
  85. }
  86. }
  87. /// <summary>
  88. /// The fan art base URL
  89. /// </summary>
  90. protected string FanArtBaseUrl = "http://api.fanart.tv/webservice/movie/{0}/{1}/xml/all/1/1";
  91. /// <summary>
  92. /// Supportses the specified item.
  93. /// </summary>
  94. /// <param name="item">The item.</param>
  95. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  96. public override bool Supports(BaseItem item)
  97. {
  98. var trailer = item as Trailer;
  99. if (trailer != null)
  100. {
  101. return !trailer.IsLocalTrailer;
  102. }
  103. return item is Movie || item is BoxSet || item is MusicVideo;
  104. }
  105. /// <summary>
  106. /// Needses the refresh internal.
  107. /// </summary>
  108. /// <param name="item">The item.</param>
  109. /// <param name="providerInfo">The provider info.</param>
  110. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  111. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  112. {
  113. if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb)))
  114. {
  115. return false;
  116. }
  117. if (!ConfigurationManager.Configuration.DownloadMovieImages.Art &&
  118. !ConfigurationManager.Configuration.DownloadMovieImages.Logo &&
  119. !ConfigurationManager.Configuration.DownloadMovieImages.Disc &&
  120. !ConfigurationManager.Configuration.DownloadMovieImages.Backdrops &&
  121. !ConfigurationManager.Configuration.DownloadMovieImages.Banner &&
  122. !ConfigurationManager.Configuration.DownloadMovieImages.Thumb)
  123. {
  124. return false;
  125. }
  126. if (item.HasImage(ImageType.Art) &&
  127. item.HasImage(ImageType.Logo) &&
  128. item.HasImage(ImageType.Disc) &&
  129. item.HasImage(ImageType.Banner) &&
  130. item.HasImage(ImageType.Thumb) &&
  131. item.BackdropImagePaths.Count > 0)
  132. {
  133. return false;
  134. }
  135. return base.NeedsRefreshInternal(item, providerInfo);
  136. }
  137. protected override DateTime CompareDate(BaseItem item)
  138. {
  139. var id = item.GetProviderId(MetadataProviders.Tmdb);
  140. if (!string.IsNullOrEmpty(id))
  141. {
  142. // Process images
  143. var path = GetMovieDataPath(ConfigurationManager.ApplicationPaths, id);
  144. var files = new DirectoryInfo(path)
  145. .EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly)
  146. .Select(i => i.LastWriteTimeUtc)
  147. .ToArray();
  148. if (files.Length > 0)
  149. {
  150. return files.Max();
  151. }
  152. }
  153. return base.CompareDate(item);
  154. }
  155. /// <summary>
  156. /// Gets the movie data path.
  157. /// </summary>
  158. /// <param name="appPaths">The app paths.</param>
  159. /// <param name="tmdbId">The TMDB id.</param>
  160. /// <returns>System.String.</returns>
  161. internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
  162. {
  163. var dataPath = Path.Combine(GetMoviesDataPath(appPaths), tmdbId);
  164. if (!Directory.Exists(dataPath))
  165. {
  166. Directory.CreateDirectory(dataPath);
  167. }
  168. return dataPath;
  169. }
  170. /// <summary>
  171. /// Gets the movie data path.
  172. /// </summary>
  173. /// <param name="appPaths">The app paths.</param>
  174. /// <returns>System.String.</returns>
  175. internal static string GetMoviesDataPath(IApplicationPaths appPaths)
  176. {
  177. var dataPath = Path.Combine(appPaths.DataPath, "fanart-movies");
  178. if (!Directory.Exists(dataPath))
  179. {
  180. Directory.CreateDirectory(dataPath);
  181. }
  182. return dataPath;
  183. }
  184. /// <summary>
  185. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  186. /// </summary>
  187. /// <param name="item">The item.</param>
  188. /// <param name="force">if set to <c>true</c> [force].</param>
  189. /// <param name="cancellationToken">The cancellation token.</param>
  190. /// <returns>Task{System.Boolean}.</returns>
  191. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  192. {
  193. cancellationToken.ThrowIfCancellationRequested();
  194. BaseProviderInfo data;
  195. if (!item.ProviderData.TryGetValue(Id, out data))
  196. {
  197. data = new BaseProviderInfo();
  198. item.ProviderData[Id] = data;
  199. }
  200. var movieId = item.GetProviderId(MetadataProviders.Tmdb);
  201. var movieDataPath = GetMovieDataPath(ConfigurationManager.ApplicationPaths, movieId);
  202. var xmlPath = Path.Combine(movieDataPath, "fanart.xml");
  203. // Only download the xml if it doesn't already exist. The prescan task will take care of getting updates
  204. if (!File.Exists(xmlPath))
  205. {
  206. await DownloadMovieXml(movieDataPath, movieId, cancellationToken).ConfigureAwait(false);
  207. }
  208. if (File.Exists(xmlPath))
  209. {
  210. await FetchFromXml(item, xmlPath, cancellationToken).ConfigureAwait(false);
  211. }
  212. SetLastRefreshed(item, DateTime.UtcNow);
  213. return true;
  214. }
  215. /// <summary>
  216. /// Downloads the movie XML.
  217. /// </summary>
  218. /// <param name="movieDataPath">The movie data path.</param>
  219. /// <param name="tmdbId">The TMDB id.</param>
  220. /// <param name="cancellationToken">The cancellation token.</param>
  221. /// <returns>Task.</returns>
  222. internal async Task DownloadMovieXml(string movieDataPath, string tmdbId, CancellationToken cancellationToken)
  223. {
  224. cancellationToken.ThrowIfCancellationRequested();
  225. string url = string.Format(FanArtBaseUrl, ApiKey, tmdbId);
  226. var xmlPath = Path.Combine(movieDataPath, "fanart.xml");
  227. using (var response = await HttpClient.Get(new HttpRequestOptions
  228. {
  229. Url = url,
  230. ResourcePool = FanArtResourcePool,
  231. CancellationToken = cancellationToken
  232. }).ConfigureAwait(false))
  233. {
  234. using (var xmlFileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  235. {
  236. await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
  237. }
  238. }
  239. }
  240. /// <summary>
  241. /// Fetches from XML.
  242. /// </summary>
  243. /// <param name="item">The item.</param>
  244. /// <param name="xmlFilePath">The XML file path.</param>
  245. /// <param name="cancellationToken">The cancellation token.</param>
  246. /// <returns>Task.</returns>
  247. private async Task FetchFromXml(BaseItem item, string xmlFilePath, CancellationToken cancellationToken)
  248. {
  249. var doc = new XmlDocument();
  250. doc.Load(xmlFilePath);
  251. var language = ConfigurationManager.Configuration.PreferredMetadataLanguage.ToLower();
  252. cancellationToken.ThrowIfCancellationRequested();
  253. var saveLocal = ConfigurationManager.Configuration.SaveLocalMeta &&
  254. item.LocationType == LocationType.FileSystem;
  255. string path;
  256. var hd = ConfigurationManager.Configuration.DownloadHDFanArt ? "hd" : "";
  257. if (ConfigurationManager.Configuration.DownloadMovieImages.Logo && !item.HasImage(ImageType.Logo))
  258. {
  259. var node =
  260. doc.SelectSingleNode("//fanart/movie/movielogos/" + hd + "movielogo[@lang = \"" + language + "\"]/@url") ??
  261. doc.SelectSingleNode("//fanart/movie/movielogos/movielogo[@lang = \"" + language + "\"]/@url");
  262. if (node == null && language != "en")
  263. {
  264. //maybe just couldn't find language - try just first one
  265. node = doc.SelectSingleNode("//fanart/movie/movielogos/" + hd + "movielogo/@url");
  266. }
  267. path = node != null ? node.Value : null;
  268. if (!string.IsNullOrEmpty(path))
  269. {
  270. item.SetImage(ImageType.Logo, await _providerManager.DownloadAndSaveImage(item, path, LogoFile, saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  271. }
  272. }
  273. cancellationToken.ThrowIfCancellationRequested();
  274. if (ConfigurationManager.Configuration.DownloadMovieImages.Art && !item.HasImage(ImageType.Art))
  275. {
  276. var node =
  277. doc.SelectSingleNode("//fanart/movie/moviearts/" + hd + "movieart[@lang = \"" + language + "\"]/@url") ??
  278. doc.SelectSingleNode("//fanart/movie/moviearts/" + hd + "movieart/@url") ??
  279. doc.SelectSingleNode("//fanart/movie/moviearts/movieart[@lang = \"" + language + "\"]/@url") ??
  280. doc.SelectSingleNode("//fanart/movie/moviearts/movieart/@url");
  281. path = node != null ? node.Value : null;
  282. if (!string.IsNullOrEmpty(path))
  283. {
  284. item.SetImage(ImageType.Art, await _providerManager.DownloadAndSaveImage(item, path, ArtFile, saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  285. }
  286. }
  287. cancellationToken.ThrowIfCancellationRequested();
  288. if (ConfigurationManager.Configuration.DownloadMovieImages.Disc && !item.HasImage(ImageType.Disc))
  289. {
  290. var node = doc.SelectSingleNode("//fanart/movie/moviediscs/moviedisc[@lang = \"" + language + "\"]/@url") ??
  291. doc.SelectSingleNode("//fanart/movie/moviediscs/moviedisc/@url");
  292. path = node != null ? node.Value : null;
  293. if (!string.IsNullOrEmpty(path))
  294. {
  295. item.SetImage(ImageType.Disc, await _providerManager.DownloadAndSaveImage(item, path, DiscFile, saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  296. }
  297. }
  298. cancellationToken.ThrowIfCancellationRequested();
  299. if (ConfigurationManager.Configuration.DownloadMovieImages.Banner && !item.HasImage(ImageType.Banner))
  300. {
  301. var node = doc.SelectSingleNode("//fanart/movie/moviebanners/moviebanner[@lang = \"" + language + "\"]/@url") ??
  302. doc.SelectSingleNode("//fanart/movie/moviebanners/moviebanner/@url");
  303. path = node != null ? node.Value : null;
  304. if (!string.IsNullOrEmpty(path))
  305. {
  306. item.SetImage(ImageType.Banner, await _providerManager.DownloadAndSaveImage(item, path, BannerFile, saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  307. }
  308. }
  309. cancellationToken.ThrowIfCancellationRequested();
  310. if (ConfigurationManager.Configuration.DownloadMovieImages.Thumb && !item.HasImage(ImageType.Thumb))
  311. {
  312. var node = doc.SelectSingleNode("//fanart/movie/moviethumbs/moviethumb[@lang = \"" + language + "\"]/@url") ??
  313. doc.SelectSingleNode("//fanart/movie/moviethumbs/moviethumb/@url");
  314. path = node != null ? node.Value : null;
  315. if (!string.IsNullOrEmpty(path))
  316. {
  317. item.SetImage(ImageType.Thumb, await _providerManager.DownloadAndSaveImage(item, path, ThumbFile, saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  318. }
  319. }
  320. if (ConfigurationManager.Configuration.DownloadMovieImages.Backdrops && item.BackdropImagePaths.Count == 0)
  321. {
  322. var nodes = doc.SelectNodes("//fanart/movie/moviebackgrounds//@url");
  323. if (nodes != null)
  324. {
  325. var numBackdrops = item.BackdropImagePaths.Count;
  326. foreach (XmlNode node in nodes)
  327. {
  328. path = node.Value;
  329. if (!string.IsNullOrEmpty(path))
  330. {
  331. item.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(item, path, ("backdrop" + (numBackdrops > 0 ? numBackdrops.ToString(UsCulture) : "") + ".jpg"), saveLocal, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  332. numBackdrops++;
  333. if (item.BackdropImagePaths.Count >= ConfigurationManager.Configuration.MaxBackdrops) break;
  334. }
  335. }
  336. }
  337. }
  338. }
  339. }
  340. }