Beispiel #1
0
        private async Task GetSeasonAndEpisodeInformation(Guid idShow, ShowInformation serieLocal)
        {
            // Si la saison est connu.
            if (_serieCollection.HaveSeason(idShow, serieLocal.Saison))
            {
                // Si Episode est non connu.
                if (!_serieCollection.HaveEpisode(idShow, serieLocal.Saison, serieLocal.Episode))
                {
                    int       idSerie = _serieCollection.GetIdSerieTmDb(idShow);
                    TvEpisode episode = await ClientTmDb.GetTvEpisodeAsync(idSerie, serieLocal.Saison, serieLocal.Episode);

                    lock (_objetToLock)
                    {
                        _serieCollection.AddEpisode(idShow, episode, serieLocal);
                    }
                }
            }
            else
            {
                // Cas ou il ne connait pas la saison.
                int      idSerie = _serieCollection.GetIdSerieTmDb(idShow);
                TvSeason saison  = await ClientTmDb.GetTvSeasonAsync(idSerie, serieLocal.Saison);

                await Task.Delay(500);

                TvEpisode episode = await ClientTmDb.GetTvEpisodeAsync(idSerie, serieLocal.Saison, serieLocal.Episode);

                lock (_objetToLock)
                {
                    _serieCollection.AddSaison(idShow, saison, episode, serieLocal);
                }
            }
        }
Beispiel #2
0
        public async Task <TvSeason> GetTvSeasonAsync(int tvShowId, int seasonNumber, string language, CancellationToken cancellationToken)
        {
            TvSeasonMethods methods    = TvSeasonMethods.Credits | TvSeasonMethods.Images | TvSeasonMethods.Videos;
            TvSeason        tmdbResult = await TMDbClient.GetTvSeasonAsync(tvShowId, seasonNumber, methods, language, cancellationToken);

            return(tmdbResult);
        }
        public async Task <bool> AskForSeasonNotificationRequestAsync(TvShow tvShow, TvSeason requestedSeason)
        {
            var message = $"Season {requestedSeason.SeasonNumber} has already been requested, you can click on the 🔔 reaction to be notified when it becomes available.";

            if (requestedSeason is FutureTvSeasons)
            {
                if (tvShow.AllSeasonsAvailable())
                {
                    message = $"All seasons are already available, you can click on the 🔔 reaction to be notified when future seasons becomes available.";
                }
                else if (tvShow.AllSeasonsAlreadyRequested())
                {
                    message = $"All seasons have been already requested, you can click on the 🔔 reaction to be notified when future seasons becomes available.";
                }
                else
                {
                    message = $"Future seasons have already been requested, you can click on the 🔔 reaction to be notified when future seasons becomes available.";
                }
            }

            await _lastCommandMessage?.AddReactionAsync(new Emoji("🔔"));

            await ReplyToUserAsync(message);

            var reaction = await WaitForReactionAsync(Context, _lastCommandMessage, new Emoji("🔔"));

            return(reaction != null);
        }
        public async Task AskForSeasonNotificationRequestAsync(TvShow tvShow, TvSeason selectedSeason)
        {
            var message = Language.Current.DiscordCommandTvNotificationRequestSeason.ReplaceTokens(tvShow, selectedSeason.SeasonNumber);

            if (selectedSeason is FutureTvSeasons)
            {
                if (tvShow.AllSeasonsAvailable())
                {
                    message = Language.Current.DiscordCommandTvNotificationRequestFutureSeasonAvailable;
                }
                else if (tvShow.AllSeasonsFullyRequested())
                {
                    message = Language.Current.DiscordCommandTvNotificationRequestFutureSeasonRequested;
                }
                else
                {
                    message = Language.Current.DiscordCommandTvNotificationRequestFutureSeasonMissing;
                }
            }

            var requestButton = new DiscordButtonComponent(ButtonStyle.Primary, $"TNR/{_interactionContext.User.Id}/{tvShow.TheTvDbId}/{selectedSeason.GetType().Name.First()}/{selectedSeason.SeasonNumber}", Language.Current.DiscordCommandNotifyMe, false, new DiscordComponentEmoji(DiscordEmoji.FromUnicode("🔔")));

            var embed   = GenerateTvShowDetailsAsync(tvShow);
            var builder = (await AddPreviousDropdownsAsync(tvShow, new DiscordWebhookBuilder().AddEmbed(embed))).AddComponents(requestButton).WithContent(message);

            await _interactionContext.EditOriginalResponseAsync(builder);
        }
