Esempio n. 1
0
        private async Task <RequestEngineResult> ProcessSendingShow(ChildRequests model)
        {
            if (model.Approved)
            {
                // Autosend
                await NotificationHelper.Notify(model, NotificationType.RequestApproved);

                var result = await TvSender.Send(model);

                if (result.Success)
                {
                    return(new RequestEngineResult {
                        Result = true, RequestId = model.Id
                    });
                }
                return(new RequestEngineResult
                {
                    ErrorMessage = result.Message,
                    RequestId = model.Id
                });
            }

            return(new RequestEngineResult {
                Result = true, RequestId = model.Id
            });
        }
Esempio n. 2
0
        private RuleResult CheckExistingContent(ChildRequests child, PlexServerContent content)
        {
            foreach (var season in child.SeasonRequests)
            {
                var episodesToRemove     = new List <EpisodeRequests>();
                var currentSeasonRequest =
                    content.Episodes.Where(x => x.SeasonNumber == season.SeasonNumber).ToList();
                if (!currentSeasonRequest.Any())
                {
                    continue;
                }
                foreach (var e in season.Episodes)
                {
                    var existingEpRequest = currentSeasonRequest.FirstOrDefault(x => x.EpisodeNumber == e.EpisodeNumber);
                    if (existingEpRequest != null)
                    {
                        episodesToRemove.Add(e);
                    }
                }

                episodesToRemove.ForEach(x =>
                {
                    season.Episodes.Remove(x);
                });
            }

            var anyEpisodes = child.SeasonRequests.SelectMany(x => x.Episodes).Any();

            if (!anyEpisodes)
            {
                return(Fail(ErrorCode.EpisodesAlreadyRequested, $"We already have episodes requested from series {child.Title}"));
            }

            return(Success());
        }
Esempio n. 3
0
        public async Task RequestShow_DoesNotExistAtAll_IsSuccessful()
        {
            TvRequestRepo.Setup(x => x.GetChild()).Returns(new List <ChildRequests>().AsQueryable().BuildMock().Object);
            var req = new ChildRequests
            {
                SeasonRequests = new List <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new List <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                Id            = 1,
                                EpisodeNumber = 1,
                            }
                        },
                        SeasonNumber = 1
                    }
                }
            };
            var result = await Rule.Execute(req);


            Assert.That(result.Success, Is.True);
        }
Esempio n. 4
0
        public void Setup(NotificationOptions opts, ChildRequests req, CustomizationSettings s)
        {
            LoadIssues(opts);
            string title;

            if (req == null)
            {
                opts.Substitutes.TryGetValue("Title", out title);
            }
            else
            {
                title = req?.ParentRequest.Title;
            }
            ApplicationUrl  = (s?.ApplicationUrl.HasValue() ?? false) ? s.ApplicationUrl : string.Empty;
            ApplicationName = string.IsNullOrEmpty(s?.ApplicationName) ? "Ombi" : s?.ApplicationName;
            RequestedUser   = string.IsNullOrEmpty(req?.RequestedUser.Alias)
                ? req?.RequestedUser.UserName
                : req?.RequestedUser.Alias;
            Title         = title;
            RequestedDate = req?.RequestedDate.ToString("D");
            Type          = req?.RequestType.ToString();
            Overview      = req?.ParentRequest.Overview;
            Year          = req?.ParentRequest.ReleaseDate.Year.ToString();
            PosterImage   = req?.RequestType == RequestType.Movie ?
                            $"https://image.tmdb.org/t/p/w300{req?.ParentRequest.PosterPath}" : req?.ParentRequest.PosterPath;
            AdditionalInformation = opts.AdditionalInformation;
            // DO Episode and Season Lists
        }
