2
0

TmdbClientManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.Extensions.Caching.Memory;
  7. using TMDbLib.Client;
  8. using TMDbLib.Objects.Collections;
  9. using TMDbLib.Objects.Find;
  10. using TMDbLib.Objects.General;
  11. using TMDbLib.Objects.Movies;
  12. using TMDbLib.Objects.People;
  13. using TMDbLib.Objects.Search;
  14. using TMDbLib.Objects.TvShows;
  15. namespace MediaBrowser.Providers.Plugins.Tmdb
  16. {
  17. /// <summary>
  18. /// Manager class for abstracting the TMDb API client library.
  19. /// </summary>
  20. public class TmdbClientManager
  21. {
  22. private const int CacheDurationInHours = 1;
  23. private readonly IMemoryCache _memoryCache;
  24. private readonly TMDbClient _tmDbClient;
  25. /// <summary>
  26. /// Initializes a new instance of the <see cref="TmdbClientManager"/> class.
  27. /// </summary>
  28. /// <param name="memoryCache">An instance of <see cref="IMemoryCache"/>.</param>
  29. public TmdbClientManager(IMemoryCache memoryCache)
  30. {
  31. _memoryCache = memoryCache;
  32. _tmDbClient = new TMDbClient(TmdbUtils.ApiKey);
  33. // Not really interested in NotFoundException
  34. _tmDbClient.ThrowApiExceptions = false;
  35. }
  36. /// <summary>
  37. /// Gets a movie from the TMDb API based on its TMDb id.
  38. /// </summary>
  39. /// <param name="tmdbId">The movie's TMDb id.</param>
  40. /// <param name="language">The movie's language.</param>
  41. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  42. /// <param name="cancellationToken">The cancellation token.</param>
  43. /// <returns>The TMDb movie or null if not found.</returns>
  44. public async Task<Movie> GetMovieAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
  45. {
  46. var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  47. if (_memoryCache.TryGetValue(key, out Movie movie))
  48. {
  49. return movie;
  50. }
  51. await EnsureClientConfigAsync().ConfigureAwait(false);
  52. movie = await _tmDbClient.GetMovieAsync(
  53. tmdbId,
  54. TmdbUtils.NormalizeLanguage(language),
  55. imageLanguages,
  56. MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Keywords | MovieMethods.Videos,
  57. cancellationToken).ConfigureAwait(false);
  58. if (movie != null)
  59. {
  60. _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
  61. }
  62. return movie;
  63. }
  64. /// <summary>
  65. /// Gets a collection from the TMDb API based on its TMDb id.
  66. /// </summary>
  67. /// <param name="tmdbId">The collection's TMDb id.</param>
  68. /// <param name="language">The collection's language.</param>
  69. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  70. /// <param name="cancellationToken">The cancellation token.</param>
  71. /// <returns>The TMDb collection or null if not found.</returns>
  72. public async Task<Collection> GetCollectionAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
  73. {
  74. var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  75. if (_memoryCache.TryGetValue(key, out Collection collection))
  76. {
  77. return collection;
  78. }
  79. await EnsureClientConfigAsync().ConfigureAwait(false);
  80. collection = await _tmDbClient.GetCollectionAsync(
  81. tmdbId,
  82. TmdbUtils.NormalizeLanguage(language),
  83. imageLanguages,
  84. CollectionMethods.Images,
  85. cancellationToken).ConfigureAwait(false);
  86. if (collection != null)
  87. {
  88. _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
  89. }
  90. return collection;
  91. }
  92. /// <summary>
  93. /// Gets a tv show from the TMDb API based on its TMDb id.
  94. /// </summary>
  95. /// <param name="tmdbId">The tv show's TMDb id.</param>
  96. /// <param name="language">The tv show's language.</param>
  97. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  98. /// <param name="cancellationToken">The cancellation token.</param>
  99. /// <returns>The TMDb tv show information or null if not found.</returns>
  100. public async Task<TvShow> GetSeriesAsync(int tmdbId, string language, string imageLanguages, CancellationToken cancellationToken)
  101. {
  102. var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
  103. if (_memoryCache.TryGetValue(key, out TvShow series))
  104. {
  105. return series;
  106. }
  107. await EnsureClientConfigAsync().ConfigureAwait(false);
  108. series = await _tmDbClient.GetTvShowAsync(
  109. tmdbId,
  110. language: TmdbUtils.NormalizeLanguage(language),
  111. includeImageLanguage: imageLanguages,
  112. extraMethods: TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.Keywords | TvShowMethods.ExternalIds | TvShowMethods.Videos | TvShowMethods.ContentRatings,
  113. cancellationToken: cancellationToken).ConfigureAwait(false);
  114. if (series != null)
  115. {
  116. _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
  117. }
  118. return series;
  119. }
  120. /// <summary>
  121. /// Gets a tv season from the TMDb API based on the tv show's TMDb id.
  122. /// </summary>
  123. /// <param name="tvShowId">The tv season's TMDb id.</param>
  124. /// <param name="seasonNumber">The season number.</param>
  125. /// <param name="language">The tv season's language.</param>
  126. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  127. /// <param name="cancellationToken">The cancellation token.</param>
  128. /// <returns>The TMDb tv season information or null if not found.</returns>
  129. public async Task<TvSeason> GetSeasonAsync(int tvShowId, int seasonNumber, string language, string imageLanguages, CancellationToken cancellationToken)
  130. {
  131. var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
  132. if (_memoryCache.TryGetValue(key, out TvSeason season))
  133. {
  134. return season;
  135. }
  136. await EnsureClientConfigAsync().ConfigureAwait(false);
  137. season = await _tmDbClient.GetTvSeasonAsync(
  138. tvShowId,
  139. seasonNumber,
  140. language: TmdbUtils.NormalizeLanguage(language),
  141. includeImageLanguage: imageLanguages,
  142. extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonMethods.Videos,
  143. cancellationToken: cancellationToken).ConfigureAwait(false);
  144. if (season != null)
  145. {
  146. _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
  147. }
  148. return season;
  149. }
  150. /// <summary>
  151. /// Gets a movie from the TMDb API based on the tv show's TMDb id.
  152. /// </summary>
  153. /// <param name="tvShowId">The tv show's TMDb id.</param>
  154. /// <param name="seasonNumber">The season number.</param>
  155. /// <param name="episodeNumber">The episode number.</param>
  156. /// <param name="language">The episode's language.</param>
  157. /// <param name="imageLanguages">A comma-separated list of image languages.</param>
  158. /// <param name="cancellationToken">The cancellation token.</param>
  159. /// <returns>The TMDb tv episode information or null if not found.</returns>
  160. public async Task<TvEpisode> GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string language, string imageLanguages, CancellationToken cancellationToken)
  161. {
  162. var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{language}";
  163. if (_memoryCache.TryGetValue(key, out TvEpisode episode))
  164. {
  165. return episode;
  166. }
  167. await EnsureClientConfigAsync().ConfigureAwait(false);
  168. episode = await _tmDbClient.GetTvEpisodeAsync(
  169. tvShowId,
  170. seasonNumber,
  171. episodeNumber,
  172. language: TmdbUtils.NormalizeLanguage(language),
  173. includeImageLanguage: imageLanguages,
  174. extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpisodeMethods.Videos,
  175. cancellationToken: cancellationToken).ConfigureAwait(false);
  176. if (episode != null)
  177. {
  178. _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
  179. }
  180. return episode;
  181. }
  182. /// <summary>
  183. /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id.
  184. /// </summary>
  185. /// <param name="personTmdbId">The person's TMDb id.</param>
  186. /// <param name="cancellationToken">The cancellation token.</param>
  187. /// <returns>The TMDb person information or null if not found.</returns>
  188. public async Task<Person> GetPersonAsync(int personTmdbId, CancellationToken cancellationToken)
  189. {
  190. var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}";
  191. if (_memoryCache.TryGetValue(key, out Person person))
  192. {
  193. return person;
  194. }
  195. await EnsureClientConfigAsync().ConfigureAwait(false);
  196. person = await _tmDbClient.GetPersonAsync(
  197. personTmdbId,
  198. PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
  199. cancellationToken).ConfigureAwait(false);
  200. if (person != null)
  201. {
  202. _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
  203. }
  204. return person;
  205. }
  206. /// <summary>
  207. /// Gets an item from the TMDb API based on its id from an external service eg. IMDb id, TvDb id.
  208. /// </summary>
  209. /// <param name="externalId">The item's external id.</param>
  210. /// <param name="source">The source of the id eg. IMDb.</param>
  211. /// <param name="language">The item's language.</param>
  212. /// <param name="cancellationToken">The cancellation token.</param>
  213. /// <returns>The TMDb item or null if not found.</returns>
  214. public async Task<FindContainer> FindByExternalIdAsync(
  215. string externalId,
  216. FindExternalSource source,
  217. string language,
  218. CancellationToken cancellationToken)
  219. {
  220. var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
  221. if (_memoryCache.TryGetValue(key, out FindContainer result))
  222. {
  223. return result;
  224. }
  225. await EnsureClientConfigAsync().ConfigureAwait(false);
  226. result = await _tmDbClient.FindAsync(
  227. source,
  228. externalId,
  229. TmdbUtils.NormalizeLanguage(language),
  230. cancellationToken).ConfigureAwait(false);
  231. if (result != null)
  232. {
  233. _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
  234. }
  235. return result;
  236. }
  237. /// <summary>
  238. /// Searches for a tv show using the TMDb API based on its name.
  239. /// </summary>
  240. /// <param name="name">The name of the tv show.</param>
  241. /// <param name="language">The tv show's language.</param>
  242. /// <param name="cancellationToken">The cancellation token.</param>
  243. /// <returns>The TMDb tv show information.</returns>
  244. public async Task<IReadOnlyList<SearchTv>> SearchSeriesAsync(string name, string language, CancellationToken cancellationToken)
  245. {
  246. var key = $"searchseries-{name}-{language}";
  247. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv> series))
  248. {
  249. return series.Results;
  250. }
  251. await EnsureClientConfigAsync().ConfigureAwait(false);
  252. var searchResults = await _tmDbClient
  253. .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
  254. .ConfigureAwait(false);
  255. if (searchResults.Results.Count > 0)
  256. {
  257. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  258. }
  259. return searchResults.Results;
  260. }
  261. /// <summary>
  262. /// Searches for a person based on their name using the TMDb API.
  263. /// </summary>
  264. /// <param name="name">The name of the person.</param>
  265. /// <param name="cancellationToken">The cancellation token.</param>
  266. /// <returns>The TMDb person information.</returns>
  267. public async Task<IReadOnlyList<SearchPerson>> SearchPersonAsync(string name, CancellationToken cancellationToken)
  268. {
  269. var key = $"searchperson-{name}";
  270. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchPerson> person))
  271. {
  272. return person.Results;
  273. }
  274. await EnsureClientConfigAsync().ConfigureAwait(false);
  275. var searchResults = await _tmDbClient
  276. .SearchPersonAsync(name, cancellationToken: cancellationToken)
  277. .ConfigureAwait(false);
  278. if (searchResults.Results.Count > 0)
  279. {
  280. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  281. }
  282. return searchResults.Results;
  283. }
  284. /// <summary>
  285. /// Searches for a movie based on its name using the TMDb API.
  286. /// </summary>
  287. /// <param name="name">The name of the movie.</param>
  288. /// <param name="language">The movie's language.</param>
  289. /// <param name="cancellationToken">The cancellation token.</param>
  290. /// <returns>The TMDb movie information.</returns>
  291. public Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, string language, CancellationToken cancellationToken)
  292. {
  293. return SearchMovieAsync(name, 0, language, cancellationToken);
  294. }
  295. /// <summary>
  296. /// Searches for a movie based on its name using the TMDb API.
  297. /// </summary>
  298. /// <param name="name">The name of the movie.</param>
  299. /// <param name="year">The release year of the movie.</param>
  300. /// <param name="language">The movie's language.</param>
  301. /// <param name="cancellationToken">The cancellation token.</param>
  302. /// <returns>The TMDb movie information.</returns>
  303. public async Task<IReadOnlyList<SearchMovie>> SearchMovieAsync(string name, int year, string language, CancellationToken cancellationToken)
  304. {
  305. var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
  306. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchMovie> movies))
  307. {
  308. return movies.Results;
  309. }
  310. await EnsureClientConfigAsync().ConfigureAwait(false);
  311. var searchResults = await _tmDbClient
  312. .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language), year: year, cancellationToken: cancellationToken)
  313. .ConfigureAwait(false);
  314. if (searchResults.Results.Count > 0)
  315. {
  316. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  317. }
  318. return searchResults.Results;
  319. }
  320. /// <summary>
  321. /// Searches for a collection based on its name using the TMDb API.
  322. /// </summary>
  323. /// <param name="name">The name of the collection.</param>
  324. /// <param name="language">The collection's language.</param>
  325. /// <param name="cancellationToken">The cancellation token.</param>
  326. /// <returns>The TMDb collection information.</returns>
  327. public async Task<IReadOnlyList<SearchCollection>> SearchCollectionAsync(string name, string language, CancellationToken cancellationToken)
  328. {
  329. var key = $"collectionsearch-{name}-{language}";
  330. if (_memoryCache.TryGetValue(key, out SearchContainer<SearchCollection> collections))
  331. {
  332. return collections.Results;
  333. }
  334. await EnsureClientConfigAsync().ConfigureAwait(false);
  335. var searchResults = await _tmDbClient
  336. .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language), cancellationToken: cancellationToken)
  337. .ConfigureAwait(false);
  338. if (searchResults.Results.Count > 0)
  339. {
  340. _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
  341. }
  342. return searchResults.Results;
  343. }
  344. /// <summary>
  345. /// Gets the absolute URL of the poster.
  346. /// </summary>
  347. /// <param name="posterPath">The relative URL of the poster.</param>
  348. /// <returns>The absolute URL.</returns>
  349. public string GetPosterUrl(string posterPath)
  350. {
  351. if (string.IsNullOrEmpty(posterPath))
  352. {
  353. return null;
  354. }
  355. return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.PosterSizes[^1], posterPath).ToString();
  356. }
  357. /// <summary>
  358. /// Gets the absolute URL of the backdrop image.
  359. /// </summary>
  360. /// <param name="posterPath">The relative URL of the backdrop image.</param>
  361. /// <returns>The absolute URL.</returns>
  362. public string GetBackdropUrl(string posterPath)
  363. {
  364. if (string.IsNullOrEmpty(posterPath))
  365. {
  366. return null;
  367. }
  368. return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.BackdropSizes[^1], posterPath).ToString();
  369. }
  370. /// <summary>
  371. /// Gets the absolute URL of the profile image.
  372. /// </summary>
  373. /// <param name="actorProfilePath">The relative URL of the profile image.</param>
  374. /// <returns>The absolute URL.</returns>
  375. public string GetProfileUrl(string actorProfilePath)
  376. {
  377. if (string.IsNullOrEmpty(actorProfilePath))
  378. {
  379. return null;
  380. }
  381. return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.ProfileSizes[^1], actorProfilePath).ToString();
  382. }
  383. /// <summary>
  384. /// Gets the absolute URL of the still image.
  385. /// </summary>
  386. /// <param name="filePath">The relative URL of the still image.</param>
  387. /// <returns>The absolute URL.</returns>
  388. public string GetStillUrl(string filePath)
  389. {
  390. if (string.IsNullOrEmpty(filePath))
  391. {
  392. return null;
  393. }
  394. return _tmDbClient.GetImageUrl(_tmDbClient.Config.Images.StillSizes[^1], filePath).ToString();
  395. }
  396. private Task EnsureClientConfigAsync()
  397. {
  398. return !_tmDbClient.HasConfig ? _tmDbClient.GetConfigAsync() : Task.CompletedTask;
  399. }
  400. }
  401. }