示例#1
0
        public bool SaveSettings(PlexSettingsDto model)
        {
            var entity = Repo.Get(model.Id);

            if (entity == null)
            {
                var newEntity = new PlexSettings();
                newEntity.InjectFrom(model);

                var insertResult = Repo.Insert(newEntity);
                return(insertResult != long.MinValue);
            }

            entity.Enabled         = model.Enabled;
            entity.IpAddress       = model.IpAddress;
            entity.Port            = model.Port;
            entity.Id              = model.Id;
            entity.ShowOnDashboard = model.ShowOnDashboard;
            entity.Username        = model.Username;
            entity.Password        = model.Password;

            var result = Repo.Update(entity);

            return(result);
        }
示例#2
0
        private async Task <Response> ChangeRequestAvailability(int requestId, bool available)
        {
            if (!Security.HasAnyPermissions(User, Permissions.Administrator, Permissions.ManageRequests))
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Sorry, you do not have the correct permissions to change a request."
                }));
            }

            Analytics.TrackEventAsync(Category.Requests, Action.Update, available ? "Make request available" : "Make request unavailable", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var originalRequest = await Service.GetAsync(requestId);

            if (originalRequest == null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Request does not exist to change the availability!"
                }));
            }

            originalRequest.Available = available;

            var result = await Service.UpdateRequestAsync(originalRequest);

            var plexService = await PlexSettings.GetSettingsAsync();

            await NotificationEngine.NotifyUsers(originalRequest, plexService.PlexAuthToken, available?NotificationType.RequestAvailable : NotificationType.RequestDeclined);

            return(Response.AsJson(result
                                       ? new { Result = true, Available = available, Message = string.Empty }
                                       : new { Result = false, Available = false, Message = "Could not update the availability, please try again or check the logs" }));
        }
        private void StartNewsLetter(NewletterSettings newletterSettings, bool testEmail = false)
        {
            var embySettings = EmbySettings.GetSettings();

            if (embySettings.Enable)
            {
                var letter = EmbyNewsletter.GetNewsletter(testEmail) ?? new Newsletter();
                if (letter.Send || testEmail)
                {
                    SendNewsletter(newletterSettings, letter.Html, testEmail, "New Content On Emby!");
                }
                else
                {
                    Log.Warn("There is no new content to send the newsletter");
                }
            }
            else
            {
                var plexSettings = PlexSettings.GetSettings();
                if (plexSettings.Enable)
                {
                    var letter = PlexNewsletter.GetNewsletter(testEmail) ?? new Newsletter();
                    if (letter.Send || testEmail)
                    {
                        SendNewsletter(newletterSettings, letter.Html, testEmail);
                    }
                }
            }
        }
示例#4
0
        private async Task <Response> ChangeRequestAvailability(int requestId, bool available)
        {
            this.RequiresClaims(UserClaims.Admin);
            Analytics.TrackEventAsync(Category.Requests, Action.Update, available ? "Make request available" : "Make request unavailable", Username, CookieHelper.GetAnalyticClientId(Cookies));
            var originalRequest = await Service.GetAsync(requestId);

            if (originalRequest == null)
            {
                return(Response.AsJson(new JsonResponseModel {
                    Result = false, Message = "Request does not exist to change the availability!"
                }));
            }

            originalRequest.Available = available;

            var result = await Service.UpdateRequestAsync(originalRequest);

            var plexService = await PlexSettings.GetSettingsAsync();

            await NotificationEngine.NotifyUsers(originalRequest, plexService.PlexAuthToken);

            return(Response.AsJson(result
                                       ? new { Result = true, Available = available, Message = string.Empty }
                                       : new { Result = false, Available = false, Message = "Could not update the availability, please try again or check the logs" }));
        }
示例#5
0
        private Response RequestAuthToken()
        {
            var user = this.Bind <PlexAuth>();

            if (string.IsNullOrEmpty(user.username) || string.IsNullOrEmpty(user.password))
            {
                return(Response.AsJson(new { Result = false, Message = "Please provide a valid username and password" }));
            }

            var model = PlexApi.SignIn(user.username, user.password);

            if (model?.user == null)
            {
                return(Response.AsJson(new { Result = false, Message = "Incorrect username or password!" }));
            }

            var oldSettings = PlexService.GetSettings();

            if (oldSettings != null)
            {
                oldSettings.PlexAuthToken = model.user.authentication_token;
                PlexService.SaveSettings(oldSettings);
            }
            else
            {
                var newModel = new PlexSettings
                {
                    PlexAuthToken = model.user.authentication_token
                };
                PlexService.SaveSettings(newModel);
            }

            return(Response.AsJson(new { Result = true, AuthToken = model.user.authentication_token }));
        }
