< 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
35%
Covered lines: 13
Uncovered lines: 24
Coverable lines: 37
Total lines: 702
Line coverage: 35.1%
Branch coverage
25%
Covered branches: 5
Total branches: 20
Branch coverage: 25%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 7/7/2025 - 12:11:23 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 69010/14/2025 - 12:11:23 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 702 7/7/2025 - 12:11:23 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 69010/14/2025 - 12:11:23 AM Line coverage: 35.1% (13/37) Branch coverage: 25% (5/20) Total lines: 702

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