< Summary - Jellyfin

Information
Class: MediaBrowser.Providers.Plugins.Tmdb.TmdbUtils
Assembly: MediaBrowser.Providers
File(s): /srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
Line coverage
69%
Covered lines: 107
Uncovered lines: 46
Coverable lines: 153
Total lines: 522
Line coverage: 69.9%
Branch coverage
66%
Covered branches: 69
Total branches: 104
Branch coverage: 66.3%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/31/2026 - 12:15:44 AM Line coverage: 32.2% (19/59) Branch coverage: 37.5% (18/48) Total lines: 2167/16/2026 - 12:13:45 AM Line coverage: 29.2% (19/65) Branch coverage: 37.5% (18/48) Total lines: 22710/29/2026 - 12:17:11 AM Line coverage: 69.9% (107/153) Branch coverage: 66.3% (69/104) Total lines: 522 5/31/2026 - 12:15:44 AM Line coverage: 32.2% (19/59) Branch coverage: 37.5% (18/48) Total lines: 2167/16/2026 - 12:13:45 AM Line coverage: 29.2% (19/65) Branch coverage: 37.5% (18/48) Total lines: 22710/29/2026 - 12:17:11 AM Line coverage: 69.9% (107/153) Branch coverage: 66.3% (69/104) Total lines: 522

Coverage delta

