Esempio n. 1
0
        public async Task <TvShowDetails> GetTvShowDetail(TvShowDetails tvshow)
        {
            TMDbClient client = new TMDbClient(ApiKey.tmdbkeyV3, true);

            TMDbLib.Objects.TvShows.TvShow result = await client.GetTvShowAsync(tvshow.TmdbID, extraMethods : TvShowMethods.Videos | TvShowMethods.ExternalIds, language : CultureInfo.CurrentCulture.TwoLetterISOLanguageName); //| MovieMethods.Credits

            if (result.Id != 0)
            {
                tvshow.ImdbID        = result.ExternalIds.ImdbId;
                tvshow.Synopsis      = result.Overview;
                tvshow.OriginalTitle = result.OriginalName;
                tvshow.HomePage      = result.Homepage;
                tvshow.Backdrop      = result.BackdropPath;

                if (result.OriginCountry.Count > 0)
                {
                    tvshow.ProductionCountry = result.OriginCountry.FirstOrDefault();
                }
                else
                {
                    tvshow.ProductionCountry = "";
                }
                if (result.Videos.Results.Count > 0)
                {
                    tvshow.Trailer = result.Videos.Results.Where(m => m.Type == "Trailer").Select(t => t.Site == "YouTube" ? "https://www.youtube.com/embed/" + t.Key : t.Key).FirstOrDefault();
                }
                else
                {
                    tvshow.Trailer = "";
                }

                if (result.Seasons.Count > 0)
                {
                    List <Episode> episodes = await DB.GetAllEpisodesAsync(tvshow.TmdbID);

                    tvshow.Seasons = result.Seasons.Select(s => new Season {
                        ID = s.Id, N = s.SeasonNumber, TmdbID = tvshow.TmdbID, PersonalRatigAVG = (int)episodes.Where(e => e.SeasonN == s.SeasonNumber).Select(a => a.Rating).Average(), Poster = (s.PosterPath ?? "").Replace("/", ""), EpisodeCount = s.EpisodeCount, EpisodeSeen = episodes.Where(e => e.SeasonN == s.SeasonNumber).Count()
                    }).ToList();
                    tvshow.SeasonCount = result.Seasons.Count;
                }
                else
                {
                    tvshow.SeasonCount = 0;
                }

                tvshow.SeasonSeen = 0;
                tvshow.Genres     = String.Join(" - ", result.Genres.Select(e => e.Name).ToList());
                tvshow.Ratings    = new List <Rating>();
                tvshow.Ratings.Add(new Rating {
                    Source = "TMDB", Value = result.VoteAverage.ToString()
                });
            }

            return(tvshow);
        }
Esempio n. 2
0
        private Season[] GetSeasons(TvShow show)
        {
            if (show.NumberOfSeasons == 0) return new Season[0];

            var seasons = new Season[show.NumberOfSeasons];

            int index = show.NumberOfSeasons != show.Seasons.Count ? 1 : 0;
            for (int i = index; i < show.Seasons.Count; i++)
            {
                var currentSeason = show.Seasons[i];
                seasons[currentSeason.SeasonNumber - 1] = new Season(currentSeason.SeasonNumber, GetEpisodes(show.Id, currentSeason));
            }

            return seasons;
        }
