< Summary - Jellyfin

Information
Class: MediaBrowser.Providers.Plugins.Tmdb.TmdbClientManager
Assembly: MediaBrowser.Providers
File(s): /srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
Line coverage
5%
Covered lines: 13
Uncovered lines: 247
Coverable lines: 260
Total lines: 718
Line coverage: 5%
Branch coverage
2%
Covered branches: 5
Total branches: 180
Branch coverage: 2.7%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 1/23/2026 - 12:11:06 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 7022/15/2026 - 12:13:43 AM Line coverage: 34.2% (13/38) Branch coverage: 22.7% (5/22) Total lines: 7052/19/2026 - 12:13:41 AM Line coverage: 26% (13/50) Branch coverage: 11.3% (5/44) Total lines: 7184/19/2026 - 12:14:27 AM Line coverage: 5% (13/260) Branch coverage: 2.7% (5/180) Total lines: 718 1/23/2026 - 12:11:06 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 7022/15/2026 - 12:13:43 AM Line coverage: 34.2% (13/38) Branch coverage: 22.7% (5/22) Total lines: 7052/19/2026 - 12:13:41 AM Line coverage: 26% (13/50) Branch coverage: 11.3% (5/44) Total lines: 7184/19/2026 - 12:14:27 AM Line coverage: 5% (13/260) Branch coverage: 2.7% (5/180) Total lines: 718

Coverage delta

Coverage delta 21 -21

Metrics

File(s)

/srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.Threading;
 5using System.Threading.Tasks;
 6using MediaBrowser.Model.Dto;
 7using MediaBrowser.Model.Entities;
 8using MediaBrowser.Model.Providers;
 9using Microsoft.Extensions.Caching.Memory;
 10using TMDbLib.Client;
 11using TMDbLib.Objects.Collections;
 12using TMDbLib.Objects.Find;
 13using TMDbLib.Objects.General;
 14using TMDbLib.Objects.Movies;
 15using TMDbLib.Objects.People;
 16using TMDbLib.Objects.Search;
 17using TMDbLib.Objects.TvShows;
 18
 19namespace 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
 28        private readonly IMemoryCache _memoryCache;
 29        private readonly TMDbClient _tmDbClient;
 30
 31        /// <summary>
 32        /// Initializes a new instance of the <see cref="TmdbClientManager"/> class.
 33        /// </summary>
 34        /// <param name="memoryCache">An instance of <see cref="IMemoryCache"/>.</param>
 35        public TmdbClientManager(IMemoryCache memoryCache)
 36        {
 2137            _memoryCache = memoryCache;
 38
 2139            var apiKey = Plugin.Instance.Configuration.TmdbApiKey;
 2140            apiKey = string.IsNullOrEmpty(apiKey) ? TmdbUtils.ApiKey : apiKey;
 2141            _tmDbClient = new TMDbClient(apiKey);
 42
 43            // Not really interested in NotFoundException
 2144            _tmDbClient.ThrowApiExceptions = false;
 2145        }
 46
 47        /// <summary>
 48        /// Gets a movie from the TMDb API based on its TMDb id.
 49        /// </summary>
 50        /// <param name="tmdbId">The movie's TMDb id.</param>
 51        /// <param name="language">The movie's language.</param>
 52        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 53        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 54        /// <param name="cancellationToken">The cancellation token.</param>
 55        /// <returns>The TMDb movie or null if not found.</returns>
 56        public async Task<Movie?> GetMovieAsync(int tmdbId, string? language, string? imageLanguages, string? countryCod
 57        {
 058            var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 059            if (_memoryCache.TryGetValue(key, out Movie? movie))
 60            {
 061                return movie;
 62            }
 63
 064            await EnsureClientConfigAsync().ConfigureAwait(false);
 65
 066            var extraMethods = MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Videos;
 067            if (!(Plugin.Instance?.Configuration.ExcludeTagsMovies).GetValueOrDefault())
 68            {
 069                extraMethods |= MovieMethods.Keywords;
 70            }
 71
 072            movie = await _tmDbClient.GetMovieAsync(
 073                tmdbId,
 074                TmdbUtils.NormalizeLanguage(language, countryCode),
 075                imageLanguages,
 076                extraMethods,
 077                cancellationToken).ConfigureAwait(false);
 78
 079            if (movie is not null)
 80            {
 081                _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
 82            }
 83
 084            return movie;
 085        }
 86
 87        /// <summary>
 88        /// Gets a collection from the TMDb API based on its TMDb id.
 89        /// </summary>
 90        /// <param name="tmdbId">The collection's TMDb id.</param>
 91        /// <param name="language">The collection's language.</param>
 92        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 93        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 94        /// <param name="cancellationToken">The cancellation token.</param>
 95        /// <returns>The TMDb collection or null if not found.</returns>
 96        public async Task<Collection?> GetCollectionAsync(int tmdbId, string? language, string? imageLanguages, string? 
 97        {
 098            var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 099            if (_memoryCache.TryGetValue(key, out Collection? collection))
 100            {
 0101                return collection;
 102            }
 103
 0104            await EnsureClientConfigAsync().ConfigureAwait(false);
 105
 0106            collection = await _tmDbClient.GetCollectionAsync(
 0107                tmdbId,
 0108                TmdbUtils.NormalizeLanguage(language, countryCode),
 0109                imageLanguages,
 0110                CollectionMethods.Images,
 0111                cancellationToken).ConfigureAwait(false);
 112
 0113            if (collection is not null)
 114            {
 0115                _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
 116            }
 117
 0118            return collection;
 0119        }
 120
 121        /// <summary>
 122        /// Gets a tv show from the TMDb API based on its TMDb id.
 123        /// </summary>
 124        /// <param name="tmdbId">The tv show's TMDb id.</param>
 125        /// <param name="language">The tv show's language.</param>
 126        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 127        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 128        /// <param name="cancellationToken">The cancellation token.</param>
 129        /// <returns>The TMDb tv show information or null if not found.</returns>
 130        public async Task<TvShow?> GetSeriesAsync(int tmdbId, string? language, string? imageLanguages, string? countryC
 131        {
 0132            var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 0133            if (_memoryCache.TryGetValue(key, out TvShow? series))
 134            {
 0135                return series;
 136            }
 137
 0138            await EnsureClientConfigAsync().ConfigureAwait(false);
 139
 0140            var extraMethods = TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.ExternalIds | TvShowMethods.
 0141            if (!(Plugin.Instance?.Configuration.ExcludeTagsSeries).GetValueOrDefault())
 142            {
 0143                extraMethods |= TvShowMethods.Keywords;
 144            }
 145
 0146            series = await _tmDbClient.GetTvShowAsync(
 0147                tmdbId,
 0148                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 0149                includeImageLanguage: imageLanguages,
 0150                extraMethods: extraMethods,
 0151                cancellationToken: cancellationToken).ConfigureAwait(false);
 152
 0153            if (series is not null)
 154            {
 0155                _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
 156            }
 157
 0158            return series;
 0159        }
 160
 161        /// <summary>
 162        /// Gets a tv show episode group from the TMDb API based on the show id and the display order.
 163        /// </summary>
 164        /// <param name="tvShowId">The tv show's TMDb id.</param>
 165        /// <param name="displayOrder">The display order.</param>
 166        /// <param name="language">The tv show's language.</param>
 167        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 168        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 169        /// <param name="cancellationToken">The cancellation token.</param>
 170        /// <returns>The TMDb tv show episode group information or null if not found.</returns>
 171        private async Task<TvGroupCollection?> GetSeriesGroupAsync(int tvShowId, string displayOrder, string? language, 
 172        {
 0173            TvGroupType? groupType =
 0174                string.Equals(displayOrder, "originalAirDate", StringComparison.Ordinal) ? TvGroupType.OriginalAirDate :
 0175                string.Equals(displayOrder, "absolute", StringComparison.Ordinal) ? TvGroupType.Absolute :
 0176                string.Equals(displayOrder, "dvd", StringComparison.Ordinal) ? TvGroupType.DVD :
 0177                string.Equals(displayOrder, "digital", StringComparison.Ordinal) ? TvGroupType.Digital :
 0178                string.Equals(displayOrder, "storyArc", StringComparison.Ordinal) ? TvGroupType.StoryArc :
 0179                string.Equals(displayOrder, "production", StringComparison.Ordinal) ? TvGroupType.Production :
 0180                string.Equals(displayOrder, "tv", StringComparison.Ordinal) ? TvGroupType.TV :
 0181                null;
 182
 0183            if (groupType is null)
 184            {
 0185                return null;
 186            }
 187
 0188            var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
 0189            if (_memoryCache.TryGetValue(key, out TvGroupCollection? group))
 190            {
 0191                return group;
 192            }
 193
 0194            await EnsureClientConfigAsync().ConfigureAwait(false);
 195
 0196            var series = await GetSeriesAsync(tvShowId, language, imageLanguages, countryCode, cancellationToken).Config
 0197            var episodeGroupId = series?.EpisodeGroups?.Results?.Find(g => g.Type == groupType)?.Id;
 198
 0199            if (episodeGroupId is null)
 200            {
 0201                return null;
 202            }
 203
 0204            group = await _tmDbClient.GetTvEpisodeGroupsAsync(
 0205                episodeGroupId,
 0206                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 0207                cancellationToken: cancellationToken).ConfigureAwait(false);
 208
 0209            if (group is not null)
 210            {
 0211                _memoryCache.Set(key, group, TimeSpan.FromHours(CacheDurationInHours));
 212            }
 213
 0214            return group;
 0215        }
 216
 217        /// <summary>
 218        /// Gets a tv season from the TMDb API based on the tv show's TMDb id.
 219        /// </summary>
 220        /// <param name="tvShowId">The tv season's TMDb id.</param>
 221        /// <param name="seasonNumber">The season number.</param>
 222        /// <param name="language">The tv season's language.</param>
 223        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 224        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 225        /// <param name="cancellationToken">The cancellation token.</param>
 226        /// <returns>The TMDb tv season information or null if not found.</returns>
 227        public async Task<TvSeason?> GetSeasonAsync(int tvShowId, int seasonNumber, string? language, string? imageLangu
 228        {
 0229            var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.Inv
 0230            if (_memoryCache.TryGetValue(key, out TvSeason? season))
 231            {
 0232                return season;
 233            }
 234
 0235            await EnsureClientConfigAsync().ConfigureAwait(false);
 236
 0237            season = await _tmDbClient.GetTvSeasonAsync(
 0238                tvShowId,
 0239                seasonNumber,
 0240                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 0241                includeImageLanguage: imageLanguages,
 0242                extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonM
 0243                cancellationToken: cancellationToken).ConfigureAwait(false);
 244
 0245            if (season is not null)
 246            {
 0247                _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
 248            }
 249
 0250            return season;
 0251        }
 252
 253        /// <summary>
 254        /// Gets a movie from the TMDb API based on the tv show's TMDb id.
 255        /// </summary>
 256        /// <param name="tvShowId">The tv show's TMDb id.</param>
 257        /// <param name="seasonNumber">The season number.</param>
 258        /// <param name="episodeNumber">The episode number.</param>
 259        /// <param name="displayOrder">The display order.</param>
 260        /// <param name="language">The episode's language.</param>
 261        /// <param name="imageLanguages">A comma-separated list of image languages.</param>
 262        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 263        /// <param name="cancellationToken">The cancellation token.</param>
 264        /// <returns>The TMDb tv episode information or null if not found.</returns>
 265        public async Task<TvEpisode?> GetEpisodeAsync(int tvShowId, int seasonNumber, long episodeNumber, string display
 266        {
 0267            var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.In
 0268            if (_memoryCache.TryGetValue(key, out TvEpisode? episode))
 269            {
 0270                return episode;
 271            }
 272
 0273            await EnsureClientConfigAsync().ConfigureAwait(false);
 274
 0275            var group = await GetSeriesGroupAsync(tvShowId, displayOrder, language, imageLanguages, countryCode, cancell
 0276            if (group is not null)
 277            {
 0278                var season = group.Groups?.Find(s => s.Order == seasonNumber);
 279                // Episode order starts at 0
 0280                var ep = season?.Episodes?.Find(e => e.Order == episodeNumber - 1);
 0281                if (ep is not null)
 282                {
 0283                    seasonNumber = ep.SeasonNumber;
 0284                    episodeNumber = ep.EpisodeNumber;
 285                }
 286            }
 287
 0288            episode = await _tmDbClient.GetTvEpisodeAsync(
 0289                tvShowId,
 0290                seasonNumber,
 0291                episodeNumber,
 0292                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 0293                includeImageLanguage: imageLanguages,
 0294                extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpis
 0295                cancellationToken: cancellationToken).ConfigureAwait(false);
 296
 0297            if (episode is not null)
 298            {
 0299                _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
 300            }
 301
 0302            return episode;
 0303        }
 304
 305        /// <summary>
 306        /// Gets a person eg. cast or crew member from the TMDb API based on its TMDb id.
 307        /// </summary>
 308        /// <param name="personTmdbId">The person's TMDb id.</param>
 309        /// <param name="language">The person's language.</param>
 310        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 311        /// <param name="cancellationToken">The cancellation token.</param>
 312        /// <returns>The TMDb person information or null if not found.</returns>
 313        public async Task<Person?> GetPersonAsync(int personTmdbId, string language, string? countryCode, CancellationTo
 314        {
 0315            var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 0316            if (_memoryCache.TryGetValue(key, out Person? person))
 317            {
 0318                return person;
 319            }
 320
 0321            await EnsureClientConfigAsync().ConfigureAwait(false);
 322
 0323            person = await _tmDbClient.GetPersonAsync(
 0324                personTmdbId,
 0325                TmdbUtils.NormalizeLanguage(language, countryCode),
 0326                PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
 0327                cancellationToken).ConfigureAwait(false);
 328
 0329            if (person is not null)
 330            {
 0331                _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
 332            }
 333
 0334            return person;
 0335        }
 336
 337        /// <summary>
 338        /// Gets an item from the TMDb API based on its id from an external service eg. IMDb id, TvDb id.
 339        /// </summary>
 340        /// <param name="externalId">The item's external id.</param>
 341        /// <param name="source">The source of the id eg. IMDb.</param>
 342        /// <param name="language">The item's language.</param>
 343        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 344        /// <param name="cancellationToken">The cancellation token.</param>
 345        /// <returns>The TMDb item or null if not found.</returns>
 346        public async Task<FindContainer?> FindByExternalIdAsync(
 347            string externalId,
 348            FindExternalSource source,
 349            string language,
 350            string? countryCode,
 351            CancellationToken cancellationToken)
 352        {
 0353            var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
 0354            if (_memoryCache.TryGetValue(key, out FindContainer? result))
 355            {
 0356                return result;
 357            }
 358
 0359            await EnsureClientConfigAsync().ConfigureAwait(false);
 360
 0361            result = await _tmDbClient.FindAsync(
 0362                source,
 0363                externalId,
 0364                TmdbUtils.NormalizeLanguage(language, countryCode),
 0365                cancellationToken).ConfigureAwait(false);
 366
 0367            if (result is not null)
 368            {
 0369                _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
 370            }
 371
 0372            return result;
 0373        }
 374
 375        /// <summary>
 376        /// Searches for a tv show using the TMDb API based on its name.
 377        /// </summary>
 378        /// <param name="name">The name of the tv show.</param>
 379        /// <param name="language">The tv show's language.</param>
 380        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 381        /// <param name="year">The year the tv show first aired.</param>
 382        /// <param name="cancellationToken">The cancellation token.</param>
 383        /// <returns>The TMDb tv show information.</returns>
 384        public async Task<IReadOnlyList<SearchTv>?> SearchSeriesAsync(string name, string language, string? countryCode,
 385        {
 0386            var key = $"searchseries-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
 0387            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv>? series) && series is not null)
 388            {
 0389                return series.Results;
 390            }
 391
 0392            await EnsureClientConfigAsync().ConfigureAwait(false);
 393
 0394            var searchResults = await _tmDbClient
 0395                .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), includeAdult: Plugin.Instan
 0396                .ConfigureAwait(false);
 397
 0398            if (searchResults?.Results?.Count > 0)
 399            {
 0400                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 401            }
 402
 0403            return searchResults?.Results;
 0404        }
 405
 406        /// <summary>
 407        /// Searches for a person based on their name using the TMDb API.
 408        /// </summary>
 409        /// <param name="name">The name of the person.</param>
 410        /// <param name="cancellationToken">The cancellation token.</param>
 411        /// <returns>The TMDb person information.</returns>
 412        public async Task<IReadOnlyList<SearchPerson>?> SearchPersonAsync(string name, CancellationToken cancellationTok
 413        {
 0414            var key = $"searchperson-{name}";
 0415            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchPerson>? person) && person is not null)
 416            {
 0417                return person.Results;
 418            }
 419
 0420            await EnsureClientConfigAsync().ConfigureAwait(false);
 421
 0422            var searchResults = await _tmDbClient
 0423                .SearchPersonAsync(name, includeAdult: Plugin.Instance.Configuration.IncludeAdult, cancellationToken: ca
 0424                .ConfigureAwait(false);
 425
 0426            if (searchResults?.Results?.Count > 0)
 427            {
 0428                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 429            }
 430
 0431            return searchResults?.Results;
 0432        }
 433
 434        /// <summary>
 435        /// Searches for a movie based on its name using the TMDb API.
 436        /// </summary>
 437        /// <param name="name">The name of the movie.</param>
 438        /// <param name="language">The movie's language.</param>
 439        /// <param name="cancellationToken">The cancellation token.</param>
 440        /// <returns>The TMDb movie information.</returns>
 441        public Task<IReadOnlyList<SearchMovie>?> SearchMovieAsync(string name, string language, CancellationToken cancel
 442        {
 0443            return SearchMovieAsync(name, 0, language, null, cancellationToken);
 444        }
 445
 446        /// <summary>
 447        /// Searches for a movie based on its name using the TMDb API.
 448        /// </summary>
 449        /// <param name="name">The name of the movie.</param>
 450        /// <param name="year">The release year of the movie.</param>
 451        /// <param name="language">The movie's language.</param>
 452        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 453        /// <param name="cancellationToken">The cancellation token.</param>
 454        /// <returns>The TMDb movie information.</returns>
 455        public async Task<IReadOnlyList<SearchMovie>?> SearchMovieAsync(string name, int year, string language, string? 
 456        {
 0457            var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
 0458            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchMovie>? movies) && movies is not null)
 459            {
 0460                return movies.Results;
 461            }
 462
 0463            await EnsureClientConfigAsync().ConfigureAwait(false);
 464
 0465            var searchResults = await _tmDbClient
 0466                .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), includeAdult: Plugin.Instanc
 0467                .ConfigureAwait(false);
 468
 0469            if (searchResults?.Results?.Count > 0)
 470            {
 0471                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 472            }
 473
 0474            return searchResults?.Results;
 0475        }
 476
 477        /// <summary>
 478        /// Searches for a collection based on its name using the TMDb API.
 479        /// </summary>
 480        /// <param name="name">The name of the collection.</param>
 481        /// <param name="language">The collection's language.</param>
 482        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 483        /// <param name="cancellationToken">The cancellation token.</param>
 484        /// <returns>The TMDb collection information.</returns>
 485        public async Task<IReadOnlyList<SearchCollection>?> SearchCollectionAsync(string name, string language, string? 
 486        {
 0487            var key = $"collectionsearch-{name}-{language}";
 0488            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchCollection>? collections) && collections is not 
 489            {
 0490                return collections.Results;
 491            }
 492
 0493            await EnsureClientConfigAsync().ConfigureAwait(false);
 494
 0495            var searchResults = await _tmDbClient
 0496                .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), cancellationToken: canc
 0497                .ConfigureAwait(false);
 498
 0499            if (searchResults?.Results?.Count > 0)
 500            {
 0501                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 502            }
 503
 0504            return searchResults?.Results;
 0505        }
 506
 507        /// <summary>
 508        /// Handles bad path checking and builds the absolute url.
 509        /// </summary>
 510        /// <param name="size">The image size to fetch.</param>
 511        /// <param name="path">The relative URL of the image.</param>
 512        /// <returns>The absolute URL.</returns>
 513        private string? GetUrl(string? size, string? path)
 514        {
 0515            if (string.IsNullOrEmpty(path))
 516            {
 0517                return null;
 518            }
 519
 520            // Use "original" as default size if size is null or empty to prevent malformed URLs
 0521            var imageSize = string.IsNullOrEmpty(size) ? "original" : size;
 522
 0523            return _tmDbClient.GetImageUrl(imageSize, path, true).ToString();
 524        }
 525
 526        /// <summary>
 527        /// Gets the absolute URL of the poster.
 528        /// </summary>
 529        /// <param name="posterPath">The relative URL of the poster.</param>
 530        /// <returns>The absolute URL.</returns>
 531        public string? GetPosterUrl(string? posterPath)
 532        {
 0533            return GetUrl(Plugin.Instance.Configuration.PosterSize, posterPath);
 534        }
 535
 536        /// <summary>
 537        /// Gets the absolute URL of the profile image.
 538        /// </summary>
 539        /// <param name="actorProfilePath">The relative URL of the profile image.</param>
 540        /// <returns>The absolute URL.</returns>
 541        public string? GetProfileUrl(string? actorProfilePath)
 542        {
 0543            return GetUrl(Plugin.Instance.Configuration.ProfileSize, actorProfilePath);
 544        }
 545
 546        /// <summary>
 547        /// Converts poster <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 548        /// </summary>
 549        /// <param name="images">The input images.</param>
 550        /// <param name="requestLanguage">The requested language.</param>
 551        /// <returns>The remote images.</returns>
 552        public IEnumerable<RemoteImageInfo> ConvertPostersToRemoteImageInfo(IReadOnlyList<ImageData> images, string requ
 0553            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.PosterSize, ImageType.Primary, requestLang
 554
 555        /// <summary>
 556        /// Converts backdrop <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 557        /// </summary>
 558        /// <param name="images">The input images.</param>
 559        /// <param name="requestLanguage">The requested language.</param>
 560        /// <returns>The remote images.</returns>
 561        public IEnumerable<RemoteImageInfo> ConvertBackdropsToRemoteImageInfo(IReadOnlyList<ImageData> images, string re
 0562            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.BackdropSize, ImageType.Backdrop, requestL
 563
 564        /// <summary>
 565        /// Converts logo <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 566        /// </summary>
 567        /// <param name="images">The input images.</param>
 568        /// <param name="requestLanguage">The requested language.</param>
 569        /// <returns>The remote images.</returns>
 570        public IEnumerable<RemoteImageInfo> ConvertLogosToRemoteImageInfo(IReadOnlyList<ImageData> images, string reques
 0571            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.LogoSize, ImageType.Logo, requestLanguage)
 572
 573        /// <summary>
 574        /// Converts profile <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 575        /// </summary>
 576        /// <param name="images">The input images.</param>
 577        /// <param name="requestLanguage">The requested language.</param>
 578        /// <returns>The remote images.</returns>
 579        public IEnumerable<RemoteImageInfo> ConvertProfilesToRemoteImageInfo(IReadOnlyList<ImageData> images, string req
 0580            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.ProfileSize, ImageType.Primary, requestLan
 581
 582        /// <summary>
 583        /// Converts still <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 584        /// </summary>
 585        /// <param name="images">The input images.</param>
 586        /// <param name="requestLanguage">The requested language.</param>
 587        /// <returns>The remote images.</returns>
 588        public IEnumerable<RemoteImageInfo> ConvertStillsToRemoteImageInfo(IReadOnlyList<ImageData> images, string reque
 0589            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.StillSize, ImageType.Primary, requestLangu
 590
 591        /// <summary>
 592        /// Converts <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 593        /// </summary>
 594        /// <param name="images">The input images.</param>
 595        /// <param name="size">The size of the image to fetch.</param>
 596        /// <param name="type">The type of the image.</param>
 597        /// <param name="requestLanguage">The requested language.</param>
 598        /// <returns>The remote images.</returns>
 599        private IEnumerable<RemoteImageInfo> ConvertToRemoteImageInfo(IReadOnlyList<ImageData> images, string? size, Ima
 600        {
 601            // sizes provided are for original resolution, don't store them when downloading scaled images
 0602            var scaleImage = !string.Equals(size, "original", StringComparison.OrdinalIgnoreCase);
 603
 0604            for (var i = 0; i < images.Count; i++)
 605            {
 0606                var image = images[i];
 607
 0608                var imageType = type;
 0609                var language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, requestLanguage);
 610
 611                // Return Backdrops with a language specified (it has text) as Thumb.
 0612                if (imageType == ImageType.Backdrop && !string.IsNullOrEmpty(language))
 613                {
 0614                    imageType = ImageType.Thumb;
 615                }
 616
 0617                yield return new RemoteImageInfo
 0618                {
 0619                    Url = GetUrl(size, image.FilePath),
 0620                    CommunityRating = image.VoteAverage,
 0621                    VoteCount = image.VoteCount,
 0622                    Width = scaleImage ? null : image.Width,
 0623                    Height = scaleImage ? null : image.Height,
 0624                    Language = language,
 0625                    ProviderName = TmdbUtils.ProviderName,
 0626                    Type = imageType,
 0627                    RatingType = RatingType.Score
 0628                };
 629            }
 0630        }
 631
 632        private async Task EnsureClientConfigAsync()
 633        {
 0634            if (!_tmDbClient.HasConfig)
 635            {
 0636                var config = await _tmDbClient.GetConfigAsync().ConfigureAwait(false);
 0637                ValidatePreferences(config);
 638            }
 0639        }
 640
 641        private static void ValidatePreferences(TMDbConfig config)
 642        {
 0643            var imageConfig = config.Images;
 0644            if (imageConfig is null)
 645            {
 0646                return;
 647            }
 648
 0649            var pluginConfig = Plugin.Instance.Configuration;
 650
 0651            if (imageConfig.PosterSizes is not null
 0652                && pluginConfig.PosterSize is not null
 0653                && !imageConfig.PosterSizes.Contains(pluginConfig.PosterSize))
 654            {
 0655                pluginConfig.PosterSize = imageConfig.PosterSizes[^1];
 656            }
 657
 0658            if (imageConfig.BackdropSizes is not null
 0659                && pluginConfig.BackdropSize is not null
 0660                && !imageConfig.BackdropSizes.Contains(pluginConfig.BackdropSize))
 661            {
 0662                pluginConfig.BackdropSize = imageConfig.BackdropSizes[^1];
 663            }
 664
 0665            if (imageConfig.LogoSizes is not null
 0666                && pluginConfig.LogoSize is not null
 0667                && !imageConfig.LogoSizes.Contains(pluginConfig.LogoSize))
 668            {
 0669                pluginConfig.LogoSize = imageConfig.LogoSizes[^1];
 670            }
 671
 0672            if (imageConfig.ProfileSizes is not null
 0673                && pluginConfig.ProfileSize is not null
 0674                && !imageConfig.ProfileSizes.Contains(pluginConfig.ProfileSize))
 675            {
 0676                pluginConfig.ProfileSize = imageConfig.ProfileSizes[^1];
 677            }
 678
 0679            if (imageConfig.StillSizes is not null
 0680                && pluginConfig.StillSize is not null
 0681                && !imageConfig.StillSizes.Contains(pluginConfig.StillSize))
 682            {
 0683                pluginConfig.StillSize = imageConfig.StillSizes[^1];
 684            }
 0685        }
 686
 687        /// <summary>
 688        /// Gets the <see cref="TMDbClient"/> configuration.
 689        /// </summary>
 690        /// <returns>The configuration.</returns>
 691        public async Task<TMDbConfig> GetClientConfiguration()
 692        {
 0693            await EnsureClientConfigAsync().ConfigureAwait(false);
 694
 0695            return _tmDbClient.Config;
 0696        }
 697
 698        /// <inheritdoc />
 699        public void Dispose()
 700        {
 21701            Dispose(true);
 21702            GC.SuppressFinalize(this);
 21703        }
 704
 705        /// <summary>
 706        /// Releases unmanaged and - optionally - managed resources.
 707        /// </summary>
 708        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release
 709        protected virtual void Dispose(bool disposing)
 710        {
 21711            if (disposing)
 712            {
 21713                _memoryCache?.Dispose();
 21714                _tmDbClient?.Dispose();
 715            }
 21716        }
 717    }
 718}