Beispiel #5
0
 /// <summary>
 /// Convert a <see cref="TvSeason"/> into a <see cref="Season"/>.
 /// </summary>
 /// <param name="season">The season to convert.</param>
 /// <param name="showID">The ID of the show inside TheMovieDb.</param>
 /// <param name="provider">The provider representing TheMovieDb.</param>
 /// <returns>The converted season as a <see cref="Season"/>.</returns>
 public static Season ToSeason(this TvSeason season, int showID, Provider provider)
 {
     return(new Season
     {
         SeasonNumber = season.SeasonNumber,
         Title = season.Name,
         Overview = season.Overview,
         StartDate = season.AirDate,
         Images = new Dictionary <int, string>
         {
             [Images.Poster] = season.PosterPath != null
                                         ? $"https://image.tmdb.org/t/p/original{season.PosterPath}"
                                         : null
         },
         ExternalIDs = new[]
         {
             new MetadataID
             {
                 Provider = provider,
                 Link = $"https://www.themoviedb.org/tv/{showID}/season/{season.SeasonNumber}",
                 DataID = season.Id?.ToString()
             }
         }
     });
 }
        public async Task WarnAlreadySeasonAlreadyRequestedAsync(TvShow tvShow, TvSeason requestedSeason)
        {
            var messageContent = Language.Current.DiscordCommandTvRequestAlreadyExistSeason.ReplaceTokens(tvShow, requestedSeason.SeasonNumber);
            var buttonMessage  = Language.Current.DiscordCommandRequestedButton;

            if (requestedSeason is FutureTvSeasons)
            {
                if (tvShow.AllSeasonsAvailable())
                {
                    messageContent = Language.Current.DiscordCommandTvRequestAlreadyExistFutureSeasonAvailable;
                    buttonMessage  = Language.Current.DiscordCommandAvailableButton;
                }
                else if (tvShow.AllSeasonsFullyRequested())
                {
                    messageContent = Language.Current.DiscordCommandTvRequestAlreadyExistFutureSeasonRequested;
                }
                else
                {
                    messageContent = Language.Current.DiscordCommandTvRequestAlreadyExistFutureSeasonFound;
                }
            }

            var embed         = GenerateTvShowDetailsAsync(tvShow);
            var requestButton = new DiscordButtonComponent(ButtonStyle.Primary, $"TTT/{_interactionContext.User.Id}/{tvShow.TheTvDbId}/999", buttonMessage, true);
            var builder       = (await AddPreviousDropdownsAsync(tvShow, new DiscordWebhookBuilder().AddEmbed(embed))).WithContent(messageContent).AddComponents(requestButton);

            await _interactionContext.EditOriginalResponseAsync(builder);
        }
Beispiel #7
0
        public void TestTvSeasonExtrasAccountState()
        {
            // TMDb is sending an extra property
            IgnoreMissingCSharp("_id / _id");

            // We will intentionally ignore errors reg. missing JSON as we do not request it
            IgnoreMissingJson(" / credits", " / external_ids", " / images", " / videos", "account_states / id");

            // Test the custom parsing code for Account State rating
            Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession);

            TvSeason season = Config.Client.GetTvSeasonAsync(IdHelper.BigBangTheory, 1, TvSeasonMethods.AccountStates).Result;

            if (season.AccountStates == null || season.AccountStates.Results.All(s => s.EpisodeNumber != 1))
            {
                Config.Client.TvEpisodeSetRatingAsync(IdHelper.BigBangTheory, 1, 1, 5).Sync();

                // Allow TMDb to update cache
                Thread.Sleep(2000);

                season = Config.Client.GetTvSeasonAsync(IdHelper.BigBangTheory, 1, TvSeasonMethods.AccountStates).Result;
            }

            Assert.NotNull(season.AccountStates);
            Assert.True(season.AccountStates.Results.Single(s => s.EpisodeNumber == 1).Rating.HasValue);
            Assert.True(Math.Abs(season.AccountStates.Results.Single(s => s.EpisodeNumber == 1).Rating.Value - 5) < double.Epsilon);
        }
