Exemplo n.º 1
0
        public async Task ShouldBe_Requested_WhenExisitngTv()
        {
            var list = new TvRequests
            {
                TvDbId        = 123,
                ChildRequests = new List <ChildRequests>
                {
                    new ChildRequests()
                    {
                        Approved = true
                    }
                }
            };

            TvMock.Setup(x => x.GetRequest(123)).Returns(list);
            var search = new SearchTvShowViewModel
            {
                Id = 123,
            };
            var result = await Rule.Execute(search);

            Assert.True(result.Success);
            Assert.True(search.Approved);
            Assert.True(search.Requested);
        }
Exemplo n.º 2
0
        public static void CheckForUnairedEpisodes(SearchTvShowViewModel search)
        {
            foreach (var season in search.SeasonRequests.ToList())
            {
                // If we have all the episodes for this season, then this season is available
                if (season.Episodes.All(x => x.Available))
                {
                    season.SeasonAvailable = true;
                }
            }
            if (search.SeasonRequests.All(x => x.Episodes.All(e => e.Available)))
            {
                search.FullyAvailable = true;
            }
            else if (search.SeasonRequests.Any(x => x.Episodes.Any(e => e.Available)))
            {
                search.PartlyAvailable = true;
            }

            if (!search.FullyAvailable)
            {
                var airedButNotAvailable = search.SeasonRequests.Any(x =>
                                                                     x.Episodes.Any(c => !c.Available && c.AirDate <= DateTime.Now.Date && c.AirDate != DateTime.MinValue));
                if (!airedButNotAvailable)
                {
                    var unairedEpisodes = search.SeasonRequests.Any(x =>
                                                                    x.Episodes.Any(c => !c.Available && c.AirDate > DateTime.Now.Date || c.AirDate != DateTime.MinValue));
                    if (unairedEpisodes)
                    {
                        search.FullyAvailable = true;
                    }
                }
            }
        }
Exemplo n.º 3
0
        public void Is_PartlyAvailable_When_All_We_Have_Some_Aired_Episodes()
        {
            var episodes = new List <EpisodeRequests>
            {
                new EpisodeRequests
                {
                    AirDate   = DateTime.Now.AddDays(-1), // Yesterday
                    Available = true
                },
                new EpisodeRequests
                {
                    AirDate   = DateTime.Now.AddDays(-14), // Yesterday
                    Available = false
                },
                new EpisodeRequests
                {
                    AirDate   = DateTime.MinValue, // Unknown date!
                    Available = false
                }
            };

            var model = new SearchTvShowViewModel
            {
                SeasonRequests = new List <SeasonRequests> {
                    new SeasonRequests {
                        Episodes = episodes
                    }
                }
            };

            AvailabilityRuleHelper.CheckForUnairedEpisodes(model);
            Assert.That(model.FullyAvailable, Is.False);
            Assert.That(model.PartlyAvailable, Is.True);
        }
Exemplo n.º 4
0
        public void Is_NotAvailable_When_All_Episodes_Are_Unknown()
        {
            var episodes = new List <EpisodeRequests>
            {
                new EpisodeRequests
                {
                    AirDate   = DateTime.MinValue,
                    Available = false
                },
                new EpisodeRequests
                {
                    AirDate   = DateTime.MinValue,
                    Available = false
                },
                new EpisodeRequests
                {
                    AirDate   = DateTime.MinValue, // Unknown date!
                    Available = false
                }
            };

            var model = new SearchTvShowViewModel
            {
                SeasonRequests = new List <SeasonRequests> {
                    new SeasonRequests {
                        Episodes = episodes
                    }
                }
            };

            AvailabilityRuleHelper.CheckForUnairedEpisodes(model);
            Assert.That(model.FullyAvailable, Is.False);
            Assert.That(model.PartlyAvailable, Is.False);
        }
Exemplo n.º 5
0
        public async Task ShouldBeFullyAvailable_NoFutureAiredEpisodes_NoRequest()
        {
            var search = new SearchTvShowViewModel()
            {
                Id             = 999,
                SeasonRequests = new List <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new List <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                Available = true,
                                AirDate   = new System.DateTime(2020, 01, 01)
                            },
                            new EpisodeRequests
                            {
                                Available = true,
                                AirDate   = new System.DateTime(2020, 01, 02)
                            },
                        }
                    }
                }
            };
            var result = await Rule.Execute(search);

            Assert.True(result.Success);
            Assert.That(search.FullyAvailable, Is.True);
            Assert.That(search.PartlyAvailable, Is.False);
        }
