Example #1
0
        public async Task HappyPathSendSeriesToSonarrAllSeason()
        {
            var seriesResult = new SonarrAddSeries()
            {
                title = "ABC"
            };

            SonarrMock.Setup(x => x.GetSeries(It.IsAny <string>(), It.IsAny <Uri>())).Returns(F.Build <Series>().With(x => x.tvdbId, 1).With(x => x.title, "ABC").CreateMany().ToList());

            Sender = new TvSender(SonarrMock.Object, SickrageMock.Object, Cache.Object);

            var request = new RequestedModel {
                SeasonsRequested = "All", ProviderId = 1, Title = "ABC"
            };

            var result = await Sender.SendToSonarr(GetSonarrSettings(), request);

            Assert.That(result.title, Is.EqualTo("ABC"));
            SonarrMock.Verify(x => x.AddSeries(It.IsAny <int>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <bool>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <int[]>(),
                                               It.IsAny <string>(),
                                               It.IsAny <Uri>(),
                                               true, It.IsAny <bool>()), Times.Never);
        }
Example #2
0
        public async Task HappyPathSendEpisodeWithExistingSeriesToSonarr()
        {
            var seriesResult = new SonarrAddSeries {
                monitored = true, title = "TitleReturned"
            };
            var selectedSeries = F.Build <Series>().With(x => x.tvdbId, 1).CreateMany();

            SonarrMock.Setup(x => x.GetSeries(It.IsAny <string>(), It.IsAny <Uri>())).Returns(selectedSeries.ToList());
            SonarrMock.Setup(x => x.AddSeries(
                                 It.IsAny <int>(),
                                 It.IsAny <string>(),
                                 It.IsAny <int>(),
                                 It.IsAny <bool>(),
                                 It.IsAny <string>(),
                                 It.IsAny <int>(),
                                 It.IsAny <int[]>(),
                                 It.IsAny <string>(),
                                 It.IsAny <Uri>(),
                                 It.IsAny <bool>(), It.IsAny <bool>())).Returns(seriesResult);
            var sonarrEpisodes = new SonarrEpisodes()
            {
                title         = "abc",
                seasonNumber  = 2,
                episodeNumber = 1,
                monitored     = false
            };
            var episodesList = F.CreateMany <SonarrEpisodes>().ToList();

            episodesList.Add(sonarrEpisodes);

            SonarrMock.Setup(x => x.GetEpisodes(It.IsAny <string>(), It.IsAny <string>(),
                                                It.IsAny <Uri>())).Returns(F.CreateMany <SonarrEpisodes>());

            Sender = new TvSender(SonarrMock.Object, SickrageMock.Object, Cache.Object);
            var episodes = new List <EpisodesModel>
            {
                new EpisodesModel
                {
                    EpisodeNumber = 1,
                    SeasonNumber  = 2
                }
            };
            var model = F.Build <RequestedModel>().With(x => x.ProviderId, 1)
                        .With(x => x.Episodes, episodes).Create();

            var result = await Sender.SendToSonarr(GetSonarrSettings(), model, "2");

            Assert.That(result, Is.EqualTo(seriesResult));
            SonarrMock.Verify(x => x.AddSeries(It.IsAny <int>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <bool>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <int[]>(),
                                               It.IsAny <string>(),
                                               It.IsAny <Uri>(),
                                               true, It.IsAny <bool>()), Times.Once);
        }
        public async Task HappyPathSendSeriesToSonarr()
        {
            var seriesResult = new SonarrAddSeries()
            {
                monitored = true
            };

            SonarrMock.Setup(x => x.GetSeries(It.IsAny <string>(), It.IsAny <Uri>())).Returns(new List <Series>());
            SonarrMock.Setup(
                x =>
                x.AddSeries(
                    It.IsAny <int>(),
                    It.IsAny <string>(),
                    It.IsAny <int>(),
                    It.IsAny <bool>(),
                    It.IsAny <string>(),
                    It.IsAny <int>(),
                    It.IsAny <int[]>(),
                    It.IsAny <string>(),
                    It.IsAny <Uri>(),
                    It.IsAny <bool>(), It.IsAny <bool>())).Returns(seriesResult);
            Sender = new TvSender(SonarrMock.Object, SickrageMock.Object);

            var request = new RequestedModel();

            var result = await Sender.SendToSonarr(GetSonarrSettings(), request);

            Assert.That(result, Is.EqualTo(seriesResult));
            SonarrMock.Verify(x => x.AddSeries(It.IsAny <int>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <bool>(),
                                               It.IsAny <string>(),
                                               It.IsAny <int>(),
                                               It.IsAny <int[]>(),
                                               It.IsAny <string>(),
                                               It.IsAny <Uri>(),
                                               true, It.IsAny <bool>()), Times.Once);
        }
        /// <summary>
        /// Requests the tv show.
        /// </summary>
        /// <param name="showId">The show identifier.</param>
        /// <param name="seasons">The seasons.</param>
        /// <param name="notify">if set to <c>true</c> [notify].</param>
        /// <returns></returns>
        private Response RequestTvShow(int showId, string seasons)
        {
            var tvApi = new TvMazeApi();

            var      showInfo = tvApi.ShowLookupByTheTvDbId(showId);
            DateTime firstAir;

            DateTime.TryParse(showInfo.premiered, out firstAir);
            string fullShowName = $"{showInfo.name} ({firstAir.Year})";
            //#if !DEBUG

            var settings = PrService.GetSettings();

            // check if the show has already been requested
            Log.Info("Requesting tv show with id {0}", showId);
            var existingRequest = RequestService.CheckRequest(showId);

            if (existingRequest != null)
            {
                // check if the current user is already marked as a requester for this show, if not, add them
                if (!existingRequest.UserHasRequested(Username))
                {
                    existingRequest.RequestedUsers.Add(Username);
                    RequestService.UpdateRequest(existingRequest);
                }
                return(Response.AsJson(new JsonResponseModel {
                    Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{fullShowName} was successfully added!" : $"{fullShowName} has already been requested!"
                }));
            }

            try
            {
                var shows = Checker.GetPlexTvShows();
                if (Checker.IsTvShowAvailable(shows.ToArray(), showInfo.name, showInfo.premiered?.Substring(0, 4)))
                {
                    return(Response.AsJson(new JsonResponseModel {
                        Result = false, Message = $"{fullShowName} is already in Plex!"
                    }));
                }
            }
            catch (ApplicationSettingsException)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = $"We could not check if {fullShowName} is in Plex, are you sure it's correctly setup?"
                }));
            }
            //#endif


            var model = new RequestedModel
            {
                ProviderId     = showInfo.externals?.thetvdb ?? 0,
                Type           = RequestType.TvShow,
                Overview       = showInfo.summary.RemoveHtml(),
                PosterPath     = showInfo.image?.medium,
                Title          = showInfo.name,
                ReleaseDate    = firstAir,
                Status         = showInfo.status,
                RequestedDate  = DateTime.UtcNow,
                Approved       = false,
                RequestedUsers = new List <string> {
                    Username
                },
                Issues      = IssueState.None,
                ImdbId      = showInfo.externals?.imdb ?? string.Empty,
                SeasonCount = showInfo.seasonCount
            };

            var seasonsList = new List <int>();

            switch (seasons)
            {
            case "first":
                seasonsList.Add(1);
                model.SeasonsRequested = "First";
                break;

            case "latest":
                seasonsList.Add(model.SeasonCount);
                model.SeasonsRequested = "Latest";
                break;

            case "all":
                model.SeasonsRequested = "All";
                break;

            default:
                var split        = seasons.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var seasonsCount = new int[split.Length];
                for (var i = 0; i < split.Length; i++)
                {
                    int tryInt;
                    int.TryParse(split[i], out tryInt);
                    seasonsCount[i] = tryInt;
                }
                seasonsList.AddRange(seasonsCount);
                break;
            }

            model.SeasonList = seasonsList.ToArray();

            if (ShouldAutoApprove(RequestType.TvShow, settings))
            {
                var sonarrSettings = SonarrService.GetSettings();
                var sender         = new TvSender(SonarrApi, SickrageApi);
                if (sonarrSettings.Enabled)
                {
                    var result = sender.SendToSonarr(sonarrSettings, model);
                    if (result != null && !string.IsNullOrEmpty(result.title))
                    {
                        model.Approved = true;
                        Log.Debug("Adding tv to database requests (No approval required & Sonarr)");
                        RequestService.AddRequest(model);

                        if (ShouldSendNotification())
                        {
                            var notify1 = new NotificationModel
                            {
                                Title            = model.Title,
                                User             = Username,
                                DateTime         = DateTime.Now,
                                NotificationType = NotificationType.NewRequest
                            };
                            NotificationService.Publish(notify1);
                        }
                        return(Response.AsJson(new JsonResponseModel {
                            Result = true, Message = $"{fullShowName} was successfully added!"
                        }));
                    }


                    return(Response.AsJson(ValidationHelper.SendSonarrError(result?.ErrorMessages)));
                }

                var srSettings = SickRageService.GetSettings();
                if (srSettings.Enabled)
                {
                    var result = sender.SendToSickRage(srSettings, model);
                    if (result?.result == "success")
                    {
                        model.Approved = true;
                        Log.Debug("Adding tv to database requests (No approval required & SickRage)");
                        RequestService.AddRequest(model);
                        if (ShouldSendNotification())
                        {
                            var notify2 = new NotificationModel
                            {
                                Title            = model.Title,
                                User             = Username,
                                DateTime         = DateTime.Now,
                                NotificationType = NotificationType.NewRequest
                            };
                            NotificationService.Publish(notify2);
                        }

                        return(Response.AsJson(new JsonResponseModel {
                            Result = true, Message = $"{fullShowName} was successfully added!"
                        }));
                    }
                    return(Response.AsJson(new JsonResponseModel {
                        Result = false, Message = result?.message != null ? "<b>Message From SickRage: </b>" + result.message : "Something went wrong adding the movie to SickRage! Please check your settings."
                    }));
                }

                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "The request of TV Shows is not correctly set up. Please contact your admin."
                }));
            }

            RequestService.AddRequest(model);

            var notificationModel = new NotificationModel {
                Title = model.Title, User = Username, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest
            };

            NotificationService.Publish(notificationModel);

            return(Response.AsJson(new JsonResponseModel {
                Result = true, Message = $"{fullShowName} was successfully added!"
            }));
        }
        private Response UpdateRequests(RequestedModel[] requestedModels)
        {
            var cpSettings      = CpService.GetSettings();
            var updatedRequests = new List <RequestedModel>();

            foreach (var r in requestedModels)
            {
                if (r.Type == RequestType.Movie)
                {
                    if (cpSettings.Enabled)
                    {
                        var res = SendMovie(cpSettings, r, CpApi);
                        if (res)
                        {
                            r.Approved = true;
                            updatedRequests.Add(r);
                        }
                        else
                        {
                            Log.Error("Could not approve and send the movie {0} to couch potato!", r.Title);
                        }
                    }
                    else
                    {
                        r.Approved = true;
                        updatedRequests.Add(r);
                    }
                }
                if (r.Type == RequestType.TvShow)
                {
                    var sender = new TvSender(SonarrApi, SickRageApi);
                    var sr     = SickRageSettings.GetSettings();
                    var sonarr = SonarrSettings.GetSettings();
                    if (sr.Enabled)
                    {
                        var res = sender.SendToSickRage(sr, r);
                        if (res?.result == "success")
                        {
                            r.Approved = true;
                            updatedRequests.Add(r);
                        }
                        else
                        {
                            Log.Error("Could not approve and send the TV {0} to SickRage!", r.Title);
                            Log.Error("SickRage Message: {0}", res?.message);
                        }
                    }

                    else if (sonarr.Enabled)
                    {
                        var res = sender.SendToSonarr(sonarr, r);
                        if (!string.IsNullOrEmpty(res?.title))
                        {
                            r.Approved = true;
                            updatedRequests.Add(r);
                        }
                        else
                        {
                            Log.Error("Could not approve and send the TV {0} to Sonarr!", r.Title);
                            res?.ErrorMessages.ForEach(x => Log.Error("Error messages: {0}", x));
                        }
                    }
                    else
                    {
                        r.Approved = true;
                        updatedRequests.Add(r);
                    }
                }
            }
            try
            {
                var result = Service.BatchUpdate(updatedRequests);
                return(Response.AsJson(result
                    ? new JsonResponseModel {
                    Result = true
                }
                    : new JsonResponseModel {
                    Result = false, Message = "We could not approve all of the requests. Please try again or check the logs."
                }));
            }
            catch (Exception e)
            {
                Log.Fatal(e);
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Something bad happened, please check the logs!"
                }));
            }
        }
        private Response RequestTvAndUpdateStatus(RequestedModel request, string qualityId)
        {
            var sender = new TvSender(SonarrApi, SickRageApi);

            var sonarrSettings = SonarrSettings.GetSettings();

            if (sonarrSettings.Enabled)
            {
                Log.Trace("Sending to Sonarr");
                var result = sender.SendToSonarr(sonarrSettings, request, qualityId);
                Log.Trace("Sonarr Result: ");
                Log.Trace(result.DumpJson());
                if (!string.IsNullOrEmpty(result.title))
                {
                    Log.Info("Sent successfully, Approving request now.");
                    request.Approved = true;
                    var requestResult = Service.UpdateRequest(request);
                    Log.Trace("Approval result: {0}", requestResult);
                    if (requestResult)
                    {
                        return(Response.AsJson(new JsonResponseModel {
                            Result = true
                        }));
                    }
                    return
                        (Response.AsJson(new JsonResponseModel
                    {
                        Result = false,
                        Message = "Updated Sonarr but could not approve it in PlexRequests :("
                    }));
                }
                return(Response.AsJson(ValidationHelper.SendSonarrError(result.ErrorMessages)));
            }

            var srSettings = SickRageSettings.GetSettings();

            if (srSettings.Enabled)
            {
                Log.Trace("Sending to SickRage");
                var result = sender.SendToSickRage(srSettings, request, qualityId);
                Log.Trace("SickRage Result: ");
                Log.Trace(result.DumpJson());
                if (result?.result == "success")
                {
                    Log.Info("Sent successfully, Approving request now.");
                    request.Approved = true;
                    var requestResult = Service.UpdateRequest(request);
                    Log.Trace("Approval result: {0}", requestResult);
                    return(Response.AsJson(requestResult
                        ? new JsonResponseModel {
                        Result = true
                    }
                        : new JsonResponseModel {
                        Result = false, Message = "Updated SickRage but could not approve it in PlexRequests :("
                    }));
                }
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = false,
                    Message = result?.message != null ? "<b>Message From SickRage: </b>" + result.message : "Could not add the series to SickRage"
                }));
            }


            request.Approved = true;
            var res = Service.UpdateRequest(request);

            return(Response.AsJson(res
                ? new JsonResponseModel {
                Result = true, Message = "This has been approved, but It has not been sent to Sonarr/SickRage because it has not been configured"
            }
                : new JsonResponseModel {
                Result = false, Message = "Updated SickRage but could not approve it in PlexRequests :("
            }));
        }