Esempio n. 5
0
        private async Task <RequestEngineResult> ProcessSendingShow(ChildRequests model)
        {
            if (model.Approved)
            {
                // Autosend
                var canNotify = await RunSpecificRule(model, SpecificRules.CanSendNotification, string.Empty);

                if (canNotify.Success)
                {
                    await NotificationHelper.Notify(model, NotificationType.RequestApproved);
                }
                var result = await TvSender.Send(model);

                if (result.Success)
                {
                    return(new RequestEngineResult {
                        Result = true, RequestId = model.Id
                    });
                }
                return(new RequestEngineResult
                {
                    ErrorMessage = result.Message,
                    RequestId = model.Id
                });
            }

            return(new RequestEngineResult {
                Result = true, RequestId = model.Id
            });
        }
Esempio n. 6
0
        public async Task RequestShow_AllEpisodesAreaRequested_IsNotSuccessful()
        {
            SetupMockData();

            var req = new ChildRequests
            {
                SeasonRequests = new List <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new List <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                Id            = 1,
                                EpisodeNumber = 1,
                            },
                            new EpisodeRequests
                            {
                                Id            = 1,
                                EpisodeNumber = 2,
                            },
                        },
                        SeasonNumber = 1
                    }
                },
                Id = 1,
            };
            var result = await Rule.Execute(req);


            Assert.That(result.Success, Is.False);
        }
Esempio n. 7
0
        private async Task<RequestEngineResult> AfterRequest(ChildRequests model)
        {
            var sendRuleResult = await RunSpecificRule(model, SpecificRules.CanSendNotification);
            if (sendRuleResult.Success)
            {
                NotificationHelper.NewRequest(model);
            }

            if (model.Approved)
            {
                // Autosend
                NotificationHelper.Notify(model, NotificationType.RequestApproved);
                var result = await TvSender.Send(model);
                if (result.Success)
                {
                    return new RequestEngineResult { Result = true };
                }
                return new RequestEngineResult
                {
                    ErrorMessage = result.Message
                };
            }

            await _requestLog.Add(new RequestLog
            {
                UserId = (await GetUser()).Id,
                RequestDate = DateTime.UtcNow,
                RequestId = model.Id,
                RequestType = RequestType.TvShow,
            });

            return new RequestEngineResult { Result = true };
        }
Esempio n. 8
0
        public async Task<ChildRequests> UpdateChildRequest(ChildRequests request)
        {
            await Audit.Record(AuditType.Updated, AuditArea.TvRequest, $"Updated Request {request.Title}", Username);

            await TvRepository.UpdateChild(request);
            return request;
        }
Esempio n. 9
0
        public async Task <RequestEngineResult> MarkAvailable(int modelId)
        {
            ChildRequests request = await TvRepository.GetChild().FirstOrDefaultAsync(x => x.Id == modelId);

            if (request == null)
            {
                return(new RequestEngineResult
                {
                    ErrorMessage = "Child Request does not exist"
                });
            }
            request.Available = true;
            foreach (var season in request.SeasonRequests)
            {
                foreach (var e in season.Episodes)
                {
                    e.Available = true;
                }
            }
            await TvRepository.UpdateChild(request);

            NotificationHelper.Notify(request, NotificationType.RequestAvailable);
            return(new RequestEngineResult
            {
                Result = true,
                Message = "Request is now available",
            });
        }
Esempio n. 10
0
        public async Task <SenderResult> Send(ChildRequests model)
        {
            var sonarr = await SonarrSettings.GetSettingsAsync();

            if (sonarr.Enabled)
            {
                var result = await SendToSonarr(model);

                if (result != null)
                {
                    return(new SenderResult
                    {
                        Sent = true,
                        Success = true
                    });
                }
            }
            var dog = await DogNzbSettings.GetSettingsAsync();

            if (dog.Enabled)
            {
                var result = await SendToDogNzb(model, dog);

                if (!result.Failure)
                {
                    return(new SenderResult
                    {
                        Sent = true,
                        Success = true
                    });
                }
                return(new SenderResult
                {
                    Message = result.ErrorMessage
                });
            }
            var sr = await SickRageSettings.GetSettingsAsync();

            if (sr.Enabled)
            {
                var result = await SendToSickRage(model, sr);

                if (result)
                {
                    return(new SenderResult
                    {
                        Sent = true,
                        Success = true
                    });
                }
                return(new SenderResult
                {
                    Message = "Could not send to SickRage!"
                });
            }
            return(new SenderResult
            {
                Success = true
            });
        }