示例#6
0
        private void StartNewsLetter(NewletterSettings newletterSettings, bool testEmail = false)
        {
            var embySettings = EmbySettings.GetSettings();

            if (embySettings.Enable)
            {
                var html = EmbyNewsletter.GetNewsletterHtml(testEmail);

                var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());
                Log.Debug(escapedHtml);
                SendNewsletter(newletterSettings, escapedHtml, testEmail, "New Content On Emby!");
            }
            else
            {
                var plexSettings = PlexSettings.GetSettings();
                if (plexSettings.Enable)
                {
                    var html = PlexNewsletter.GetNewsletterHtml(testEmail);

                    var escapedHtml = new string(html.Where(c => !char.IsControl(c)).ToArray());
                    Log.Debug(escapedHtml);
                    SendNewsletter(newletterSettings, html, testEmail);
                }
            }
        }
示例#7
0
        private async Task <ProcessedContent> StartTheCache(PlexSettings plexSettings, bool recentlyAddedSearch)
        {
            var processedContent = new ProcessedContent();

            foreach (var servers in plexSettings.Servers ?? new List <PlexServers>())
            {
                try
                {
                    Logger.LogInformation("Starting to cache the content on server {0}", servers.Name);

                    if (recentlyAddedSearch)
                    {
                        // If it's recently added search then we want the results to pass to the metadata job
                        // This way the metadata job is smaller in size to process, it only need to look at newly added shit
                        return(await ProcessServer(servers, true));
                    }
                    else
                    {
                        await ProcessServer(servers, false);
                    }
                }
                catch (Exception e)
                {
                    Logger.LogWarning(LoggingEvents.PlexContentCacher, e, "Exception thrown when attempting to cache the Plex Content in server {0}", servers.Name);
                }
            }

            return(processedContent);
        }
示例#8
0
        public void SetUp()
        {
            var mockRepo = new Mock <ISqlRepository <PlexSettings> >();

            ExpectedLink = new PlexSettings
            {
                Id              = 1,
                Enabled         = true,
                IpAddress       = "192",
                Password        = "******",
                Port            = 25,
                Username        = "******",
                ShowOnDashboard = true
            };
            ExpectedGetLinks = new List <PlexSettings>
            {
                ExpectedLink,
            };


            mockRepo.Setup(x => x.GetAll()).Returns(ExpectedGetLinks).Verifiable();

            mockRepo.Setup(x => x.Get(1)).Returns(ExpectedLink).Verifiable();

            mockRepo.Setup(x => x.Update(It.IsAny <PlexSettings>())).Returns(true).Verifiable();

            mockRepo.Setup(x => x.Insert(It.IsAny <PlexSettings>())).Returns(1).Verifiable();


            MockRepo = mockRepo;
            Service  = new PlexSettingsService(MockRepo.Object);
        }
        public static void ResetDatabase()
        {
            var defaultSettings = new PlexRequestSettings
            {
                RequireTvShowApproval = true,
                RequireMovieApproval  = true,
                SearchForMovies       = true,
                SearchForTvShows      = true,
                BaseUrl             = string.Empty,
                CollectAnalyticData = true,
            };

            UpdateSettings(defaultSettings);

            LandingPageSettings lp           = null;
            PlexSettings        plexSettings = null;
            SonarrSettings      sonarr       = null;
            CouchPotatoSettings cp           = null;
            SickRageSettings    sr           = null;

            UpdateSettings(lp);
            UpdateSettings(plexSettings);
            UpdateSettings(sonarr);
            UpdateSettings(cp);
            UpdateSettings(sr);
        }
