Ejemplo n.º 1
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var tmdbId = item.GetProviderId(MetadataProvider.Tmdb);

            if (string.IsNullOrEmpty(tmdbId))
            {
                return(null);
            }

            var language = item.GetPreferredMetadataLanguage();

            var series = await _tmdbClientManager
                         .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
                         .ConfigureAwait(false);

            if (series?.Images == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var posters   = series.Images.Posters;
            var backdrops = series.Images.Backdrops;

            var remoteImages = new RemoteImageInfo[posters.Count + backdrops.Count];

            for (var i = 0; i < posters.Count; i++)
            {
                var poster = posters[i];
                remoteImages[i] = new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(poster.FilePath),
                    CommunityRating = poster.VoteAverage,
                    VoteCount       = poster.VoteCount,
                    Width           = poster.Width,
                    Height          = poster.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                };
            }

            for (var i = 0; i < backdrops.Count; i++)
            {
                var backdrop = series.Images.Backdrops[i];
                remoteImages[posters.Count + i] = new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
                    CommunityRating = backdrop.VoteAverage,
                    VoteCount       = backdrop.VoteCount,
                    Width           = backdrop.Width,
                    Height          = backdrop.Height,
                    ProviderName    = Name,
                    Type            = ImageType.Backdrop,
                    RatingType      = RatingType.Score
                };
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 2
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var person = (Person)item;

            if (!person.TryGetProviderId(MetadataProvider.Tmdb, out var personTmdbId))
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var personResult = await _tmdbClientManager.GetPersonAsync(int.Parse(personTmdbId, CultureInfo.InvariantCulture), cancellationToken).ConfigureAwait(false);

            if (personResult?.Images?.Profiles == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new RemoteImageInfo[personResult.Images.Profiles.Count];
            var language     = item.GetPreferredMetadataLanguage();

            for (var i = 0; i < personResult.Images.Profiles.Count; i++)
            {
                var image = personResult.Images.Profiles[i];
                remoteImages[i] = new RemoteImageInfo
                {
                    ProviderName = Name,
                    Type         = ImageType.Primary,
                    Width        = image.Width,
                    Height       = image.Height,
                    Language     = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
                    Url          = _tmdbClientManager.GetProfileUrl(image.FilePath)
                };
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 3
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var tmdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (tmdbId <= 0)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var language = item.GetPreferredMetadataLanguage();

            // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
            var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, null, null, cancellationToken).ConfigureAwait(false);

            if (collection?.Images == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new List <RemoteImageInfo>();

            for (var i = 0; i < collection.Images.Posters.Count; i++)
            {
                var poster = collection.Images.Posters[i];
                remoteImages.Add(new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(poster.FilePath),
                    CommunityRating = poster.VoteAverage,
                    VoteCount       = poster.VoteCount,
                    Width           = poster.Width,
                    Height          = poster.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                });
            }

            for (var i = 0; i < collection.Images.Backdrops.Count; i++)
            {
                var backdrop = collection.Images.Backdrops[i];
                remoteImages.Add(new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetBackdropUrl(backdrop.FilePath),
                    CommunityRating = backdrop.VoteAverage,
                    VoteCount       = backdrop.VoteCount,
                    Width           = backdrop.Width,
                    Height          = backdrop.Height,
                    ProviderName    = Name,
                    Type            = ImageType.Backdrop,
                    RatingType      = RatingType.Score
                });
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 4
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var episode = (Controller.Entities.TV.Episode)item;
            var series  = episode.Series;

            var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (seriesTmdbId <= 0)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var seasonNumber  = episode.ParentIndexNumber;
            var episodeNumber = episode.IndexNumber;

            if (!seasonNumber.HasValue || !episodeNumber.HasValue)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var language = item.GetPreferredMetadataLanguage();

            // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
            var episodeResult = await _tmdbClientManager
                                .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, null, null, cancellationToken)
                                .ConfigureAwait(false);

            var stills = episodeResult?.Images?.Stills;

            if (stills == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new RemoteImageInfo[stills.Count];

            for (var i = 0; i < stills.Count; i++)
            {
                var image = stills[i];
                remoteImages[i] = new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetStillUrl(image.FilePath),
                    CommunityRating = image.VoteAverage,
                    VoteCount       = image.VoteCount,
                    Width           = image.Width,
                    Height          = image.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                };
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 5
0
        private IEnumerable <PersonInfo> GetPersons(TvShow seriesResult)
        {
            if (seriesResult.Credits?.Cast != null)
            {
                foreach (var actor in seriesResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order,
                        ImageUrl  = _tmdbClientManager.GetPosterUrl(actor.ProfilePath)
                    };

                    if (actor.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    yield return(personInfo);
                }
            }

            if (seriesResult.Credits?.Crew != null)
            {
                var keepTypes = new[]
                {
                    PersonType.Director,
                    PersonType.Writer,
                    PersonType.Producer
                };

                foreach (var person in seriesResult.Credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!keepTypes.Contains(type, StringComparison.OrdinalIgnoreCase) &&
                        !keepTypes.Contains(person.Job ?? string.Empty, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    yield return(new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    });
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var season = (Season)item;
            var series = season?.Series;

            var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (seriesTmdbId <= 0 || season?.IndexNumber == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var language = item.GetPreferredMetadataLanguage();

            // TODO use image languages if All Languages isn't toggled, but there's currently no way to get that value in here
            var seasonResult = await _tmdbClientManager
                               .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, null, null, cancellationToken)
                               .ConfigureAwait(false);

            var posters = seasonResult?.Images?.Posters;

            if (posters == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new RemoteImageInfo[posters.Count];

            for (var i = 0; i < posters.Count; i++)
            {
                var image = posters[i];
                remoteImages[i] = new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(image.FilePath),
                    CommunityRating = image.VoteAverage,
                    VoteCount       = image.VoteCount,
                    Width           = image.Width,
                    Height          = image.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                };
            }

            return(remoteImages);
        }
Ejemplo n.º 7
0
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var season = (Season)item;
            var series = season?.Series;

            var seriesTmdbId = Convert.ToInt32(series?.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (seriesTmdbId <= 0 || season?.IndexNumber == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var language = item.GetPreferredMetadataLanguage();

            var seasonResult = await _tmdbClientManager
                               .GetSeasonAsync(seriesTmdbId, season.IndexNumber.Value, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
                               .ConfigureAwait(false);

            if (seasonResult?.Images?.Posters == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new List <RemoteImageInfo>();

            for (var i = 0; i < seasonResult.Images.Posters.Count; i++)
            {
                var image = seasonResult.Images.Posters[i];
                remoteImages.Add(new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(image.FilePath),
                    CommunityRating = image.VoteAverage,
                    VoteCount       = image.VoteCount,
                    Width           = image.Width,
                    Height          = image.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(image.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                });
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 8
0
        public async Task <MetadataResult <BoxSet> > GetMetadata(BoxSetInfo info, CancellationToken cancellationToken)
        {
            var tmdbId   = Convert.ToInt32(info.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
            var language = info.MetadataLanguage;

            // We don't already have an Id, need to fetch it
            if (tmdbId <= 0)
            {
                // ParseName is required here.
                // Caller provides the filename with extension stripped and NOT the parsed filename
                var parsedName    = _libraryManager.ParseName(info.Name);
                var cleanedName   = TmdbUtils.CleanName(parsedName.Name);
                var searchResults = await _tmdbClientManager.SearchCollectionAsync(cleanedName, language, cancellationToken).ConfigureAwait(false);

                if (searchResults != null && searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id;
                }
            }

            var result = new MetadataResult <BoxSet>();

            if (tmdbId > 0)
            {
                var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);

                if (collection != null)
                {
                    var item = new BoxSet
                    {
                        Name     = collection.Name,
                        Overview = collection.Overview
                    };

                    item.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));

                    result.HasMetadata = true;
                    result.Item        = item;
                }
            }

            return(result);
        }
Ejemplo n.º 9
0
        public async Task <MetadataResult <BoxSet> > GetMetadata(BoxSetInfo id, CancellationToken cancellationToken)
        {
            var tmdbId   = Convert.ToInt32(id.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
            var language = id.MetadataLanguage;

            // We don't already have an Id, need to fetch it
            if (tmdbId <= 0)
            {
                var searchResults = await _tmdbClientManager.SearchCollectionAsync(id.Name, language, cancellationToken).ConfigureAwait(false);

                if (searchResults != null && searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id;
                }
            }

            var result = new MetadataResult <BoxSet>();

            if (tmdbId > 0)
            {
                var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);

                if (collection != null)
                {
                    var item = new BoxSet
                    {
                        Name     = collection.Name,
                        Overview = collection.Overview
                    };

                    item.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));

                    result.HasMetadata = true;
                    result.Item        = item;
                }
            }

            return(result);
        }
Ejemplo n.º 10
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(BoxSetInfo searchInfo, CancellationToken cancellationToken)
        {
            var tmdbId   = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);
            var language = searchInfo.MetadataLanguage;

            if (tmdbId > 0)
            {
                var collection = await _tmdbClientManager.GetCollectionAsync(tmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken).ConfigureAwait(false);

                if (collection == null)
                {
                    return(Enumerable.Empty <RemoteSearchResult>());
                }

                var result = new RemoteSearchResult
                {
                    Name = collection.Name,
                    SearchProviderName = Name
                };

                if (collection.Images != null)
                {
                    result.ImageUrl = _tmdbClientManager.GetPosterUrl(collection.PosterPath);
                }

                result.SetProviderId(MetadataProvider.Tmdb, collection.Id.ToString(CultureInfo.InvariantCulture));

                return(new[] { result });
            }

            var collectionSearchResults = await _tmdbClientManager.SearchCollectionAsync(searchInfo.Name, language, cancellationToken).ConfigureAwait(false);

            var collections = new List <RemoteSearchResult>();

            for (var i = 0; i < collectionSearchResults.Count; i++)
            {
                var collection = new RemoteSearchResult
                {
                    Name = collectionSearchResults[i].Name,
                    SearchProviderName = Name
                };
                collection.SetProviderId(MetadataProvider.Tmdb, collectionSearchResults[i].Id.ToString(CultureInfo.InvariantCulture));

                collections.Add(collection);
            }

            return(collections);
        }
Ejemplo n.º 11
0
 public static void AdjustImageLanguage_Valid_Success(string imageLanguage, string requestLanguage, string expected)
 {
     Assert.Equal(expected, TmdbUtils.AdjustImageLanguage(imageLanguage, requestLanguage));
 }
Ejemplo n.º 12
0
 public static void NormalizeLanguage_Valid_Success(string input, string expected)
 {
     Assert.Equal(expected, TmdbUtils.NormalizeLanguage(input));
 }
Ejemplo n.º 13
0
        private void ProcessMainInfo(MetadataResult <Series> seriesResult, SeriesResult seriesInfo, string preferredCountryCode, TmdbSettingsResult settings)
        {
            var series = seriesResult.Item;

            series.Name          = seriesInfo.Name;
            series.OriginalTitle = seriesInfo.Original_Name;
            series.SetProviderId(MetadataProvider.Tmdb, seriesInfo.Id.ToString(_usCulture));

            string voteAvg = seriesInfo.Vote_Average.ToString(CultureInfo.InvariantCulture);

            if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out float rating))
            {
                series.CommunityRating = rating;
            }

            series.Overview = seriesInfo.Overview;

            if (seriesInfo.Networks != null)
            {
                series.Studios = seriesInfo.Networks.Select(i => i.Name).ToArray();
            }

            if (seriesInfo.Genres != null)
            {
                series.Genres = seriesInfo.Genres.Select(i => i.Name).ToArray();
            }

            series.HomePageUrl = seriesInfo.Homepage;

            series.RunTimeTicks = seriesInfo.Episode_Run_Time.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();

            if (string.Equals(seriesInfo.Status, "Ended", StringComparison.OrdinalIgnoreCase))
            {
                series.Status  = SeriesStatus.Ended;
                series.EndDate = seriesInfo.Last_Air_Date;
            }
            else
            {
                series.Status = SeriesStatus.Continuing;
            }

            series.PremiereDate = seriesInfo.First_Air_Date;

            var ids = seriesInfo.External_Ids;

            if (ids != null)
            {
                if (!string.IsNullOrWhiteSpace(ids.Imdb_Id))
                {
                    series.SetProviderId(MetadataProvider.Imdb, ids.Imdb_Id);
                }

                if (ids.Tvrage_Id > 0)
                {
                    series.SetProviderId(MetadataProvider.TvRage, ids.Tvrage_Id.ToString(_usCulture));
                }

                if (ids.Tvdb_Id > 0)
                {
                    series.SetProviderId(MetadataProvider.Tvdb, ids.Tvdb_Id.ToString(_usCulture));
                }
            }

            var contentRatings = (seriesInfo.Content_Ratings ?? new ContentRatings()).Results ?? new List <ContentRating>();

            var ourRelease     = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
            var usRelease      = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
            var minimumRelease = contentRatings.FirstOrDefault();

            if (ourRelease != null)
            {
                series.OfficialRating = ourRelease.Rating;
            }
            else if (usRelease != null)
            {
                series.OfficialRating = usRelease.Rating;
            }
            else if (minimumRelease != null)
            {
                series.OfficialRating = minimumRelease.Rating;
            }

            if (seriesInfo.Videos != null && seriesInfo.Videos.Results != null)
            {
                foreach (var video in seriesInfo.Videos.Results)
                {
                    if ((video.Type.Equals("trailer", StringComparison.OrdinalIgnoreCase) ||
                         video.Type.Equals("clip", StringComparison.OrdinalIgnoreCase)) &&
                        video.Site.Equals("youtube", StringComparison.OrdinalIgnoreCase))
                    {
                        series.AddTrailerUrl($"http://www.youtube.com/watch?v={video.Key}");
                    }
                }
            }

            seriesResult.ResetPeople();
            var tmdbImageUrl = settings.images.GetImageUrl("original");

            if (seriesInfo.Credits != null)
            {
                if (seriesInfo.Credits.Cast != null)
                {
                    foreach (var actor in seriesInfo.Credits.Cast.OrderBy(a => a.Order))
                    {
                        var personInfo = new PersonInfo
                        {
                            Name      = actor.Name.Trim(),
                            Role      = actor.Character,
                            Type      = PersonType.Actor,
                            SortOrder = actor.Order
                        };

                        if (!string.IsNullOrWhiteSpace(actor.Profile_Path))
                        {
                            personInfo.ImageUrl = tmdbImageUrl + actor.Profile_Path;
                        }

                        if (actor.Id > 0)
                        {
                            personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                        }

                        seriesResult.AddPerson(personInfo);
                    }
                }

                if (seriesInfo.Credits.Crew != null)
                {
                    var keepTypes = new[]
                    {
                        PersonType.Director,
                        PersonType.Writer,
                        PersonType.Producer
                    };

                    foreach (var person in seriesInfo.Credits.Crew)
                    {
                        // Normalize this
                        var type = TmdbUtils.MapCrewToPersonType(person);

                        if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                            !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        seriesResult.AddPerson(new PersonInfo
                        {
                            Name = person.Name.Trim(),
                            Role = person.Job,
                            Type = type
                        });
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public async Task <MetadataResult <Episode> > GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
        {
            var metadataResult = new MetadataResult <Episode>();

            // Allowing this will dramatically increase scan times
            if (info.IsMissingEpisode)
            {
                return(metadataResult);
            }

            info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string tmdbId);

            var seriesTmdbId = Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture);

            if (seriesTmdbId <= 0)
            {
                return(metadataResult);
            }

            var seasonNumber  = info.ParentIndexNumber;
            var episodeNumber = info.IndexNumber;

            if (!seasonNumber.HasValue || !episodeNumber.HasValue)
            {
                return(metadataResult);
            }

            var episodeResult = await _tmdbClientManager
                                .GetEpisodeAsync(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                                .ConfigureAwait(false);

            if (episodeResult == null)
            {
                return(metadataResult);
            }

            metadataResult.HasMetadata = true;
            metadataResult.QueriedById = true;

            if (!string.IsNullOrEmpty(episodeResult.Overview))
            {
                // if overview is non-empty, we can assume that localized data was returned
                metadataResult.ResultLanguage = info.MetadataLanguage;
            }

            var item = new Episode
            {
                Name              = info.Name,
                IndexNumber       = info.IndexNumber,
                ParentIndexNumber = info.ParentIndexNumber,
                IndexNumberEnd    = info.IndexNumberEnd
            };

            if (!string.IsNullOrEmpty(episodeResult.ExternalIds?.TvdbId))
            {
                item.SetProviderId(MetadataProvider.Tvdb, episodeResult.ExternalIds.TvdbId);
            }

            item.PremiereDate   = episodeResult.AirDate;
            item.ProductionYear = episodeResult.AirDate?.Year;

            item.Name     = episodeResult.Name;
            item.Overview = episodeResult.Overview;

            item.CommunityRating = Convert.ToSingle(episodeResult.VoteAverage);

            if (episodeResult.Videos?.Results != null)
            {
                foreach (var video in episodeResult.Videos.Results)
                {
                    if (TmdbUtils.IsTrailerType(video))
                    {
                        item.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
                    }
                }
            }

            var credits = episodeResult.Credits;

            if (credits?.Cast != null)
            {
                foreach (var actor in credits.Cast.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
                {
                    metadataResult.AddPerson(new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order
                    });
                }
            }

            if (credits?.GuestStars != null)
            {
                foreach (var guest in credits.GuestStars.OrderBy(a => a.Order).Take(TmdbUtils.MaxCastMembers))
                {
                    metadataResult.AddPerson(new PersonInfo
                    {
                        Name      = guest.Name.Trim(),
                        Role      = guest.Character,
                        Type      = PersonType.GuestStar,
                        SortOrder = guest.Order
                    });
                }
            }

            // and the rest from crew
            if (credits?.Crew != null)
            {
                foreach (var person in credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                        !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    metadataResult.AddPerson(new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    });
                }
            }

            metadataResult.Item = item;

            return(metadataResult);
        }
Ejemplo n.º 15
0
        private static Series MapTvShowToSeries(TvShow seriesResult, string preferredCountryCode)
        {
            var series = new Series
            {
                Name          = seriesResult.Name,
                OriginalTitle = seriesResult.OriginalName
            };

            series.SetProviderId(MetadataProvider.Tmdb, seriesResult.Id.ToString(CultureInfo.InvariantCulture));

            series.CommunityRating = Convert.ToSingle(seriesResult.VoteAverage);

            series.Overview = seriesResult.Overview;

            if (seriesResult.Networks != null)
            {
                series.Studios = seriesResult.Networks.Select(i => i.Name).ToArray();
            }

            if (seriesResult.Genres != null)
            {
                series.Genres = seriesResult.Genres.Select(i => i.Name).ToArray();
            }

            if (seriesResult.Keywords?.Results != null)
            {
                for (var i = 0; i < seriesResult.Keywords.Results.Count; i++)
                {
                    series.AddTag(seriesResult.Keywords.Results[i].Name);
                }
            }

            series.HomePageUrl = seriesResult.Homepage;

            series.RunTimeTicks = seriesResult.EpisodeRunTime.Select(i => TimeSpan.FromMinutes(i).Ticks).FirstOrDefault();

            if (string.Equals(seriesResult.Status, "Ended", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(seriesResult.Status, "Canceled", StringComparison.OrdinalIgnoreCase))
            {
                series.Status  = SeriesStatus.Ended;
                series.EndDate = seriesResult.LastAirDate;
            }
            else
            {
                series.Status = SeriesStatus.Continuing;
            }

            series.PremiereDate = seriesResult.FirstAirDate;

            var ids = seriesResult.ExternalIds;

            if (ids != null)
            {
                if (!string.IsNullOrWhiteSpace(ids.ImdbId))
                {
                    series.SetProviderId(MetadataProvider.Imdb, ids.ImdbId);
                }

                if (!string.IsNullOrEmpty(ids.TvrageId))
                {
                    series.SetProviderId(MetadataProvider.TvRage, ids.TvrageId);
                }

                if (!string.IsNullOrEmpty(ids.TvdbId))
                {
                    series.SetProviderId(MetadataProvider.Tvdb, ids.TvdbId);
                }
            }

            var contentRatings = seriesResult.ContentRatings.Results ?? new List <ContentRating>();

            var ourRelease     = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
            var usRelease      = contentRatings.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
            var minimumRelease = contentRatings.FirstOrDefault();

            if (ourRelease != null)
            {
                series.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Rating);
            }
            else if (usRelease != null)
            {
                series.OfficialRating = usRelease.Rating;
            }
            else if (minimumRelease != null)
            {
                series.OfficialRating = minimumRelease.Rating;
            }

            if (seriesResult.Videos?.Results != null)
            {
                foreach (var video in seriesResult.Videos.Results)
                {
                    if (TmdbUtils.IsTrailerType(video))
                    {
                        series.AddTrailerUrl("https://www.youtube.com/watch?v=" + video.Key);
                    }
                }
            }

            return(series);
        }
Ejemplo n.º 16
0
        /// <inheritdoc />
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var language = item.GetPreferredMetadataLanguage();

            var movieTmdbId = Convert.ToInt32(item.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (movieTmdbId <= 0)
            {
                var movieImdbId = item.GetProviderId(MetadataProvider.Imdb);
                if (string.IsNullOrEmpty(movieImdbId))
                {
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var movieResult = await _tmdbClientManager.FindByExternalIdAsync(movieImdbId, FindExternalSource.Imdb, language, cancellationToken).ConfigureAwait(false);

                if (movieResult?.MovieResults != null && movieResult.MovieResults.Count > 0)
                {
                    movieTmdbId = movieResult.MovieResults[0].Id;
                }
            }

            if (movieTmdbId <= 0)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var movie = await _tmdbClientManager
                        .GetMovieAsync(movieTmdbId, language, TmdbUtils.GetImageLanguagesParam(language), cancellationToken)
                        .ConfigureAwait(false);

            if (movie?.Images == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var remoteImages = new List <RemoteImageInfo>();

            for (var i = 0; i < movie.Images.Posters.Count; i++)
            {
                var poster = movie.Images.Posters[i];
                remoteImages.Add(new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(poster.FilePath),
                    CommunityRating = poster.VoteAverage,
                    VoteCount       = poster.VoteCount,
                    Width           = poster.Width,
                    Height          = poster.Height,
                    Language        = TmdbUtils.AdjustImageLanguage(poster.Iso_639_1, language),
                    ProviderName    = Name,
                    Type            = ImageType.Primary,
                    RatingType      = RatingType.Score
                });
            }

            for (var i = 0; i < movie.Images.Backdrops.Count; i++)
            {
                var backdrop = movie.Images.Backdrops[i];
                remoteImages.Add(new RemoteImageInfo
                {
                    Url             = _tmdbClientManager.GetPosterUrl(backdrop.FilePath),
                    CommunityRating = backdrop.VoteAverage,
                    VoteCount       = backdrop.VoteCount,
                    Width           = backdrop.Width,
                    Height          = backdrop.Height,
                    ProviderName    = Name,
                    Type            = ImageType.Backdrop,
                    RatingType      = RatingType.Score
                });
            }

            return(remoteImages.OrderByLanguageDescending(language));
        }
Ejemplo n.º 17
0
        public async Task <MetadataResult <Episode> > GetMetadata(EpisodeInfo info, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Episode>();

            // Allowing this will dramatically increase scan times
            if (info.IsMissingEpisode)
            {
                return(result);
            }

            info.SeriesProviderIds.TryGetValue(MetadataProviders.Tmdb.ToString(), out string seriesTmdbId);

            if (string.IsNullOrEmpty(seriesTmdbId))
            {
                return(result);
            }

            var seasonNumber  = info.ParentIndexNumber;
            var episodeNumber = info.IndexNumber;

            if (!seasonNumber.HasValue || !episodeNumber.HasValue)
            {
                return(result);
            }

            try
            {
                var response = await GetEpisodeInfo(seriesTmdbId, seasonNumber.Value, episodeNumber.Value, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                result.HasMetadata = true;
                result.QueriedById = true;

                if (!string.IsNullOrEmpty(response.Overview))
                {
                    // if overview is non-empty, we can assume that localized data was returned
                    result.ResultLanguage = info.MetadataLanguage;
                }

                var item = new Episode();
                result.Item = item;

                item.Name              = info.Name;
                item.IndexNumber       = info.IndexNumber;
                item.ParentIndexNumber = info.ParentIndexNumber;
                item.IndexNumberEnd    = info.IndexNumberEnd;

                if (response.External_Ids.Tvdb_Id > 0)
                {
                    item.SetProviderId(MetadataProviders.Tvdb, response.External_Ids.Tvdb_Id.ToString(CultureInfo.InvariantCulture));
                }

                item.PremiereDate   = response.Air_Date;
                item.ProductionYear = result.Item.PremiereDate.Value.Year;

                item.Name     = response.Name;
                item.Overview = response.Overview;

                item.CommunityRating = (float)response.Vote_Average;

                if (response.Videos?.Results != null)
                {
                    foreach (var video in response.Videos.Results)
                    {
                        if (video.Type.Equals("trailer", System.StringComparison.OrdinalIgnoreCase) ||
                            video.Type.Equals("clip", System.StringComparison.OrdinalIgnoreCase))
                        {
                            if (video.Site.Equals("youtube", System.StringComparison.OrdinalIgnoreCase))
                            {
                                var videoUrl = string.Format("http://www.youtube.com/watch?v={0}", video.Key);
                                item.AddTrailerUrl(videoUrl);
                            }
                        }
                    }
                }

                result.ResetPeople();

                var credits = response.Credits;
                if (credits != null)
                {
                    //Actors, Directors, Writers - all in People
                    //actors come from cast
                    if (credits.Cast != null)
                    {
                        foreach (var actor in credits.Cast.OrderBy(a => a.Order))
                        {
                            result.AddPerson(new PersonInfo {
                                Name = actor.Name.Trim(), Role = actor.Character, Type = PersonType.Actor, SortOrder = actor.Order
                            });
                        }
                    }

                    // guest stars
                    if (credits.Guest_Stars != null)
                    {
                        foreach (var guest in credits.Guest_Stars.OrderBy(a => a.Order))
                        {
                            result.AddPerson(new PersonInfo {
                                Name = guest.Name.Trim(), Role = guest.Character, Type = PersonType.GuestStar, SortOrder = guest.Order
                            });
                        }
                    }

                    //and the rest from crew
                    if (credits.Crew != null)
                    {
                        var keepTypes = new[]
                        {
                            PersonType.Director,
                            PersonType.Writer,
                            PersonType.Producer
                        };

                        foreach (var person in credits.Crew)
                        {
                            // Normalize this
                            var type = TmdbUtils.MapCrewToPersonType(person);

                            if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                                !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                            {
                                continue;
                            }

                            result.AddPerson(new PersonInfo {
                                Name = person.Name.Trim(), Role = person.Job, Type = type
                            });
                        }
                    }
                }
            }
            catch (HttpException ex)
            {
                if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
                {
                    return(result);
                }

                throw;
            }

            return(result);
        }
Ejemplo n.º 18
0
        public async Task <MetadataResult <Season> > GetMetadata(SeasonInfo info, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Season>();

            info.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out string?seriesTmdbId);

            var seasonNumber = info.IndexNumber;

            if (string.IsNullOrWhiteSpace(seriesTmdbId) || !seasonNumber.HasValue)
            {
                return(result);
            }

            var seasonResult = await _tmdbClientManager
                               .GetSeasonAsync(Convert.ToInt32(seriesTmdbId, CultureInfo.InvariantCulture), seasonNumber.Value, info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                               .ConfigureAwait(false);

            if (seasonResult == null)
            {
                return(result);
            }

            result.HasMetadata = true;
            result.Item        = new Season
            {
                IndexNumber = seasonNumber,
                Overview    = seasonResult.Overview
            };

            if (Plugin.Instance.Configuration.ImportSeasonName)
            {
                result.Item.Name = seasonResult.Name;
            }

            if (!string.IsNullOrEmpty(seasonResult.ExternalIds?.TvdbId))
            {
                result.Item.SetProviderId(MetadataProvider.Tvdb, seasonResult.ExternalIds.TvdbId);
            }

            // TODO why was this disabled?
            var credits = seasonResult.Credits;

            if (credits?.Cast != null)
            {
                var cast = credits.Cast.OrderBy(c => c.Order).Take(Plugin.Instance.Configuration.MaxCastMembers).ToList();
                for (var i = 0; i < cast.Count; i++)
                {
                    result.AddPerson(new PersonInfo
                    {
                        Name      = cast[i].Name.Trim(),
                        Role      = cast[i].Character,
                        Type      = PersonType.Actor,
                        SortOrder = cast[i].Order
                    });
                }
            }

            if (credits?.Crew != null)
            {
                foreach (var person in credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!TmdbUtils.WantedCrewTypes.Contains(type, StringComparison.OrdinalIgnoreCase) &&
                        !TmdbUtils.WantedCrewTypes.Contains(person.Job ?? string.Empty, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    result.AddPerson(new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    });
                }
            }

            result.Item.PremiereDate   = seasonResult.AirDate;
            result.Item.ProductionYear = seasonResult.AirDate?.Year;

            return(result);
        }
Ejemplo n.º 19
0
        /// <inheritdoc />
        public async Task <MetadataResult <Series>?> GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Series>
            {
                QueriedById = true
            };

            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);

            if (string.IsNullOrEmpty(tmdbId))
            {
                var imdbId = info.GetProviderId(MetadataProvider.Imdb);

                if (!string.IsNullOrEmpty(imdbId))
                {
                    var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                    if (searchResult != null)
                    {
                        tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture);
                    }
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                var tvdbId = info.GetProviderId(MetadataProvider.Tvdb);

                if (!string.IsNullOrEmpty(tvdbId))
                {
                    var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                    if (searchResult != null)
                    {
                        tmdbId = searchResult.TvResults.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture);
                    }
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                result.QueriedById = false;
                var searchResults = await _tmdbClientManager.SearchSeriesAsync(info.Name, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (!string.IsNullOrEmpty(tmdbId))
            {
                cancellationToken.ThrowIfCancellationRequested();

                var tvShow = await _tmdbClientManager
                             .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                             .ConfigureAwait(false);

                if (tvShow == null)
                {
                    return(null);
                }

                result = new MetadataResult <Series>
                {
                    Item           = MapTvShowToSeries(tvShow, info.MetadataCountryCode),
                    ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage
                };

                foreach (var person in GetPersons(tvShow))
                {
                    result.AddPerson(person);
                }

                result.HasMetadata = result.Item != null;
            }

            return(result);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Processes the main info.
        /// </summary>
        /// <param name="resultItem">The result item.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="preferredCountryCode">The preferred country code.</param>
        /// <param name="movieData">The movie data.</param>
        private void ProcessMainInfo(MetadataResult <T> resultItem, TmdbSettingsResult settings, string preferredCountryCode, MovieResult movieData)
        {
            var movie = resultItem.Item;

            movie.Name = movieData.GetTitle() ?? movie.Name;

            movie.OriginalTitle = movieData.GetOriginalTitle();

            movie.Overview = string.IsNullOrWhiteSpace(movieData.Overview) ? null : WebUtility.HtmlDecode(movieData.Overview);
            movie.Overview = movie.Overview != null?movie.Overview.Replace("\n\n", "\n") : null;

            // movie.HomePageUrl = movieData.homepage;

            if (!string.IsNullOrEmpty(movieData.Tagline))
            {
                movie.Tagline = movieData.Tagline;
            }

            if (movieData.Production_Countries != null)
            {
                movie.ProductionLocations = movieData
                                            .Production_Countries
                                            .Select(i => i.Name)
                                            .ToArray();
            }

            movie.SetProviderId(MetadataProvider.Tmdb, movieData.Id.ToString(_usCulture));
            movie.SetProviderId(MetadataProvider.Imdb, movieData.Imdb_Id);

            if (movieData.Belongs_To_Collection != null)
            {
                movie.SetProviderId(MetadataProvider.TmdbCollection,
                                    movieData.Belongs_To_Collection.Id.ToString(CultureInfo.InvariantCulture));

                if (movie is Movie movieItem)
                {
                    movieItem.CollectionName = movieData.Belongs_To_Collection.Name;
                }
            }

            string voteAvg = movieData.Vote_Average.ToString(CultureInfo.InvariantCulture);

            if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rating))
            {
                movie.CommunityRating = rating;
            }

            // movie.VoteCount = movieData.vote_count;

            if (movieData.Releases != null && movieData.Releases.Countries != null)
            {
                var releases = movieData.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();

                var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
                var usRelease  = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));

                if (ourRelease != null)
                {
                    var ratingPrefix = string.Equals(preferredCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? "" : preferredCountryCode + "-";
                    var newRating    = ratingPrefix + ourRelease.Certification;

                    newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);

                    movie.OfficialRating = newRating;
                }
                else if (usRelease != null)
                {
                    movie.OfficialRating = usRelease.Certification;
                }
            }

            if (!string.IsNullOrWhiteSpace(movieData.Release_Date))
            {
                // These dates are always in this exact format
                if (DateTime.TryParse(movieData.Release_Date, _usCulture, DateTimeStyles.None, out var r))
                {
                    movie.PremiereDate   = r.ToUniversalTime();
                    movie.ProductionYear = movie.PremiereDate.Value.Year;
                }
            }

            // studios
            if (movieData.Production_Companies != null)
            {
                movie.SetStudios(movieData.Production_Companies.Select(c => c.Name));
            }

            // genres
            // Movies get this from imdb
            var genres = movieData.Genres ?? new List <Tmdb.Models.General.Genre>();

            foreach (var genre in genres.Select(g => g.Name))
            {
                movie.AddGenre(genre);
            }

            resultItem.ResetPeople();
            var tmdbImageUrl = settings.images.GetImageUrl("original");

            // Actors, Directors, Writers - all in People
            // actors come from cast
            if (movieData.Casts != null && movieData.Casts.Cast != null)
            {
                foreach (var actor in movieData.Casts.Cast.OrderBy(a => a.Order))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order
                    };

                    if (!string.IsNullOrWhiteSpace(actor.Profile_Path))
                    {
                        personInfo.ImageUrl = tmdbImageUrl + actor.Profile_Path;
                    }

                    if (actor.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    resultItem.AddPerson(personInfo);
                }
            }

            // and the rest from crew
            if (movieData.Casts?.Crew != null)
            {
                var keepTypes = new[]
                {
                    PersonType.Director,
                    PersonType.Writer,
                    PersonType.Producer
                };

                foreach (var person in movieData.Casts.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                        !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var personInfo = new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    };

                    if (!string.IsNullOrWhiteSpace(person.Profile_Path))
                    {
                        personInfo.ImageUrl = tmdbImageUrl + person.Profile_Path;
                    }

                    if (person.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    resultItem.AddPerson(personInfo);
                }
            }

            // if (movieData.keywords != null && movieData.keywords.keywords != null)
            //{
            //    movie.Keywords = movieData.keywords.keywords.Select(i => i.name).ToList();
            //}

            if (movieData.Trailers != null && movieData.Trailers.Youtube != null)
            {
                movie.RemoteTrailers = movieData.Trailers.Youtube.Select(i => new MediaUrl
                {
                    Url  = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", i.Source),
                    Name = i.Name
                }).ToArray();
            }
        }
Ejemplo n.º 21
0
        public async Task <MetadataResult <Series> > GetMetadata(SeriesInfo info, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Series>
            {
                QueriedById = true
            };

            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);

            if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
            {
                var searchResult = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (searchResult?.TvResults.Count > 0)
                {
                    tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId) && info.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
            {
                var searchResult = await _tmdbClientManager.FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (searchResult?.TvResults.Count > 0)
                {
                    tmdbId = searchResult.TvResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                result.QueriedById = false;
                // ParseName is required here.
                // Caller provides the filename with extension stripped and NOT the parsed filename
                var parsedName    = _libraryManager.ParseName(info.Name);
                var cleanedName   = TmdbUtils.CleanName(parsedName.Name);
                var searchResults = await _tmdbClientManager.SearchSeriesAsync(cleanedName, info.MetadataLanguage, info.Year ?? parsedName.Year ?? 0, cancellationToken).ConfigureAwait(false);

                if (searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                return(result);
            }

            cancellationToken.ThrowIfCancellationRequested();

            var tvShow = await _tmdbClientManager
                         .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                         .ConfigureAwait(false);

            result = new MetadataResult <Series>
            {
                Item           = MapTvShowToSeries(tvShow, info.MetadataCountryCode),
                ResultLanguage = info.MetadataLanguage ?? tvShow.OriginalLanguage
            };

            foreach (var person in GetPersons(tvShow))
            {
                result.AddPerson(person);
            }

            result.HasMetadata = result.Item != null;

            return(result);
        }
Ejemplo n.º 22
0
        public async Task <MetadataResult <Movie> > GetMetadata(MovieInfo info, CancellationToken cancellationToken)
        {
            var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
            var imdbId = info.GetProviderId(MetadataProvider.Imdb);

            if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
            {
                // ParseName is required here.
                // Caller provides the filename with extension stripped and NOT the parsed filename
                var parsedName    = _libraryManager.ParseName(info.Name);
                var cleanedName   = TmdbUtils.CleanName(parsedName.Name);
                var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (searchResults.Count > 0)
                {
                    tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId))
            {
                var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (movieResultFromImdbId?.MovieResults.Count > 0)
                {
                    tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString(CultureInfo.InvariantCulture);
                }
            }

            if (string.IsNullOrEmpty(tmdbId))
            {
                return(new MetadataResult <Movie>());
            }

            var movieResult = await _tmdbClientManager
                              .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
                              .ConfigureAwait(false);

            if (movieResult == null)
            {
                return(new MetadataResult <Movie>());
            }

            var movie = new Movie
            {
                Name                = movieResult.Title ?? movieResult.OriginalTitle,
                OriginalTitle       = movieResult.OriginalTitle,
                Overview            = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
                Tagline             = movieResult.Tagline,
                ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
            };
            var metadataResult = new MetadataResult <Movie>
            {
                HasMetadata    = true,
                ResultLanguage = info.MetadataLanguage,
                Item           = movie
            };

            movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
            movie.SetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
            if (movieResult.BelongsToCollection != null)
            {
                movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(CultureInfo.InvariantCulture));
                movie.CollectionName = movieResult.BelongsToCollection.Name;
            }

            movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);

            if (movieResult.Releases?.Countries != null)
            {
                var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();

                var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
                var usRelease  = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));

                if (ourRelease != null)
                {
                    movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification);
                }
                else if (usRelease != null)
                {
                    movie.OfficialRating = usRelease.Certification;
                }
            }

            movie.PremiereDate   = movieResult.ReleaseDate;
            movie.ProductionYear = movieResult.ReleaseDate?.Year;

            if (movieResult.ProductionCompanies != null)
            {
                movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
            }

            var genres = movieResult.Genres;

            foreach (var genre in genres.Select(g => g.Name))
            {
                movie.AddGenre(genre);
            }

            if (movieResult.Keywords?.Keywords != null)
            {
                for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
                {
                    movie.AddTag(movieResult.Keywords.Keywords[i].Name);
                }
            }

            if (movieResult.Credits?.Cast != null)
            {
                foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers))
                {
                    var personInfo = new PersonInfo
                    {
                        Name      = actor.Name.Trim(),
                        Role      = actor.Character,
                        Type      = PersonType.Actor,
                        SortOrder = actor.Order
                    };

                    if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
                    {
                        personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
                    }

                    if (actor.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    metadataResult.AddPerson(personInfo);
                }
            }

            if (movieResult.Credits?.Crew != null)
            {
                var keepTypes = new[]
                {
                    PersonType.Director,
                    PersonType.Writer,
                    PersonType.Producer
                };

                foreach (var person in movieResult.Credits.Crew)
                {
                    // Normalize this
                    var type = TmdbUtils.MapCrewToPersonType(person);

                    if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
                        !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    var personInfo = new PersonInfo
                    {
                        Name = person.Name.Trim(),
                        Role = person.Job,
                        Type = type
                    };

                    if (!string.IsNullOrWhiteSpace(person.ProfilePath))
                    {
                        personInfo.ImageUrl = _tmdbClientManager.GetPosterUrl(person.ProfilePath);
                    }

                    if (person.Id > 0)
                    {
                        personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
                    }

                    metadataResult.AddPerson(personInfo);
                }
            }

            if (movieResult.Videos?.Results != null)
            {
                var trailers = new List <MediaUrl>();
                for (var i = 0; i < movieResult.Videos.Results.Count; i++)
                {
                    var video = movieResult.Videos.Results[0];
                    if (!TmdbUtils.IsTrailerType(video))
                    {
                        continue;
                    }

                    trailers.Add(new MediaUrl
                    {
                        Url  = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.Key),
                        Name = video.Name
                    });
                }

                movie.RemoteTrailers = trailers;
            }

            return(metadataResult);
        }