Beispiel #8
0
        /// <summary>
        /// Permet de créer un nouveau ShowModel.
        /// </summary>
        /// <param name="serie"></param>
        /// <returns></returns>
        private async Task <ShowModel> CreateNewShowModel(ShowInformation serie)
        {
            ShowModel showModel = new ShowModel();

            var temp = await ClientTmDb.SearchTvShowAsync(serie.Titre);

            await Task.Delay(500);

            if (temp.Results.Count > 0)
            {
                var tempSerieTrouve = temp.Results[0];

                // Récupération des informations de TmDb.
                TvShow tvShow = await ClientTmDb.GetTvShowAsync(tempSerieTrouve.Id);

                await Task.Delay(500);

                TvSeason saison = await ClientTmDb.GetTvSeasonAsync(tempSerieTrouve.Id, serie.Saison);

                await Task.Delay(500);

                TvEpisode episode = await ClientTmDb.GetTvEpisodeAsync(tempSerieTrouve.Id, serie.Saison, serie.Episode);

                showModel.TvShow = tvShow;
                showModel.TvSeasons.Add(saison);
                showModel.TvEpisodes.Add(episode);
                showModel.ShowInformation.Add(serie);
            }

            return(showModel);
        }
        public async Task WarnSeasonAlreadyAvailableAsync(TvShow tvShow, TvSeason selectedSeason)
        {
            var embed         = GenerateTvShowDetailsAsync(tvShow);
            var requestButton = new DiscordButtonComponent(ButtonStyle.Primary, $"TTT/{_interactionContext.User.Id}/{tvShow.TheTvDbId}/999", Language.Current.DiscordCommandAvailableButton, true);
            var builder       = (await AddPreviousDropdownsAsync(tvShow, new DiscordWebhookBuilder().AddEmbed(embed))).WithContent(Language.Current.DiscordCommandTvRequestAlreadyAvailableSeason.ReplaceTokens(LanguageTokens.SeasonNumber, selectedSeason.SeasonNumber.ToString())).AddComponents(requestButton);

            await _interactionContext.EditOriginalResponseAsync(builder);
        }
        public async Task DisplayRequestDeniedForSeasonAsync(TvShow tvShow, TvSeason selectedSeason)
        {
            var embed        = GenerateTvShowDetailsAsync(tvShow);
            var deniedButton = new DiscordButtonComponent(ButtonStyle.Danger, $"0/1/0", Language.Current.DiscordCommandRequestButtonDenied);
            var builder      = (await AddPreviousDropdownsAsync(tvShow, new DiscordWebhookBuilder().AddEmbed(embed))).AddComponents(deniedButton).WithContent(Language.Current.DiscordCommandTvRequestDenied);

            await _interactionContext.EditOriginalResponseAsync(builder);
        }
        public async Task TestTvSeasonGetTvSeasonWithImageLanguageAsync()
        {
            TvSeason resp = await TMDbClient.GetTvSeasonAsync(IdHelper.BreakingBad, 1, language : "en-US", includeImageLanguage : "en", extraMethods : TvSeasonMethods.Images);

            ImageData poster = resp.Images.Posters.Single(s => s.FilePath == "/uFh3OrBvkwKSU3N5y0XnXOhqBJz.jpg");

            await Verify(poster);
        }