Coverage delta 41 -41

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.cctor()100%210%
TryGetTmdbId(...)100%11100%
TryParseTmdbId(...)100%22100%
CleanName(...)100%11100%
NormalizeTitle(...)100%22100%
FindBestMatch(...)100%11100%
FindBestMatch(...)100%11100%
FindBestMatch(...)91.66%1212100%
ScoreTitle(...)100%88100%
ScoreYear(...)100%66100%
MapCrewToPersonType(...)0%210140%
MapAggregateCast()91.66%1212100%
MapCast()75%88100%
CreateCredit(...)50%22100%
IsTrailerType(...)0%2040%
GetImageLanguagesParam(...)0%2040%
NormalizeLanguage(...)58.33%141275%
GetImageLanguage(...)92.85%141490%
IsOriginalImageSize(...)100%22100%
BuildParentalRating(...)0%620%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Collections.Frozen;
 3using System.Collections.Generic;
 4using System.Diagnostics.CodeAnalysis;
 5using System.Globalization;
 6using System.Linq;
 7using System.Text.RegularExpressions;
 8using Jellyfin.Data.Enums;
 9using MediaBrowser.Model.Entities;
 10using TMDbLib.Objects.General;
 11using TMDbLib.Objects.Search;
 12using TMDbLib.Objects.TvShows;
 13using PersonInfo = MediaBrowser.Controller.Entities.PersonInfo;
 14
 15namespace MediaBrowser.Providers.Plugins.Tmdb
 16{
 17    /// <summary>
 18    /// Utilities for the TMDb provider.
 19    /// </summary>
 20    public static partial class TmdbUtils
 21    {
 22        /// <summary>
 23        /// URL of the TMDb instance to use.
 24        /// </summary>
 25        public const string BaseTmdbUrl = "https://www.themoviedb.org/";
 26
 27        /// <summary>
 28        /// Name of the provider.
 29        /// </summary>
 30        public const string ProviderName = "TheMovieDb";
 31
 32        /// <summary>
 33        /// API key to use when performing an API call.
 34        /// </summary>
 35        public const string ApiKey = "4219e299c89411838049ab0dab19ebd5";
 36
 37        /// <summary>
 38        /// The image size representing the unscaled image as served by TMDb.
 39        /// </summary>
 40        public const string OriginalImageSize = "original";
 41
 42        private const int TitleExactScore = 8;
 43        private const int TitlePrefixScore = 4;
 44        private const int YearScore = 2;
 45
 46        /// <summary>
 47        /// The crew types to keep.
 48        /// </summary>
 049        public static readonly string[] WantedCrewTypes =
 050        {
 051            PersonType.Director,
 052            PersonType.Writer,
 053            PersonType.Producer
 054        };
 55
 56        /// <summary>
 57        /// The crew kinds to keep.
 58        /// </summary>
 059        public static readonly PersonKind[] WantedCrewKinds =
 060        {
 061            PersonKind.Director,
 062            PersonKind.Writer,
 063            PersonKind.Producer
 064        };
 65
 66        /// <summary>
 67        /// Writing jobs to keep.
 68        /// </summary>
 069        private static readonly FrozenSet<string> _writerJobs = new[]
 070        {
 071            "writer",
 072            "screenplay",
 073            "novel"
 074        }.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
 75
 76        /// <summary>
 77        /// Everything that is not a letter, a number or a combining mark separates two search terms. The
 78        /// interpunct is kept because TMDb uses it inside titles such as "WALL·E", where it matches better
 79        /// than a space does.
 80        /// </summary>
 81        [GeneratedRegex(@"[^\p{L}\p{N}\p{M}·]+")]
 82        private static partial Regex NonSearchTermRegex();
 83
 84        /// <summary>
 85        /// As <see cref="NonSearchTermRegex"/>, but the interpunct is a separator too, so a "WALL-E" folder
 86        /// and the "WALL·E" title TMDb returns compare equal.
 87        /// </summary>
 88        [GeneratedRegex(@"[^\p{L}\p{N}\p{M}]+")]
 89        private static partial Regex NonComparableRegex();
 90
 91        /// <summary>
 92        /// Gets the TMDb id of an item, if it has one TMDb can be queried with.
 93        /// </summary>
 94        /// <param name="instance">The item.</param>
 95        /// <param name="tmdbId">The TMDb id.</param>
 96        /// <returns><c>true</c> if the item has a usable TMDb id; otherwise, <c>false</c>.</returns>
 97        public static bool TryGetTmdbId(this IHasProviderIds instance, out int tmdbId)
 98        {
 399            instance.TryGetProviderId(MetadataProvider.Tmdb, out var value);
 100
 3101            return TryParseTmdbId(value, out tmdbId);
 102        }
 103
 104        /// <summary>
 105        /// Parses a TMDb id.
 106        /// </summary>
 107        /// <param name="value">The stored id.</param>
 108        /// <param name="tmdbId">The TMDb id.</param>
 109        /// <returns><c>true</c> if the value is a usable TMDb id; otherwise, <c>false</c>.</returns>
 110        public static bool TryParseTmdbId(string? value, out int tmdbId)
 111        {
 112            // Another provider can have filed one of its own ids under the TMDb key, e.g. an IMDb person
 113            // id. Reporting that as "no id" lets the caller fall back to a search and repair the id,
 114            // instead of throwing on every refresh of the item.
 11115            return int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out tmdbId) && tmdbId > 0;
 116        }
 117
 118        /// <summary>
 119        /// Cleans the name according to TMDb requirements.
 120        /// </summary>
 121        /// <param name="name">The name of the entity.</param>
 122        /// <returns>The cleaned name.</returns>
 123        public static string CleanName(string name)
 124        {
 125            // TMDb expects a space separated list of words make sure that is the case
 8126            return NonSearchTermRegex().Replace(name, " ").Trim();
 127        }
 128
 129        /// <summary>
 130        /// Reduces a title to the form used to compare a local name against a TMDb search result.
 131        /// </summary>
 132        /// <param name="title">The title to normalize.</param>
 133        /// <returns>The normalized title, or an empty string if there was nothing to normalize.</returns>
 134        public static string NormalizeTitle(string? title)
 135        {
 97136            return string.IsNullOrEmpty(title)
 97137                ? string.Empty
 97138                : NonComparableRegex().Replace(title, " ").Trim().ToLowerInvariant();
 139        }
 140
 141        /// <summary>
 142        /// Picks the movie search result that best matches the name and year an item was looked up by.
 143        /// </summary>
 144        /// <param name="results">The search results, in the order TMDb returned them.</param>
 145        /// <param name="name">The parsed name of the local item.</param>
 146        /// <param name="year">The year of the local item, or 0 if it is unknown.</param>
 147        /// <returns>The best match, or <c>null</c> if there were no results.</returns>
 148        public static SearchMovie? FindBestMatch(IReadOnlyList<SearchMovie>? results, string? name, int year)
 149        {
 17150            return FindBestMatch(
 17151                results,
 17152                name,
 17153                year,
 17154                static movie => movie.Title,
 17155                static movie => movie.OriginalTitle,
 17156                static movie => movie.ReleaseDate);
 157        }
 158
 159        /// <summary>
 160        /// Picks the series search result that best matches the name and year an item was looked up by.
 161        /// </summary>
 162        /// <param name="results">The search results, in the order TMDb returned them.</param>
 163        /// <param name="name">The parsed name of the local item.</param>
 164        /// <param name="year">The year of the local item, or 0 if it is unknown.</param>
 165        /// <returns>The best match, or <c>null</c> if there were no results.</returns>
 166        public static SearchTv? FindBestMatch(IReadOnlyList<SearchTv>? results, string? name, int year)
 167        {
 3168            return FindBestMatch(
 3169                results,
 3170                name,
 3171                year,
 3172                static series => series.Name,
 3173                static series => series.OriginalName,
 3174                static series => series.FirstAirDate);
 175        }
 176
 177        /// <summary>
 178        /// Picks the search result that best matches the name and year an item was looked up by.
 179        /// </summary>
 180        /// <remarks>
 181        /// TMDb's year parameter only nudges relevance, it does not filter, so the first hit is regularly a
 182        /// different film or show that happens to share the title - searching for "Mulan" with year 2020
 183        /// returns the 1998 film first. A title that matches outranks one that does not, and the year only
 184        /// separates candidates that are otherwise equally good. When nothing matches at all TMDb's own
 185        /// ordering is kept, so a name that needs fuzzy matching, such as "A Christmas No. 1" for
 186        /// "A Christmas Number One", still resolves.
 187        /// </remarks>
 188        private static T? FindBestMatch<T>(
 189            IReadOnlyList<T>? results,
 190            string? name,
 191            int year,
 192            Func<T, string?> titleSelector,
 193            Func<T, string?> originalTitleSelector,
 194            Func<T, DateTime?> releaseDateSelector)
 195            where T : class
 196        {
 20197            if (results is null || results.Count == 0)
 198            {
 4199                return null;
 200            }
 201
 16202            var normalizedName = NormalizeTitle(name);
 16203            if (normalizedName.Length == 0)
 204            {
 1205                return results[0];
 206            }
 207
 15208            var best = results[0];
 15209            var bestScore = 0;
 210
 104211            foreach (var result in results)
 212            {
 37213                var score = Math.Max(
 37214                        ScoreTitle(normalizedName, titleSelector(result)),
 37215                        ScoreTitle(normalizedName, originalTitleSelector(result)))
 37216                    + ScoreYear(year, releaseDateSelector(result)?.Year);
 217
 218                // Strictly greater, so ties keep the earlier, more relevant result.
 37219                if (score > bestScore)
 220                {
 26221                    bestScore = score;
 26222                    best = result;
 223                }
 224            }
 225
 15226            return best;
 227        }
 228
 229        private static int ScoreTitle(string normalizedName, string? title)
 230        {
 74231            var normalizedTitle = NormalizeTitle(title);
 232
 74233            if (string.Equals(normalizedName, normalizedTitle, StringComparison.Ordinal))
 234            {
 49235                return TitleExactScore;
 236            }
 237
 238            // Whole words only, otherwise "Wall" half matches "Wall Street".
 25239            return normalizedTitle.Length > normalizedName.Length
 25240                && normalizedTitle[normalizedName.Length] == ' '
 25241                && normalizedTitle.StartsWith(normalizedName, StringComparison.Ordinal)
 25242                    ? TitlePrefixScore
 25243                    : 0;
 244        }
 245
 246        private static int ScoreYear(int year, int? resultYear)
 247        {
 37248            if (year <= 0 || resultYear is not int candidateYear)
 249            {
 2250                return 0;
 251            }
 252
 253            // Regional and festival release dates routinely straddle a new year, so a year off by one is as good as an 
 35254            return Math.Abs(candidateYear - year) <= 1 ? YearScore : 0;
 255        }
 256
 257        /// <summary>
 258        /// Maps the TMDb provided roles for crew members to Jellyfin roles.
 259        /// </summary>
 260        /// <param name="crew">Crew member to map against the Jellyfin person types.</param>
 261        /// <returns>The Jellyfin person type.</returns>
 262        public static PersonKind MapCrewToPersonType(Crew crew)
 263        {
 0264            if (string.Equals(crew.Department, "directing", StringComparison.OrdinalIgnoreCase)
 0265                && string.Equals(crew.Job, "director", StringComparison.OrdinalIgnoreCase))
 266            {
 0267                return PersonKind.Director;
 268            }
 269
 0270            if (string.Equals(crew.Department, "production", StringComparison.OrdinalIgnoreCase)
 0271                && string.Equals(crew.Job, "producer", StringComparison.OrdinalIgnoreCase))
 272            {
 0273                return PersonKind.Producer;
 274            }
 275
 0276            if (string.Equals(crew.Department, "writing", StringComparison.OrdinalIgnoreCase)
 0277                && crew.Job is not null && _writerJobs.Contains(crew.Job))
 278            {
 0279                return PersonKind.Writer;
 280            }
 281
 0282            return PersonKind.Unknown;
 283        }
 284
 285        /// <summary>
 286        /// Maps an aggregated TMDb cast list, whose entries hold every role their member played.
 287        /// </summary>
 288        /// <param name="cast">The aggregated cast list, or <c>null</c>.</param>
 289        /// <param name="config">The configuration deciding how much of the cast to keep.</param>
 290        /// <param name="getProfileUrl">Resolves a profile path into an absolute image url.</param>
 291        /// <returns>One credit per role played.</returns>
 292        internal static IEnumerable<PersonInfo> MapAggregateCast(
 293            IReadOnlyList<CastAggregate>? cast,
 294            PluginConfiguration config,
 295            Func<string?, string?> getProfileUrl)
 296        {
 5297            if (cast is null)
 298            {
 1299                yield break;
 300            }
 301
 4302            var billed = cast
 4303                .Where(member => !string.IsNullOrWhiteSpace(member.Name))
 4304                .Where(member => !config.HideMissingCastMembers || !string.IsNullOrEmpty(member.ProfilePath))
 4305                .OrderBy(member => member.Order)
 4306                .Take(config.MaxCastMembers);
 307
 18308            foreach (var member in billed)
 309            {
 310                // An actor playing several characters over the run gets one aggregated entry holding
 311                // every role, so each of them becomes a credit of its own here. Their own billing puts
 312                // the character they played the longest first.
 5313                var characters = member.Roles?
 5314                    .Where(role => !string.IsNullOrWhiteSpace(role.Character))
 5315                    .OrderByDescending(role => role.EpisodeCount)
 5316                    .Select(role => role.Character!.Trim())
 5317                    .ToArray();
 318
 5319                if (characters is null || characters.Length == 0)
 320                {
 1321                    characters = [string.Empty];
 322                }
 323
 22324                foreach (var character in characters)
 325                {
 6326                    yield return CreateCredit(member.Name!, member.Id, member.ProfilePath, member.Order, character, getP
 327                }
 5328            }
 4329        }
 330
 331        /// <summary>
 332        /// Maps a TMDb cast list whose entries hold the one character their member is credited for.
 333        /// </summary>
 334        /// <param name="cast">The cast list, or <c>null</c>.</param>
 335        /// <param name="config">The configuration deciding how much of the cast to keep.</param>
 336        /// <param name="getProfileUrl">Resolves a profile path into an absolute image url.</param>
 337        /// <returns>One credit per cast entry.</returns>
 338        internal static IEnumerable<PersonInfo> MapCast(
 339            IReadOnlyList<Cast>? cast,
 340            PluginConfiguration config,
 341            Func<string?, string?> getProfileUrl)
 342        {
 2343            if (cast is null)
 344            {
 1345                yield break;
 346            }
 347
 1348            var billed = cast
 1349                .Where(member => !string.IsNullOrWhiteSpace(member.Name))
 1350                .Where(member => !config.HideMissingCastMembers || !string.IsNullOrEmpty(member.ProfilePath))
 1351                .OrderBy(member => member.Order)
 1352                .Take(config.MaxCastMembers);
 353
 4354            foreach (var member in billed)
 355            {
 1356                yield return CreateCredit(member.Name!, member.Id, member.ProfilePath, member.Order, member.Character?.T
 357            }
 1358        }
 359
 360        private static PersonInfo CreateCredit(string name, int id, string? profilePath, int? order, string role, Func<s
 361        {
 7362            var personInfo = new PersonInfo
 7363            {
 7364                Name = name.Trim(),
 7365                Role = role,
 7366                Type = PersonKind.Actor,
 7367                SortOrder = order,
 7368                ImageUrl = getProfileUrl(profilePath)
 7369            };
 370
 7371            if (id > 0)
 372            {
 7373                personInfo.SetProviderId(MetadataProvider.Tmdb, id.ToString(CultureInfo.InvariantCulture));
 374            }
 375
 7376            return personInfo;
 377        }
 378
 379        /// <summary>
 380        /// Determines whether a video is a trailer.
 381        /// </summary>
 382        /// <param name="video">The TMDb video.</param>
 383        /// <returns>A boolean indicating whether the video is a trailer.</returns>
 384        public static bool IsTrailerType(Video video)
 385        {
 0386            return string.Equals(video.Site, "youtube", StringComparison.OrdinalIgnoreCase)
 0387                   && (string.Equals(video.Type, "trailer", StringComparison.OrdinalIgnoreCase)
 0388                       || string.Equals(video.Type, "teaser", StringComparison.OrdinalIgnoreCase));
 389        }
 390
 391        /// <summary>
 392        /// Normalizes a language string for use with TMDb's include image language parameter.
 393        /// </summary>
 394        /// <param name="preferredLanguage">The preferred language as either a 2 letter code with or without country cod
 395        /// <param name="countryCode">The country code, ISO 3166-1.</param>
 396        /// <returns>The comma separated language string.</returns>
 397        public static string GetImageLanguagesParam(string preferredLanguage, string? countryCode = null)
 398        {
 0399            var languages = new List<string>();
 400
 0401            if (!string.IsNullOrEmpty(preferredLanguage))
 402            {
 0403                preferredLanguage = NormalizeLanguage(preferredLanguage, countryCode);
 404
 0405                languages.Add(preferredLanguage);
 406            }
 407
 0408            languages.Add("null");
 409
 410            // Always add English as fallback language
 0411            if (!string.Equals(preferredLanguage, "en", StringComparison.OrdinalIgnoreCase))
 412            {
 0413                languages.Add("en");
 414            }
 415
 0416            return string.Join(',', languages);
 417        }
 418
 419        /// <summary>
 420        /// Normalizes a language string for use with TMDb's language parameter.
 421        /// </summary>
 422        /// <param name="language">The language code.</param>
 423        /// <param name="countryCode">The country code.</param>
 424        /// <returns>The normalized language code.</returns>
 425        [return: NotNullIfNotNull(nameof(language))]
 426        public static string? NormalizeLanguage(string? language, string? countryCode = null)
 427        {
 7428            if (string.IsNullOrEmpty(language))
 429            {
 2430                return language;
 431            }
 432
 433            // Handle es-419 (Latin American Spanish) by converting to regional variant
 5434            if (string.Equals(language, "es-419", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(countryCo
 435            {
 0436                language = string.Equals(countryCode, "AR", StringComparison.OrdinalIgnoreCase)
 0437                    ? "es-AR"
 0438                    : "es-MX";
 439            }
 440
 441            // TMDb requires this to be uppercase
 442            // Everything after the hyphen must be written in uppercase due to a way TMDb wrote their API.
 443            // See here: https://www.themoviedb.org/talk/5119221d760ee36c642af4ad?page=3#56e372a0c3a3685a9e0019ab
 5444            var parts = language.Split('-');
 445
 5446            if (parts.Length == 2)
 447            {
 448                // TMDb doesn't support Switzerland (de-CH, it-CH or fr-CH) so use the language (de, it or fr) without c
 3449                if (string.Equals(parts[1], "CH", StringComparison.OrdinalIgnoreCase))
 450                {
 1451                    return parts[0];
 452                }
 453
 2454                language = parts[0] + "-" + parts[1].ToUpperInvariant();
 455            }
 456
 4457            return language;
 458        }
 459
 460        /// <summary>
 461        /// Determines the language code to report for an image.
 462        /// </summary>
 463        /// <remarks>
 464        /// TMDb keeps an image's region in iso_3166_1, which is what separates a pt-PT poster from a pt-BR
 465        /// one. The region is added to the returned code only when it differs from the requested one, as in
 466        /// a pt-PT image for a pt-BR request. TMDb files nearly every image under a region, so adding it
 467        /// unconditionally would return en-US for an image that has to keep matching a plain "en" request.
 468        /// </remarks>
 469        /// <param name="imageLanguage">The image's ISO 639-1 language code.</param>
 470        /// <param name="imageRegion">The image's ISO 3166-1 country code.</param>
 471        /// <param name="requestLanguage">The requested language code.</param>
 472        /// <returns>The language code.</returns>
 473        public static string GetImageLanguage(string? imageLanguage, string? imageRegion, string? requestLanguage)
 474        {
 475            // TMDb now returns xx for no language instead of an empty string.
 12476            if (string.IsNullOrEmpty(imageLanguage) || string.Equals(imageLanguage, "xx", StringComparison.OrdinalIgnore
 477            {
 3478                return string.Empty;
 479            }
 480
 9481            if (string.IsNullOrEmpty(requestLanguage))
 482            {
 0483                return imageLanguage;
 484            }
 485
 9486            var requestParts = requestLanguage.Split('-');
 487
 9488            if (requestParts.Length != 2 || !string.Equals(requestParts[0], imageLanguage, StringComparison.OrdinalIgnor
 489            {
 4490                return imageLanguage;
 491            }
 492
 5493            return string.IsNullOrEmpty(imageRegion) || string.Equals(imageRegion, requestParts[1], StringComparison.Ord
 5494                ? requestLanguage
 5495                : imageLanguage + "-" + imageRegion.ToUpperInvariant();
 496        }
 497
 498        /// <summary>
 499        /// Determines whether the configured image size fetches the image at its original resolution.
 500        /// An unset size falls back to <see cref="OriginalImageSize"/>, see TmdbClientManager.GetUrl.
 501        /// </summary>
 502        /// <param name="size">The configured image size.</param>
 503        /// <returns><c>true</c> if the original image is fetched; otherwise, <c>false</c>.</returns>
 504        public static bool IsOriginalImageSize(string? size)
 6505            => string.IsNullOrEmpty(size) || string.Equals(size, OriginalImageSize, StringComparison.OrdinalIgnoreCase);
 506
 507        /// <summary>
 508        /// Combines the metadata country code and the parental rating from the API into the value we store in our datab
 509        /// </summary>
 510        /// <param name="countryCode">The ISO 3166-1 country code of the rating country.</param>
 511        /// <param name="ratingValue">The rating value returned by the TMDb API.</param>
 512        /// <returns>The combined parental rating of country code+rating value.</returns>
 513        public static string BuildParentalRating(string countryCode, string ratingValue)
 514        {
 515            // Exclude US because we store US values as TV-14 without the country code.
 0516            var ratingPrefix = string.Equals(countryCode, "US", StringComparison.OrdinalIgnoreCase) ? string.Empty : cou
 0517            var newRating = ratingPrefix + ratingValue;
 518
 0519            return newRating.Replace("DE-", "FSK-", StringComparison.OrdinalIgnoreCase);
 520        }
 521    }
 522}