Ejemplo n.º 23
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
        {
            var tmdbId = Convert.ToInt32(searchInfo.GetProviderId(MetadataProvider.Tmdb), CultureInfo.InvariantCulture);

            if (tmdbId == 0)
            {
                var movieResults = await _tmdbClientManager
                                   .SearchMovieAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken)
                                   .ConfigureAwait(false);

                var remoteSearchResults = new List <RemoteSearchResult>();
                for (var i = 0; i < movieResults.Count; i++)
                {
                    var movieResult        = movieResults[i];
                    var remoteSearchResult = new RemoteSearchResult
                    {
                        Name               = movieResult.Title ?? movieResult.OriginalTitle,
                        ImageUrl           = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
                        Overview           = movieResult.Overview,
                        SearchProviderName = Name
                    };

                    var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
                    remoteSearchResult.PremiereDate   = releaseDate;
                    remoteSearchResult.ProductionYear = releaseDate?.Year;

                    remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture));
                    remoteSearchResults.Add(remoteSearchResult);
                }

                return(remoteSearchResults);
            }

            var movie = await _tmdbClientManager
                        .GetMovieAsync(tmdbId, searchInfo.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage), cancellationToken)
                        .ConfigureAwait(false);

            var remoteResult = new RemoteSearchResult
            {
                Name = movie.Title ?? movie.OriginalTitle,
                SearchProviderName = Name,
                ImageUrl           = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
                Overview           = movie.Overview
            };

            if (movie.ReleaseDate != null)
            {
                var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
                remoteResult.PremiereDate   = releaseDate;
                remoteResult.ProductionYear = releaseDate.Year;
            }

            remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));

            if (!string.IsNullOrWhiteSpace(movie.ImdbId))
            {
                remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId);
            }

            return(new[] { remoteResult });
        }