Beispiel #12
0
        public Season(TvSeason apiSeason)
        {
            Id           = apiSeason.Id.Value;
            SeasonNumber = apiSeason.SeasonNumber;
            Title        = apiSeason.Name;
            PosterPath   = apiSeason.PosterPath;

            Episodes = apiSeason.Episodes.Select(e => new Episode(e)).ToList();
        }
        public Task DisplayNotificationSuccessForSeasonAsync(TvSeason requestedSeason)
        {
            if (requestedSeason is FutureTvSeasons)
            {
                return(ReplyToUserAsync($"You will now receive a notification as soon as any **future seasons** becomes available to watch."));
            }

            return(ReplyToUserAsync($"You will now receive a notification as soon as **season {requestedSeason.SeasonNumber}** becomes available to watch."));
        }
Beispiel #14
0
        public void TestTvSeasonExtrasAll()
        {
            TvSeasonMethods combinedEnum = _methods.Keys.Aggregate((methods, tvSeasonMethods) => methods | tvSeasonMethods);
            TvSeason        tvSeason     = _config.Client.GetTvSeason(BreakingBad, 1, combinedEnum);

            TestBreakingBadBaseProperties(tvSeason);

            TestMethodsHelper.TestAllNotNull(_methods, tvSeason);
        }
Beispiel #15
0
        public async Task GetSeasonDetailsAsync_ValidId_ReturnsValidResult(int tvId, int seasonNumber)
        {
            ITelevisionApi apiUnderTest = new TelevisionApi(_clientWithNoApiKey);

            TvSeason result = await apiUnderTest.GetSeasonDetailsAsync(tvId, seasonNumber, apiKey : _userApiKey);

            Assert.IsNotNull(result);
            Assert.IsNotEmpty(result.Episodes);
        }
        public void TestTvSeasonEpisodeCount()
        {
            TvSeason season = _config.Client.GetTvSeason(BreakingBad, 1);

            Assert.IsNotNull(season);
            Assert.IsNotNull(season.Episodes);

            Assert.AreEqual(season.Episodes.Count, season.EpisodeCount);
        }
        public void TestTvSeasonEpisodeCount()
        {
            TvSeason season = _config.Client.GetTvSeasonAsync(IdHelper.BreakingBad, 1).Result;

            Assert.IsNotNull(season);
            Assert.IsNotNull(season.Episodes);

            Assert.AreEqual(season.Episodes.Count, season.EpisodeCount);
        }
        public Task DisplayRequestSuccessForSeasonAsync(TvSeason season)
        {
            var message = season is AllTvSeasons
                ? $"Your request for **all seasons** was sent successfully, they should be available soon!"
                : season is FutureTvSeasons
                    ? $"Your request for **future seasons** was sent successfully, you will be notified when they become available."
                    : $"Your request for season **{season.SeasonNumber}** was sent successfully, it should be available soon!";

            return(ReplyToUserAsync(message));
        }
Beispiel #19
0
        /// <summary>
        /// Ajoute la saison et un épisode à la série donnée par l'id.
        /// </summary>
        /// <param name="idShow"></param>
        /// <param name="saison"></param>
        /// <param name="episode"></param>
        /// <param name="serieLocal"></param>
        public void AddSaison(Guid idShow, TvSeason saison, TvEpisode episode, ShowInformation serieLocal)
        {
            ShowModel showModel = GetShowModel(idShow);

            showModel.TvSeasons.Add(saison);
            showModel.TvEpisodes.Add(episode);
            showModel.ShowInformation.Add(serieLocal);

            AddNouveaute(saison, episode);
        }
        public void TestTvSeasonGetTvSeasonWithImageLanguage()
        {
            // TMDb is sending an extra property
            IgnoreMissingCSharp("_id / _id", "episodes[array].show_id / show_id");
            IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / content_ratings", " / genre_ids", "images / id", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", " / recommendations", " / external_ids");

            TvSeason resp = Config.Client.GetTvSeasonAsync(IdHelper.BreakingBad, 1, language: "en-US", includeImageLanguage: "en", extraMethods: TvSeasonMethods.Images).Result;

            Assert.True(resp.Images.Posters.Count > 0);
            Assert.True(resp.Images.Posters.All(p => p.Iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase)));
        }
