< Summary - Jellyfin

Information
Class: MediaBrowser.Providers.Plugins.Tmdb.Movies.TmdbMovieProvider
Assembly: MediaBrowser.Providers
File(s): /srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
Line coverage
57%
Covered lines: 4
Uncovered lines: 3
Coverable lines: 7
Total lines: 376
Line coverage: 57.1%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
get_Order()100%210%
get_Name()100%210%
GetImageResponse(...)100%210%

File(s)

/srv/git/jellyfin/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.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.Movies;
 13using MediaBrowser.Controller.Library;
 14using MediaBrowser.Controller.Providers;
 15using MediaBrowser.Model.Entities;
 16using MediaBrowser.Model.Providers;
 17using TMDbLib.Objects.Find;
 18using TMDbLib.Objects.Search;
 19
 20namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
 21{
 22    /// <summary>
 23    /// Movie provider powered by TMDb.
 24    /// </summary>
 25    public class TmdbMovieProvider : IRemoteMetadataProvider<Movie, MovieInfo>, IHasOrder
 26    {
 27        private readonly IHttpClientFactory _httpClientFactory;
 28        private readonly ILibraryManager _libraryManager;
 29        private readonly TmdbClientManager _tmdbClientManager;
 30
 31        /// <summary>
 32        /// Initializes a new instance of the <see cref="TmdbMovieProvider"/> class.
 33        /// </summary>
 34        /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param>
 35        /// <param name="httpClientFactory">The <see cref="IHttpClientFactory"/>.</param>
 36        /// <param name="tmdbClientManager">The <see cref="TmdbClientManager"/>.</param>
 37        public TmdbMovieProvider(
 38            ILibraryManager libraryManager,
 39            TmdbClientManager tmdbClientManager,
 40            IHttpClientFactory httpClientFactory)
 41        {
 2142            _libraryManager = libraryManager;
 2143            _tmdbClientManager = tmdbClientManager;
 2144            _httpClientFactory = httpClientFactory;
 2145        }
 46
 47        /// <inheritdoc />
 048        public int Order => 1;
 49
 50        /// <inheritdoc />
 051        public string Name => TmdbUtils.ProviderName;
 52
 53        /// <inheritdoc />
 54        public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken canc
 55        {
 56            if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var id))
 57            {
 58                var movie = await _tmdbClientManager
 59                    .GetMovieAsync(
 60                        int.Parse(id, CultureInfo.InvariantCulture),
 61                        searchInfo.MetadataLanguage,
 62                        TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
 63                        cancellationToken)
 64                    .ConfigureAwait(false);
 65
 66                if (movie is not null)
 67                {
 68                    var remoteResult = new RemoteSearchResult
 69                    {
 70                        Name = movie.Title ?? movie.OriginalTitle,
 71                        SearchProviderName = Name,
 72                        ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
 73                        Overview = movie.Overview
 74                    };
 75
 76                    if (movie.ReleaseDate is not null)
 77                    {
 78                        var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
 79                        remoteResult.PremiereDate = releaseDate;
 80                        remoteResult.ProductionYear = releaseDate.Year;
 81                    }
 82
 83                    remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));
 84                    remoteResult.TrySetProviderId(MetadataProvider.Imdb, movie.ImdbId);
 85
 86                    return new[] { remoteResult };
 87                }
 88            }
 89
 90            IReadOnlyList<SearchMovie>? movieResults = null;
 91            if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out id))
 92            {
 93                var result = await _tmdbClientManager.FindByExternalIdAsync(
 94                    id,
 95                    FindExternalSource.Imdb,
 96                    TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
 97                    cancellationToken).ConfigureAwait(false);
 98                movieResults = result?.MovieResults;
 99            }
 100
 101            if (movieResults is null && searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out id))
 102            {
 103                var result = await _tmdbClientManager.FindByExternalIdAsync(
 104                    id,
 105                    FindExternalSource.TvDb,
 106                    TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
 107                    cancellationToken).ConfigureAwait(false);
 108                movieResults = result?.MovieResults;
 109            }
 110
 111            if (movieResults is null)
 112            {
 113                movieResults = await _tmdbClientManager
 114                    .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationTo
 115                    .ConfigureAwait(false);
 116            }
 117
 118            var len = movieResults.Count;
 119            var remoteSearchResults = new RemoteSearchResult[len];
 120            for (var i = 0; i < len; i++)
 121            {
 122                var movieResult = movieResults[i];
 123                var remoteSearchResult = new RemoteSearchResult
 124                {
 125                    Name = movieResult.Title ?? movieResult.OriginalTitle,
 126                    ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
 127                    Overview = movieResult.Overview,
 128                    SearchProviderName = Name
 129                };
 130
 131                var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
 132                remoteSearchResult.PremiereDate = releaseDate;
 133                remoteSearchResult.ProductionYear = releaseDate?.Year;
 134
 135                remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCul
 136                remoteSearchResults[i] = remoteSearchResult;
 137            }
 138
 139            return remoteSearchResults;
 140        }
 141
 142        /// <inheritdoc />
 143        public async Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
 144        {
 145            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
 146            var imdbId = info.GetProviderId(MetadataProvider.Imdb);
 147            var config = Plugin.Instance.Configuration;
 148
 149            if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
 150            {
 151                // ParseName is required here.
 152                // Caller provides the filename with extension stripped and NOT the parsed filename
 153                var parsedName = _libraryManager.ParseName(info.Name);
 154                var cleanedName = TmdbUtils.CleanName(parsedName.Name);
 155                var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year 
 156
 157                if (searchResults.Count > 0)
 158                {
 159                    tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
 160                }
 161            }
 162
 163            if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId))
 164            {
 165                var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Im
 166                if (movieResultFromImdbId?.MovieResults.Count > 0)
 167                {
 168                    tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString(CultureInfo.InvariantCulture);
 169                }
 170            }
 171
 172            if (string.IsNullOrEmpty(tmdbId))
 173            {
 174                return new MetadataResult<Movie>();
 175            }
 176
 177            var movieResult = await _tmdbClientManager
 178                .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.G
 179                .ConfigureAwait(false);
 180
 181            if (movieResult is null)
 182            {
 183                return new MetadataResult<Movie>();
 184            }
 185
 186            var movie = new Movie
 187            {
 188                Name = movieResult.Title ?? movieResult.OriginalTitle,
 189                OriginalTitle = movieResult.OriginalTitle,
 190                Overview = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
 191                Tagline = movieResult.Tagline,
 192                ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
 193            };
 194            var metadataResult = new MetadataResult<Movie>
 195            {
 196                HasMetadata = true,
 197                ResultLanguage = info.MetadataLanguage,
 198                Item = movie
 199            };
 200
 201            movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
 202            movie.TrySetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
 203            if (movieResult.BelongsToCollection is not null)
 204            {
 205                movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(Culture
 206                movie.CollectionName = movieResult.BelongsToCollection.Name;
 207            }
 208
 209            movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);
 210
 211            if (movieResult.Releases?.Countries is not null)
 212            {
 213                var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).To
 214
 215                var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, Stri
 216
 217                if (ourRelease is not null)
 218                {
 219                    movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification
 220                }
 221                else
 222                {
 223                    var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.Ordi
 224                    if (usRelease is not null)
 225                    {
 226                        movie.OfficialRating = usRelease.Certification;
 227                    }
 228                }
 229            }
 230
 231            movie.PremiereDate = movieResult.ReleaseDate;
 232            movie.ProductionYear = movieResult.ReleaseDate?.Year;
 233
 234            if (movieResult.ProductionCompanies is not null)
 235            {
 236                movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
 237            }
 238
 239            var genres = movieResult.Genres;
 240
 241            foreach (var genre in genres.Select(g => g.Name).Trimmed())
 242            {
 243                movie.AddGenre(genre);
 244            }
 245
 246            if (movieResult.Keywords?.Keywords is not null)
 247            {
 248                for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
 249                {
 250                    movie.AddTag(movieResult.Keywords.Keywords[i].Name);
 251                }
 252            }
 253
 254            if (movieResult.Credits?.Cast is not null)
 255            {
 256                var castQuery = movieResult.Credits.Cast.AsEnumerable();
 257
 258                if (config.HideMissingCastMembers)
 259                {
 260                    castQuery = castQuery.Where(a => !string.IsNullOrEmpty(a.ProfilePath));
 261                }
 262
 263                castQuery = castQuery.OrderBy(a => a.Order).Take(config.MaxCastMembers);
 264
 265                foreach (var actor in castQuery)
 266                {
 267                    if (string.IsNullOrWhiteSpace(actor.Name))
 268                    {
 269                        continue;
 270                    }
 271
 272                    var personInfo = new PersonInfo
 273                    {
 274                        Name = actor.Name.Trim(),
 275                        Role = actor.Character?.Trim() ?? string.Empty,
 276                        Type = PersonKind.Actor,
 277                        SortOrder = actor.Order
 278                    };
 279
 280                    if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
 281                    {
 282                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
 283                    }
 284
 285                    if (actor.Id > 0)
 286                    {
 287                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture))
 288                    }
 289
 290                    metadataResult.AddPerson(personInfo);
 291                }
 292            }
 293
 294            if (movieResult.Credits?.Crew is not null)
 295            {
 296                var crewQuery = movieResult.Credits.Crew
 297                    .Select(crewMember => new
 298                    {
 299                        CrewMember = crewMember,
 300                        PersonType = TmdbUtils.MapCrewToPersonType(crewMember)
 301                    })
 302                    .Where(entry =>
 303                        TmdbUtils.WantedCrewKinds.Contains(entry.PersonType) ||
 304                        TmdbUtils.WantedCrewTypes.Contains(entry.CrewMember.Job ?? string.Empty, StringComparison.Ordina
 305
 306                if (config.HideMissingCrewMembers)
 307                {
 308                    crewQuery = crewQuery.Where(entry => !string.IsNullOrEmpty(entry.CrewMember.ProfilePath));
 309                }
 310
 311                crewQuery = crewQuery.Take(config.MaxCrewMembers);
 312
 313                foreach (var entry in crewQuery)
 314                {
 315                    var crewMember = entry.CrewMember;
 316
 317                    if (string.IsNullOrWhiteSpace(crewMember.Name))
 318                    {
 319                        continue;
 320                    }
 321
 322                    var personInfo = new PersonInfo
 323                    {
 324                        Name = crewMember.Name.Trim(),
 325                        Role = crewMember.Job?.Trim() ?? string.Empty,
 326                        Type = entry.PersonType
 327                    };
 328
 329                    if (!string.IsNullOrWhiteSpace(crewMember.ProfilePath))
 330                    {
 331                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(crewMember.ProfilePath);
 332                    }
 333
 334                    if (crewMember.Id > 0)
 335                    {
 336                        personInfo.SetProviderId(MetadataProvider.Tmdb, crewMember.Id.ToString(CultureInfo.InvariantCult
 337                    }
 338
 339                    metadataResult.AddPerson(personInfo);
 340                }
 341            }
 342
 343            if (movieResult.Videos?.Results is not null)
 344            {
 345                var trailers = new List<MediaUrl>();
 346
 347                var sortedVideos = movieResult.Videos.Results
 348                    .OrderByDescending(video => string.Equals(video.Type, "trailer", StringComparison.OrdinalIgnoreCase)
 349
 350                foreach (var video in sortedVideos)
 351                {
 352                    if (!TmdbUtils.IsTrailerType(video))
 353                    {
 354                        continue;
 355                    }
 356
 357                    trailers.Add(new MediaUrl
 358                    {
 359                        Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.K
 360                        Name = video.Name
 361                    });
 362                }
 363
 364                movie.RemoteTrailers = trailers;
 365            }
 366
 367            return metadataResult;
 368        }
 369
 370        /// <inheritdoc />
 371        public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
 372        {
 0373            return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
 374        }
 375    }
 376}