Esempio n. 11
0
        public async Task <RequestEngineResult> MarkAvailable(int modelId, bool is4K)
        {
            ChildRequests request = await TvRepository.GetChild().FirstOrDefaultAsync(x => x.Id == modelId);

            if (request == null)
            {
                return(new RequestEngineResult
                {
                    ErrorCode = ErrorCode.ChildRequestDoesNotExist,
                    ErrorMessage = "Child Request does not exist"
                });
            }
            request.Available         = true;
            request.MarkedAsAvailable = DateTime.Now;
            foreach (var season in request.SeasonRequests)
            {
                foreach (var e in season.Episodes)
                {
                    e.Available = true;
                }
            }
            await TvRepository.UpdateChild(request);

            await NotificationHelper.Notify(request, NotificationType.RequestAvailable);

            await _mediaCacheService.Purge();

            return(new RequestEngineResult
            {
                Result = true,
                Message = "Request is now available",
            });
        }
Esempio n. 12
0
        public async Task <ChildRequests> AddChild(ChildRequests request)
        {
            await Db.ChildRequests.AddAsync(request);

            await Db.SaveChangesAsync();

            return(request);
        }
Esempio n. 13
0
        public async Task <ChildRequests> UpdateChildRequest(ChildRequests request)
        {
            await TvRepository.UpdateChild(request);

            await _mediaCacheService.Purge();

            return(request);
        }
Esempio n. 14
0
        private async Task <RequestEngineResult> AddExistingRequest(ChildRequests newRequest, TvRequests existingRequest)
        {
            // Add the child
            existingRequest.ChildRequests.Add(newRequest);

            await TvRepository.Update(existingRequest);

            return(await AfterRequest(newRequest));
        }
Esempio n. 15
0
        public void Setup(NotificationOptions opts, ChildRequests req, CustomizationSettings s,
                          UserNotificationPreferences pref)
        {
            LoadIssues(opts);
            LoadCommon(req, s, pref, opts);
            LoadTitle(opts, req);
            ProviderId            = req?.ParentRequest?.ExternalProviderId.ToString() ?? string.Empty;
            Year                  = req?.ParentRequest?.ReleaseDate.Year.ToString();
            Overview              = req?.ParentRequest?.Overview;
            AdditionalInformation = opts.AdditionalInformation;
            var img = req?.ParentRequest?.PosterPath ?? string.Empty;

            if (img.HasValue())
            {
                if (img.StartsWith("http"))
                {
                    // This means it's a legacy request from when we used TvMaze as a provider.
                    // The poster url is the fully qualified address, so just use it
                    PosterImage = img;
                }
                else
                {
                    PosterImage =
                        $"https://image.tmdb.org/t/p/w300/{img?.TrimStart('/') ?? string.Empty}";
                }
            }

            // Generate episode list.
            StringBuilder epSb = new StringBuilder();
            IEnumerable <EpisodeRequests> episodes = req?.SeasonRequests?
                                                     .SelectMany(x => x.Episodes) ?? new List <EpisodeRequests>();

            episodes
            .OrderBy(x => x.EpisodeNumber)
            .ToList()
            .ForEach(ep => epSb.Append($"{ep.EpisodeNumber},"));
            if (epSb.Length > 0)
            {
                epSb.Remove(epSb.Length - 1, 1);
            }
            EpisodesList = epSb.ToString();

            // Generate season list.
            StringBuilder         seasonSb = new StringBuilder();
            List <SeasonRequests> seasons  = req?.SeasonRequests ?? new List <SeasonRequests>();

            seasons
            .OrderBy(x => x.SeasonNumber)
            .ToList()
            .ForEach(ep => seasonSb.Append($"{ep.SeasonNumber},"));
            if (seasonSb.Length > 0)
            {
                seasonSb.Remove(seasonSb.Length - 1, 1);
            }
            SeasonsList = seasonSb.ToString();
            CalculateRequestStatus(req);
        }
