< Summary - Jellyfin

Information
Class: MediaBrowser.Providers.Plugins.Tmdb.TV.TmdbSeriesProvider
Assembly: MediaBrowser.Providers
File(s): /srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs
Line coverage
1%
Covered lines: 4
Uncovered lines: 232
Coverable lines: 236
Total lines: 493
Line coverage: 1.6%
Branch coverage
0%
Covered branches: 0
Total branches: 196
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 5/29/2026 - 12:15:07 AM Line coverage: 2% (4/200) Branch coverage: 0% (0/152) Total lines: 4286/18/2026 - 12:16:24 AM Line coverage: 1.8% (4/212) Branch coverage: 0% (0/160) Total lines: 4537/18/2026 - 12:15:19 AM Line coverage: 1.8% (4/216) Branch coverage: 0% (0/162) Total lines: 4627/21/2026 - 12:16:33 AM Line coverage: 1.7% (4/224) Branch coverage: 0% (0/162) Total lines: 47510/29/2026 - 12:17:11 AM Line coverage: 1.6% (4/236) Branch coverage: 0% (0/196) Total lines: 493 5/29/2026 - 12:15:07 AM Line coverage: 2% (4/200) Branch coverage: 0% (0/152) Total lines: 4286/18/2026 - 12:16:24 AM Line coverage: 1.8% (4/212) Branch coverage: 0% (0/160) Total lines: 4537/18/2026 - 12:15:19 AM Line coverage: 1.8% (4/216) Branch coverage: 0% (0/162) Total lines: 4627/21/2026 - 12:16:33 AM Line coverage: 1.7% (4/224) Branch coverage: 0% (0/162) Total lines: 47510/29/2026 - 12:17:11 AM Line coverage: 1.6% (4/236) Branch coverage: 0% (0/196) Total lines: 493

Coverage delta

Coverage delta 1 -1

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Name()100%210%
get_Order()100%210%
GetSearchResults()0%600240%
MapTvShowToRemoteSearchResult(...)0%7280%
MapSearchTvToRemoteSearchResult(...)0%4260%
GetMetadata()0%1190340%
MapTvShowToSeries(...)0%2352480%
GetPersons()0%1190340%
GetImageResponse(...)100%210%
MapDisplayOrderToTvGroupType(...)0%1056320%
WithDisplayOrder(...)0%110100%

File(s)

/srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesProvider.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Globalization;
 4using System.Linq;
 5using System.Net.Http;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using Jellyfin.Data.Enums;
 9using Jellyfin.Extensions;
 10using MediaBrowser.Common.Net;
 11using MediaBrowser.Controller.Entities;
 12using MediaBrowser.Controller.Entities.TV;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Controller.Providers;
 15using MediaBrowser.Model.Entities;
 16using MediaBrowser.Model.Providers;
 17using TMDbLib.Objects.Find;
 18using TMDbLib.Objects.Search;
 19using TMDbLib.Objects.TvShows;
 20
 21namespace MediaBrowser.Providers.Plugins.Tmdb.TV
 22{
 23    /// <summary>
 24    /// TV series provider powered by TheMovieDb.
 25    /// </summary>
 26    public class TmdbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
 27    {
 28        private readonly IHttpClientFactory _httpClientFactory;
 29        private readonly ILibraryManager _libraryManager;
 30        private readonly TmdbClientManager _tmdbClientManager;
 31
 32        /// <summary>
 33        /// Initializes a new instance of the <see cref="TmdbSeriesProvider"/> class.
 34        /// </summary>
 35        /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
 36        /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
 37        /// <param name="tmdbClientManager">The <see cref="TmdbClientManager"/>.</param>
 38        public TmdbSeriesProvider(
 39            ILibraryManager libraryManager,
 40            IHttpClientFactory httpClientFactory,
 41            TmdbClientManager tmdbClientManager)
 42        {
 2743            _libraryManager = libraryManager;
 2744            _httpClientFactory = httpClientFactory;
 2745            _tmdbClientManager = tmdbClientManager;
 2746        }
 47
 48        /// <inheritdoc />
 049        public string Name => TmdbUtils.ProviderName;
 50
 51        /// <inheritdoc />
 052        public int Order => 1;
 53
 54        /// <inheritdoc />
 55        public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken can
 56        {
 057            if (searchInfo.TryGetTmdbId(out var tmdbId))
 58            {
 059                var series = await _tmdbClientManager
 060                    .GetSeriesAsync(tmdbId, searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, searchInfo.Metadat
 061                    .ConfigureAwait(false);
 62
 063                if (series is not null)
 64                {
 065                    var remoteResult = MapTvShowToRemoteSearchResult(series, searchInfo);
 66
 067                    return new[] { remoteResult };
 68                }
 69            }
 70
 071            if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
 72            {
 073                var findResult = await _tmdbClientManager
 074                    .FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, searchInfo.MetadataLanguage, searchInfo.Meta
 075                    .ConfigureAwait(false);
 76
 077                var tvResults = findResult?.TvResults;
 078                if (tvResults is not null)
 79                {
 080                    var imdbIdResults = new RemoteSearchResult[tvResults.Count];
 081                    for (var i = 0; i < tvResults.Count; i++)
 82                    {
 083                        var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
 084                        remoteResult.SetProviderId(MetadataProvider.Imdb, imdbId);
 085                        imdbIdResults[i] = remoteResult;
 86                    }
 87
 088                    return imdbIdResults;
 89                }
 90            }
 91
 092            if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
 93            {
 094                var findResult = await _tmdbClientManager
 095                    .FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, searchInfo.MetadataLanguage, searchInfo.Meta
 096                    .ConfigureAwait(false);
 97
 098                var tvResults = findResult?.TvResults;
 099                if (tvResults is not null)
 100                {
 0101                    var tvIdResults = new RemoteSearchResult[tvResults.Count];
 0102                    for (var i = 0; i < tvResults.Count; i++)
 103                    {
 0104                        var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
 0105                        remoteResult.SetProviderId(MetadataProvider.Tvdb, tvdbId);
 0106                        tvIdResults[i] = remoteResult;
 107                    }
 108
 0109                    return tvIdResults;
 110                }
 111            }
 112
 0113            var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguag
 0114                .ConfigureAwait(false);
 0115            if (tvSearchResults is null)
 116            {
 0117                return [];
 118            }
 119
 0120            var remoteResults = new RemoteSearchResult[tvSearchResults.Count];
 0121            for (var i = 0; i < tvSearchResults.Count; i++)
 122            {
 0123                remoteResults[i] = MapSearchTvToRemoteSearchResult(tvSearchResults[i]);
 124            }
 125
 0126            return remoteResults;
 0127        }
 128
 129        private RemoteSearchResult MapTvShowToRemoteSearchResult(TvShow series, SeriesInfo search)
 130        {
 0131            var remoteResult = new RemoteSearchResult
 0132            {
 0133                Name = series.Name ?? series.OriginalName,
 0134                SearchProviderName = Name,
 0135                ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
 0136                Overview = series.Overview
 0137            };
 138
 0139            remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
 0140            if (series.ExternalIds is not null)
 141            {
 0142                remoteResult.TrySetProviderId(MetadataProvider.Imdb, series.ExternalIds.ImdbId);
 143
 0144                remoteResult.TrySetProviderId(MetadataProvider.Tvdb, series.ExternalIds.TvdbId);
 145            }
 146
 0147            WithDisplayOrder(series, remoteResult, search);
 148
 0149            remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
 0150            remoteResult.ProductionYear = series.FirstAirDate?.Year;
 151
 0152            return remoteResult;
 153        }
 154
 155        private RemoteSearchResult MapSearchTvToRemoteSearchResult(SearchTv series)
 156        {
 0157            var remoteResult = new RemoteSearchResult
 0158            {
 0159                Name = series.Name ?? series.OriginalName,
 0160                SearchProviderName = Name,
 0161                ImageUrl = _tmdbClientManager.GetPosterUrl(series.PosterPath),
 0162                Overview = series.Overview
 0163            };
 164
 0165            remoteResult.SetProviderId(MetadataProvider.Tmdb, series.Id.ToString(CultureInfo.InvariantCulture));
 0166            remoteResult.PremiereDate = series.FirstAirDate?.ToUniversalTime();
 0167            remoteResult.ProductionYear = series.FirstAirDate?.Year;
 168
 0169            return remoteResult;
 170        }
 171
 172        /// <inheritdoc />
 173        public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
 174        {
 0175            var result = new MetadataResult<Series>
 0176            {
 0177                QueriedById = true
 0178            };
 179
 0180            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
 181
 0182            if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
 183            {
 0184                var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.
 0185                if (searchResult?.TvResults?.Count > 0)
 186                {
 0187                    tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
 188                }
 189            }
 190
 0191            if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
 192            {
 0193                var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.
 0194                if (searchResult?.TvResults?.Count > 0)
 195                {
 0196                    tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
 197                }
 198            }
 199
 0200            if (string.IsNullOrEmpty(tmdbId))
 201            {
 0202                result.QueriedById = false;
 203                // ParseName is required here.
 204                // Caller provides the filename with extension stripped and NOT the parsed filename
 0205                var parsedName = _libraryManager.ParseName(info.Name);
 0206                var cleanedName = TmdbUtils.CleanName(parsedName.Name);
 0207                var searchYear = info.Year ?? parsedName.Year ?? 0;
 0208                var searchResults = await _tmdbClientManager.SearchSeriesAsync(cleanedName, info.MetadataLanguage, info.
 209
 0210                var match = TmdbUtils.FindBestMatch(searchResults, parsedName.Name, searchYear);
 211
 0212                if (match is not null)
 213                {
 0214                    tmdbId = match.Id.ToString(CultureInfo.InvariantCulture);
 215                }
 0216            }
 217
 0218            if (!int.TryParse(tmdbId, CultureInfo.InvariantCulture, out int tmdbIdInt))
 219            {
 0220                return result;
 221            }
 222
 0223            cancellationToken.ThrowIfCancellationRequested();
 224
 0225            var tvShow = await _tmdbClientManager
 0226                .GetSeriesAsync(tmdbIdInt, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage
 0227                .ConfigureAwait(false);
 228
 0229            if (tvShow is null)
 230            {
 0231                return result;
 232            }
 233
 0234            result = new MetadataResult<Series>
 0235            {
 0236                Item = MapTvShowToSeries(tvShow, info.MetadataCountryCode, info),
 0237                ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage
 0238            };
 239
 0240            foreach (var person in GetPersons(tvShow))
 241            {
 0242                result.AddPerson(person);
 243            }
 244
 0245            result.HasMetadata = result.Item is not null;
 246
 0247            return result;
 0248        }
 249
 250        private static Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode, SeriesInfo search)
 251        {
 0252            var series = new Series
 0253            {
 0254                Name = seriesResult.Name,
 0255                OriginalTitle = seriesResult.OriginalName
 0256            };
 257
 0258            series.SetProviderId(MetadataProvider.Tmdb, seriesResult.Id.ToString(CultureInfo.InvariantCulture));
 259
 0260            series.CommunityRating = Convert.ToSingle(seriesResult.VoteAverage);
 261
 0262            series.Overview = seriesResult.Overview;
 263
 0264            var studios = Enumerable.Empty<string>();
 265
 0266            if (seriesResult.Networks is not null)
 267            {
 0268                studios = studios.Concat(seriesResult.Networks.Select(i => i.Name).OfType<string>());
 269            }
 270
 0271            if (seriesResult.ProductionCompanies is not null)
 272            {
 0273                studios = studios.Concat(seriesResult.ProductionCompanies.Select(i => i.Name).OfType<string>());
 274            }
 275
 0276            series.SetStudios(studios);
 277
 0278            if (seriesResult.Genres is not null)
 279            {
 0280                series.Genres = seriesResult.Genres.Select(i => i.Name).ToArray();
 281            }
 282
 0283            if (seriesResult.Keywords?.Results is not null)
 284            {
 0285                foreach (var result in seriesResult.Keywords.Results)
 286                {
 0287                    var name = result.Name;
 0288                    if (!string.IsNullOrWhiteSpace(name))
 289                    {
 0290                        series.AddTag(name);
 291                    }
 292                }
 293            }
 294
 0295            series.HomePageUrl = seriesResult.Homepage;
 296
 0297            series.RunTimeTicks = seriesResult.EpisodeRunTime?.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault
 298
 0299            if (Emby.Naming.TV.TvParserHelpers.TryParseSeriesStatus(seriesResult.Status, out var seriesStatus))
 300            {
 0301                series.Status = seriesStatus;
 302            }
 303
 0304            series.EndDate = seriesResult.LastAirDate;
 0305            series.PremiereDate = seriesResult.FirstAirDate;
 0306            series.ProductionYear = seriesResult.FirstAirDate?.Year;
 307
 0308            var ids = seriesResult.ExternalIds;
 0309            if (ids is not null)
 310            {
 0311                series.TrySetProviderId(MetadataProvider.Imdb, ids.ImdbId);
 0312                series.TrySetProviderId(MetadataProvider.TvRage, ids.TvrageId);
 0313                series.TrySetProviderId(MetadataProvider.Tvdb, ids.TvdbId);
 314            }
 315
 0316            var contentRatings = seriesResult.ContentRatings?.Results ?? new List<ContentRating>();
 317
 0318            var ourRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, String
 0319            var usRelease = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.Ordina
 0320            var minimumRelease = contentRatings.FirstOrDefault();
 321
 0322            if (ourRelease?.Rating is not null)
 323            {
 0324                series.OfficialRating = TmdbUtils.BuildParentalRating(preferredCountryCode, ourRelease.Rating);
 325            }
 0326            else if (usRelease?.Rating is not null)
 327            {
 0328                series.OfficialRating = usRelease.Rating;
 329            }
 0330            else if (minimumRelease?.Rating is not null)
 331            {
 0332                series.OfficialRating = minimumRelease.Rating;
 333            }
 334
 0335            if (seriesResult.Videos?.Results is not null)
 336            {
 0337                var trailers = new List<MediaUrl>();
 338
 0339                var sortedVideos = seriesResult.Videos.Results
 0340                    .OrderByDescending(video => string.Equals(video.Type, "trailer", StringComparison.OrdinalIgnoreCase)
 341
 0342                foreach (var video in sortedVideos)
 343                {
 0344                    if (!TmdbUtils.IsTrailerType(video))
 345                    {
 346                        continue;
 347                    }
 348
 0349                    trailers.Add(new MediaUrl
 0350                    {
 0351                        Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.K
 0352                        Name = video.Name
 0353                    });
 354                }
 355
 0356                series.RemoteTrailers = trailers;
 357            }
 358
 0359            if (!string.IsNullOrEmpty(seriesResult.OriginalLanguage))
 360            {
 0361                series.OriginalLanguage = seriesResult.OriginalLanguage;
 362            }
 363
 0364            WithDisplayOrder(seriesResult, series, search);
 365
 0366            return series;
 367        }
 368
 369        private IEnumerable<PersonInfo> GetPersons(TvShow seriesResult)
 370        {
 0371            var config = Plugin.Instance.Configuration;
 372
 373            // The aggregated credits are what hold an actor's several characters apart; the flat ones
 374            // put them in a single string. Only the aggregated list carries the whole run, so prefer it
 375            // and fall back for the rare show TMDb has no aggregation for.
 0376            var cast = seriesResult.AggregateCredits?.Cast is { Count: > 0 } aggregated
 0377                ? TmdbUtils.MapAggregateCast(aggregated, config, _tmdbClientManager.GetProfileUrl)
 0378                : TmdbUtils.MapCast(seriesResult.Credits?.Cast, config, _tmdbClientManager.GetProfileUrl);
 379
 0380            foreach (var actor in cast)
 381            {
 0382                yield return actor;
 383            }
 384
 0385            if (seriesResult.Credits?.Crew is not null)
 386            {
 0387                var crewQuery = seriesResult.Credits.Crew
 0388                    .Select(crewMember => new
 0389                    {
 0390                        CrewMember = crewMember,
 0391                        PersonType = TmdbUtils.MapCrewToPersonType(crewMember)
 0392                    })
 0393                    .Where(entry => TmdbUtils.WantedCrewKinds.Contains(entry.PersonType));
 394
 0395                if (config.HideMissingCrewMembers)
 396                {
 0397                    crewQuery = crewQuery.Where(entry => !string.IsNullOrEmpty(entry.CrewMember.ProfilePath));
 398                }
 399
 0400                foreach (var entry in crewQuery.Take(config.MaxCrewMembers))
 401                {
 0402                    var crewMember = entry.CrewMember;
 403
 0404                    if (string.IsNullOrWhiteSpace(crewMember.Name))
 405                    {
 406                        continue;
 407                    }
 408
 0409                    var personInfo = new PersonInfo
 0410                    {
 0411                        Name = crewMember.Name.Trim(),
 0412                        Role = crewMember.Job?.Trim() ?? string.Empty,
 0413                        Type = entry.PersonType,
 0414                        // NOTE: Null values are filtered out above
 0415                        ImageUrl = _tmdbClientManager.GetProfileUrl(crewMember.ProfilePath!)
 0416                    };
 417
 0418                    if (crewMember.Id > 0)
 419                    {
 0420                        personInfo.SetProviderId(MetadataProvider.Tmdb, crewMember.Id.ToString(CultureInfo.InvariantCult
 421                    }
 422
 0423                    yield return personInfo;
 424                }
 425            }
 426
 0427            if (seriesResult.CreatedBy is not null)
 428            {
 0429                foreach (var person in seriesResult.CreatedBy)
 430                {
 0431                    if (string.IsNullOrWhiteSpace(person.Name))
 432                    {
 433                        continue;
 434                    }
 435
 0436                    var personInfo = new PersonInfo
 0437                    {
 0438                        Name = person.Name.Trim(),
 0439                        Type = PersonKind.Creator,
 0440                        ImageUrl = _tmdbClientManager.GetProfileUrl(person.ProfilePath)
 0441                    };
 442
 0443                    if (person.Id > 0)
 444                    {
 0445                        personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture)
 446                    }
 447
 0448                    yield return personInfo;
 449                }
 450            }
 0451        }
 452
 453        /// <inheritdoc />
 454        public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
 455        {
 0456            return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
 457        }
 458
 459        private static TvGroupType? MapDisplayOrderToTvGroupType(string? displayOrder)
 460        {
 0461            return displayOrder switch
 0462            {
 0463                "originalAirDate" => TvGroupType.OriginalAirDate,
 0464                "absolute" => TvGroupType.Absolute,
 0465                "dvd" => TvGroupType.DVD,
 0466                "digital" => TvGroupType.Digital,
 0467                "storyArc" => TvGroupType.StoryArc,
 0468                "production" => TvGroupType.Production,
 0469                "tv" => TvGroupType.TV,
 0470                _ => null,
 0471            };
 472        }
 473
 474        private static void WithDisplayOrder(TvShow searchResult, IHasProviderIds providerIds, SeriesInfo search)
 475        {
 0476            if (!search.TryGetProviderId(TmdbEpisodeGroupId.ProviderKey, out var episodeGroupId)
 0477                && searchResult.EpisodeGroups?.Results is not null)
 478            {
 0479                var tvGroupType = MapDisplayOrderToTvGroupType(search.DisplayOrder);
 0480                if (tvGroupType is not null)
 481                {
 0482                    var episodeGroup = searchResult.EpisodeGroups.Results.Find(g => g.Type == tvGroupType);
 0483                    if (episodeGroup is not null)
 484                    {
 0485                        episodeGroupId = episodeGroup.Id;
 486                    }
 487                }
 488            }
 489
 0490            providerIds.TrySetProviderId(TmdbEpisodeGroupId.ProviderKey, episodeGroupId);
 0491        }
 492    }
 493}