示例#10
0
        private void GenerateTvHtml(List <Metadata> tv, PlexSettings plexSettings, StringBuilder sb)
        {
            var orderedTv = tv.OrderByDescending(x => x?.addedAt.UnixTimeStampToDateTime()).ToList();

            // TV
            sb.Append("<h1>New Episodes:</h1><br/><br/>");
            sb.Append(
                "<table border=\"0\" cellpadding=\"0\"  align=\"center\" cellspacing=\"0\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;\" width=\"100%\">");
            foreach (var t in orderedTv)
            {
                var plexGUID = string.Empty;
                try
                {
                    var parentMetaData = Api.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                         t.parentRatingKey.ToString());

                    plexGUID = parentMetaData.Directory.Guid;

                    var info = TvApi.ShowLookupByTheTvDbId(int.Parse(PlexHelper.GetProviderIdFromPlexGuid(plexGUID)));

                    var banner = info.image?.original;
                    if (!string.IsNullOrEmpty(banner))
                    {
                        banner = banner.Replace("http", "https"); // Always use the Https banners
                    }
                    AddImageInsideTable(sb, banner);

                    sb.Append("<tr>");
                    sb.Append(
                        "<td align=\"center\" style=\"font-family: sans-serif; font-size: 14px; vertical-align: top;\" valign=\"top\">");

                    var title = $"{t.grandparentTitle} - {t.title}  {t.originallyAvailableAt?.Substring(0, 4)}";

                    Href(sb, $"https://www.imdb.com/title/{info.externals.imdb}/");
                    Header(sb, 3, title);
                    EndTag(sb, "a");

                    AddParagraph(sb, $"Season: {t.parentIndex}, Episode: {t.index}");
                    if (info.genres.Any())
                    {
                        AddParagraph(sb, $"Genre: {string.Join(", ", info.genres.Select(x => x.ToString()).ToArray())}");
                    }

                    AddParagraph(sb, string.IsNullOrEmpty(t.summary) ? info.summary : t.summary);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    Log.Error(
                        "Exception when trying to process a TV Show, either in getting the metadata from Plex OR getting the information from TVMaze, Plex GUID = {0}",
                        plexGUID);
                }
                finally
                {
                    EndLoopHtml(sb);
                }
            }
            sb.Append("</table><br/><br/>");
        }
示例#11
0
 private async Task CheckInstallId(PlexSettings s)
 {
     if (s.InstallId == null || s.InstallId == Guid.Empty)
     {
         s.InstallId = Guid.NewGuid();
         await _plexSettings.SaveSettingsAsync(s);
     }
 }
示例#12
0
 private bool ValidateSettings(PlexSettings plex)
 {
     if (plex?.Ip == null || plex?.PlexAuthToken == null)
     {
         Log.Warn("A setting is null, Ensure Plex is configured correctly, and we have a Plex Auth token.");
         return(false);
     }
     return(true);
 }
 private bool ValidateSettings(PlexSettings plex, AuthenticationSettings auth)
 {
     if (plex?.Ip == null || auth?.PlexAuthToken == null)
     {
         Log.Warn("A setting is null, Ensure Plex is configured correctly, and we have a Plex Auth token.");
         return false;
     }
     return true;
 }
示例#14
0
        public async Task <bool> PlexSettings([FromBody] PlexSettings plex)
        {
            if (plex.InstallId == null || plex.InstallId == Guid.Empty)
            {
                plex.InstallId = Guid.NewGuid();
            }
            var result = await Save(plex);

            return(result);
        }
示例#15
0
        private void GenerateMovieHtml(List <Metadata> movies, PlexSettings plexSettings, StringBuilder sb)
        {
            var orderedMovies = movies.OrderByDescending(x => x?.addedAt.UnixTimeStampToDateTime()).ToList() ?? new List <Metadata>();

            sb.Append("<h1>New Movies:</h1><br/><br/>");
            sb.Append(
                "<table border=\"0\" cellpadding=\"0\"  align=\"center\" cellspacing=\"0\" style=\"border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;\" width=\"100%\">");
            foreach (var movie in orderedMovies)
            {
                var plexGUID = string.Empty;
                try
                {
                    var metaData = Api.GetMetadata(plexSettings.PlexAuthToken, plexSettings.FullUri,
                                                   movie.ratingKey.ToString());

                    plexGUID = metaData.Video.Guid;

                    var imdbId = PlexHelper.GetProviderIdFromPlexGuid(plexGUID);
                    var info   = _movieApi.GetMovieInformation(imdbId).Result;
                    if (info == null)
                    {
                        throw new Exception($"Movie with Imdb id {imdbId} returned null from the MovieApi");
                    }
                    AddImageInsideTable(sb, $"https://image.tmdb.org/t/p/w500{info.BackdropPath}");

                    sb.Append("<tr>");
                    sb.Append(
                        "<td align=\"center\" style=\"font-family: sans-serif; font-size: 14px; vertical-align: top;\" valign=\"top\">");

                    Href(sb, $"https://www.imdb.com/title/{info.ImdbId}/");
                    Header(sb, 3, $"{info.Title} {info.ReleaseDate?.ToString("yyyy") ?? string.Empty}");
                    EndTag(sb, "a");

                    if (info.Genres.Any())
                    {
                        AddParagraph(sb,
                                     $"Genre: {string.Join(", ", info.Genres.Select(x => x.Name.ToString()).ToArray())}");
                    }

                    AddParagraph(sb, info.Overview);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    Log.Error(
                        "Exception when trying to process a Movie, either in getting the metadata from Plex OR getting the information from TheMovieDB, Plex GUID = {0}",
                        plexGUID);
                }
                finally
                {
                    EndLoopHtml(sb);
                }
            }
            sb.Append("</table><br/><br/>");
        }