Beispiel #21
0
 private async Task RequestNotificationsForSeasonAsync(TvShow tvShow, TvSeason selectedSeason)
 {
     if (selectedSeason.IsAvailable)
     {
         await _userInterface.WarnSeasonAlreadyAvailableAsync(selectedSeason);
     }
     else
     {
         await _tvShowNotificationWorkflow.NotifyForExistingRequestAsync(_user.UserId, tvShow, selectedSeason);
     }
 }
Beispiel #22
0
        public void TestTvSeasonExtrasNone()
        {
            TvSeason tvSeason = _config.Client.GetTvSeason(BreakingBad, 1);

            TestBreakingBadBaseProperties(tvSeason);

            // Test all extras, ensure none of them are populated
            foreach (Func <TvSeason, object> selector in _methods.Values)
            {
                Assert.IsNull(selector(tvSeason));
            }
        }
Beispiel #23
0
 public static int getFinalNumberEpispdeTV(string SerieName, int seasonNumber)
 {
     try
     {
         TvSeason MySeason = client.GetTvSeasonAsync(getIDofSerie(SerieName), seasonNumber, language: "fr-FR").Result;
         return(MySeason.Episodes.Count(x => x != null));
     }
     catch
     {
         return(-1);
     }
 }
        public async Task TestTvSeasonExtrasNoneAsync()
        {
            TvSeason tvSeason = await TMDbClient.GetTvSeasonAsync(IdHelper.BreakingBad, 1);

            await Verify(tvSeason);

            // Test all extras, ensure none of them are populated
            foreach (Func <TvSeason, object> selector in Methods.Values)
            {
                Assert.Null(selector(tvSeason));
            }
        }
Beispiel #25
0
        public async Task RequestTvShowAsync(string username, TvShow tvShow, TvSeason season)
        {
            var retryCount = 0;

            while (retryCount <= 5)
            {
                try
                {
                    var jsonTvShow = await FindTvShowByTheTvDbIdAsync(tvShow.TheTvDbId.ToString());

                    var wantedSeasonIds = season is AllTvSeasons
                        ? new HashSet <int>(tvShow.Seasons.Select(x => x.SeasonNumber))
                        : season is FutureTvSeasons
                            ? new HashSet <int>()
                            : new HashSet <int> {
                        season.SeasonNumber
                    };

                    var response = await HttpPostAsync(username, $"{BaseURL}/api/v1/Request/Tv", JsonConvert.SerializeObject(new
                    {
                        tvDbId       = tvShow.TheTvDbId,
                        requestAll   = false,
                        latestSeason = false,
                        firstSeason  = false,
                        seasons      = jsonTvShow.seasonRequests.Select(s => new
                        {
                            seasonNumber = s.seasonNumber,
                            episodes     = wantedSeasonIds.Contains(s.seasonNumber) && s.CanBeRequested() ? s.episodes.Select(e => new JSONTvEpisode {
                                episodeNumber = e.episodeNumber
                            }) : Array.Empty <JSONTvEpisode>()
                        }),
                    }));

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception(response.ReasonPhrase);
                    }

                    return;
                }
                catch (System.Exception ex)
                {
                    _logger.LogWarning($"An error while requesting tv show \"{tvShow.Title}\" from Ombi: " + ex.Message);
                    retryCount++;
                    await Task.Delay(1000);
                }
            }

            throw new System.Exception("Something went wrong while requesting a tv show from Ombi");
        }
        public void TestTvSeasonExtrasAll()
        {
            _config.Client.SetSessionInformation(_config.UserSessionId, SessionType.UserSession);

            // Account states will only show up if we've done something
            _config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 1, 5).Wait();

            TvSeasonMethods combinedEnum = _methods.Keys.Aggregate((methods, tvSeasonMethods) => methods | tvSeasonMethods);
            TvSeason        tvSeason     = _config.Client.GetTvSeasonAsync(IdHelper.BreakingBad, 1, combinedEnum).Result;

            TestBreakingBadBaseProperties(tvSeason);

            TestMethodsHelper.TestAllNotNull(_methods, tvSeason);
        }