Esempio n. 3
0
        private void TestBreakingBadBaseProperties(TvShow tvShow)
        {
            Assert.IsNotNull(tvShow);
            Assert.IsNotNull(tvShow.Id);
            Assert.AreEqual("Breaking Bad", tvShow.Name);
            Assert.AreEqual("Breaking Bad", tvShow.OriginalName);
            Assert.IsNotNull(tvShow.Overview);
            Assert.IsNotNull(tvShow.Homepage);
            Assert.AreEqual(new DateTime(2008, 01, 19), tvShow.FirstAirDate);
            Assert.AreEqual(new DateTime(2013, 09, 29), tvShow.LastAirDate);
            Assert.AreEqual(false, tvShow.InProduction);
            Assert.AreEqual("Ended", tvShow.Status);
            Assert.AreEqual("Scripted", tvShow.Type);
            Assert.AreEqual("en", tvShow.OriginalLanguage);

            Assert.IsNotNull(tvShow.ProductionCompanies);
            Assert.AreEqual(3, tvShow.ProductionCompanies.Count);
            Assert.AreEqual(2605, tvShow.ProductionCompanies[0].Id);
            Assert.AreEqual("Gran Via Productions", tvShow.ProductionCompanies[0].Name);

            Assert.IsNotNull(tvShow.CreatedBy);
            Assert.AreEqual(1, tvShow.CreatedBy.Count);
            Assert.AreEqual(66633, tvShow.CreatedBy[0].Id);
            Assert.AreEqual("Vince Gilligan", tvShow.CreatedBy[0].Name);

            Assert.IsNotNull(tvShow.EpisodeRunTime);
            Assert.AreEqual(2, tvShow.EpisodeRunTime.Count);

            Assert.IsNotNull(tvShow.Genres);
            Assert.AreEqual(18, tvShow.Genres[0].Id);
            Assert.AreEqual("Drama", tvShow.Genres[0].Name);

            Assert.IsNotNull(tvShow.Languages);
            Assert.AreEqual("en", tvShow.Languages[0]);

            Assert.IsNotNull(tvShow.Networks);
            Assert.AreEqual(1, tvShow.Networks.Count);
            Assert.AreEqual(174, tvShow.Networks[0].Id);
            Assert.AreEqual("AMC", tvShow.Networks[0].Name);

            Assert.IsNotNull(tvShow.OriginCountry);
            Assert.AreEqual(1, tvShow.OriginCountry.Count);
            Assert.AreEqual("US", tvShow.OriginCountry[0]);

            Assert.IsNotNull(tvShow.Seasons);
            Assert.AreEqual(6, tvShow.Seasons.Count);
            Assert.AreEqual(0, tvShow.Seasons[0].SeasonNumber);
            Assert.AreEqual(1, tvShow.Seasons[1].SeasonNumber);
            Assert.IsNull(tvShow.Seasons[1].Episodes);

            Assert.AreEqual(62, tvShow.NumberOfEpisodes);
            Assert.AreEqual(5, tvShow.NumberOfSeasons);

            Assert.IsNotNull(tvShow.PosterPath);
            Assert.IsNotNull(tvShow.BackdropPath);

            Assert.AreNotEqual(0, tvShow.Popularity);
            Assert.AreNotEqual(0, tvShow.VoteAverage);
            Assert.AreNotEqual(0, tvShow.VoteAverage);
        }
        public async Task <TvShowMetadata> GetTmdbMetadataAsync(int tmdbId)
        {
            TMDbLib.Objects.TvShows.TvShow tvShow = null;
            Directory.CreateDirectory(this.AppSettings.TmdbCacheDirectoryPath);
            var cacheFilePath = $"{this.AppSettings.TmdbCacheDirectoryPath}/{tmdbId}.json";

            //if a cache file exists, and it's was updated less than a month ago, use it.
            if (File.Exists(cacheFilePath) && (DateTime.Now - File.GetLastWriteTime(cacheFilePath)).TotalDays < 30)
            {
                try
                {
                    tvShow = Newtonsoft.Json.JsonConvert.DeserializeObject <TMDbLib.Objects.TvShows.TvShow>(File.ReadAllText(cacheFilePath));
                }
                catch (Exception)
                {
                }
            }
            //if the movie could not be loaded from cache, retrieve a fresh copy from TMDB
            if (tvShow == null)
            {
                //only allow one thread to use the client at a time
                lock (Client)
                {
                    tvShow = Client.GetTvShowAsync(tmdbId,
                                                   TvShowMethods.AlternativeTitles |
                                                   TvShowMethods.Credits |
                                                   TvShowMethods.Images |
                                                   TvShowMethods.Keywords |
                                                   //    TvShowMethods.Releases |
                                                   //    TvShowMethods.ReleaseDates |
                                                   TvShowMethods.Videos
                                                   ).Result;
                }
                //save this result to disc
                var camelCaseFormatter = new JsonSerializerSettings();
                camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
                camelCaseFormatter.Formatting       = Formatting.Indented;

                var json = Newtonsoft.Json.JsonConvert.SerializeObject(tvShow, camelCaseFormatter);
                await File.WriteAllTextAsync(cacheFilePath, json);
            }

            var metadata = new TvShowMetadata();

            metadata.AddCast(tvShow.Credits?.Cast);
            metadata.AddCrew(tvShow.Credits?.Crew);
            //TODO
            // metadata.Description = movie.Overview;
            // metadata.Genres = movie.Genres?.Select(x => x.Name).ToList();
            // metadata.Keywords = movie.Keywords?.Keywords?.Select(x => x.Name).ToList();
            // var release = movie.Releases?.Countries
            //     ?.Where(x => x.Iso_3166_1.ToLower() == "us")
            //     ?.OrderBy(x => x.ReleaseDate)
            //     ?.First();
            // //get the oldest US rating
            // metadata.Rating = release?.Certification;
            // metadata.ReleaseDate = release?.ReleaseDate;
            // //conver the runtime to seconds
            // metadata.RuntimeSeconds = movie.Runtime * 60;
            // metadata.Summary = movie.Overview;
            // metadata.Title = movie.Title;
            // metadata.SortTitle = movie.Title;

            // metadata.ExtraSearchText.AddRange(
            //     movie.AlternativeTitles?.Titles?.Where(x => x.Iso_3166_1.ToLower() == "us").Select(x => x.Title).ToList() ?? new List<string>()
            // );
            // metadata.ExtraSearchText.Add(movie.OriginalTitle);

            // metadata.ExtraSearchText = metadata.ExtraSearchText.Distinct().ToList();

            // metadata.TmdbId = movie.Id;


            // if (movie.PosterPath != null)
            // {
            //     metadata.PosterUrls.Add(Client.GetImageUrl("original", movie.PosterPath).ToString());
            // }
            // metadata.PosterUrls.AddRange(
            //     movie.Images?.Posters
            //     ?.Where(x => x.Iso_639_1?.ToLower() == "en")
            //     ?.Select(x => Client.GetImageUrl("original", x.FilePath).ToString())
            //     ?.ToList() ?? new List<string>()
            // );
            // metadata.PosterUrls = metadata.PosterUrls.Distinct().ToList();


            // //add the marked backdrop path first
            // if (movie.BackdropPath != null)
            // {
            //     metadata.BackdropUrls.Add(Client.GetImageUrl("original", movie.BackdropPath).ToString());
            // }
            // //add all additional backdrops
            // metadata.BackdropUrls.AddRange(
            //     movie.Images?.Backdrops
            //     //move the highest rated backdrops to the top
            //     ?.OrderByDescending(x => x.VoteAverage)
            //     ?.Where(x => x.Iso_639_1?.ToLower() == "en" || x.Iso_639_1 == null)
            //     ?.Select(x => Client.GetImageUrl("original", x.FilePath).ToString())
            //     ?.ToList() ?? new List<string>()
            // );
            // metadata.BackdropUrls = metadata.BackdropUrls.Distinct().ToList();
            return(metadata);
        }
