MovieDbImagesProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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.Providers;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  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.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.Last; }
  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. /// Gets a value indicating whether [refresh on version change].
  91. /// </summary>
  92. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  93. protected override bool RefreshOnVersionChange
  94. {
  95. get
  96. {
  97. return true;
  98. }
  99. }
  100. /// <summary>
  101. /// Gets the provider version.
  102. /// </summary>
  103. /// <value>The provider version.</value>
  104. protected override string ProviderVersion
  105. {
  106. get
  107. {
  108. return "3";
  109. }
  110. }
  111. /// <summary>
  112. /// Needses the refresh internal.
  113. /// </summary>
  114. /// <param name="item">The item.</param>
  115. /// <param name="providerInfo">The provider info.</param>
  116. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  117. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  118. {
  119. if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb)))
  120. {
  121. return false;
  122. }
  123. // Don't refresh if we already have both poster and backdrop and we're not refreshing images
  124. if (item.HasImage(ImageType.Primary) && item.BackdropImagePaths.Count > 0)
  125. {
  126. return false;
  127. }
  128. return base.NeedsRefreshInternal(item, providerInfo);
  129. }
  130. /// <summary>
  131. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  132. /// </summary>
  133. /// <param name="item">The item.</param>
  134. /// <param name="force">if set to <c>true</c> [force].</param>
  135. /// <param name="cancellationToken">The cancellation token</param>
  136. /// <returns>Task{System.Boolean}.</returns>
  137. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  138. {
  139. BaseProviderInfo data;
  140. if (!item.ProviderData.TryGetValue(Id, out data))
  141. {
  142. data = new BaseProviderInfo();
  143. item.ProviderData[Id] = data;
  144. }
  145. var images = await FetchImages(item, item.GetProviderId(MetadataProviders.Tmdb), cancellationToken).ConfigureAwait(false);
  146. var status = await ProcessImages(item, images, cancellationToken).ConfigureAwait(false);
  147. SetLastRefreshed(item, DateTime.UtcNow, status);
  148. return true;
  149. }
  150. /// <summary>
  151. /// Fetches the images.
  152. /// </summary>
  153. /// <param name="item">The item.</param>
  154. /// <param name="id">The id.</param>
  155. /// <param name="cancellationToken">The cancellation token.</param>
  156. /// <returns>Task{MovieImages}.</returns>
  157. private async Task<MovieImages> FetchImages(BaseItem item, string id, CancellationToken cancellationToken)
  158. {
  159. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  160. {
  161. Url = string.Format(GetImages, id, MovieDbProvider.ApiKey, item is BoxSet ? "collection" : "movie"),
  162. CancellationToken = cancellationToken,
  163. AcceptHeader = MovieDbProvider.AcceptHeader
  164. }).ConfigureAwait(false))
  165. {
  166. return _jsonSerializer.DeserializeFromStream<MovieImages>(json);
  167. }
  168. }
  169. /// <summary>
  170. /// Processes the images.
  171. /// </summary>
  172. /// <param name="item">The item.</param>
  173. /// <param name="images">The images.</param>
  174. /// <param name="cancellationToken">The cancellation token</param>
  175. /// <returns>Task.</returns>
  176. protected virtual async Task<ProviderRefreshStatus> ProcessImages(BaseItem item, MovieImages images, CancellationToken cancellationToken)
  177. {
  178. cancellationToken.ThrowIfCancellationRequested();
  179. var status = ProviderRefreshStatus.Success;
  180. // poster
  181. if (images.posters != null && images.posters.Count > 0 && !item.HasImage(ImageType.Primary))
  182. {
  183. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  184. var tmdbImageUrl = tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedPosterSize;
  185. // get highest rated poster for our language
  186. var postersSortedByVote = images.posters.OrderByDescending(i => i.vote_average);
  187. var poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals(ConfigurationManager.Configuration.PreferredMetadataLanguage, StringComparison.OrdinalIgnoreCase));
  188. if (poster == null && !ConfigurationManager.Configuration.PreferredMetadataLanguage.Equals("en"))
  189. {
  190. // couldn't find our specific language, find english (if that wasn't our language)
  191. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 != null && p.iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase));
  192. }
  193. if (poster == null)
  194. {
  195. //still couldn't find it - try highest rated null one
  196. poster = postersSortedByVote.FirstOrDefault(p => p.iso_639_1 == null);
  197. }
  198. if (poster == null)
  199. {
  200. //finally - just get the highest rated one
  201. poster = postersSortedByVote.FirstOrDefault();
  202. }
  203. if (poster != null)
  204. {
  205. var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  206. {
  207. Url = tmdbImageUrl + poster.file_path,
  208. CancellationToken = cancellationToken
  209. }).ConfigureAwait(false);
  210. item.PrimaryImagePath = await _providerManager.SaveImage(item, img, "folder" + Path.GetExtension(poster.file_path), ConfigurationManager.Configuration.SaveLocalMeta && item.LocationType == LocationType.FileSystem, cancellationToken).ConfigureAwait(false);
  211. }
  212. }
  213. cancellationToken.ThrowIfCancellationRequested();
  214. // backdrops - only download if earlier providers didn't find any (fanart)
  215. if (images.backdrops != null && images.backdrops.Count > 0 && ConfigurationManager.Configuration.DownloadMovieImages.Backdrops && item.BackdropImagePaths.Count == 0)
  216. {
  217. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  218. var tmdbImageUrl = tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedBackdropSize;
  219. for (var i = 0; i < images.backdrops.Count; i++)
  220. {
  221. var bdName = "backdrop" + (i == 0 ? "" : i.ToString(CultureInfo.InvariantCulture));
  222. var hasLocalBackdrop = item.LocationType == LocationType.FileSystem && ConfigurationManager.Configuration.SaveLocalMeta ? item.HasLocalImage(bdName) : item.BackdropImagePaths.Count > i;
  223. if (!hasLocalBackdrop)
  224. {
  225. var img = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  226. {
  227. Url = tmdbImageUrl + images.backdrops[i].file_path,
  228. CancellationToken = cancellationToken
  229. }).ConfigureAwait(false);
  230. 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));
  231. }
  232. if (item.BackdropImagePaths.Count >= ConfigurationManager.Configuration.MaxBackdrops)
  233. {
  234. break;
  235. }
  236. }
  237. }
  238. return status;
  239. }
  240. /// <summary>
  241. /// Class Backdrop
  242. /// </summary>
  243. protected class Backdrop
  244. {
  245. /// <summary>
  246. /// Gets or sets the file_path.
  247. /// </summary>
  248. /// <value>The file_path.</value>
  249. public string file_path { get; set; }
  250. /// <summary>
  251. /// Gets or sets the width.
  252. /// </summary>
  253. /// <value>The width.</value>
  254. public int width { get; set; }
  255. /// <summary>
  256. /// Gets or sets the height.
  257. /// </summary>
  258. /// <value>The height.</value>
  259. public int height { get; set; }
  260. /// <summary>
  261. /// Gets or sets the iso_639_1.
  262. /// </summary>
  263. /// <value>The iso_639_1.</value>
  264. public string iso_639_1 { get; set; }
  265. /// <summary>
  266. /// Gets or sets the aspect_ratio.
  267. /// </summary>
  268. /// <value>The aspect_ratio.</value>
  269. public double aspect_ratio { get; set; }
  270. /// <summary>
  271. /// Gets or sets the vote_average.
  272. /// </summary>
  273. /// <value>The vote_average.</value>
  274. public double vote_average { get; set; }
  275. /// <summary>
  276. /// Gets or sets the vote_count.
  277. /// </summary>
  278. /// <value>The vote_count.</value>
  279. public int vote_count { get; set; }
  280. }
  281. /// <summary>
  282. /// Class Poster
  283. /// </summary>
  284. protected class Poster
  285. {
  286. /// <summary>
  287. /// Gets or sets the file_path.
  288. /// </summary>
  289. /// <value>The file_path.</value>
  290. public string file_path { get; set; }
  291. /// <summary>
  292. /// Gets or sets the width.
  293. /// </summary>
  294. /// <value>The width.</value>
  295. public int width { get; set; }
  296. /// <summary>
  297. /// Gets or sets the height.
  298. /// </summary>
  299. /// <value>The height.</value>
  300. public int height { get; set; }
  301. /// <summary>
  302. /// Gets or sets the iso_639_1.
  303. /// </summary>
  304. /// <value>The iso_639_1.</value>
  305. public string iso_639_1 { get; set; }
  306. /// <summary>
  307. /// Gets or sets the aspect_ratio.
  308. /// </summary>
  309. /// <value>The aspect_ratio.</value>
  310. public double aspect_ratio { get; set; }
  311. /// <summary>
  312. /// Gets or sets the vote_average.
  313. /// </summary>
  314. /// <value>The vote_average.</value>
  315. public double vote_average { get; set; }
  316. /// <summary>
  317. /// Gets or sets the vote_count.
  318. /// </summary>
  319. /// <value>The vote_count.</value>
  320. public int vote_count { get; set; }
  321. }
  322. /// <summary>
  323. /// Class MovieImages
  324. /// </summary>
  325. protected class MovieImages
  326. {
  327. /// <summary>
  328. /// Gets or sets the backdrops.
  329. /// </summary>
  330. /// <value>The backdrops.</value>
  331. public List<Backdrop> backdrops { get; set; }
  332. /// <summary>
  333. /// Gets or sets the posters.
  334. /// </summary>
  335. /// <value>The posters.</value>
  336. public List<Poster> posters { get; set; }
  337. }
  338. }
  339. }