Beispiel #27
0
        public bool HasSeasonNotification(string userId, int tvShowId, TvSeason tvSeason)
        {
            var hasNotification = false;

            lock (_lock)
            {
                var hasFutureNotificationForSeason = _notifications.TryGetValue(new FutureSeasonsNotification(userId, tvShowId), out var notification) && notification.SeasonNumber == tvSeason.SeasonNumber;
                var hasNotificationForSeason       = _notifications.Contains(new SeasonNotification(userId, tvShowId, tvSeason.SeasonNumber));

                hasNotification = hasFutureNotificationForSeason || hasNotificationForSeason;
            }

            return(hasNotification);
        }
Beispiel #28
0
        public static Show getShow(int TmdbID)
        {
            if (db.Shows.Where(x => x.TmdbId == TmdbID).Count() == 0)
            {
                TMDbClient client = new TMDbClient(apikey);

                TvShow tvshow = client.GetTvShowAsync(TmdbID).Result;

                List <Season> allSeason = new List <Season>();
                foreach (var season in tvshow.Seasons)
                {
                    List <Episode> allEpisode = new List <Episode>();

                    TvSeason tvseason = client.GetTvSeasonAsync(TmdbID, season.SeasonNumber).Result;

                    foreach (var episode in tvseason.Episodes)
                    {
                        Episode newEpisode = new Episode
                        {
                            Name          = episode.Name,
                            EpisodeNumber = episode.EpisodeNumber,
                            Overview      = episode.Overview,
                            TmdbId        = TmdbID,
                            ReleaseDate   = episode.AirDate,
                            Watched       = false
                        };

                        allEpisode.Add(newEpisode);
                    }

                    Season newSeason = new Season
                    {
                        SeasonNumber = season.SeasonNumber,
                        TmdbId       = TmdbID,
                        EpisodeCount = season.EpisodeCount,
                        Episodes     = allEpisode
                    };
                    allSeason.Add(newSeason);
                }

                Show show = new Show {
                    Name = tvshow.Name, TmdbId = TmdbID, Overview = tvshow.Overview, Seasons = allSeason
                };
                db.Shows.Add(show);
                db.SaveChanges();
            }

            return(db.Shows.Where(x => x.TmdbId == TmdbID).FirstOrDefault());
        }
        public async Task DisplayRequestSuccessForSeasonAsync(TvShow tvShow, TvSeason requestedSeason)
        {
            var embed = GenerateTvShowDetailsAsync(tvShow);

            var message = requestedSeason is AllTvSeasons
                ? Language.Current.DiscordCommandTvRequestSuccessAllSeasons.ReplaceTokens(tvShow, requestedSeason.SeasonNumber)
                : requestedSeason is FutureTvSeasons
                    ? Language.Current.DiscordCommandTvRequestSuccessFutureSeasons.ReplaceTokens(tvShow, requestedSeason.SeasonNumber)
                    : Language.Current.DiscordCommandTvRequestSuccessSeason.ReplaceTokens(tvShow, requestedSeason.SeasonNumber);

            var successButton = new DiscordButtonComponent(ButtonStyle.Success, $"0/1/0", Language.Current.DiscordCommandRequestButtonSuccess);
            var builder       = (await AddPreviousDropdownsAsync(tvShow, new DiscordWebhookBuilder().AddEmbed(embed))).AddComponents(successButton).WithContent(message);

            await _interactionContext.EditOriginalResponseAsync(builder);
        }
        public void TestTvSeasonExtrasNone()
        {
            // We will intentionally ignore errors reg. missing JSON as we do not request it
            IgnoreMissingJson = true;

            TvSeason tvSeason = _config.Client.GetTvSeasonAsync(IdHelper.BreakingBad, 1).Result;

            TestBreakingBadBaseProperties(tvSeason);

            // Test all extras, ensure none of them are populated
            foreach (Func <TvSeason, object> selector in _methods.Values)
            {
                Assert.IsNull(selector(tvSeason));
            }
        }