TmdbClientManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Data.Enums;
  7. using MediaBrowser.Model.Dto;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Providers;
  10. using Microsoft.Extensions.Caching.Memory;
  11. using TMDbLib.Client;
  12. using TMDbLib.Objects.Collections;
  13. using TMDbLib.Objects.Find;
  14. using TMDbLib.Objects.General;
  15. using TMDbLib.Objects.Movies;
  16. using TMDbLib.Objects.People;
  17. using TMDbLib.Objects.Search;
  18. using TMDbLib.Objects.TvShows;
  19. namespace MediaBrowser.Providers.Plugins.Tmdb
  20. {
  21. /// <summary>
  22. /// Manager class for abstracting the TMDb API client library.
  23. /// </summary>
  24. public class TmdbClientManager : IDisposable
  25. {
  26. private const int CacheDurationInHours = 1;
  27. private readonly IMemoryCache _memoryCache;
  28. private readonly TMDbClient _tmDbClient;
  29. /// <summary>
  30. /// Initializes a new instance of the <see cref="TmdbClientManager"/> class.
  31. /// </summary>
  32. /// <param name="memoryCache">An instance of <see cref="IMemoryCache"/>.</param>
  33. public TmdbClientManager(IMemoryCache memoryCache)
  34. {
  35. _memoryCache = memoryCache;
  36. _tmDbClient = new TMDbClient(TmdbUtils.ApiKey);
  37. // Not really interested in NotFoundException
  38. _tmDbClient.ThrowApiExceptions = false;
  39. }
  40. /// <summary>
  41. /// Gets a movie from the TMDb API based on its TMDb id.
  42. /// </summary>
  43. /// <param name="tmdbId">The movie's TMDb id.</param>
  44. /// <param name="language">The movie's language.</param>
  45. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  46. /// <param name="cancellationToken">The cancellation token.</param>
  47. /// <returns>The TMDb movie or null if not found.</returns>
  48. public async Task<Movie?> GetMovieAsync(int tmdbId, string? language, string? imageLanguages, CancellationToken cancellationToken)
  49. {
  50. var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  51. if (_memoryCache.TryGetValue(key, out Movie? movie))
  52. {
  53. return movie;
  54. }
  55. await EnsureClientConfigAsync().ConfigureAwait(false);
  56. var extraMethods = MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Videos;
  57. if (!(Plugin.Instance?.Configuration.ExcludeTagsMovies).GetValueOrDefault())
  58. {
  59. extraMethods |= MovieMethods.Keywords;
  60. }
  61. movie = await _tmDbClient.GetMovieAsync(
  62. tmdbId,
  63. TmdbUtils.NormalizeLanguage(language),
  64. imageLanguages,
  65. extraMethods,
  66. cancellationToken).ConfigureAwait(false);
  67. if (movie is not null)
  68. {
  69. _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
  70. }
  71. return movie;
  72. }
  73. /// <summary>
  74. /// Gets a collection from the TMDb API based on its TMDb id.
  75. /// </summary>
  76. /// <param name="tmdbId">The collection's TMDb id.</param>
  77. /// <param name="language">The collection's language.</param>
  78. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  79. /// <param name="cancellationToken">The cancellation token.</param>
  80. /// <returns>The TMDb collection or null if not found.</returns>
  81. public async Task<Collection?> GetCollectionAsync(int tmdbId, string? language, string? imageLanguages, CancellationToken cancellationToken)
  82. {
  83. var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  84. if (_memoryCache.TryGetValue(key, out Collection? collection))
  85. {
  86. return collection;
  87. }
  88. await EnsureClientConfigAsync().ConfigureAwait(false);
  89. collection = await _tmDbClient.GetCollectionAsync(
  90. tmdbId,
  91. TmdbUtils.NormalizeLanguage(language),
  92. imageLanguages,
  93. CollectionMethods.Images,
  94. cancellationToken).ConfigureAwait(false);
  95. if (collection is not null)
  96. {
  97. _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
  98. }
  99. return collection;
  100. }
  101. /// <summary>
  102. /// Gets a tv show from the TMDb API based on its TMDb id.
  103. /// </summary>
  104. /// <param name="tmdbId">The tv show's TMDb id.</param>
  105. /// <param name="language">The tv show's language.</param>
  106. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  107. /// <param name="cancellationToken">The cancellation token.</param>
  108. /// <returns>The TMDb tv show information or null if not found.</returns>
  109. public async Task<TvShow?> GetSeriesAsync(int tmdbId, string? language, string? imageLanguages, CancellationToken cancellationToken)
  110. {
  111. var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  112. if (_memoryCache.TryGetValue(key, out TvShow? series))
  113. {
  114. return series;
  115. }
  116. await EnsureClientConfigAsync().ConfigureAwait(false);
  117. var extraMethods = TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings | TvShowMethods.EpisodeGroups;
  118. if (!(Plugin.Instance?.Configuration.ExcludeTagsSeries).GetValueOrDefault())
  119. {
  120. extraMethods |= TvShowMethods.Keywords;
  121. }
  122. series = await _tmDbClient.GetTvShowAsync(
  123. tmdbId,
  124. language: TmdbUtils.NormalizeLanguage(language),
  125. includeImageLanguage: imageLanguages,
  126. extraMethods: extraMethods,
  127. cancellationToken: cancellationToken).ConfigureAwait(false);
  128. if (series is not null)
  129. {
  130. _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
  131. }
  132. return series;
  133. }
  134. /// <summary>
  135. /// Gets a tv show episode group from the TMDb API based on the show id and the display order.
  136. /// </summary>
  137. /// <param name="tvShowId">The tv show's TMDb id.</param>
  138. /// <param name="displayOrder">The display order.</param>
  139. /// <param name="language">The tv show's language.</param>
  140. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  141. /// <param name="cancellationToken">The cancellation token.</param>
  142. /// <returns>The TMDb tv show episode group information or null if not found.</returns>
  143. private async Task<TvGroupCollection?> GetSeriesGroupAsync(int tvShowId, string displayOrder, string? language, string? imageLanguages, CancellationToken cancellationToken)
  144. {
  145. TvGroupType? groupType =
  146. string.Equals(displayOrder, "originalAirDate", StringComparison.Ordinal) ? TvGroupType.OriginalAirDate :
  147. string.Equals(displayOrder, "absolute", StringComparison.Ordinal) ? TvGroupType.Absolute :
  148. string.Equals(displayOrder, "dvd", StringComparison.Ordinal) ? TvGroupType.DVD :
  149. string.Equals(displayOrder, "digital", StringComparison.Ordinal) ? TvGroupType.Digital :
  150. string.Equals(displayOrder, "storyArc", StringComparison.Ordinal) ? TvGroupType.StoryArc :
  151. string.Equals(displayOrder, "production", StringComparison.Ordinal) ? TvGroupType.Production :
  152. string.Equals(displayOrder, "tv", StringComparison.Ordinal) ? TvGroupType.TV :
  153. null;
  154. if (groupType is null)
  155. {
  156. return null;
  157. }
  158. var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
  159. if (_memoryCache.TryGetValue(key, out TvGroupCollection? group))
  160. {
  161. return group;
  162. }
  163. await EnsureClientConfigAsync().ConfigureAwait(false);
  164. var series = await GetSeriesAsync(tvShowId, language, imageLanguages, cancellationToken).ConfigureAwait(false);
  165. var episodeGroupId = series?.EpisodeGroups.Results.Find(g => g.Type == groupType)?.Id;
  166. if (episodeGroupId is null)
  167. {
  168. return null;
  169. }
  170. group = await _tmDbClient.GetTvEpisodeGroupsAsync(
  171. episodeGroupId,
  172. language: TmdbUtils.NormalizeLanguage(language),
  173. cancellationToken: cancellationToken).ConfigureAwait(false);
  174. if (group is not null)
  175. {
  176. _memoryCache.Set(key, group, TimeSpan.FromHours(CacheDurationInHours));
  177. }
  178. return group;
  179. }
  180. /// <summary>
  181. /// Gets a tv season from the TMDb API based on the tv show's TMDb id.
  182. /// </summary>
  183. /// <param name="tvShowId">The tv season's TMDb id.</param>
  184. /// <param name="seasonNumber">The season number.</param>
  185. /// <param name="language">The tv season's language.</param>
  186. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>The TMDb tv season information or null if not found.</returns>
  189. public async Task<TvSeason?> GetSeasonAsync(int tvShowId, int seasonNumber, string? language, string? imageLanguages, CancellationToken cancellationToken)
  190. {
  191. var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
  192. if (_memoryCache.TryGetValue(key, out TvSeason? season))
  193. {
  194. return season;
  195. }
  196. await EnsureClientConfigAsync().ConfigureAwait(false);
  197. season = await _tmDbClient.GetTvSeasonAsync(
  198. tvShowId,
  199. seasonNumber,
  200. language: TmdbUtils.NormalizeLanguage(language),
  201. includeImageLanguage: imageLanguages,
  202. extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonMethods.Videos,
  203. cancellationToken: cancellationToken).ConfigureAwait(false);
  204. if (season is not null)
  205. {
  206. _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
  207. }
  208. return season;
  209. }
  210. /// <summary>
  211. /// Gets a movie from the TMDb API based on the tv show's TMDb id.
  212. /// </summary>
  213. /// <param name="tvShowId">The tv show's TMDb id.</param>
  214. /// <param name="seasonNumber">The season number.</param>
  215. /// <param name="episodeNumber">The episode number.</param>
  216. /// <param name="displayOrder">The display order.</param>
  217. /// <param name="language">The episode's language.</param>
  218. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  219. /// <param name="cancellationToken">The cancellation token.</param>
  220. /// <returns>The TMDb tv episode information or null if not found.</returns>
  221. public async Task<TvEpisode?> GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string displayOrder, string? language, string? imageLanguages, CancellationToken cancellationToken)
  222. {
  223. var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
  224. if (_memoryCache.TryGetValue(key, out TvEpisode? episode))
  225. {
  226. return episode;
  227. }
  228. await EnsureClientConfigAsync().ConfigureAwait(false);
  229. var group = await GetSeriesGroupAsync(tvShowId, displayOrder, language, imageLanguages, cancellationToken).ConfigureAwait(false);
  230. if (group is not null)
  231. {
  232. var season = group.Groups.Find(s => s.Order == seasonNumber);
  233. // Episode order starts at 0
  234. var ep = season?.Episodes.Find(e => e.Order == episodeNumber - 1);
  235. if (ep is not null)
  236. {
  237. seasonNumber = ep.SeasonNumber;
  238. episodeNumber = ep.EpisodeNumber;
  239. }
  240. }
  241. episode = await _tmDbClient.GetTvEpisodeAsync(
  242. tvShowId,
  243. seasonNumber,
  244. episodeNumber,
  245. language: TmdbUtils.NormalizeLanguage(language),
  246. includeImageLanguage: imageLanguages,
  247. extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpisodeMethods.Videos,
  248. cancellationToken: cancellationToken).ConfigureAwait(false);
  249. if (episode is not null)
  250. {
  251. _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
  252. }
  253. return episode;
  254. }
  255. /// <summary>
  256. /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id.
  257. /// </summary>
  258. /// <param name="personTmdbId">The person's TMDb id.</param>
  259. /// <param name="language">The episode's language.</param>
  260. /// <param name="cancellationToken">The cancellation token.</param>
  261. /// <returns>The TMDb person information or null if not found.</returns>
  262. public async Task<Person?> GetPersonAsync(int personTmdbId, string language, CancellationToken cancellationToken)
  263. {
  264. var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  265. if (_memoryCache.TryGetValue(key, out Person? person))
  266. {
  267. return person;
  268. }
  269. await EnsureClientConfigAsync().ConfigureAwait(false);
  270. person = await _tmDbClient.GetPersonAsync(
  271. personTmdbId,
  272. TmdbUtils.NormalizeLanguage(language),
  273. PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
  274. cancellationToken).ConfigureAwait(false);
  275. if (person is not null)
  276. {
  277. _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
  278. }
  279. return person;
  280. }
  281. /// <summary>
  282. /// Gets an item from the TMDb API based on its id from an external service eg. IMDb id, TvDb id.
  283. /// </summary>
  284. /// <param name="externalId">The item's external id.</param>
  285. /// <param name="source">The source of the id eg. IMDb.</param>
  286. /// <param name="language">The item's language.</param>
  287. /// <param name="cancellationToken">The cancellation token.</param>
  288. /// <returns>The TMDb item or null if not found.</returns>
  289. public async Task<FindContainer?> FindByExternalIdAsync(
  290. string externalId,
  291. FindExternalSource source,
  292. string language,
  293. CancellationToken cancellationToken)
  294. {
  295. var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
  296. if (_memoryCache.TryGetValue(key, out FindContainer? result))
  297. {
  298. return result;
  299. }
  300. await EnsureClientConfigAsync().ConfigureAwait(false);
  301. result = await _tmDbClient.FindAsync(
  302. source,
  303. externalId,
  304. TmdbUtils.NormalizeLanguage(language),
  305. cancellationToken).ConfigureAwait(false);
  306. if (result is not null)
  307. {
  308. _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
  309. }
  310. return result;
  311. }
  312. /// <summary>
  313. /// Searches for a tv show using the TMDb API based on its name.
  314. /// </summary>
  315. /// <param name="name">The name of the tv show.</param>
  316. /// <param name="language">The tv show's language.</param>
  317. /// <param name="year">The year the tv show first aired.</param>
  318. /// <param name="cancellationToken">The cancellation token.</param>
  319. /// <returns>The TMDb tv show information.</returns>
  320. public async Task<IReadOnlyList<SearchTv>> SearchSeriesAsync(string name, string language, int year = 0, CancellationToken cancellationToken = default)
  321. {
  322. var key = $"searchseries-{name}-{language}";
  323. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv>? series) && series is not null)
  324. {
  325. return series.Results;
  326. }
  327. await EnsureClientConfigAsync().ConfigureAwait(false);
  328. var searchResults = await _tmDbClient
  329. .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), includeAdult: Plugin.Instance.Configuration.IncludeAdult, firstAirDateYear: year, cancellationToken: cancellationToken)
  330. .ConfigureAwait(false);
  331. if (searchResults.Results.Count > 0)
  332. {
  333. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  334. }
  335. return searchResults.Results;
  336. }
  337. /// <summary>
  338. /// Searches for a person based on their name using the TMDb API.
  339. /// </summary>
  340. /// <param name="name">The name of the person.</param>
  341. /// <param name="cancellationToken">The cancellation token.</param>
  342. /// <returns>The TMDb person information.</returns>
  343. public async Task<IReadOnlyList<SearchPerson>> SearchPersonAsync(string name, CancellationToken cancellationToken)
  344. {
  345. var key = $"searchperson-{name}";
  346. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchPerson>? person) && person is not null)
  347. {
  348. return person.Results;
  349. }
  350. await EnsureClientConfigAsync().ConfigureAwait(false);
  351. var searchResults = await _tmDbClient
  352. .SearchPersonAsync(name, includeAdult: Plugin.Instance.Configuration.IncludeAdult, cancellationToken: cancellationToken)
  353. .ConfigureAwait(false);
  354. if (searchResults.Results.Count > 0)
  355. {
  356. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  357. }
  358. return searchResults.Results;
  359. }
  360. /// <summary>
  361. /// Searches for a movie based on its name using the TMDb API.
  362. /// </summary>
  363. /// <param name="name">The name of the movie.</param>
  364. /// <param name="language">The movie's language.</param>
  365. /// <param name="cancellationToken">The cancellation token.</param>
  366. /// <returns>The TMDb movie information.</returns>
  367. public Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, string language, CancellationToken cancellationToken)
  368. {
  369. return SearchMovieAsync(name, 0, language, cancellationToken);
  370. }
  371. /// <summary>
  372. /// Searches for a movie based on its name using the TMDb API.
  373. /// </summary>
  374. /// <param name="name">The name of the movie.</param>
  375. /// <param name="year">The release year of the movie.</param>
  376. /// <param name="language">The movie's language.</param>
  377. /// <param name="cancellationToken">The cancellation token.</param>
  378. /// <returns>The TMDb movie information.</returns>
  379. public async Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, int year, string language, CancellationToken cancellationToken)
  380. {
  381. var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
  382. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchMovie>? movies) && movies is not null)
  383. {
  384. return movies.Results;
  385. }
  386. await EnsureClientConfigAsync().ConfigureAwait(false);
  387. var searchResults = await _tmDbClient
  388. .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language), includeAdult: Plugin.Instance.Configuration.IncludeAdult, year: year, cancellationToken: cancellationToken)
  389. .ConfigureAwait(false);
  390. if (searchResults.Results.Count > 0)
  391. {
  392. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  393. }
  394. return searchResults.Results;
  395. }
  396. /// <summary>
  397. /// Searches for a collection based on its name using the TMDb API.
  398. /// </summary>
  399. /// <param name="name">The name of the collection.</param>
  400. /// <param name="language">The collection's language.</param>
  401. /// <param name="cancellationToken">The cancellation token.</param>
  402. /// <returns>The TMDb collection information.</returns>
  403. public async Task<IReadOnlyList<SearchCollection>> SearchCollectionAsync(string name, string language, CancellationToken cancellationToken)
  404. {
  405. var key = $"collectionsearch-{name}-{language}";
  406. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchCollection>? collections) && collections is not null)
  407. {
  408. return collections.Results;
  409. }
  410. await EnsureClientConfigAsync().ConfigureAwait(false);
  411. var searchResults = await _tmDbClient
  412. .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
  413. .ConfigureAwait(false);
  414. if (searchResults.Results.Count > 0)
  415. {
  416. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  417. }
  418. return searchResults.Results;
  419. }
  420. /// <summary>
  421. /// Handles bad path checking and builds the absolute url.
  422. /// </summary>
  423. /// <param name="size">The image size to fetch.</param>
  424. /// <param name="path">The relative URL of the image.</param>
  425. /// <returns>The absolute URL.</returns>
  426. private string? GetUrl(string? size, string path)
  427. {
  428. if (string.IsNullOrEmpty(path))
  429. {
  430. return null;
  431. }
  432. return _tmDbClient.GetImageUrl(size, path, true).ToString();
  433. }
  434. /// <summary>
  435. /// Gets the absolute URL of the poster.
  436. /// </summary>
  437. /// <param name="posterPath">The relative URL of the poster.</param>
  438. /// <returns>The absolute URL.</returns>
  439. public string? GetPosterUrl(string posterPath)
  440. {
  441. return GetUrl(Plugin.Instance.Configuration.PosterSize, posterPath);
  442. }
  443. /// <summary>
  444. /// Gets the absolute URL of the profile image.
  445. /// </summary>
  446. /// <param name="actorProfilePath">The relative URL of the profile image.</param>
  447. /// <returns>The absolute URL.</returns>
  448. public string? GetProfileUrl(string actorProfilePath)
  449. {
  450. return GetUrl(Plugin.Instance.Configuration.ProfileSize, actorProfilePath);
  451. }
  452. /// <summary>
  453. /// Converts poster <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  454. /// </summary>
  455. /// <param name="images">The input images.</param>
  456. /// <param name="requestLanguage">The requested language.</param>
  457. /// <returns>The remote images.</returns>
  458. public IEnumerable<RemoteImageInfo> ConvertPostersToRemoteImageInfo(IReadOnlyList<ImageData> images, string requestLanguage)
  459. => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.PosterSize, ImageType.Primary, requestLanguage);
  460. /// <summary>
  461. /// Converts backdrop <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  462. /// </summary>
  463. /// <param name="images">The input images.</param>
  464. /// <param name="requestLanguage">The requested language.</param>
  465. /// <returns>The remote images.</returns>
  466. public IEnumerable<RemoteImageInfo> ConvertBackdropsToRemoteImageInfo(IReadOnlyList<ImageData> images, string requestLanguage)
  467. => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.BackdropSize, ImageType.Backdrop, requestLanguage);
  468. /// <summary>
  469. /// Converts logo <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  470. /// </summary>
  471. /// <param name="images">The input images.</param>
  472. /// <param name="requestLanguage">The requested language.</param>
  473. /// <returns>The remote images.</returns>
  474. public IEnumerable<RemoteImageInfo> ConvertLogosToRemoteImageInfo(IReadOnlyList<ImageData> images, string requestLanguage)
  475. => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.LogoSize, ImageType.Logo, requestLanguage);
  476. /// <summary>
  477. /// Converts profile <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  478. /// </summary>
  479. /// <param name="images">The input images.</param>
  480. /// <param name="requestLanguage">The requested language.</param>
  481. /// <returns>The remote images.</returns>
  482. public IEnumerable<RemoteImageInfo> ConvertProfilesToRemoteImageInfo(IReadOnlyList<ImageData> images, string requestLanguage)
  483. => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.ProfileSize, ImageType.Primary, requestLanguage);
  484. /// <summary>
  485. /// Converts still <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  486. /// </summary>
  487. /// <param name="images">The input images.</param>
  488. /// <param name="requestLanguage">The requested language.</param>
  489. /// <returns>The remote images.</returns>
  490. public IEnumerable<RemoteImageInfo> ConvertStillsToRemoteImageInfo(IReadOnlyList<ImageData> images, string requestLanguage)
  491. => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.StillSize, ImageType.Primary, requestLanguage);
  492. /// <summary>
  493. /// Converts <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
  494. /// </summary>
  495. /// <param name="images">The input images.</param>
  496. /// <param name="size">The size of the image to fetch.</param>
  497. /// <param name="type">The type of the image.</param>
  498. /// <param name="requestLanguage">The requested language.</param>
  499. /// <returns>The remote images.</returns>
  500. private IEnumerable<RemoteImageInfo> ConvertToRemoteImageInfo(IReadOnlyList<ImageData> images, string? size, ImageType type, string requestLanguage)
  501. {
  502. // sizes provided are for original resolution, don't store them when downloading scaled images
  503. var scaleImage = !string.Equals(size, "original", StringComparison.OrdinalIgnoreCase);
  504. for (var i = 0; i < images.Count; i++)
  505. {
  506. var image = images[i];
  507. yield return new RemoteImageInfo
  508. {
  509. Url = GetUrl(size, image.FilePath),
  510. CommunityRating = image.VoteAverage,
  511. VoteCount = image.VoteCount,
  512. Width = scaleImage ? null : image.Width,
  513. Height = scaleImage ? null : image.Height,
  514. Language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, requestLanguage),
  515. ProviderName = TmdbUtils.ProviderName,
  516. Type = type,
  517. RatingType = RatingType.Score
  518. };
  519. }
  520. }
  521. private async Task EnsureClientConfigAsync()
  522. {
  523. if (!_tmDbClient.HasConfig)
  524. {
  525. var config = await _tmDbClient.GetConfigAsync().ConfigureAwait(false);
  526. ValidatePreferences(config);
  527. }
  528. }
  529. private static void ValidatePreferences(TMDbConfig config)
  530. {
  531. var imageConfig = config.Images;
  532. var pluginConfig = Plugin.Instance.Configuration;
  533. if (!imageConfig.PosterSizes.Contains(pluginConfig.PosterSize))
  534. {
  535. pluginConfig.PosterSize = imageConfig.PosterSizes[^1];
  536. }
  537. if (!imageConfig.BackdropSizes.Contains(pluginConfig.BackdropSize))
  538. {
  539. pluginConfig.BackdropSize = imageConfig.BackdropSizes[^1];
  540. }
  541. if (!imageConfig.LogoSizes.Contains(pluginConfig.LogoSize))
  542. {
  543. pluginConfig.LogoSize = imageConfig.LogoSizes[^1];
  544. }
  545. if (!imageConfig.ProfileSizes.Contains(pluginConfig.ProfileSize))
  546. {
  547. pluginConfig.ProfileSize = imageConfig.ProfileSizes[^1];
  548. }
  549. if (!imageConfig.StillSizes.Contains(pluginConfig.StillSize))
  550. {
  551. pluginConfig.StillSize = imageConfig.StillSizes[^1];
  552. }
  553. }
  554. /// <summary>
  555. /// Gets the <see cref="TMDbClient"/> configuration.
  556. /// </summary>
  557. /// <returns>The configuration.</returns>
  558. public async Task<TMDbConfig> GetClientConfiguration()
  559. {
  560. await EnsureClientConfigAsync().ConfigureAwait(false);
  561. return _tmDbClient.Config;
  562. }
  563. /// <inheritdoc />
  564. public void Dispose()
  565. {
  566. Dispose(true);
  567. GC.SuppressFinalize(this);
  568. }
  569. /// <summary>
  570. /// Releases unmanaged and - optionally - managed resources.
  571. /// </summary>
  572. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  573. protected virtual void Dispose(bool disposing)
  574. {
  575. if (disposing)
  576. {
  577. _memoryCache?.Dispose();
  578. _tmDbClient?.Dispose();
  579. }
  580. }
  581. }
  582. }