예제 #1
0
        private Response SaveAdmin()
        {
            var model = this.Bind <PlexRequestSettings>();
            var valid = this.Validate(model);

            if (!valid.IsValid)
            {
                return(Response.AsJson(valid.SendJsonError()));
            }

            if (!string.IsNullOrWhiteSpace(model.BaseUrl))
            {
                if (model.BaseUrl.StartsWith("/") || model.BaseUrl.StartsWith("\\"))
                {
                    model.BaseUrl = model.BaseUrl.Remove(0, 1);
                }
            }
            var result = PrService.SaveSettings(model);

            if (result)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = true
                }));
            }

            return(Response.AsJson(new JsonResponseModel {
                Result = false, Message = "We could not save to the database, please try again"
            }));
        }
예제 #2
0
        private Negotiator RequestLoad()
        {
            var settings = PrService.GetSettings();

            Log.Trace("Loading Index");
            return(View["Search/Index", settings]);
        }
예제 #3
0
        private async Task <Response> SaveAdmin()
        {
            var model = this.Bind <PlexRequestSettings>();
            var valid = this.Validate(model);

            if (!valid.IsValid)
            {
                return(Response.AsJson(valid.SendJsonError()));
            }
            model.Wizard = true;

            if (!string.IsNullOrWhiteSpace(model.BaseUrl))
            {
                if (model.BaseUrl.StartsWith("/", StringComparison.CurrentCultureIgnoreCase) || model.BaseUrl.StartsWith("\\", StringComparison.CurrentCultureIgnoreCase))
                {
                    model.BaseUrl = model.BaseUrl.Remove(0, 1);
                }
            }
            if (!model.CollectAnalyticData)
            {
                Analytics.TrackEventAsync(Category.Admin, Action.Save, "CollectAnalyticData turned off", Username, CookieHelper.GetAnalyticClientId(Cookies));
            }
            var result = PrService.SaveSettings(model);

            Analytics.TrackEventAsync(Category.Admin, Action.Save, "PlexRequestSettings", Username, CookieHelper.GetAnalyticClientId(Cookies));
            return(Response.AsJson(result
                ? new JsonResponseModel {
                Result = true
            }
                : new JsonResponseModel {
                Result = false, Message = "We could not save to the database, please try again"
            }));
        }
예제 #4
0
        private async Task <Negotiator> RequestLoad()
        {
            var settings = await PrService.GetSettingsAsync();

            Log.Trace("Loading Index");
            return(View["Search/Index", settings]);
        }
        private Response SaveAdmin()
        {
            var model = this.Bind <PlexRequestSettings>();

            PrService.SaveSettings(model);

            return(Context.GetRedirect(!string.IsNullOrEmpty(BaseUrl) ? $"~/{BaseUrl}/admin" : "~/admin"));
        }
예제 #6
0
        private Negotiator Admin()
        {
            var settings = PrService.GetSettings();

            Log.Trace("Getting Settings:");
            Log.Trace(settings.DumpJson());

            return(View["Settings", settings]);
        }
예제 #7
0
        private Response CreateApiKey()
        {
            this.RequiresClaims(UserClaims.Admin);
            var apiKey   = Guid.NewGuid().ToString("N");
            var settings = PrService.GetSettings();

            settings.ApiKey = apiKey;
            PrService.SaveSettings(settings);

            return(Response.AsJson(apiKey));
        }
