< 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
26%
Covered lines: 13
Uncovered lines: 37
Coverable lines: 50
Total lines: 718
Line coverage: 26%
Branch coverage
11%
Covered branches: 5
Total branches: 44
Branch coverage: 11.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 11/9/2025 - 12:11:18 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: 718 11/9/2025 - 12:11:18 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: 718

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        {
 58            var key = $"movie-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 59            if (_memoryCache.TryGetValue(key, out Movie? movie))
 60            {
 61                return movie;
 62            }
 63
 64            await EnsureClientConfigAsync().ConfigureAwait(false);
 65
 66            var extraMethods = MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Videos;
 67            if (!(Plugin.Instance?.Configuration.ExcludeTagsMovies).GetValueOrDefault())
 68            {
 69                extraMethods |= MovieMethods.Keywords;
 70            }
 71
 72            movie = await _tmDbClient.GetMovieAsync(
 73                tmdbId,
 74                TmdbUtils.NormalizeLanguage(language, countryCode),
 75                imageLanguages,
 76                extraMethods,
 77                cancellationToken).ConfigureAwait(false);
 78
 79            if (movie is not null)
 80            {
 81                _memoryCache.Set(key, movie, TimeSpan.FromHours(CacheDurationInHours));
 82            }
 83
 84            return movie;
 85        }
 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        {
 98            var key = $"collection-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 99            if (_memoryCache.TryGetValue(key, out Collection? collection))
 100            {
 101                return collection;
 102            }
 103
 104            await EnsureClientConfigAsync().ConfigureAwait(false);
 105
 106            collection = await _tmDbClient.GetCollectionAsync(
 107                tmdbId,
 108                TmdbUtils.NormalizeLanguage(language, countryCode),
 109                imageLanguages,
 110                CollectionMethods.Images,
 111                cancellationToken).ConfigureAwait(false);
 112
 113            if (collection is not null)
 114            {
 115                _memoryCache.Set(key, collection, TimeSpan.FromHours(CacheDurationInHours));
 116            }
 117
 118            return collection;
 119        }
 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        {
 132            var key = $"series-{tmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 133            if (_memoryCache.TryGetValue(key, out TvShow? series))
 134            {
 135                return series;
 136            }
 137
 138            await EnsureClientConfigAsync().ConfigureAwait(false);
 139
 140            var extraMethods = TvShowMethods.Credits | TvShowMethods.Images | TvShowMethods.ExternalIds | TvShowMethods.
 141            if (!(Plugin.Instance?.Configuration.ExcludeTagsSeries).GetValueOrDefault())
 142            {
 143                extraMethods |= TvShowMethods.Keywords;
 144            }
 145
 146            series = await _tmDbClient.GetTvShowAsync(
 147                tmdbId,
 148                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 149                includeImageLanguage: imageLanguages,
 150                extraMethods: extraMethods,
 151                cancellationToken: cancellationToken).ConfigureAwait(false);
 152
 153            if (series is not null)
 154            {
 155                _memoryCache.Set(key, series, TimeSpan.FromHours(CacheDurationInHours));
 156            }
 157
 158            return series;
 159        }
 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        {
 173            TvGroupType? groupType =
 174                string.Equals(displayOrder, "originalAirDate", StringComparison.Ordinal) ? TvGroupType.OriginalAirDate :
 175                string.Equals(displayOrder, "absolute", StringComparison.Ordinal) ? TvGroupType.Absolute :
 176                string.Equals(displayOrder, "dvd", StringComparison.Ordinal) ? TvGroupType.DVD :
 177                string.Equals(displayOrder, "digital", StringComparison.Ordinal) ? TvGroupType.Digital :
 178                string.Equals(displayOrder, "storyArc", StringComparison.Ordinal) ? TvGroupType.StoryArc :
 179                string.Equals(displayOrder, "production", StringComparison.Ordinal) ? TvGroupType.Production :
 180                string.Equals(displayOrder, "tv", StringComparison.Ordinal) ? TvGroupType.TV :
 181                null;
 182
 183            if (groupType is null)
 184            {
 185                return null;
 186            }
 187
 188            var key = $"group-{tvShowId.ToString(CultureInfo.InvariantCulture)}-{displayOrder}-{language}";
 189            if (_memoryCache.TryGetValue(key, out TvGroupCollection? group))
 190            {
 191                return group;
 192            }
 193
 194            await EnsureClientConfigAsync().ConfigureAwait(false);
 195
 196            var series = await GetSeriesAsync(tvShowId, language, imageLanguages, countryCode, cancellationToken).Config
 197            var episodeGroupId = series?.EpisodeGroups?.Results?.Find(g => g.Type == groupType)?.Id;
 198
 199            if (episodeGroupId is null)
 200            {
 201                return null;
 202            }
 203
 204            group = await _tmDbClient.GetTvEpisodeGroupsAsync(
 205                episodeGroupId,
 206                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 207                cancellationToken: cancellationToken).ConfigureAwait(false);
 208
 209            if (group is not null)
 210            {
 211                _memoryCache.Set(key, group, TimeSpan.FromHours(CacheDurationInHours));
 212            }
 213
 214            return group;
 215        }
 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        {
 229            var key = $"season-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.Inv
 230            if (_memoryCache.TryGetValue(key, out TvSeason? season))
 231            {
 232                return season;
 233            }
 234
 235            await EnsureClientConfigAsync().ConfigureAwait(false);
 236
 237            season = await _tmDbClient.GetTvSeasonAsync(
 238                tvShowId,
 239                seasonNumber,
 240                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 241                includeImageLanguage: imageLanguages,
 242                extraMethods: TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.ExternalIds | TvSeasonM
 243                cancellationToken: cancellationToken).ConfigureAwait(false);
 244
 245            if (season is not null)
 246            {
 247                _memoryCache.Set(key, season, TimeSpan.FromHours(CacheDurationInHours));
 248            }
 249
 250            return season;
 251        }
 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        {
 267            var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.In
 268            if (_memoryCache.TryGetValue(key, out TvEpisode? episode))
 269            {
 270                return episode;
 271            }
 272
 273            await EnsureClientConfigAsync().ConfigureAwait(false);
 274
 275            var group = await GetSeriesGroupAsync(tvShowId, displayOrder, language, imageLanguages, countryCode, cancell
 276            if (group is not null)
 277            {
 278                var season = group.Groups?.Find(s => s.Order == seasonNumber);
 279                // Episode order starts at 0
 280                var ep = season?.Episodes?.Find(e => e.Order == episodeNumber - 1);
 281                if (ep is not null)
 282                {
 283                    seasonNumber = ep.SeasonNumber;
 284                    episodeNumber = ep.EpisodeNumber;
 285                }
 286            }
 287
 288            episode = await _tmDbClient.GetTvEpisodeAsync(
 289                tvShowId,
 290                seasonNumber,
 291                episodeNumber,
 292                language: TmdbUtils.NormalizeLanguage(language, countryCode),
 293                includeImageLanguage: imageLanguages,
 294                extraMethods: TvEpisodeMethods.Credits | TvEpisodeMethods.Images | TvEpisodeMethods.ExternalIds | TvEpis
 295                cancellationToken: cancellationToken).ConfigureAwait(false);
 296
 297            if (episode is not null)
 298            {
 299                _memoryCache.Set(key, episode, TimeSpan.FromHours(CacheDurationInHours));
 300            }
 301
 302            return episode;
 303        }
 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        {
 315            var key = $"person-{personTmdbId.ToString(CultureInfo.InvariantCulture)}-{language}";
 316            if (_memoryCache.TryGetValue(key, out Person? person))
 317            {
 318                return person;
 319            }
 320
 321            await EnsureClientConfigAsync().ConfigureAwait(false);
 322
 323            person = await _tmDbClient.GetPersonAsync(
 324                personTmdbId,
 325                TmdbUtils.NormalizeLanguage(language, countryCode),
 326                PersonMethods.TvCredits | PersonMethods.MovieCredits | PersonMethods.Images | PersonMethods.ExternalIds,
 327                cancellationToken).ConfigureAwait(false);
 328
 329            if (person is not null)
 330            {
 331                _memoryCache.Set(key, person, TimeSpan.FromHours(CacheDurationInHours));
 332            }
 333
 334            return person;
 335        }
 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        {
 353            var key = $"find-{source.ToString()}-{externalId.ToString(CultureInfo.InvariantCulture)}-{language}";
 354            if (_memoryCache.TryGetValue(key, out FindContainer? result))
 355            {
 356                return result;
 357            }
 358
 359            await EnsureClientConfigAsync().ConfigureAwait(false);
 360
 361            result = await _tmDbClient.FindAsync(
 362                source,
 363                externalId,
 364                TmdbUtils.NormalizeLanguage(language, countryCode),
 365                cancellationToken).ConfigureAwait(false);
 366
 367            if (result is not null)
 368            {
 369                _memoryCache.Set(key, result, TimeSpan.FromHours(CacheDurationInHours));
 370            }
 371
 372            return result;
 373        }
 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        {
 386            var key = $"searchseries-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
 387            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchTv>? series) && series is not null)
 388            {
 389                return series.Results;
 390            }
 391
 392            await EnsureClientConfigAsync().ConfigureAwait(false);
 393
 394            var searchResults = await _tmDbClient
 395                .SearchTvShowAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), includeAdult: Plugin.Instan
 396                .ConfigureAwait(false);
 397
 398            if (searchResults?.Results?.Count > 0)
 399            {
 400                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 401            }
 402
 403            return searchResults?.Results;
 404        }
 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        {
 414            var key = $"searchperson-{name}";
 415            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchPerson>? person) && person is not null)
 416            {
 417                return person.Results;
 418            }
 419
 420            await EnsureClientConfigAsync().ConfigureAwait(false);
 421
 422            var searchResults = await _tmDbClient
 423                .SearchPersonAsync(name, includeAdult: Plugin.Instance.Configuration.IncludeAdult, cancellationToken: ca
 424                .ConfigureAwait(false);
 425
 426            if (searchResults?.Results?.Count > 0)
 427            {
 428                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 429            }
 430
 431            return searchResults?.Results;
 432        }
 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        {
 457            var key = $"moviesearch-{name}-{year.ToString(CultureInfo.InvariantCulture)}-{language}";
 458            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchMovie>? movies) && movies is not null)
 459            {
 460                return movies.Results;
 461            }
 462
 463            await EnsureClientConfigAsync().ConfigureAwait(false);
 464
 465            var searchResults = await _tmDbClient
 466                .SearchMovieAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), includeAdult: Plugin.Instanc
 467                .ConfigureAwait(false);
 468
 469            if (searchResults?.Results?.Count > 0)
 470            {
 471                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 472            }
 473
 474            return searchResults?.Results;
 475        }
 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        {
 487            var key = $"collectionsearch-{name}-{language}";
 488            if (_memoryCache.TryGetValue(key, out SearchContainer<SearchCollection>? collections) && collections is not 
 489            {
 490                return collections.Results;
 491            }
 492
 493            await EnsureClientConfigAsync().ConfigureAwait(false);
 494
 495            var searchResults = await _tmDbClient
 496                .SearchCollectionAsync(name, TmdbUtils.NormalizeLanguage(language, countryCode), cancellationToken: canc
 497                .ConfigureAwait(false);
 498
 499            if (searchResults?.Results?.Count > 0)
 500            {
 501                _memoryCache.Set(key, searchResults, TimeSpan.FromHours(CacheDurationInHours));
 502            }
 503
 504            return searchResults?.Results;
 505        }
 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
 602            var scaleImage = !string.Equals(size, "original", StringComparison.OrdinalIgnoreCase);
 603
 604            for (var i = 0; i < images.Count; i++)
 605            {
 606                var image = images[i];
 607
 608                var imageType = type;
 609                var language = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, requestLanguage);
 610
 611                // Return Backdrops with a language specified (it has text) as Thumb.
 612                if (imageType == ImageType.Backdrop && !string.IsNullOrEmpty(language))
 613                {
 614                    imageType = ImageType.Thumb;
 615                }
 616
 617                yield return new RemoteImageInfo
 618                {
 619                    Url = GetUrl(size, image.FilePath),
 620                    CommunityRating = image.VoteAverage,
 621                    VoteCount = image.VoteCount,
 622                    Width = scaleImage ? null : image.Width,
 623                    Height = scaleImage ? null : image.Height,
 624                    Language = language,
 625                    ProviderName = TmdbUtils.ProviderName,
 626                    Type = imageType,
 627                    RatingType = RatingType.Score
 628                };
 629            }
 630        }
 631
 632        private async Task EnsureClientConfigAsync()
 633        {
 634            if (!_tmDbClient.HasConfig)
 635            {
 636                var config = await _tmDbClient.GetConfigAsync().ConfigureAwait(false);
 637                ValidatePreferences(config);
 638            }
 639        }
 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        {
 693            await EnsureClientConfigAsync().ConfigureAwait(false);
 694
 695            return _tmDbClient.Config;
 696        }
 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}