Exemplo n.º 6
0
        private async Task <SearchTvShowViewModel> ProcessResult(SearchTvShowViewModel item)
        {
            item.TheTvDbId = item.Id.ToString();

            await RunSearchRules(item);

            return(item);
        }
Exemplo n.º 7
0
 private static TreeNode <SearchTvShowViewModel> ParseIntoTreeNode(SearchTvShowViewModel result)
 {
     return(new TreeNode <SearchTvShowViewModel>
     {
         Data = result,
         Children = new List <TreeNode <SearchTvShowViewModel> >
         {
             new TreeNode <SearchTvShowViewModel>
             {
                 Data = result, Leaf = true
             }
         },
         Leaf = false
     });
 }
Exemplo n.º 8
0
        public TvShowRequestBuilder CreateChild(SearchTvShowViewModel model, string userId)
        {
            ChildRequest = new ChildRequests
            {
                Id              = model.Id,
                RequestType     = RequestType.TvShow,
                RequestedDate   = DateTime.UtcNow,
                Approved        = false,
                RequestedUserId = userId,
                SeasonRequests  = new List <SeasonRequests>(),
                Title           = model.Title,
                SeriesType      = ShowInfo.type.Equals("Animation", StringComparison.CurrentCultureIgnoreCase) ? SeriesType.Anime : SeriesType.Standard
            };

            return(this);
        }
Exemplo n.º 9
0
        public TvShowRequestBuilder CreateNewRequest(SearchTvShowViewModel tv)
        {
            NewRequest = new TvRequests
            {
                Id            = tv.Id,
                Overview      = ShowInfo.summary.RemoveHtml(),
                PosterPath    = PosterPath,
                Title         = ShowInfo.name,
                ReleaseDate   = FirstAir,
                Status        = ShowInfo.status,
                ImdbId        = ShowInfo.externals?.imdb ?? string.Empty,
                TvDbId        = tv.Id,
                ChildRequests = new List <ChildRequests>(),
                TotalSeasons  = tv.SeasonRequests.Count()
            };
            NewRequest.ChildRequests.Add(ChildRequest);

            return(this);
        }
Exemplo n.º 10
0
        private async Task <SearchTvShowViewModel> ProcessResult(SearchTvShowViewModel item, bool includeImages)
        {
            if (item.Id == 0)
            {
                return(null);
            }
            item.TheMovieDbId = item.Id.ToString();
            //item.TheTvDbId = item.Id.ToString();
            //if (includeImages)
            //{
            //    if (item.TheTvDbId.HasValue())
            //    {
            //        item.BackdropPath = await _imageService.GetTvBackground(item.TheTvDbId);
            //    }
            //}

            await RunSearchRules(item);

            return(item);
        }
Exemplo n.º 11
0
 public static void CheckForUnairedEpisodes(SearchTvShowViewModel search)
 {
     if (search.SeasonRequests.All(x => x.Episodes.All(e => e.Available)))
     {
         search.FullyAvailable = true;
     }
     else
     {
         var airedButNotAvailable = search.SeasonRequests.Any(x =>
                                                              x.Episodes.Any(c => !c.Available && c.AirDate <= DateTime.Now.Date && c.AirDate != DateTime.MinValue));
         if (!airedButNotAvailable)
         {
             var unairedEpisodes = search.SeasonRequests.Any(x =>
                                                             x.Episodes.Any(c => !c.Available && c.AirDate > DateTime.Now.Date || c.AirDate != DateTime.MinValue));
             if (unairedEpisodes)
             {
                 search.FullyAvailable = true;
             }
         }
     }
 }
Exemplo n.º 12
0
        public TvShowRequestBuilder CreateTvList(SearchTvShowViewModel tv)
        {
            TvRequests = new List <SeasonRequests>();
            // Only have the TV requests we actually requested and not everything
            foreach (var season in tv.SeasonRequests)
            {
                for (int i = season.Episodes.Count - 1; i >= 0; i--)
                {
                    if (!season.Episodes[i].Requested)
                    {
                        season.Episodes.RemoveAt(i); // Remove the episode since it's not requested
                    }
                }

                if (season.Episodes.Any())
                {
                    TvRequests.Add(season);
                }
            }

            return(this);
        }