Esempio n. 5
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
        {
            if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var tmdbId))
            {
                var series = await _tmdbClientManager
                             .GetSeriesAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, cancellationToken)
                             .ConfigureAwait(false);

                if (series != null)
                {
                    var remoteResult = MapTvShowToRemoteSearchResult(series);

                    return(new[] { remoteResult });
                }
            }

            if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out var imdbId))
            {
                var findResult = await _tmdbClientManager
                                 .FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, searchInfo.MetadataLanguage, cancellationToken)
                                 .ConfigureAwait(false);

                var tvResults = findResult?.TvResults;
                if (tvResults != null)
                {
                    var imdbIdResults = new RemoteSearchResult[tvResults.Count];
                    for (var i = 0; i < tvResults.Count; i++)
                    {
                        var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
                        remoteResult.SetProviderId(MetadataProvider.Imdb, imdbId);
                        imdbIdResults[i] = remoteResult;
                    }

                    return(imdbIdResults);
                }
            }

            if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out var tvdbId))
            {
                var findResult = await _tmdbClientManager
                                 .FindByExternalIdAsync(tvdbId, FindExternalSource.TvDb, searchInfo.MetadataLanguage, cancellationToken)
                                 .ConfigureAwait(false);

                var tvResults = findResult?.TvResults;
                if (tvResults != null)
                {
                    var tvIdResults = new RemoteSearchResult[tvResults.Count];
                    for (var i = 0; i < tvResults.Count; i++)
                    {
                        var remoteResult = MapSearchTvToRemoteSearchResult(tvResults[i]);
                        remoteResult.SetProviderId(MetadataProvider.Tvdb, tvdbId);
                        tvIdResults[i] = remoteResult;
                    }

                    return(tvIdResults);
                }
            }

            var tvSearchResults = await _tmdbClientManager.SearchSeriesAsync(searchInfo.Name, searchInfo.MetadataLanguage, cancellationToken : cancellationToken)
                                  .ConfigureAwait(false);

            var tmdbSearchResults = new TMDbLib.Objects.TvShows.TvShow[tvSearchResults.Count];

            var remoteResults = new RemoteSearchResult[tvSearchResults.Count];

            for (var i = 0; i < tvSearchResults.Count; i++)
            {
                tmdbSearchResults[i] = await _tmdbClientManager
                                       .GetSeriesAsync(Convert.ToInt32(tvSearchResults[i].Id, CultureInfo.InvariantCulture), searchInfo.MetadataLanguage, searchInfo.MetadataLanguage, cancellationToken)
                                       .ConfigureAwait(false);

                remoteResults[i] = MapTvShowToRemoteSearchResult(tmdbSearchResults[i]);
            }

            int resultCountHelper = 0;

            for (var i = 0; i < remoteResults.Length; i++)
            {
                resultCountHelper += 1 + remoteResults[i].EpisodeGroups.Results.Count;
            }

            var remoteResultEpisodeGroups = new RemoteSearchResult[resultCountHelper];

            for (var i = 0; i < remoteResultEpisodeGroups.Length; i++)
            {
                for (var j = 0; j < tmdbSearchResults.Length; j++)
                {
                    remoteResultEpisodeGroups[i++] = MapTvShowToRemoteSearchResult(tmdbSearchResults[j]);

                    for (var k = 0; k < tmdbSearchResults[j].EpisodeGroups.Results.Count; k++)
                    {
                        remoteResultEpisodeGroups[i++] = MapTvShowEpisodeGroupToRemoteSearchResult(tmdbSearchResults[j], k);
                    }
                }
            }

            return(remoteResultEpisodeGroups);
        }