예제 #8
0
파일: AdminModule.cs 프로젝트: ZinnerC/Ombi
        private Response CreateApiKey()
        {
            Analytics.TrackEventAsync(Category.Admin, Action.Create, "Created API Key", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var apiKey   = Guid.NewGuid().ToString("N");
            var settings = PrService.GetSettings();

            settings.ApiKey = apiKey;
            PrService.SaveSettings(settings);

            return(Response.AsJson(apiKey));
        }
예제 #9
0
        private Response RequestAlbum(string releaseId)
        {
            var settings        = PrService.GetSettings();
            var existingRequest = RequestService.CheckRequest(releaseId);

            Log.Debug("Checking for an existing request");

            if (existingRequest != null)
            {
                Log.Debug("We do have an existing album request");
                if (!existingRequest.UserHasRequested(Username))
                {
                    Log.Debug("Not in the requested list so adding them and updating the request. User: {0}", Username);
                    existingRequest.RequestedUsers.Add(Username);
                    RequestService.UpdateRequest(existingRequest);
                }
                return(Response.AsJson(new JsonResponseModel {
                    Result = true, Message = settings.UsersCanViewOnlyOwnRequests ? $"{existingRequest.Title} was successfully added!" : $"{existingRequest.Title} has already been requested!"
                }));
            }


            Log.Debug("This is a new request");

            var      albumInfo = MusicBrainzApi.GetAlbum(releaseId);
            DateTime release;

            DateTimeHelper.CustomParse(albumInfo.ReleaseEvents?.FirstOrDefault()?.date, out release);

            var artist = albumInfo.ArtistCredits?.FirstOrDefault()?.artist;

            if (artist == null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "We could not find the artist on MusicBrainz. Please try again later or contact your admin"
                }));
            }

            var albums        = Checker.GetPlexAlbums();
            var alreadyInPlex = Checker.IsAlbumAvailable(albums.ToArray(), albumInfo.title, release.ToString("yyyy"), artist.name);

            if (alreadyInPlex)
            {
                return(Response.AsJson(new JsonResponseModel
                {
                    Result = false,
                    Message = $"{albumInfo.title} is already in Plex!"
                }));
            }

            var img = GetMusicBrainzCoverArt(albumInfo.id);

            Log.Trace("Album Details:");
            Log.Trace(albumInfo.DumpJson());
            Log.Trace("CoverArt Details:");
            Log.Trace(img.DumpJson());


            var model = new RequestedModel
            {
                Title          = albumInfo.title,
                MusicBrainzId  = albumInfo.id,
                Overview       = albumInfo.disambiguation,
                PosterPath     = img,
                Type           = RequestType.Album,
                ProviderId     = 0,
                RequestedUsers = new List <string> {
                    Username
                },
                Status        = albumInfo.status,
                Issues        = IssueState.None,
                RequestedDate = DateTime.UtcNow,
                ReleaseDate   = release,
                ArtistName    = artist.name,
                ArtistId      = artist.id
            };

            if (ShouldAutoApprove(RequestType.Album, settings))
            {
                Log.Debug("We don't require approval OR the user is in the whitelist");
                var hpSettings = HeadphonesService.GetSettings();

                Log.Trace("Headphone Settings:");
                Log.Trace(hpSettings.DumpJson());

                if (!hpSettings.Enabled)
                {
                    RequestService.AddRequest(model);
                    return
                        (Response.AsJson(new JsonResponseModel
                    {
                        Result = true,
                        Message = $"{model.Title} was successfully added!"
                    }));
                }

                var sender = new HeadphonesSender(HeadphonesApi, hpSettings, RequestService);
                sender.AddAlbum(model).Wait();
                model.Approved = true;
                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 = $"{model.Title} was successfully added!"
                }));
            }

            if (ShouldSendNotification())
            {
                var notify2 = new NotificationModel
                {
                    Title            = model.Title,
                    User             = Username,
                    DateTime         = DateTime.Now,
                    NotificationType = NotificationType.NewRequest
                };
                NotificationService.Publish(notify2);
            }
            var result = RequestService.AddRequest(model);

            return(Response.AsJson(new JsonResponseModel
            {
                Result = true,
                Message = $"{model.Title} was successfully added!"
            }));
        }
예제 #10
0
        /// <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!"
            }));
        }
예제 #11
0
        private Response RequestMovie(int movieId)
        {
            var movieApi      = new TheMovieDbApi();
            var movieInfo     = movieApi.GetMovieInformation(movieId).Result;
            var fullMovieName = $"{movieInfo.Title}{(movieInfo.ReleaseDate.HasValue ? $" ({movieInfo.ReleaseDate.Value.Year})" : string.Empty)}";

            Log.Trace("Getting movie info from TheMovieDb");
            Log.Trace(movieInfo.DumpJson);
            //#if !DEBUG

            var settings = PrService.GetSettings();

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

            if (existingRequest != null)
            {
                // check if the current user is already marked as a requester for this movie, 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 ? $"{fullMovieName} was successfully added!" : $"{fullMovieName} has already been requested!"
                }));
            }

            Log.Debug("movie with id {0} doesnt exists", movieId);

            try
            {
                var movies = Checker.GetPlexMovies();
                if (Checker.IsMovieAvailable(movies.ToArray(), movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString()))
                {
                    return(Response.AsJson(new JsonResponseModel {
                        Result = false, Message = $"{fullMovieName} is already in Plex!"
                    }));
                }
            }
            catch (ApplicationSettingsException)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = $"We could not check if {fullMovieName} is in Plex, are you sure it's correctly setup?"
                }));
            }
            //#endif

            var model = new RequestedModel
            {
                ProviderId     = movieInfo.Id,
                Type           = RequestType.Movie,
                Overview       = movieInfo.Overview,
                ImdbId         = movieInfo.ImdbId,
                PosterPath     = "http://image.tmdb.org/t/p/w150/" + movieInfo.PosterPath,
                Title          = movieInfo.Title,
                ReleaseDate    = movieInfo.ReleaseDate ?? DateTime.MinValue,
                Status         = movieInfo.Status,
                RequestedDate  = DateTime.UtcNow,
                Approved       = false,
                RequestedUsers = new List <string> {
                    Username
                },
                Issues = IssueState.None,
            };

            Log.Trace(settings.DumpJson());
            if (ShouldAutoApprove(RequestType.Movie, settings))
            {
                var cpSettings = CpService.GetSettings();

                Log.Trace("Settings: ");
                Log.Trace(cpSettings.DumpJson);
                if (cpSettings.Enabled)
                {
                    Log.Info("Adding movie to CP (No approval required)");
                    var result = CouchPotatoApi.AddMovie(model.ImdbId, cpSettings.ApiKey, model.Title,
                                                         cpSettings.FullUri, cpSettings.ProfileId);
                    Log.Debug("Adding movie to CP result {0}", result);
                    if (result)
                    {
                        model.Approved = true;
                        Log.Info("Adding movie to database (No approval required)");
                        RequestService.AddRequest(model);


                        if (ShouldSendNotification())
                        {
                            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 = $"{fullMovieName} was successfully added!"
                        }));
                    }
                    return
                        (Response.AsJson(new JsonResponseModel
                    {
                        Result = false,
                        Message =
                            "Something went wrong adding the movie to CouchPotato! Please check your settings."
                    }));
                }
                else
                {
                    model.Approved = true;
                    Log.Info("Adding movie to database (No approval required)");
                    RequestService.AddRequest(model);

                    if (ShouldSendNotification())
                    {
                        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 = $"{fullMovieName} was successfully added!"
                    }));
                }
            }

            try
            {
                Log.Info("Adding movie to database");
                var id = 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 = $"{fullMovieName} was successfully added!"
                }));
            }
            catch (Exception e)
            {
                Log.Fatal(e);

                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Something went wrong adding the movie to CouchPotato! Please check your settings."
                }));
            }
        }