Exemplo n.º 13
0
        private Response SearchTvShow(string searchTerm)
        {
            Log.Trace("Searching for TV Show {0}", searchTerm);

            var taskList = new List <Task>();

            var apiTv = new List <TvMazeSearch>();

            taskList.Add(Task.Factory.StartNew(() =>
            {
                return(new TvMazeApi().Search(searchTerm));
            }).ContinueWith((t) =>
            {
                apiTv = t.Result;
            }));

            var dbTv = new Dictionary <int, RequestedModel>();

            taskList.Add(Task.Factory.StartNew(() =>
            {
                return(RequestService.GetAll().Where(x => x.Type == RequestType.TvShow));
            }).ContinueWith((t) =>
            {
                dbTv = t.Result.ToDictionary(x => x.ProviderId);
            }));

            Task.WaitAll(taskList.ToArray());

            if (!apiTv.Any())
            {
                Log.Trace("TV Show data is null");
                return(Response.AsJson(""));
            }

            var sonarrCached  = SonarrCacher.QueuedIds();
            var sickRageCache = SickRageCacher.QueuedIds(); // consider just merging sonarr/sickrage arrays
            var plexTvShows   = Checker.GetPlexTvShows();

            var viewTv = new List <SearchTvShowViewModel>();

            foreach (var t in apiTv)
            {
                var viewT = new SearchTvShowViewModel
                {
                    // We are constructing the banner with the id:
                    // http://thetvdb.com/banners/_cache/posters/ID-1.jpg
                    Banner     = t.show.image?.medium,
                    FirstAired = t.show.premiered,
                    Id         = t.show.externals?.thetvdb ?? 0,
                    ImdbId     = t.show.externals?.imdb,
                    Network    = t.show.network?.name,
                    NetworkId  = t.show.network?.id.ToString(),
                    Overview   = t.show.summary.RemoveHtml(),
                    Rating     = t.score.ToString(CultureInfo.CurrentUICulture),
                    Runtime    = t.show.runtime.ToString(),
                    SeriesId   = t.show.id,
                    SeriesName = t.show.name,
                    Status     = t.show.status
                };

                if (Checker.IsTvShowAvailable(plexTvShows.ToArray(), t.show.name, t.show.premiered?.Substring(0, 4)))
                {
                    viewT.Available = true;
                }
                else if (t.show?.externals?.thetvdb != null)
                {
                    int tvdbid = (int)t.show.externals.thetvdb;

                    if (dbTv.ContainsKey(tvdbid))
                    {
                        var dbt = dbTv[tvdbid];

                        viewT.Requested = true;
                        viewT.Approved  = dbt.Approved;
                        viewT.Available = dbt.Available;
                    }
                    else if (sonarrCached.Contains(tvdbid) || sickRageCache.Contains(tvdbid)) // compare to the sonarr/sickrage db
                    {
                        viewT.Requested = true;
                    }
                }

                viewTv.Add(viewT);
            }

            Log.Trace("Returning TV Show results: ");
            Log.Trace(viewTv.DumpJson());
            return(Response.AsJson(viewTv));
        }
Exemplo n.º 14
0
 public async Task <RequestEngineResult> RequestTv([FromBody] SearchTvShowViewModel tv)
 {
     return(await TvRequestEngine.RequestTvShow(tv));
 }
Exemplo n.º 15
0
        public async Task <TvShowRequestBuilder> BuildEpisodes(SearchTvShowViewModel tv)
        {
            if (tv.RequestAll)
            {
                var episodes = await TvApi.EpisodeLookup(ShowInfo.id);

                foreach (var ep in episodes)
                {
                    var season = ChildRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == ep.season);
                    if (season == null)
                    {
                        ChildRequest.SeasonRequests.Add(new SeasonRequests
                        {
                            Episodes = new List <EpisodeRequests> {
                                new EpisodeRequests
                                {
                                    EpisodeNumber = ep.number,
                                    AirDate       = FormatDate(ep.airdate),
                                    Title         = ep.name,
                                    Url           = ep.url
                                }
                            },
                            SeasonNumber = ep.season,
                        });
                    }
                    else
                    {
                        season.Episodes.Add(new EpisodeRequests
                        {
                            EpisodeNumber = ep.number,
                            AirDate       = FormatDate(ep.airdate),
                            Title         = ep.name,
                            Url           = ep.url
                        });
                    }
                }
            }
            else if (tv.LatestSeason)
            {
                var episodes = await TvApi.EpisodeLookup(ShowInfo.id);

                var latest           = episodes.OrderByDescending(x => x.season).FirstOrDefault();
                var episodesRequests = new List <EpisodeRequests>();
                foreach (var ep in episodes)
                {
                    if (ep.season == latest.season)
                    {
                        episodesRequests.Add(new EpisodeRequests
                        {
                            EpisodeNumber = ep.number,
                            AirDate       = FormatDate(ep.airdate),
                            Title         = ep.name,
                            Url           = ep.url
                        });
                    }
                }
                ChildRequest.SeasonRequests.Add(new SeasonRequests
                {
                    Episodes     = episodesRequests,
                    SeasonNumber = latest.season,
                });
            }
            else if (tv.FirstSeason)
            {
                var episodes = await TvApi.EpisodeLookup(ShowInfo.id);

                var first            = episodes.OrderBy(x => x.season).FirstOrDefault();
                var episodesRequests = new List <EpisodeRequests>();
                foreach (var ep in episodes)
                {
                    if (ep.season == first.season)
                    {
                        episodesRequests.Add(new EpisodeRequests
                        {
                            EpisodeNumber = ep.number,
                            AirDate       = FormatDate(ep.airdate),
                            Title         = ep.name,
                            Url           = ep.url
                        });
                    }
                }
                ChildRequest.SeasonRequests.Add(new SeasonRequests
                {
                    Episodes     = episodesRequests,
                    SeasonNumber = first.season,
                });
            }
            else
            {
                // It's a custom request
                ChildRequest.SeasonRequests = TvRequests;
            }
            return(this);
        }