示例#16
0
        private void UpdatePlexSettings()
        {
#if !DEBUG
            var s = PlexSettings.GetSettings();
            if (!string.IsNullOrEmpty(s.Ip))
            {
                s.Enable = true;
                PlexSettings.SaveSettings(s);
            }
#endif
        }
示例#17
0
 public SyncLibrariesCommandHandler(
     IPlexApi plexApi,
     IPlexService plexService,
     IUnitOfWork unitOfWork,
     IOptionsSnapshot <PlexSettings> plexSettings)
 {
     _plexApi      = plexApi;
     _plexService  = plexService;
     _unitOfWork   = unitOfWork;
     _plexSettings = plexSettings.Value;
 }
示例#18
0
 public MovieProcessor(
     IPlexService plexService,
     IMediaItemProcessor mediaItemProcessor,
     PlexSettings plexSettings,
     ILoggerFactory loggerFactory)
 {
     _plexService        = plexService;
     _mediaItemProcessor = mediaItemProcessor;
     _plexSettings       = plexSettings;
     _logger             = loggerFactory.CreateLogger <MovieProcessor>();
 }
示例#19
0
        private async Task <Response> LoadUsers()
        {
            var localUsers = await UserMapper.GetUsersAsync();

            var plexDbUsers = await PlexUsersRepository.GetAllAsync();

            var model = new List <UserManagementUsersViewModel>();

            var userLogins = UserLoginsRepo.GetAll().ToList();

            foreach (var user in localUsers)
            {
                var userDb = userLogins.FirstOrDefault(x => x.UserId == user.UserGuid);
                model.Add(MapLocalUser(user, userDb?.LastLoggedIn ?? DateTime.MinValue));
            }

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);
                if (plexUsers != null && plexUsers.User != null)
                {
                    foreach (var u in plexUsers.User)
                    {
                        var dbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == u.Id);
                        var userDb = userLogins.FirstOrDefault(x => x.UserId == u.Id);

                        // We don't have the user in the database yet
                        if (dbUser == null)
                        {
                            model.Add(MapPlexUser(u, null, userDb?.LastLoggedIn ?? DateTime.MinValue));
                        }
                        else
                        {
                            // The Plex User is in the database
                            model.Add(MapPlexUser(u, dbUser, userDb?.LastLoggedIn ?? DateTime.MinValue));
                        }
                    }
                }

                // Also get the server admin
                var account = PlexApi.GetAccount(plexSettings.PlexAuthToken);
                if (account != null)
                {
                    var dbUser = plexDbUsers.FirstOrDefault(x => x.PlexUserId == account.Id);
                    var userDb = userLogins.FirstOrDefault(x => x.UserId == account.Id);
                    model.Add(MapPlexAdmin(account, dbUser, userDb?.LastLoggedIn ?? DateTime.MinValue));
                }
            }
            return(Response.AsJson(model));
        }
示例#20
0
        private async Task StartPlex(PlexSettings settings)
        {
            // Ensure we check that we have not linked this item to a request
            var allMovies = await _plexRepo.GetAll().Where(x =>
                                                           x.Type == MediaType.Movie && x.RequestId == null && ((x.TheMovieDbId == null || x.TheMovieDbId == string.Empty) || (x.ImdbId == null || x.ImdbId == string.Empty))).ToListAsync();

            await StartPlexMovies(allMovies, settings);

            // Now Tv
            var allTv = await _plexRepo.GetAll().Where(x =>
                                                       x.Type == MediaType.Series && x.RequestId == null && (x.TheMovieDbId == null || x.ImdbId == null || x.TvDbId == null)).ToListAsync();

            await StartPlexTv(allTv);
        }
示例#21
0
 private static bool ValidateSettings(PlexSettings plex)
 {
     if (plex.Enable)
     {
         foreach (var server in plex.Servers ?? new List <PlexServers>())
         {
             if (string.IsNullOrEmpty(server?.Ip) || string.IsNullOrEmpty(server?.PlexAuthToken))
             {
                 return(false);
             }
         }
     }
     return(plex.Enable);
 }
