MovieDbImagesProvider.cs 15 KB

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