< 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: 370
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                var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalI
 217
 218                if (ourRelease is not null)
 219                {
 220                    movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification
 221                }
 222                else if (usRelease is not null)
 223                {
 224                    movie.OfficialRating = usRelease.Certification;
 225                }
 226            }
 227
 228            movie.PremiereDate = movieResult.ReleaseDate;
 229            movie.ProductionYear = movieResult.ReleaseDate?.Year;
 230
 231            if (movieResult.ProductionCompanies is not null)
 232            {
 233                movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
 234            }
 235
 236            var genres = movieResult.Genres;
 237
 238            foreach (var genre in genres.Select(g => g.Name).Trimmed())
 239            {
 240                movie.AddGenre(genre);
 241            }
 242
 243            if (movieResult.Keywords?.Keywords is not null)
 244            {
 245                for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
 246                {
 247                    movie.AddTag(movieResult.Keywords.Keywords[i].Name);
 248                }
 249            }
 250
 251            if (movieResult.Credits?.Cast is not null)
 252            {
 253                var castQuery = movieResult.Credits.Cast.AsEnumerable();
 254
 255                if (config.HideMissingCastMembers)
 256                {
 257                    castQuery = castQuery.Where(a => !string.IsNullOrEmpty(a.ProfilePath));
 258                }
 259
 260                castQuery = castQuery.OrderBy(a => a.Order).Take(config.MaxCastMembers);
 261
 262                foreach (var actor in castQuery)
 263                {
 264                    if (string.IsNullOrWhiteSpace(actor.Name))
 265                    {
 266                        continue;
 267                    }
 268
 269                    var personInfo = new PersonInfo
 270                    {
 271                        Name = actor.Name.Trim(),
 272                        Role = actor.Character?.Trim() ?? string.Empty,
 273                        Type = PersonKind.Actor,
 274                        SortOrder = actor.Order
 275                    };
 276
 277                    if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
 278                    {
 279                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
 280                    }
 281
 282                    if (actor.Id > 0)
 283                    {
 284                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture))
 285                    }
 286
 287                    metadataResult.AddPerson(personInfo);
 288                }
 289            }
 290
 291            if (movieResult.Credits?.Crew is not null)
 292            {
 293                var crewQuery = movieResult.Credits.Crew
 294                    .Select(crewMember => new
 295                    {
 296                        CrewMember = crewMember,
 297                        PersonType = TmdbUtils.MapCrewToPersonType(crewMember)
 298                    })
 299                    .Where(entry =>
 300                        TmdbUtils.WantedCrewKinds.Contains(entry.PersonType) ||
 301                        TmdbUtils.WantedCrewTypes.Contains(entry.CrewMember.Job ?? string.Empty, StringComparison.Ordina
 302
 303                if (config.HideMissingCrewMembers)
 304                {
 305                    crewQuery = crewQuery.Where(entry => !string.IsNullOrEmpty(entry.CrewMember.ProfilePath));
 306                }
 307
 308                crewQuery = crewQuery.Take(config.MaxCrewMembers);
 309
 310                foreach (var entry in crewQuery)
 311                {
 312                    var crewMember = entry.CrewMember;
 313
 314                    if (string.IsNullOrWhiteSpace(crewMember.Name))
 315                    {
 316                        continue;
 317                    }
 318
 319                    var personInfo = new PersonInfo
 320                    {
 321                        Name = crewMember.Name.Trim(),
 322                        Role = crewMember.Job?.Trim() ?? string.Empty,
 323                        Type = entry.PersonType
 324                    };
 325
 326                    if (!string.IsNullOrWhiteSpace(crewMember.ProfilePath))
 327                    {
 328                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(crewMember.ProfilePath);
 329                    }
 330
 331                    if (crewMember.Id > 0)
 332                    {
 333                        personInfo.SetProviderId(MetadataProvider.Tmdb, crewMember.Id.ToString(CultureInfo.InvariantCult
 334                    }
 335
 336                    metadataResult.AddPerson(personInfo);
 337                }
 338            }
 339
 340            if (movieResult.Videos?.Results is not null)
 341            {
 342                var trailers = new List<MediaUrl>();
 343                for (var i = 0; i < movieResult.Videos.Results.Count; i++)
 344                {
 345                    var video = movieResult.Videos.Results[i];
 346                    if (!TmdbUtils.IsTrailerType(video))
 347                    {
 348                        continue;
 349                    }
 350
 351                    trailers.Add(new MediaUrl
 352                    {
 353                        Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.K
 354                        Name = video.Name
 355                    });
 356                }
 357
 358                movie.RemoteTrailers = trailers;
 359            }
 360
 361            return metadataResult;
 362        }
 363
 364        /// <inheritdoc />
 365        public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
 366        {
 0367            return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
 368        }
 369    }
 370}