TmdbClientManager.cs 31 KB

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