Esempio n. 6
0
        /// <summary>
        /// Match the series information by Episode name
        /// </summary>
        private static bool MatchByEpisodeName(TMDbClient client, VideoTags videoTags, TvShow tvShow)
        {
            if (String.IsNullOrWhiteSpace(videoTags.SubTitle))
                return false; //Nothing to match here


            // Cycle through all Seasons and Episodes looking for a match
            for (int sNo = 0; sNo <= tvShow.NumberOfSeasons; sNo++)
            {
                TvSeason season = client.GetTvSeason(tvShow.Id, sNo);
                if (season == null || season.Episodes == null)
                    continue;

                for (int eNo = 0; eNo <= season.Episodes.Count; eNo++)
                {
                    TvEpisode episode = client.GetTvEpisode(tvShow.Id, sNo, eNo);
                    if (episode == null)
                        continue;

                    string episodeName = episode.Name;

                    if (!String.IsNullOrWhiteSpace(episodeName))
                    {
                        if (String.Compare(videoTags.SubTitle.Trim(), episodeName.Trim(), CultureInfo.InvariantCulture, (CompareOptions.IgnoreSymbols | CompareOptions.IgnoreCase)) == 0) // Compare the episode names (case / special characters / whitespace can change very often)
                        {
                            int episodeNo = episode.EpisodeNumber;
                            int seasonNo = season.SeasonNumber;
                            string episodeOverview = episode.Overview;
                            string overview = season.Overview;
                            string tvdbID = (episode.ExternalIds != null ? (episode.ExternalIds.TvdbId != null ? episode.ExternalIds.TvdbId.ToString() : "") : "");
                            string imdbID = (episode.ExternalIds != null ? episode.ExternalIds.ImdbId : "");
                            string tmdbID = (tvShow.Id != 0 ? tvShow.Id.ToString() : "");
                            string network = (tvShow.Networks != null ? String.Join(";", tvShow.Networks.Select(s => s.Name)) : "");
                            DateTime premiereDate = GlobalDefs.NO_BROADCAST_TIME;
                            if (tvShow.FirstAirDate != null)
                                premiereDate = (DateTime)tvShow.FirstAirDate;
                            List<string> genres = (tvShow.Genres != null ? tvShow.Genres.Select(s => s.Name).ToList() : new List<string>());
                            DateTime firstAired = (episode.AirDate != null ? episode.AirDate : GlobalDefs.NO_BROADCAST_TIME);
                            string mediaCredits = (tvShow.Credits != null ? ((tvShow.Credits.Cast != null) ? String.Join(";", tvShow.Credits.Cast.Select(s => s.Name)) : "") : "");

                            client.GetConfig(); // First we need to get the config
                            VideoMetaData.DownloadBannerFile(videoTags, client.GetImageUrl("original", tvShow.PosterPath).OriginalString); // Get bannerfile

                            if ((episodeNo != 0) && (videoTags.Episode == 0)) videoTags.Episode = episodeNo;
                            if ((seasonNo != 0) && (videoTags.Season == 0)) videoTags.Season = seasonNo;
                            if (!String.IsNullOrWhiteSpace(episodeOverview) && String.IsNullOrWhiteSpace(videoTags.Description)) videoTags.Description = episodeOverview;
                            else if (!String.IsNullOrWhiteSpace(overview) && (String.IsNullOrWhiteSpace(videoTags.Description))) videoTags.Description = overview;
                            if (!String.IsNullOrWhiteSpace(tvdbID) && String.IsNullOrWhiteSpace(videoTags.tvdbId)) videoTags.tvdbId = tvdbID;
                            if (!String.IsNullOrWhiteSpace(imdbID) && String.IsNullOrWhiteSpace(videoTags.imdbId)) videoTags.imdbId = imdbID;
                            if (!String.IsNullOrWhiteSpace(tmdbID) && String.IsNullOrWhiteSpace(videoTags.tmdbId)) videoTags.tmdbId = tmdbID;
                            if (!String.IsNullOrWhiteSpace(network) && String.IsNullOrWhiteSpace(videoTags.Network)) videoTags.Network = network;
                            if (!String.IsNullOrWhiteSpace(mediaCredits) && String.IsNullOrWhiteSpace(videoTags.MediaCredits)) videoTags.MediaCredits = mediaCredits;
                            if (premiereDate > GlobalDefs.NO_BROADCAST_TIME)
                                if ((videoTags.SeriesPremiereDate <= GlobalDefs.NO_BROADCAST_TIME) || (videoTags.SeriesPremiereDate.Date > premiereDate.Date)) // Sometimes the metadata from the video recordings are incorrect and report the recorded date (which is more recent than the release date) then use TVDB dates, TVDB Dates are more reliable than video metadata usually
                                    videoTags.SeriesPremiereDate = premiereDate; // TVDB stores time in network (local) timezone
                            if (genres.Count > 0)
                            {
                                if (videoTags.Genres != null)
                                {
                                    if (videoTags.Genres.Length == 0)
                                        videoTags.Genres = genres.ToArray();
                                }
                                else
                                    videoTags.Genres = genres.ToArray();
                            }

                            if (firstAired > GlobalDefs.NO_BROADCAST_TIME)
                                if ((videoTags.OriginalBroadcastDateTime <= GlobalDefs.NO_BROADCAST_TIME) || (videoTags.OriginalBroadcastDateTime.Date > firstAired.Date)) // Sometimes the metadata from the video recordings are incorrect and report the recorded date (which is more recent than the release date) then use TVDB dates, TVDB Dates are more reliable than video metadata usually
                                    videoTags.OriginalBroadcastDateTime = firstAired; // TVDB stores time in network (local) timezone

                            return true; // Found a match got all the data, we're done here
                        }
                    }
                }
            }

            return false; // nothing matches
        }