예제 #12
0
        private Response ProcessMovies(MovieSearchType searchType, string searchTerm)
        {
            var taskList = new List <Task>();

            var apiMovies = new List <MovieResult>();

            taskList.Add(Task.Factory.StartNew(() =>
            {
                switch (searchType)
                {
                case MovieSearchType.Search:
                    return(MovieApi.SearchMovie(searchTerm).Result.Select(x => new MovieResult()
                    {
                        Adult = x.Adult,
                        BackdropPath = x.BackdropPath,
                        GenreIds = x.GenreIds,
                        Id = x.Id,
                        OriginalLanguage = x.OriginalLanguage,
                        OriginalTitle = x.OriginalTitle,
                        Overview = x.Overview,
                        Popularity = x.Popularity,
                        PosterPath = x.PosterPath,
                        ReleaseDate = x.ReleaseDate,
                        Title = x.Title,
                        Video = x.Video,
                        VoteAverage = x.VoteAverage,
                        VoteCount = x.VoteCount
                    }).ToList());

                case MovieSearchType.CurrentlyPlaying:
                    return(MovieApi.GetCurrentPlayingMovies().Result.ToList());

                case MovieSearchType.Upcoming:
                    return(MovieApi.GetUpcomingMovies().Result.ToList());

                default:
                    return(new List <MovieResult>());
                }
            }).ContinueWith((t) =>
            {
                apiMovies = t.Result;
            }));

            Dictionary <int, RequestedModel> dbMovies = new Dictionary <int, RequestedModel>();

            taskList.Add(Task.Factory.StartNew(() =>
            {
                return(RequestService.GetAll().Where(x => x.Type == RequestType.Movie));
            }).ContinueWith((t) =>
            {
                var distinctResults = t.Result.DistinctBy(x => x.ProviderId);
                dbMovies            = distinctResults.ToDictionary(x => x.ProviderId);
            }));

            Task.WaitAll(taskList.ToArray());

            var cpCached   = CpCacher.QueuedIds();
            var plexMovies = Checker.GetPlexMovies();
            var settings   = PrService.GetSettings();
            var viewMovies = new List <SearchMovieViewModel>();

            foreach (MovieResult movie in apiMovies)
            {
                var viewMovie = new SearchMovieViewModel
                {
                    Adult            = movie.Adult,
                    BackdropPath     = movie.BackdropPath,
                    GenreIds         = movie.GenreIds,
                    Id               = movie.Id,
                    OriginalLanguage = movie.OriginalLanguage,
                    OriginalTitle    = movie.OriginalTitle,
                    Overview         = movie.Overview,
                    Popularity       = movie.Popularity,
                    PosterPath       = movie.PosterPath,
                    ReleaseDate      = movie.ReleaseDate,
                    Title            = movie.Title,
                    Video            = movie.Video,
                    VoteAverage      = movie.VoteAverage,
                    VoteCount        = movie.VoteCount
                };
                var canSee = CanUserSeeThisRequest(viewMovie.Id, settings.UsersCanViewOnlyOwnRequests, dbMovies);
                if (Checker.IsMovieAvailable(plexMovies.ToArray(), movie.Title, movie.ReleaseDate?.Year.ToString()))
                {
                    viewMovie.Available = true;
                }
                else if (dbMovies.ContainsKey(movie.Id) && canSee) // compare to the requests db
                {
                    var dbm = dbMovies[movie.Id];

                    viewMovie.Requested = true;
                    viewMovie.Approved  = dbm.Approved;
                    viewMovie.Available = dbm.Available;
                }
                else if (cpCached.Contains(movie.Id) && canSee) // compare to the couchpotato db
                {
                    viewMovie.Requested = true;
                }

                viewMovies.Add(viewMovie);
            }

            return(Response.AsJson(viewMovies));
        }
예제 #13
0
        private Negotiator Admin()
        {
            var settings = PrService.GetSettings();

            return(View["Settings", settings]);
        }