Esempio n. 16
0
        public async Task MarkChildAsAvailable(int id)
        {
            var request = new ChildRequests {
                Id = id, Available = true, MarkedAsAvailable = DateTime.UtcNow
            };
            var attached = Db.ChildRequests.Attach(request);

            attached.Property(x => x.Available).IsModified         = true;
            attached.Property(x => x.MarkedAsAvailable).IsModified = true;
            await Db.SaveChangesAsync();
        }
Esempio n. 17
0
        public void NewRequest(ChildRequests model)
        {
            var notificationModel = new NotificationOptions
            {
                RequestId        = model.Id,
                DateTime         = DateTime.Now,
                NotificationType = NotificationType.NewRequest,
                RequestType      = model.RequestType
            };

            BackgroundJob.Enqueue(() => NotificationService.Publish(notificationModel));
        }
        public async Task ProcessTv_ShouldMark_Episode_Available_WhenInPlex()
        {
            var request = new ChildRequests
            {
                ParentRequest = new TvRequests {
                    TvDbId = 1
                },
                SeasonRequests = new EditableList <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new EditableList <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                EpisodeNumber = 1,
                                Season        = new SeasonRequests
                                {
                                    SeasonNumber = 2
                                }
                            }
                        }
                    }
                },
                RequestedUser = new OmbiUser
                {
                    Email = "abc"
                }
            };

            _tv.Setup(x => x.GetChild()).Returns(new List <ChildRequests> {
                request
            }.AsQueryable().BuildMock().Object);
            _repo.Setup(x => x.GetAllEpisodes()).Returns(new List <PlexEpisode>
            {
                new PlexEpisode
                {
                    Series = new  PlexServerContent
                    {
                        TvDbId = 1.ToString(),
                    },
                    EpisodeNumber = 1,
                    SeasonNumber  = 2
                }
            }.AsQueryable().BuildMock().Object);
            _repo.Setup(x => x.Include(It.IsAny <IQueryable <PlexEpisode> >(), It.IsAny <Expression <Func <PlexEpisode, PlexServerContent> > >()));

            await Checker.Execute(null);

            _tv.Verify(x => x.Save(), Times.Once);

            Assert.True(request.SeasonRequests[0].Episodes[0].Available);
        }
Esempio n. 19
0
        public void Notify(ChildRequests model, NotificationType type)
        {
            var notificationModel = new NotificationOptions
            {
                RequestId        = model.Id,
                DateTime         = DateTime.Now,
                NotificationType = type,
                RequestType      = model.RequestType,
                Recipient        = model.RequestedUser?.Email ?? string.Empty
            };

            BackgroundJob.Enqueue(() => NotificationService.Publish(notificationModel));
        }
Esempio n. 20
0
 public async Task NewRequest(ChildRequests model)
 {
     var notificationModel = new NotificationOptions
     {
         RequestId        = model.Id,
         DateTime         = DateTime.Now,
         NotificationType = NotificationType.NewRequest,
         RequestType      = model.RequestType
     };
     await OmbiQuartz.TriggerJob(nameof(INotificationService), "Notifications", new Dictionary <string, object>
     {
         { JobDataKeys.NotificationOptions, notificationModel }
     });
 }