Ejemplo n.º 24
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
        {
            if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var id))
            {
                var movie = await _tmdbClientManager
                            .GetMovieAsync(
                    int.Parse(id, CultureInfo.InvariantCulture),
                    searchInfo.MetadataLanguage,
                    TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
                    cancellationToken)
                            .ConfigureAwait(false);

                var remoteResult = new RemoteSearchResult
                {
                    Name = movie.Title ?? movie.OriginalTitle,
                    SearchProviderName = Name,
                    ImageUrl           = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
                    Overview           = movie.Overview
                };

                if (movie.ReleaseDate != null)
                {
                    var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
                    remoteResult.PremiereDate   = releaseDate;
                    remoteResult.ProductionYear = releaseDate.Year;
                }

                remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));

                if (!string.IsNullOrWhiteSpace(movie.ImdbId))
                {
                    remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId);
                }

                return(new[] { remoteResult });
            }

            IReadOnlyList <SearchMovie> movieResults;

            if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out id))
            {
                var result = await _tmdbClientManager.FindByExternalIdAsync(
                    id,
                    FindExternalSource.Imdb,
                    TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
                    cancellationToken).ConfigureAwait(false);

                movieResults = result.MovieResults;
            }
            else if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out id))
            {
                var result = await _tmdbClientManager.FindByExternalIdAsync(
                    id,
                    FindExternalSource.TvDb,
                    TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
                    cancellationToken).ConfigureAwait(false);

                movieResults = result.MovieResults;
            }
            else
            {
                movieResults = await _tmdbClientManager
                               .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationToken)
                               .ConfigureAwait(false);
            }

            var len = movieResults.Count;
            var remoteSearchResults = new RemoteSearchResult[len];

            for (var i = 0; i < len; i++)
            {
                var movieResult        = movieResults[i];
                var remoteSearchResult = new RemoteSearchResult
                {
                    Name               = movieResult.Title ?? movieResult.OriginalTitle,
                    ImageUrl           = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
                    Overview           = movieResult.Overview,
                    SearchProviderName = Name
                };

                var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
                remoteSearchResult.PremiereDate   = releaseDate;
                remoteSearchResult.ProductionYear = releaseDate?.Year;

                remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture));
                remoteSearchResults[i] = remoteSearchResult;
            }

            return(remoteSearchResults);
        }