MovieDbImagesProvider.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Controller.Providers.Movies
  18. {
  19. /// <summary>
  20. /// Class MovieDbImagesProvider
  21. /// </summary>
  22. public class MovieDbImagesProvider : BaseMetadataProvider
  23. {
  24. /// <summary>
  25. /// The get images
  26. /// </summary>
  27. private const string GetImages = @"http://api.themoviedb.org/3/{2}/{0}/images?api_key={1}";
  28. /// <summary>
  29. /// The _provider manager
  30. /// </summary>
  31. private readonly IProviderManager _providerManager;
  32. /// <summary>
  33. /// The _json serializer
  34. /// </summary>
  35. private readonly IJsonSerializer _jsonSerializer;
  36. /// <summary>
  37. /// The _HTTP client
  38. /// </summary>
  39. private readonly IHttpClient _httpClient;
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="MovieDbImagesProvider"/> class.
  42. /// </summary>
  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. /// <param name="jsonSerializer">The json serializer.</param>
  47. /// <param name="httpClient">The HTTP client.</param>
  48. public MovieDbImagesProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager, IJsonSerializer jsonSerializer, IHttpClient httpClient)
  49. : base(logManager, configurationManager)
  50. {
  51. _providerManager = providerManager;
  52. _jsonSerializer = jsonSerializer;
  53. _httpClient = httpClient;
  54. }
  55. /// <summary>
  56. /// Gets the priority.
  57. /// </summary>
  58. /// <value>The priority.</value>
  59. public override MetadataProviderPriority Priority
  60. {
  61. get { return MetadataProviderPriority.Fourth; }
  62. }
  63. /// <summary>
  64. /// Supports the specified item.
  65. /// </summary>
  66. /// <param name="item">The item.</param>
  67. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  68. public override bool Supports(BaseItem item)
  69. {
  70. var trailer = item as Trailer;
  71. if (trailer != null)
  72. {
  73. return !trailer.IsLocalTrailer;
  74. }
  75. // Don't support local trailers
  76. return item is Movie || item is BoxSet;
  77. }
  78. /// <summary>
  79. /// Gets a value indicating whether [requires internet].
  80. /// </summary>
  81. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  82. public override bool RequiresInternet
  83. {
  84. get
  85. {
  86. return true;
  87. }
  88. }
  89. /// <summary>
  90. /// If we save locally, refresh if they delete something
  91. /// </summary>
  92. /// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
  93. protected override bool RefreshOnFileSystemStampChange
  94. {
  95. get
  96. {
  97. return ConfigurationManager.Configuration.SaveLocalMeta;
  98. }
  99. }
  100. /// <summary>
  101. /// Gets a value indicating whether [refresh on version change].
  102. /// </summary>
  103. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  104. protected override bool RefreshOnVersionChange
  105. {
  106. get
  107. {
  108. return true;
  109. }
  110. }
  111. /// <summary>
  112. /// Gets the provider version.
  113. /// </summary>
  114. /// <value>The provider version.</value>
  115. protected override string ProviderVersion
  116. {
  117. get
  118. {
  119. return "3";
  120. }
  121. }
  122. /// <summary>
  123. /// Needses the refresh internal.
  124. /// </summary>
  125. /// <param name="item">The item.</param>
  126. /// <param name="providerInfo">The provider info.</param>
  127. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  128. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  129. {
  130. if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb)))
  131. {
  132. return false;
  133. }
  134. // Refresh if tmdb id has changed
  135. if (providerInfo.Data != GetComparisonData(item.GetProviderId(MetadataProviders.Tmdb)))
  136. {
  137. return true;
  138. }
  139. return base.NeedsRefreshInternal(item, providerInfo);
  140. }
  141. /// <summary>
  142. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  143. /// </summary>
  144. /// <param name="item">The item.</param>
  145. /// <param name="force">if set to <c>true</c> [force].</param>
  146. /// <param name="cancellationToken">The cancellation token</param>
  147. /// <returns>Task{System.Boolean}.</returns>
  148. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  149. {
  150. BaseProviderInfo data;
  151. if (!item.ProviderData.TryGetValue(Id, out data))
  152. {
  153. data = new BaseProviderInfo();
  154. item.ProviderData[Id] = data;
  155. }
  156. var images = await FetchImages(item, item.GetProviderId(MetadataProviders.Tmdb), cancellationToken).ConfigureAwait(false);
  157. var status = await ProcessImages(item, images, cancellationToken).ConfigureAwait(false);
  158. data.Data = GetComparisonData(item.GetProviderId(MetadataProviders.Tmdb));
  159. SetLastRefreshed(item, DateTime.UtcNow, status);
  160. return true;
  161. }
  162. /// <summary>
  163. /// Gets the comparison data.
  164. /// </summary>
  165. /// <returns>Guid.</returns>
  166. private Guid GetComparisonData(string id)
  167. {
  168. return string.IsNullOrEmpty(id) ? Guid.Empty : id.GetMD5();
  169. }
  170. /// <summary>
  171. /// Fetches the images.
  172. /// </summary>
  173. /// <param name="item">The item.</param>
  174. /// <param name="id">The id.</param>
  175. /// <param name="cancellationToken">The cancellation token.</param>
  176. /// <returns>Task{MovieImages}.</returns>
  177. private async Task<MovieImages> FetchImages(BaseItem item, string id, CancellationToken cancellationToken)
  178. {
  179. using (var json = await _httpClient.Get(new HttpRequestOptions
  180. {
  181. Url = string.Format(GetImages, id, MovieDbProvider.ApiKey, item is BoxSet ? "collection" : "movie"),
  182. CancellationToken = cancellationToken,
  183. ResourcePool = MovieDbProvider.Current.MovieDbResourcePool,
  184. AcceptHeader = MovieDbProvider.AcceptHeader,
  185. EnableResponseCache = true
  186. }).ConfigureAwait(false))
  187. {
  188. return _jsonSerializer.DeserializeFromStream<MovieImages>(json);
  189. }
  190. }
  191. /// <summary>
  192. /// Processes the images.
  193. /// </summary>
  194. /// <param name="item">The item.</param>
  195. /// <param name="images">The images.</param>
  196. /// <param name="cancellationToken">The cancellation token</param>
  197. /// <returns>Task.</returns>
  198. protected virtual async Task<ProviderRefreshStatus> ProcessImages(BaseItem item, MovieImages images, CancellationToken cancellationToken)
  199. {
  200. cancellationToken.ThrowIfCancellationRequested();
  201. var status = ProviderRefreshStatus.Success;
  202. var hasLocalPoster = item.LocationType == LocationType.FileSystem ? item.HasLocalImage("folder") : item.HasImage(ImageType.Primary);
  203. // poster
  204. if (images.posters != null && images.posters.Count > 0 && (ConfigurationManager.Configuration.RefreshItemImages || !hasLocalPoster))
  205. {
  206. var tmdbSettings = await MovieDbProvider.Current.TmdbSettings.ConfigureAwait(false);
  207. var tmdbImageUrl = tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedPosterSize;
  208. // get highest rated poster for our language
  209. var postersSortedByVote = images.posters.OrderByDescending(i => i.vote_average);
  210. var poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals(ConfigurationManager.Configuration.PreferredMetadataLanguage, StringComparison.OrdinalIgnoreCase));
  211. if (poster == null && !ConfigurationManager.Configuration.PreferredMetadataLanguage.Equals("en"))
  212. {
  213. // couldn't find our specific language, find english (if that wasn't our language)
  214. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase));
  215. }
  216. if (poster == null)
  217. {
  218. //still couldn't find it - try highest rated null one
  219. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 == null);
  220. }
  221. if (poster == null)
  222. {
  223. //finally - just get the highest rated one
  224. poster = postersSortedByVote.FirstOrDefault();
  225. }
  226. if (poster != null)
  227. {
  228. try
  229. {
  230. item.PrimaryImagePath = await _providerManager.DownloadAndSaveImage(item, tmdbImageUrl + poster.file_path, "folder" + Path.GetExtension(poster.file_path), ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem, MovieDbProvider.Current.MovieDbResourcePool, cancellationToken).ConfigureAwait(false);
  231. }
  232. catch (HttpException)
  233. {
  234. status = ProviderRefreshStatus.CompletedWithErrors;
  235. }
  236. }
  237. }
  238. cancellationToken.ThrowIfCancellationRequested();
  239. // backdrops - only download if earlier providers didn't find any (fanart)
  240. if (images.backdrops != null && images.backdrops.Count > 0 && ConfigurationManager.Configuration.DownloadMovieImages.Backdrops && item.BackdropImagePaths.Count == 0)
  241. {
  242. item.BackdropImagePaths = new List<string>();
  243. var tmdbSettings = await MovieDbProvider.Current.TmdbSettings.ConfigureAwait(false);
  244. var tmdbImageUrl = tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedBackdropSize;
  245. //backdrops should be in order of rating. get first n ones
  246. var numToFetch = Math.Min(ConfigurationManager.Configuration.MaxBackdrops, images.backdrops.Count);
  247. for (var i = 0; i < numToFetch; i++)
  248. {
  249. var bdName = "backdrop" + (i == 0 ? "" : i.ToString(CultureInfo.InvariantCulture));
  250. var hasLocalBackdrop = item.LocationType == LocationType.FileSystem ? item.HasLocalImage(bdName) : item.BackdropImagePaths.Count > i;
  251. if (ConfigurationManager.Configuration.RefreshItemImages || !hasLocalBackdrop)
  252. {
  253. try
  254. {
  255. item.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(item, tmdbImageUrl + images.backdrops[i].file_path, bdName + Path.GetExtension(images.backdrops[i].file_path), ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem, MovieDbProvider.Current.MovieDbResourcePool, cancellationToken).ConfigureAwait(false));
  256. }
  257. catch (HttpException)
  258. {
  259. status = ProviderRefreshStatus.CompletedWithErrors;
  260. }
  261. }
  262. }
  263. }
  264. return status;
  265. }
  266. /// <summary>
  267. /// Class Backdrop
  268. /// </summary>
  269. protected class Backdrop
  270. {
  271. /// <summary>
  272. /// Gets or sets the file_path.
  273. /// </summary>
  274. /// <value>The file_path.</value>
  275. public string file_path { get; set; }
  276. /// <summary>
  277. /// Gets or sets the width.
  278. /// </summary>
  279. /// <value>The width.</value>
  280. public int width { get; set; }
  281. /// <summary>
  282. /// Gets or sets the height.
  283. /// </summary>
  284. /// <value>The height.</value>
  285. public int height { get; set; }
  286. /// <summary>
  287. /// Gets or sets the iso_639_1.
  288. /// </summary>
  289. /// <value>The iso_639_1.</value>
  290. public string iso_639_1 { get; set; }
  291. /// <summary>
  292. /// Gets or sets the aspect_ratio.
  293. /// </summary>
  294. /// <value>The aspect_ratio.</value>
  295. public double aspect_ratio { get; set; }
  296. /// <summary>
  297. /// Gets or sets the vote_average.
  298. /// </summary>
  299. /// <value>The vote_average.</value>
  300. public double vote_average { get; set; }
  301. /// <summary>
  302. /// Gets or sets the vote_count.
  303. /// </summary>
  304. /// <value>The vote_count.</value>
  305. public int vote_count { get; set; }
  306. }
  307. /// <summary>
  308. /// Class Poster
  309. /// </summary>
  310. protected class Poster
  311. {
  312. /// <summary>
  313. /// Gets or sets the file_path.
  314. /// </summary>
  315. /// <value>The file_path.</value>
  316. public string file_path { get; set; }
  317. /// <summary>
  318. /// Gets or sets the width.
  319. /// </summary>
  320. /// <value>The width.</value>
  321. public int width { get; set; }
  322. /// <summary>
  323. /// Gets or sets the height.
  324. /// </summary>
  325. /// <value>The height.</value>
  326. public int height { get; set; }
  327. /// <summary>
  328. /// Gets or sets the iso_639_1.
  329. /// </summary>
  330. /// <value>The iso_639_1.</value>
  331. public string iso_639_1 { get; set; }
  332. /// <summary>
  333. /// Gets or sets the aspect_ratio.
  334. /// </summary>
  335. /// <value>The aspect_ratio.</value>
  336. public double aspect_ratio { get; set; }
  337. /// <summary>
  338. /// Gets or sets the vote_average.
  339. /// </summary>
  340. /// <value>The vote_average.</value>
  341. public double vote_average { get; set; }
  342. /// <summary>
  343. /// Gets or sets the vote_count.
  344. /// </summary>
  345. /// <value>The vote_count.</value>
  346. public int vote_count { get; set; }
  347. }
  348. /// <summary>
  349. /// Class MovieImages
  350. /// </summary>
  351. protected class MovieImages
  352. {
  353. /// <summary>
  354. /// Gets or sets the backdrops.
  355. /// </summary>
  356. /// <value>The backdrops.</value>
  357. public List<Backdrop> backdrops { get; set; }
  358. /// <summary>
  359. /// Gets or sets the posters.
  360. /// </summary>
  361. /// <value>The posters.</value>
  362. public List<Poster> posters { get; set; }
  363. }
  364. }
  365. }