示例#22
0
 public TvProcessor(
     IPlexApi plexApi,
     IPlexService plexService,
     IMediaItemProcessor mediaItemProcessor,
     PlexSettings plexSettings,
     IAgentGuidParser agentGuidParser,
     ILoggerFactory loggerFactory)
 {
     _plexApi            = plexApi;
     _plexService        = plexService;
     _mediaItemProcessor = mediaItemProcessor;
     _plexSettings       = plexSettings;
     _agentGuidParser    = agentGuidParser;
     _logger             = loggerFactory.CreateLogger <TvProcessor>();
 }
示例#23
0
 private async Task StartTheCache(PlexSettings plexSettings, bool recentlyAddedSearch)
 {
     foreach (var servers in plexSettings.Servers ?? new List <PlexServers>())
     {
         try
         {
             Logger.LogInformation("Starting to cache the content on server {0}", servers.Name);
             await ProcessServer(servers, recentlyAddedSearch);
         }
         catch (Exception e)
         {
             Logger.LogWarning(LoggingEvents.PlexContentCacher, e, "Exception thrown when attempting to cache the Plex Content in server {0}", servers.Name);
         }
     }
 }
示例#24
0
 public PlexSync(IPlexApi plexApi,
                 IPlexService plexService,
                 ICompletionService completionService,
                 IProcessorProvider processorProvider,
                 IUnitOfWork unitOfWork,
                 IOptionsSnapshot <PlexSettings> plexSettings,
                 ILogger <PlexSync> logger)
 {
     _plexApi           = plexApi;
     _plexService       = plexService;
     _completionService = completionService;
     _processorProvider = processorProvider;
     _unitOfWork        = unitOfWork;
     _plexSettings      = plexSettings.Value;
     _logger            = logger;
 }
示例#25
0
        public async Task <bool> PlexSettings([FromBody] PlexSettings plex)
        {
            if (plex?.InstallId == Guid.Empty || plex.InstallId == Guid.Empty)
            {
                plex.InstallId = Guid.NewGuid();
            }
            var result = await Save(plex);

            if (result)
            {
                // Kick off the plex sync
                await OmbiQuartz.TriggerJob(nameof(IPlexContentSync), "Plex");
            }

            return(result);
        }
示例#26
0
        private async Task <Response> LoadUsers()
        {
            var plexSettings = await PlexSettings.GetSettingsAsync();

            var embySettings = await EmbySettings.GetSettingsAsync();

            if (plexSettings.Enable)
            {
                return(await LoadPlexUsers());
            }
            if (embySettings.Enable)
            {
                return(await LoadEmbyUsers());
            }

            return(null);
        }
        private Response GetPlexSettings()
        {
            var model = new ApiModel <PlexSettings>();

            try
            {
                var settings = PlexSettings.GetSettings();
                model.Data = settings;
                return(ReturnReponse(model));
            }
            catch (Exception e)
            {
                model.ErrorMessage = e.Message;
                model.Error        = true;
                return(ReturnReponse(model));
            }
        }
示例#28
0
        private async Task <Response> CheckStatus()
        {
            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (string.IsNullOrEmpty(plexSettings.PlexAuthToken) || string.IsNullOrEmpty(plexSettings.Ip))
            {
                return(Response.AsJson(false));
            }
            try
            {
                var status = PlexApi.GetStatus(plexSettings.PlexAuthToken, plexSettings.FullUri);
                return(Response.AsJson(status != null));
            }
            catch (Exception)
            {
                return(Response.AsJson(false));
            }
        }
示例#29
0
        private async Task <Response> PlexDetails(string id)
        {
            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (!string.IsNullOrEmpty(plexSettings.PlexAuthToken))
            {
                //Get Plex Users
                var plexUsers = PlexApi.GetUsers(plexSettings.PlexAuthToken);

                var selectedUser = plexUsers.User?.FirstOrDefault(x => x.Id.ToString() == id);
                if (selectedUser != null)
                {
                    return(Response.AsJson(selectedUser));
                }
            }

            return(Nancy.Response.NoBody);
        }
 public AddAdminCommandHandler(
     IUserService userService,
     IPlexService plexService,
     ITokenService tokenService,
     IUnitOfWork unitOfWork,
     IPlexApi plexApi,
     IOptionsSnapshot <PlexSettings> plexSettings,
     ILogger <AddAdminCommandHandler> logger
     )
 {
     _userService  = userService;
     _plexService  = plexService;
     _tokenService = tokenService;
     _unitOfWork   = unitOfWork;
     _plexApi      = plexApi;
     _plexSettings = plexSettings.Value;
     _logger       = logger;
 }