< 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
4%
Covered lines: 13
Uncovered lines: 263
Coverable lines: 276
Total lines: 766
Line coverage: 4.7%
Branch coverage
2%
Covered branches: 4
Total branches: 192
Branch coverage: 2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 2/7/2026 - 12:13:45 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: 7185/16/2026 - 12:15:55 AM Line coverage: 4.7% (13/276) Branch coverage: 2.6% (5/192) Total lines: 7665/20/2026 - 12:15:44 AM Line coverage: 4.7% (13/276) Branch coverage: 2% (4/192) Total lines: 766 2/7/2026 - 12:13:45 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: 7185/16/2026 - 12:15:55 AM Line coverage: 4.7% (13/276) Branch coverage: 2.6% (5/192) Total lines: 7665/20/2026 - 12:15:44 AM Line coverage: 4.7% (13/276) Branch coverage: 2% (4/192) Total lines: 766

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        /// Gets a single page of similar movies for a movie from the TMDb API.
 509        /// </summary>
 510        /// <param name="tmdbId">The TMDb id of the movie.</param>
 511        /// <param name="page">The page number to fetch (1-based).</param>
 512        /// <param name="language">The language for results.</param>
 513        /// <param name="cancellationToken">The cancellation token.</param>
 514        /// <returns>A tuple containing the list of similar movies and the total number of pages available.</returns>
 515        public async Task<(IReadOnlyList<SearchMovie> Results, int TotalPages)> GetMovieSimilarPageAsync(int tmdbId, int
 516        {
 0517            await EnsureClientConfigAsync().ConfigureAwait(false);
 518
 0519            var searchResults = await _tmDbClient
 0520                .GetMovieSimilarAsync(tmdbId, language, page, cancellationToken)
 0521                .ConfigureAwait(false);
 522
 0523            if (searchResults?.Results is null || searchResults.Results.Count == 0)
 524            {
 0525                return ([], 0);
 526            }
 527
 0528            return (searchResults.Results, searchResults.TotalPages);
 0529        }
 530
 531        /// <summary>
 532        /// Gets a single page of similar TV shows for a series from the TMDb API.
 533        /// </summary>
 534        /// <param name="tmdbId">The TMDb id of the TV show.</param>
 535        /// <param name="page">The page number to fetch (1-based).</param>
 536        /// <param name="language">The language for results.</param>
 537        /// <param name="cancellationToken">The cancellation token.</param>
 538        /// <returns>A tuple containing the list of similar TV shows and the total number of pages available.</returns>
 539        public async Task<(IReadOnlyList<SearchTv> Results, int TotalPages)> GetSeriesSimilarPageAsync(int tmdbId, int p
 540        {
 0541            await EnsureClientConfigAsync().ConfigureAwait(false);
 542
 0543            var searchResults = await _tmDbClient
 0544                .GetTvShowSimilarAsync(tmdbId, language, page, cancellationToken)
 0545                .ConfigureAwait(false);
 546
 0547            if (searchResults?.Results is null || searchResults.Results.Count == 0)
 548            {
 0549                return ([], 0);
 550            }
 551
 0552            return (searchResults.Results, searchResults.TotalPages);
 0553        }
 554
 555        /// <summary>
 556        /// Handles bad path checking and builds the absolute url.
 557        /// </summary>
 558        /// <param name="size">The image size to fetch.</param>
 559        /// <param name="path">The relative URL of the image.</param>
 560        /// <returns>The absolute URL.</returns>
 561        private string? GetUrl(string? size, string? path)
 562        {
 0563            if (string.IsNullOrEmpty(path))
 564            {
 0565                return null;
 566            }
 567
 568            // Use "original" as default size if size is null or empty to prevent malformed URLs
 0569            var imageSize = string.IsNullOrEmpty(size) ? "original" : size;
 570
 0571            return _tmDbClient.GetImageUrl(imageSize, path, true).ToString();
 572        }
 573
 574        /// <summary>
 575        /// Gets the absolute URL of the poster.
 576        /// </summary>
 577        /// <param name="posterPath">The relative URL of the poster.</param>
 578        /// <returns>The absolute URL.</returns>
 579        public string? GetPosterUrl(string? posterPath)
 580        {
 0581            return GetUrl(Plugin.Instance.Configuration.PosterSize, posterPath);
 582        }
 583
 584        /// <summary>
 585        /// Gets the absolute URL of the profile image.
 586        /// </summary>
 587        /// <param name="actorProfilePath">The relative URL of the profile image.</param>
 588        /// <returns>The absolute URL.</returns>
 589        public string? GetProfileUrl(string? actorProfilePath)
 590        {
 0591            return GetUrl(Plugin.Instance.Configuration.ProfileSize, actorProfilePath);
 592        }
 593
 594        /// <summary>
 595        /// Converts poster <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 596        /// </summary>
 597        /// <param name="images">The input images.</param>
 598        /// <param name="requestLanguage">The requested language.</param>
 599        /// <returns>The remote images.</returns>
 600        public IEnumerable<RemoteImageInfo> ConvertPostersToRemoteImageInfo(IReadOnlyList<ImageData> images, string requ
 0601            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.PosterSize, ImageType.Primary, requestLang
 602
 603        /// <summary>
 604        /// Converts backdrop <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 605        /// </summary>
 606        /// <param name="images">The input images.</param>
 607        /// <param name="requestLanguage">The requested language.</param>
 608        /// <returns>The remote images.</returns>
 609        public IEnumerable<RemoteImageInfo> ConvertBackdropsToRemoteImageInfo(IReadOnlyList<ImageData> images, string re
 0610            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.BackdropSize, ImageType.Backdrop, requestL
 611
 612        /// <summary>
 613        /// Converts logo <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 614        /// </summary>
 615        /// <param name="images">The input images.</param>
 616        /// <param name="requestLanguage">The requested language.</param>
 617        /// <returns>The remote images.</returns>
 618        public IEnumerable<RemoteImageInfo> ConvertLogosToRemoteImageInfo(IReadOnlyList<ImageData> images, string reques
 0619            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.LogoSize, ImageType.Logo, requestLanguage)
 620
 621        /// <summary>
 622        /// Converts profile <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 623        /// </summary>
 624        /// <param name="images">The input images.</param>
 625        /// <param name="requestLanguage">The requested language.</param>
 626        /// <returns>The remote images.</returns>
 627        public IEnumerable<RemoteImageInfo> ConvertProfilesToRemoteImageInfo(IReadOnlyList<ImageData> images, string req
 0628            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.ProfileSize, ImageType.Primary, requestLan
 629
 630        /// <summary>
 631        /// Converts still <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 632        /// </summary>
 633        /// <param name="images">The input images.</param>
 634        /// <param name="requestLanguage">The requested language.</param>
 635        /// <returns>The remote images.</returns>
 636        public IEnumerable<RemoteImageInfo> ConvertStillsToRemoteImageInfo(IReadOnlyList<ImageData> images, string reque
 0637            => ConvertToRemoteImageInfo(images, Plugin.Instance.Configuration.StillSize, ImageType.Primary, requestLangu
 638
 639        /// <summary>
 640        /// Converts <see cref="ImageData"/>s into <see cref="RemoteImageInfo"/>s.
 641        /// </summary>
 642        /// <param name="images">The input images.</param>
 643        /// <param name="size">The size of the image to fetch.</param>
 644        /// <param name="type">The type of the image.</param>
 645        /// <param name="requestLanguage">The requested language.</param>
 646        /// <returns>The remote images.</returns>
 647        private IEnumerable<RemoteImageInfo> ConvertToRemoteImageInfo(IReadOnlyList<ImageData> images, string? size, Ima
 648        {
 649            // sizes provided are for original resolution, don't store them when downloading scaled images
 0650            var scaleImage = !string.Equals(size, "original", StringComparison.OrdinalIgnoreCase);
 651
 0652            for (var i = 0; i < images.Count; i++)
 653            {
 0654                var image = images[i];
 655
 0656                var imageType = type;
 0657                var language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, requestLanguage);
 658
 659                // Return Backdrops with a language specified (it has text) as Thumb.
 0660                if (imageType == ImageType.Backdrop && !string.IsNullOrEmpty(language))
 661                {
 0662                    imageType = ImageType.Thumb;
 663                }
 664
 0665                yield return new RemoteImageInfo
 0666                {
 0667                    Url = GetUrl(size, image.FilePath),
 0668                    CommunityRating = image.VoteAverage,
 0669                    VoteCount = image.VoteCount,
 0670                    Width = scaleImage ? null : image.Width,
 0671                    Height = scaleImage ? null : image.Height,
 0672                    Language = language,
 0673                    ProviderName = TmdbUtils.ProviderName,
 0674                    Type = imageType,
 0675                    RatingType = RatingType.Score
 0676                };
 677            }
 0678        }
 679
 680        private async Task EnsureClientConfigAsync()
 681        {
 0682            if (!_tmDbClient.HasConfig)
 683            {
 0684                var config = await _tmDbClient.GetConfigAsync().ConfigureAwait(false);
 0685                ValidatePreferences(config);
 686            }
 0687        }
 688
 689        private static void ValidatePreferences(TMDbConfig config)
 690        {
 0691            var imageConfig = config.Images;
 0692            if (imageConfig is null)
 693            {
 0694                return;
 695            }
 696
 0697            var pluginConfig = Plugin.Instance.Configuration;
 698
 0699            if (imageConfig.PosterSizes is not null
 0700                && pluginConfig.PosterSize is not null
 0701                && !imageConfig.PosterSizes.Contains(pluginConfig.PosterSize))
 702            {
 0703                pluginConfig.PosterSize = imageConfig.PosterSizes[^1];
 704            }
 705
 0706            if (imageConfig.BackdropSizes is not null
 0707                && pluginConfig.BackdropSize is not null
 0708                && !imageConfig.BackdropSizes.Contains(pluginConfig.BackdropSize))
 709            {
 0710                pluginConfig.BackdropSize = imageConfig.BackdropSizes[^1];
 711            }
 712
 0713            if (imageConfig.LogoSizes is not null
 0714                && pluginConfig.LogoSize is not null
 0715                && !imageConfig.LogoSizes.Contains(pluginConfig.LogoSize))
 716            {
 0717                pluginConfig.LogoSize = imageConfig.LogoSizes[^1];
 718            }
 719
 0720            if (imageConfig.ProfileSizes is not null
 0721                && pluginConfig.ProfileSize is not null
 0722                && !imageConfig.ProfileSizes.Contains(pluginConfig.ProfileSize))
 723            {
 0724                pluginConfig.ProfileSize = imageConfig.ProfileSizes[^1];
 725            }
 726
 0727            if (imageConfig.StillSizes is not null
 0728                && pluginConfig.StillSize is not null
 0729                && !imageConfig.StillSizes.Contains(pluginConfig.StillSize))
 730            {
 0731                pluginConfig.StillSize = imageConfig.StillSizes[^1];
 732            }
 0733        }
 734
 735        /// <summary>
 736        /// Gets the <see cref="TMDbClient"/> configuration.
 737        /// </summary>
 738        /// <returns>The configuration.</returns>
 739        public async Task<TMDbConfig> GetClientConfiguration()
 740        {
 0741            await EnsureClientConfigAsync().ConfigureAwait(false);
 742
 0743            return _tmDbClient.Config;
 0744        }
 745
 746        /// <inheritdoc />
 747        public void Dispose()
 748        {
 21749            Dispose(true);
 21750            GC.SuppressFinalize(this);
 21751        }
 752
 753        /// <summary>
 754        /// Releases unmanaged and - optionally - managed resources.
 755        /// </summary>
 756        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release
 757        protected virtual void Dispose(bool disposing)
 758        {
 21759            if (disposing)
 760            {
 21761                _memoryCache?.Dispose();
 21762                _tmDbClient?.Dispose();
 763            }
 21764        }
 765    }
 766}