Esempio n. 7
0
 /// <summary>
 /// Match and download the series information
 /// </summary>
 /// <param name="videoTags">Video tags</param>
 /// <param name="tvShow">TVDB Series ID</param>
 /// <param name="matchByAirDate">True to match by original broadcast date, false to match by episode name</param>
 /// <returns></returns>
 private static bool MatchSeriesInformation(TMDbClient client, VideoTags videoTags, TvShow tvShow, bool matchByAirDate)
 {
     if (matchByAirDate) // User requested priority
         // Match by original broadcast date
         return MatchByBroadcastTime(client, videoTags, tvShow);
     else
         // Match by Episode name
         return MatchByEpisodeName(client, videoTags, tvShow);
 }
Esempio n. 8
0
        private void TestBreakingBadBaseProperties(TvShow tvShow)
        {
            Assert.IsNotNull(tvShow);
            Assert.IsNotNull(tvShow.Id);
            Assert.AreEqual("Breaking Bad", tvShow.Name);
            Assert.AreEqual("Breaking Bad", tvShow.OriginalName);
            Assert.IsNotNull(tvShow.Overview);
            Assert.IsNotNull(tvShow.Homepage);
            Assert.IsNotNull(tvShow.FirstAirDate);
            Assert.AreEqual(false, tvShow.InProduction);
            Assert.IsNotNull(tvShow.LastAirDate);
            Assert.AreEqual(TvShowStatus.Ended, tvShow.Status);

            Assert.IsNotNull(tvShow.CreatedBy);
            Assert.AreEqual(1, tvShow.CreatedBy.Count);
            Assert.AreEqual(66633, tvShow.CreatedBy[0].Id);

            Assert.IsNotNull(tvShow.EpisodeRunTime);
            Assert.AreEqual(2, tvShow.EpisodeRunTime.Count);

            Assert.IsNotNull(tvShow.Genres);
            Assert.AreEqual(18, tvShow.Genres[0].Id);

            Assert.IsNotNull(tvShow.Languages);
            Assert.AreEqual("en", tvShow.Languages[0]);

            Assert.IsNotNull(tvShow.Networks);
            Assert.AreEqual(1, tvShow.Networks.Count);
            Assert.AreEqual("AMC", tvShow.Networks[0].Name);

            Assert.IsNotNull(tvShow.OriginCountry);
            Assert.AreEqual(1, tvShow.OriginCountry.Count);
            Assert.AreEqual("US", tvShow.OriginCountry[0]);

            Assert.IsNotNull(tvShow.Seasons);
            Assert.AreEqual(6, tvShow.Seasons.Count);
            Assert.AreEqual(0, tvShow.Seasons[0].SeasonNumber);
            Assert.AreEqual(1, tvShow.Seasons[1].SeasonNumber);
            Assert.IsNull(tvShow.Seasons[1].Episodes);

            Assert.AreEqual(62, tvShow.NumberOfEpisodes);
            Assert.AreEqual(5, tvShow.NumberOfSeasons);

            Assert.IsNotNull(tvShow.PosterPath);
            Assert.IsNotNull(tvShow.BackdropPath);

            Assert.AreNotEqual(0, tvShow.Popularity);
            Assert.AreNotEqual(0, tvShow.VoteAverage);
            Assert.AreNotEqual(0, tvShow.VoteAverage);
        }