Exemplo n.º 16
0
        public async Task <RequestEngineResult> RequestTvShow(SearchTvShowViewModel tv)
        {
            var user = await GetUser();

            var tvBuilder = new TvShowRequestBuilder(TvApi);

            (await tvBuilder
             .GetShowInfo(tv.Id))
            .CreateTvList(tv)
            .CreateChild(tv, user.Id);

            await tvBuilder.BuildEpisodes(tv);

            var ruleResults = await RunRequestRules(tvBuilder.ChildRequest);

            var results = ruleResults as RuleResult[] ?? ruleResults.ToArray();

            if (results.Any(x => !x.Success))
            {
                return(new RequestEngineResult
                {
                    ErrorMessage = results.FirstOrDefault(x => !string.IsNullOrEmpty(x.Message)).Message
                });
            }

            // Check if we have auto approved the request, if we have then mark the episodes as approved
            if (tvBuilder.ChildRequest.Approved)
            {
                foreach (var seasons in tvBuilder.ChildRequest.SeasonRequests)
                {
                    foreach (var ep in seasons.Episodes)
                    {
                        ep.Approved  = true;
                        ep.Requested = true;
                    }
                }
            }

            await Audit.Record(AuditType.Added, AuditArea.TvRequest, $"Added Request {tv.Title}", Username);

            var existingRequest = await TvRepository.Get().FirstOrDefaultAsync(x => x.TvDbId == tv.Id);

            if (existingRequest != null)
            {
                // Remove requests we already have, we just want new ones
                foreach (var existingSeason in existingRequest.ChildRequests)
                {
                    foreach (var existing in existingSeason.SeasonRequests)
                    {
                        var newChild = tvBuilder.ChildRequest.SeasonRequests.FirstOrDefault(x => x.SeasonNumber == existing.SeasonNumber);
                        if (newChild != null)
                        {
                            // We have some requests in this season...
                            // Let's find the episodes.
                            foreach (var existingEp in existing.Episodes)
                            {
                                var duplicateEpisode = newChild.Episodes.FirstOrDefault(x => x.EpisodeNumber == existingEp.EpisodeNumber);
                                if (duplicateEpisode != null)
                                {
                                    // Remove it.
                                    newChild.Episodes.Remove(duplicateEpisode);
                                }
                            }
                            if (!newChild.Episodes.Any())
                            {
                                // We may have removed all episodes
                                tvBuilder.ChildRequest.SeasonRequests.Remove(newChild);
                            }
                        }
                    }
                }

                // Remove the ID since this is a new child
                tvBuilder.ChildRequest.Id = 0;
                if (!tvBuilder.ChildRequest.SeasonRequests.Any())
                {
                    // Looks like we have removed them all! They were all duplicates...
                    return(new RequestEngineResult
                    {
                        Result = false,
                        ErrorMessage = "This has already been requested"
                    });
                }
                return(await AddExistingRequest(tvBuilder.ChildRequest, existingRequest));
            }

            // This is a new request
            var newRequest = tvBuilder.CreateNewRequest(tv);

            return(await AddRequest(newRequest.NewRequest));
        }