MovieDbImagesProvider.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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 || item is MusicVideo;
  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. // Don't refresh if we already have both poster and backdrop and we're not refreshing images
  140. if (!ConfigurationManager.Configuration.RefreshItemImages && item.HasImage(ImageType.Primary) && item.BackdropImagePaths.Count > 0)
  141. {
  142. return false;
  143. }
  144. return base.NeedsRefreshInternal(item, providerInfo);
  145. }
  146. /// <summary>
  147. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  148. /// </summary>
  149. /// <param name="item">The item.</param>
  150. /// <param name="force">if set to <c>true</c> [force].</param>
  151. /// <param name="cancellationToken">The cancellation token</param>
  152. /// <returns>Task{System.Boolean}.</returns>
  153. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  154. {
  155. BaseProviderInfo data;
  156. if (!item.ProviderData.TryGetValue(Id, out data))
  157. {
  158. data = new BaseProviderInfo();
  159. item.ProviderData[Id] = data;
  160. }
  161. var images = await FetchImages(item, item.GetProviderId(MetadataProviders.Tmdb), cancellationToken).ConfigureAwait(false);
  162. var status = await ProcessImages(item, images, cancellationToken).ConfigureAwait(false);
  163. data.Data = GetComparisonData(item.GetProviderId(MetadataProviders.Tmdb));
  164. SetLastRefreshed(item, DateTime.UtcNow, status);
  165. return true;
  166. }
  167. /// <summary>
  168. /// Gets the comparison data.
  169. /// </summary>
  170. /// <returns>Guid.</returns>
  171. private Guid GetComparisonData(string id)
  172. {
  173. return string.IsNullOrEmpty(id) ? Guid.Empty : id.GetMD5();
  174. }
  175. /// <summary>
  176. /// Fetches the images.
  177. /// </summary>
  178. /// <param name="item">The item.</param>
  179. /// <param name="id">The id.</param>
  180. /// <param name="cancellationToken">The cancellation token.</param>
  181. /// <returns>Task{MovieImages}.</returns>
  182. private async Task<MovieImages> FetchImages(BaseItem item, string id, CancellationToken cancellationToken)
  183. {
  184. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  185. {
  186. Url = string.Format(GetImages, id, MovieDbProvider.ApiKey, item is BoxSet ? "collection" : "movie"),
  187. CancellationToken = cancellationToken,
  188. AcceptHeader = MovieDbProvider.AcceptHeader
  189. }).ConfigureAwait(false))
  190. {
  191. return _jsonSerializer.DeserializeFromStream<MovieImages>(json);
  192. }
  193. }
  194. /// <summary>
  195. /// Processes the images.
  196. /// </summary>
  197. /// <param name="item">The item.</param>
  198. /// <param name="images">The images.</param>
  199. /// <param name="cancellationToken">The cancellation token</param>
  200. /// <returns>Task.</returns>
  201. protected virtual async Task<ProviderRefreshStatus> ProcessImages(BaseItem item, MovieImages images, CancellationToken cancellationToken)
  202. {
  203. cancellationToken.ThrowIfCancellationRequested();
  204. var status = ProviderRefreshStatus.Success;
  205. var hasLocalPoster = item.HasImage(ImageType.Primary);
  206. // poster
  207. if (images.posters != null && images.posters.Count > 0 && (ConfigurationManager.Configuration.RefreshItemImages || !hasLocalPoster))
  208. {
  209. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  210. var tmdbImageUrl = tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedPosterSize;
  211. // get highest rated poster for our language
  212. var postersSortedByVote = images.posters.OrderByDescending(i => i.vote_average);
  213. var poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals(ConfigurationManager.Configuration.PreferredMetadataLanguage, StringComparison.OrdinalIgnoreCase));
  214. if (poster == null && !ConfigurationManager.Configuration.PreferredMetadataLanguage.Equals("en"))
  215. {
  216. // couldn't find our specific language, find english (if that wasn't our language)
  217. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase));
  218. }
  219. if (poster == null)
  220. {
  221. //still couldn't find it - try highest rated null one
  222. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 == null);
  223. }
  224. if (poster == null)
  225. {
  226. //finally - just get the highest rated one
  227. poster = postersSortedByVote.FirstOrDefault();
  228. }
  229. if (poster != null)
  230. {
  231. var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  232. {
  233. Url = tmdbImageUrl + poster.file_path,
  234. CancellationToken = cancellationToken
  235. }).ConfigureAwait(false);
  236. item.PrimaryImagePath = await _providerManager.SaveImage(item, img, "folder" + Path.GetExtension(poster.file_path), ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem, cancellationToken).ConfigureAwait(false);
  237. }
  238. }
  239. cancellationToken.ThrowIfCancellationRequested();
  240. // backdrops - only download if earlier providers didn't find any (fanart)
  241. if (images.backdrops != null && images.backdrops.Count > 0 && ConfigurationManager.Configuration.DownloadMovieImages.Backdrops && item.BackdropImagePaths.Count == 0)
  242. {
  243. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).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.Max(images.backdrops.Count - ConfigurationManager.Configuration.MaxBackdrops, 0);
  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 && ConfigurationManager.Configuration.SaveLocalMeta ? item.HasLocalImage(bdName) : item.BackdropImagePaths.Count > i;
  251. if (ConfigurationManager.Configuration.RefreshItemImages || !hasLocalBackdrop)
  252. {
  253. var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  254. {
  255. Url = tmdbImageUrl + images.backdrops[i].file_path,
  256. CancellationToken = cancellationToken
  257. }).ConfigureAwait(false);
  258. item.BackdropImagePaths.Add(await _providerManager.SaveImage(item, img, bdName + Path.GetExtension(images.backdrops[i].file_path), ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem, cancellationToken).ConfigureAwait(false));
  259. }
  260. }
  261. }
  262. return status;
  263. }
  264. /// <summary>
  265. /// Class Backdrop
  266. /// </summary>
  267. protected class Backdrop
  268. {
  269. /// <summary>
  270. /// Gets or sets the file_path.
  271. /// </summary>
  272. /// <value>The file_path.</value>
  273. public string file_path { get; set; }
  274. /// <summary>
  275. /// Gets or sets the width.
  276. /// </summary>
  277. /// <value>The width.</value>
  278. public int width { get; set; }
  279. /// <summary>
  280. /// Gets or sets the height.
  281. /// </summary>
  282. /// <value>The height.</value>
  283. public int height { get; set; }
  284. /// <summary>
  285. /// Gets or sets the iso_639_1.
  286. /// </summary>
  287. /// <value>The iso_639_1.</value>
  288. public string iso_639_1 { get; set; }
  289. /// <summary>
  290. /// Gets or sets the aspect_ratio.
  291. /// </summary>
  292. /// <value>The aspect_ratio.</value>
  293. public double aspect_ratio { get; set; }
  294. /// <summary>
  295. /// Gets or sets the vote_average.
  296. /// </summary>
  297. /// <value>The vote_average.</value>
  298. public double vote_average { get; set; }
  299. /// <summary>
  300. /// Gets or sets the vote_count.
  301. /// </summary>
  302. /// <value>The vote_count.</value>
  303. public int vote_count { get; set; }
  304. }
  305. /// <summary>
  306. /// Class Poster
  307. /// </summary>
  308. protected class Poster
  309. {
  310. /// <summary>
  311. /// Gets or sets the file_path.
  312. /// </summary>
  313. /// <value>The file_path.</value>
  314. public string file_path { get; set; }
  315. /// <summary>
  316. /// Gets or sets the width.
  317. /// </summary>
  318. /// <value>The width.</value>
  319. public int width { get; set; }
  320. /// <summary>
  321. /// Gets or sets the height.
  322. /// </summary>
  323. /// <value>The height.</value>
  324. public int height { get; set; }
  325. /// <summary>
  326. /// Gets or sets the iso_639_1.
  327. /// </summary>
  328. /// <value>The iso_639_1.</value>
  329. public string iso_639_1 { get; set; }
  330. /// <summary>
  331. /// Gets or sets the aspect_ratio.
  332. /// </summary>
  333. /// <value>The aspect_ratio.</value>
  334. public double aspect_ratio { get; set; }
  335. /// <summary>
  336. /// Gets or sets the vote_average.
  337. /// </summary>
  338. /// <value>The vote_average.</value>
  339. public double vote_average { get; set; }
  340. /// <summary>
  341. /// Gets or sets the vote_count.
  342. /// </summary>
  343. /// <value>The vote_count.</value>
  344. public int vote_count { get; set; }
  345. }
  346. /// <summary>
  347. /// Class MovieImages
  348. /// </summary>
  349. protected class MovieImages
  350. {
  351. /// <summary>
  352. /// Gets or sets the backdrops.
  353. /// </summary>
  354. /// <value>The backdrops.</value>
  355. public List<Backdrop> backdrops { get; set; }
  356. /// <summary>
  357. /// Gets or sets the posters.
  358. /// </summary>
  359. /// <value>The posters.</value>
  360. public List<Poster> posters { get; set; }
  361. }
  362. }
  363. }