Esempio n. 21
0
        private async Task CheckForSubscription(HideResult shouldHide, ChildRequests x)
        {
            if (shouldHide.UserId == x.RequestedUserId)
            {
                x.ShowSubscribe = false;
            }
            else
            {
                x.ShowSubscribe = true;
                var sub = await _subscriptionRepository.GetAll().FirstOrDefaultAsync(s =>
                                                                                     s.UserId == shouldHide.UserId && s.RequestId == x.Id && s.RequestType == RequestType.TvShow);

                x.Subscribed = sub != null;
            }
        }
Esempio n. 22
0
 public async Task Notify(ChildRequests model, NotificationType type)
 {
     var notificationModel = new NotificationOptions
     {
         RequestId        = model.Id,
         DateTime         = DateTime.Now,
         NotificationType = type,
         RequestType      = model.RequestType,
         Recipient        = model.RequestedUser?.Email ?? string.Empty
     };
     await OmbiQuartz.TriggerJob(nameof(INotificationService), "Notifications", new Dictionary <string, object>
     {
         { JobDataKeys.NotificationOptions, notificationModel }
     });
 }
Esempio n. 23
0
        public TvShowRequestBuilder CreateChild(TvRequestViewModel model, string userId)
        {
            ChildRequest = new ChildRequests
            {
                Id              = model.TvDbId,
                RequestType     = RequestType.TvShow,
                RequestedDate   = DateTime.UtcNow,
                Approved        = false,
                RequestedUserId = userId,
                SeasonRequests  = new List <SeasonRequests>(),
                Title           = ShowInfo.name,
                SeriesType      = ShowInfo.genres.Any(s => s.Equals("Anime", StringComparison.OrdinalIgnoreCase)) ? SeriesType.Anime : SeriesType.Standard
            };

            return(this);
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        private static List <Season> GetSeasonsToCreate(ChildRequests model)
        {
            // Let's get a list of seasons just incase we need to change it
            var seasonsToUpdate = new List <Season>();

            for (var i = 0; i < model.ParentRequest.TotalSeasons + 1; i++)
            {
                var sea = new Season
                {
                    seasonNumber = i,
                    monitored    = false
                };
                seasonsToUpdate.Add(sea);
            }

            return(seasonsToUpdate);
        }
Esempio n. 26
0
        private async Task <RequestEngineResult> AddExistingRequest(ChildRequests newRequest, TvRequests existingRequest, string requestOnBehalf, int rootFolder, int qualityProfile)
        {
            // Add the child
            existingRequest.ChildRequests.Add(newRequest);
            if (qualityProfile > 0)
            {
                existingRequest.QualityOverride = qualityProfile;
            }
            if (rootFolder > 0)
            {
                existingRequest.RootFolder = rootFolder;
            }

            await TvRepository.Update(existingRequest);

            return(await AfterRequest(newRequest, requestOnBehalf));
        }
Esempio n. 27
0
        public TvShowRequestBuilder CreateChild(TvRequestViewModel model, string userId)
        {
            ChildRequest = new ChildRequests
            {
                Id              = model.TvDbId, // This is set to 0 after the request rules have run, the request rules needs it to identify the request
                RequestType     = RequestType.TvShow,
                RequestedDate   = DateTime.UtcNow,
                Approved        = false,
                RequestedUserId = userId,
                SeasonRequests  = new List <SeasonRequests>(),
                Title           = ShowInfo.name,
                ReleaseYear     = FirstAir,
                SeriesType      = ShowInfo.genres.Any(s => s.Equals("Anime", StringComparison.InvariantCultureIgnoreCase)) ? SeriesType.Anime : SeriesType.Standard
            };

            return(this);
        }
Esempio n. 28
0
        public async Task RequestShow_SomeEpisodesAreaRequested_IsSuccessful()
        {
            SetupMockData();

            var req = new ChildRequests
            {
                RequestType    = RequestType.TvShow,
                SeasonRequests = new List <SeasonRequests>
                {
                    new SeasonRequests
                    {
                        Episodes = new List <EpisodeRequests>
                        {
                            new EpisodeRequests
                            {
                                Id            = 1,
                                EpisodeNumber = 1,
                            },
                            new EpisodeRequests
                            {
                                Id            = 2,
                                EpisodeNumber = 2,
                            },
                            new EpisodeRequests
                            {
                                Id            = 3,
                                EpisodeNumber = 3,
                            },
                        },
                        SeasonNumber = 1
                    }
                },
                Id = 1,
            };
            var result = await Rule.Execute(req);


            Assert.That(result.Success, Is.True);

            var episodes = req.SeasonRequests.SelectMany(x => x.Episodes);

            Assert.That(episodes.Count() == 1, "We didn't remove the episodes that have already been requested!");
            Assert.That(episodes.First().EpisodeNumber == 3, "We removed the wrong episode");
        }
Esempio n. 29
0
        public void Setup(NotificationOptions opts, ChildRequests req, CustomizationSettings s,
                          UserNotificationPreferences pref)
        {
            LoadIssues(opts);
            LoadCommon(req, s, pref);
            LoadTitle(opts, req);
            ProviderId            = req?.ParentRequest?.ExternalProviderId.ToString() ?? string.Empty;
            Year                  = req?.ParentRequest?.ReleaseDate.Year.ToString();
            Overview              = req?.ParentRequest?.Overview;
            AdditionalInformation = opts.AdditionalInformation;
            PosterImage           =
                $"https://image.tmdb.org/t/p/w300/{req?.ParentRequest?.PosterPath?.TrimStart('/') ?? string.Empty}";

            // Generate episode list.
            StringBuilder epSb = new StringBuilder();
            IEnumerable <EpisodeRequests> episodes = req?.SeasonRequests?
                                                     .SelectMany(x => x.Episodes) ?? new List <EpisodeRequests>();

            episodes
            .OrderBy(x => x.EpisodeNumber)
            .ToList()
            .ForEach(ep => epSb.Append($"{ep.EpisodeNumber},"));
            if (epSb.Length > 0)
            {
                epSb.Remove(epSb.Length - 1, 1);
            }
            EpisodesList = epSb.ToString();

            // Generate season list.
            StringBuilder         seasonSb = new StringBuilder();
            List <SeasonRequests> seasons  = req?.SeasonRequests ?? new List <SeasonRequests>();

            seasons
            .OrderBy(x => x.SeasonNumber)
            .ToList()
            .ForEach(ep => seasonSb.Append($"{ep.SeasonNumber},"));
            if (seasonSb.Length > 0)
            {
                seasonSb.Remove(seasonSb.Length - 1, 1);
            }
            SeasonsList = seasonSb.ToString();
            CalculateRequestStatus(req);
        }
Esempio n. 30
0
        private async Task <RequestEngineResult> AfterRequest(ChildRequests model, string requestOnBehalf)
        {
            var sendRuleResult = await RunSpecificRule(model, SpecificRules.CanSendNotification);

            if (sendRuleResult.Success)
            {
                await NotificationHelper.NewRequest(model);
            }

            await _requestLog.Add(new RequestLog
            {
                UserId       = requestOnBehalf.HasValue() ? requestOnBehalf : (await GetUser()).Id,
                RequestDate  = DateTime.UtcNow,
                RequestId    = model.Id,
                RequestType  = RequestType.TvShow,
                EpisodeCount = model.SeasonRequests.Select(m => m.Episodes.Count).Sum(),
            });

            if (model.Approved)
            {
                // Autosend
                await NotificationHelper.Notify(model, NotificationType.RequestApproved);

                var result = await TvSender.Send(model);

                if (result.Success)
                {
                    return(new RequestEngineResult {
                        Result = true, RequestId = model.Id
                    });
                }
                return(new RequestEngineResult
                {
                    ErrorMessage = result.Message,
                    RequestId = model.Id
                });
            }

            return(new RequestEngineResult {
                Result = true, RequestId = model.Id
            });
        }