TmdbClientManager.cs 30 KB

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