From e49b160500476b7bee38c6b4e2eb9017734e3598 Mon Sep 17 00:00:00 2001 From: tidusjar Date: Fri, 20 May 2016 17:20:17 +0100 Subject: [PATCH] Fully finished #27 just need to test it! --- .../Jobs/PlexAvailabilityChecker.cs | 12 +- PlexRequests.Store/Models/UsersToNotify.cs | 36 +++ PlexRequests.Store/PlexRequests.Store.csproj | 1 + PlexRequests.Store/RequestedModel.cs | 16 -- PlexRequests.Store/SqlTables.sql | 9 +- PlexRequests.UI/Bootstrapper.cs | 1 + PlexRequests.UI/Content/search.js | 52 +++- .../RequestedModelDataProvider.cs | 1 - PlexRequests.UI/Modules/AdminModule.cs | 6 +- PlexRequests.UI/Modules/SearchModule.cs | 257 +++++++++++------- PlexRequests.UI/Views/Search/Index.cshtml | 2 +- 11 files changed, 254 insertions(+), 139 deletions(-) create mode 100644 PlexRequests.Store/Models/UsersToNotify.cs diff --git a/PlexRequests.Services/Jobs/PlexAvailabilityChecker.cs b/PlexRequests.Services/Jobs/PlexAvailabilityChecker.cs index 0e29b93d5..d6bd244ca 100644 --- a/PlexRequests.Services/Jobs/PlexAvailabilityChecker.cs +++ b/PlexRequests.Services/Jobs/PlexAvailabilityChecker.cs @@ -39,6 +39,8 @@ using PlexRequests.Services.Interfaces; using PlexRequests.Services.Models; using PlexRequests.Services.Notification; using PlexRequests.Store; +using PlexRequests.Store.Models; +using PlexRequests.Store.Repository; using Quartz; @@ -47,7 +49,7 @@ namespace PlexRequests.Services.Jobs public class PlexAvailabilityChecker : IJob, IAvailabilityChecker { public PlexAvailabilityChecker(ISettingsService plexSettings, ISettingsService auth, IRequestService request, IPlexApi plex, ICacheProvider cache, - INotificationService notify, IJobRecord rec) + INotificationService notify, IJobRecord rec, IRepository users) { Plex = plexSettings; Auth = auth; @@ -56,6 +58,7 @@ namespace PlexRequests.Services.Jobs Cache = cache; Notification = notify; Job = rec; + UserNotifyRepo = users; } private ISettingsService Plex { get; } @@ -66,7 +69,7 @@ namespace PlexRequests.Services.Jobs private ICacheProvider Cache { get; } private INotificationService Notification { get; } private IJobRecord Job { get; } - + private IRepository UserNotifyRepo { get; } public void CheckAndUpdateAll() { Log.Trace("Getting the settings"); @@ -328,10 +331,11 @@ namespace PlexRequests.Services.Jobs return; } + var users = UserNotifyRepo.GetAll().ToList(); foreach (var model in modelChanged) { - var usersToNotify = model.UsersToNotify; // Users that selected the notification button when requesting a movie/tv show - foreach (var user in usersToNotify) + var selectedUsers = users.Select(x => x.Username).Intersect(model.RequestedUsers); + foreach (var user in selectedUsers) { var email = plexUser.User.FirstOrDefault(x => x.Username == user); if (email == null) diff --git a/PlexRequests.Store/Models/UsersToNotify.cs b/PlexRequests.Store/Models/UsersToNotify.cs new file mode 100644 index 000000000..521288894 --- /dev/null +++ b/PlexRequests.Store/Models/UsersToNotify.cs @@ -0,0 +1,36 @@ +#region Copyright +// /************************************************************************ +// Copyright (c) 2016 Jamie Rees +// File: UsersToNotify.cs +// Created By: Jamie Rees +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// ************************************************************************/ +#endregion +using Dapper.Contrib.Extensions; + +namespace PlexRequests.Store.Models +{ + [Table("UsersToNotify")] + public class UsersToNotify : Entity + { + public string Username { get; set; } + } +} \ No newline at end of file diff --git a/PlexRequests.Store/PlexRequests.Store.csproj b/PlexRequests.Store/PlexRequests.Store.csproj index 8d52b35d7..19578aee5 100644 --- a/PlexRequests.Store/PlexRequests.Store.csproj +++ b/PlexRequests.Store/PlexRequests.Store.csproj @@ -60,6 +60,7 @@ + diff --git a/PlexRequests.Store/RequestedModel.cs b/PlexRequests.Store/RequestedModel.cs index 0f4a28f23..e8fc41e08 100644 --- a/PlexRequests.Store/RequestedModel.cs +++ b/PlexRequests.Store/RequestedModel.cs @@ -40,7 +40,6 @@ namespace PlexRequests.Store public List RequestedUsers { get; set; } public string ArtistName { get; set; } public string ArtistId { get; set; } - public List UsersToNotify { get; private set; } [JsonIgnore] public List AllUsers @@ -68,21 +67,6 @@ namespace PlexRequests.Store { return AllUsers.Any(x => x.Equals(username, StringComparison.OrdinalIgnoreCase)); } - - public void AddUserToNotification(string username) - { - if (UsersToNotify == null) - { - UsersToNotify = new List(); - } - if (UsersToNotify.FirstOrDefault(x => x == username) != null) - { - // User already exists in the notification list - return; - } - - UsersToNotify.Add(username); - } } public enum RequestType diff --git a/PlexRequests.Store/SqlTables.sql b/PlexRequests.Store/SqlTables.sql index 31db785b8..74d5f2c13 100644 --- a/PlexRequests.Store/SqlTables.sql +++ b/PlexRequests.Store/SqlTables.sql @@ -65,4 +65,11 @@ CREATE TABLE IF NOT EXISTS ScheduledJobs Name varchar(100) NOT NULL, LastRun varchar(100) NOT NULL ); -CREATE UNIQUE INDEX IF NOT EXISTS ScheduledJobs_Id ON ScheduledJobs (Id); \ No newline at end of file +CREATE UNIQUE INDEX IF NOT EXISTS ScheduledJobs_Id ON ScheduledJobs (Id); + +CREATE TABLE IF NOT EXISTS UsersToNotify +( + Id INTEGER PRIMARY KEY AUTOINCREMENT, + Username varchar(100) NOT NULL +); +CREATE UNIQUE INDEX IF NOT EXISTS UsersToNotify_Id ON UsersToNotify (Id); \ No newline at end of file diff --git a/PlexRequests.UI/Bootstrapper.cs b/PlexRequests.UI/Bootstrapper.cs index 4966373c3..5f95ea9ba 100644 --- a/PlexRequests.UI/Bootstrapper.cs +++ b/PlexRequests.UI/Bootstrapper.cs @@ -86,6 +86,7 @@ namespace PlexRequests.UI // Repo's container.Register, GenericRepository>(); + container.Register, GenericRepository>(); container.Register, GenericRepository>(); container.Register(); container.Register(); diff --git a/PlexRequests.UI/Content/search.js b/PlexRequests.UI/Content/search.js index ad1dcf298..6c502eef0 100644 --- a/PlexRequests.UI/Content/search.js +++ b/PlexRequests.UI/Content/search.js @@ -29,6 +29,21 @@ $(function () { }); focusSearch($('li.active a', '#nav-tabs').first().attr('href')); + // Get the user notification setting + var url = createBaseUrl(base, '/search/notifyuser/'); + $.ajax({ + type: "get", + url: url, + dataType: "json", + success: function (response) { + $('#notifyUser').prop("checked", response); + }, + error: function (e) { + console.log(e); + generateNotify("Something went wrong!", "danger"); + } + }); + // Type in movie search $("#movieSearchContent").on("input", function () { if (searchTimer) { @@ -80,10 +95,6 @@ $(function () { data = data + "&seasons=first"; } - var $notify = $('#notifyUser').is(':checked'); - - data = data + "¬ify=" + $notify; - var type = $form.prop('method'); var url = $form.prop('action'); @@ -117,10 +128,6 @@ $(function () { var url = $form.prop('action'); var data = $form.serialize(); - var $notify = $('#notifyUser').is(':checked'); - - data = data + "¬ify=" + $notify; - sendRequestAjax(data, type, url, buttonId); }); @@ -142,13 +149,36 @@ $(function () { var type = $form.prop('method'); var url = $form.prop('action'); var data = $form.serialize(); - var $notify = $('#notifyUser').is(':checked'); - - data = data + "¬ify=" + $notify; sendRequestAjax(data, type, url, buttonId); }); + // Enable/Disable user notifications + $('#saveNotificationSettings') + .click(function (e) { + e.preventDefault(); + var url = createBaseUrl(base, '/search/notifyuser/'); + var checked = $('#notifyUser').prop('checked'); + $.ajax({ + type: "post", + url: url, + data: {notify: checked}, + dataType: "json", + success: function (response) { + console.log(response); + if (response.result === true) { + generateNotify(response.message || "Success!", "success"); + } else { + generateNotify(response.message, "warning"); + } + }, + error: function (e) { + console.log(e); + generateNotify("Something went wrong!", "danger"); + } + }); + }); + function focusSearch($content) { if ($content.length > 0) { $('input[type=text].form-control', $content).first().focus(); diff --git a/PlexRequests.UI/ModelDataProviders/RequestedModelDataProvider.cs b/PlexRequests.UI/ModelDataProviders/RequestedModelDataProvider.cs index fe75957d8..efaac31ed 100644 --- a/PlexRequests.UI/ModelDataProviders/RequestedModelDataProvider.cs +++ b/PlexRequests.UI/ModelDataProviders/RequestedModelDataProvider.cs @@ -64,7 +64,6 @@ namespace PlexRequests.UI.ModelDataProviders with.Property(x => x.RequestedDate).Description("The date if the request, if this is not set, the request date will be set at the time of the Api call"); with.Property(x => x.RequestedUsers).Description("A collection of the requested users").Required(true); with.Property(x => x.Type).Description("The type of request: Movie = 0, TvShow = 1, Album = 2").Required(true); - with.Property(x => x.UsersToNotify).Description("A list of Plex users to notify"); }); } } diff --git a/PlexRequests.UI/Modules/AdminModule.cs b/PlexRequests.UI/Modules/AdminModule.cs index 2e3c4233d..ee7bcb0b8 100644 --- a/PlexRequests.UI/Modules/AdminModule.cs +++ b/PlexRequests.UI/Modules/AdminModule.cs @@ -502,7 +502,11 @@ namespace PlexRequests.UI.Modules private Response AutoUpdate() { var url = Request.Form["url"]; - var startInfo = new ProcessStartInfo("PlexRequests.Updater.exe") { Arguments = url}; + + var startInfo = Type.GetType("Mono.Runtime") != null + ? new ProcessStartInfo("mono PlexRequests.Updater.exe") { Arguments = url } + : new ProcessStartInfo("PlexRequests.Updater.exe") { Arguments = url }; + Process.Start(startInfo); Environment.Exit(0); diff --git a/PlexRequests.UI/Modules/SearchModule.cs b/PlexRequests.UI/Modules/SearchModule.cs index 62601aee8..31f875453 100644 --- a/PlexRequests.UI/Modules/SearchModule.cs +++ b/PlexRequests.UI/Modules/SearchModule.cs @@ -31,7 +31,6 @@ using System.Linq; using Nancy; using Nancy.Responses.Negotiation; -using Nancy.Security; using NLog; @@ -42,7 +41,6 @@ using PlexRequests.Core; using PlexRequests.Core.SettingModels; using PlexRequests.Helpers; using PlexRequests.Helpers.Exceptions; -using PlexRequests.Services; using PlexRequests.Services.Interfaces; using PlexRequests.Services.Notification; using PlexRequests.Store; @@ -50,6 +48,9 @@ using PlexRequests.UI.Helpers; using PlexRequests.UI.Models; using System.Threading.Tasks; using PlexRequests.Api.Models.Tv; +using PlexRequests.Store.Models; +using PlexRequests.Store.Repository; + using TMDbLib.Objects.General; namespace PlexRequests.UI.Modules @@ -60,9 +61,9 @@ namespace PlexRequests.UI.Modules ISettingsService prSettings, IAvailabilityChecker checker, IRequestService request, ISonarrApi sonarrApi, ISettingsService sonarrSettings, ISettingsService sickRageService, ICouchPotatoApi cpApi, ISickRageApi srApi, - INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService hpService, - ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi, - ISettingsService plexService, ISettingsService auth) : base("search", prSettings) + INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService hpService, + ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi, + ISettingsService plexService, ISettingsService auth, IRepository u) : base("search", prSettings) { Auth = auth; PlexService = plexService; @@ -85,6 +86,7 @@ namespace PlexRequests.UI.Modules MusicBrainzApi = mbApi; HeadphonesApi = hpApi; HeadphonesService = hpService; + UsersToNotifyRepo = u; Get["/"] = parameters => RequestLoad(); @@ -97,9 +99,12 @@ namespace PlexRequests.UI.Modules Get["movie/upcoming"] = parameters => UpcomingMovies(); Get["movie/playing"] = parameters => CurrentlyPlayingMovies(); - Post["request/movie"] = parameters => RequestMovie((int)Request.Form.movieId, (bool)Request.Form.notify); - Post["request/tv"] = parameters => RequestTvShow((int)Request.Form.tvId, (string)Request.Form.seasons, (bool)Request.Form.notify); - Post["request/album"] = parameters => RequestAlbum((string)Request.Form.albumId, (bool)Request.Form.notify); + Post["request/movie"] = parameters => RequestMovie((int)Request.Form.movieId); + Post["request/tv"] = parameters => RequestTvShow((int)Request.Form.tvId, (string)Request.Form.seasons); + Post["request/album"] = parameters => RequestAlbum((string)Request.Form.albumId); + + Post["/notifyuser"] = x => NotifyUser((bool)Request.Form.notify); + Get["/notifyuser"] = x => GetUserNotificationSettings(); } private IPlexApi PlexApi { get; } private TheMovieDbApi MovieApi { get; } @@ -122,6 +127,7 @@ namespace PlexRequests.UI.Modules private ISickRageCacher SickRageCacher { get; } private IMusicBrainzApi MusicBrainzApi { get; } private IHeadphonesApi HeadphonesApi { get; } + private IRepository UsersToNotifyRepo { get; } private static Logger Log = LogManager.GetCurrentClassLogger(); private Negotiator RequestLoad() @@ -157,7 +163,7 @@ namespace PlexRequests.UI.Modules var apiMovies = new List(); taskList.Add(Task.Factory.StartNew(() => { - switch(searchType) + switch (searchType) { case MovieSearchType.Search: return MovieApi.SearchMovie(searchTerm).Result.Select(x => new MovieResult() @@ -263,7 +269,7 @@ namespace PlexRequests.UI.Modules { Log.Trace("Searching for TV Show {0}", searchTerm); - var taskList = new List(); + var taskList = new List(); var apiTv = new List(); taskList.Add(Task.Factory.StartNew(() => @@ -412,7 +418,7 @@ namespace PlexRequests.UI.Modules return Response.AsJson(viewAlbum); } - private Response RequestMovie(int movieId, bool notify = false) + private Response RequestMovie(int movieId) { var movieApi = new TheMovieDbApi(); var movieInfo = movieApi.GetMovieInformation(movieId).Result; @@ -431,10 +437,6 @@ namespace PlexRequests.UI.Modules // check if the current user is already marked as a requester for this movie, if not, add them if (!existingRequest.UserHasRequested(Username)) { - if (notify) - { - existingRequest.AddUserToNotification(Username); - } existingRequest.RequestedUsers.Add(Username); RequestService.UpdateRequest(existingRequest); } @@ -472,13 +474,8 @@ namespace PlexRequests.UI.Modules Approved = false, RequestedUsers = new List { Username }, Issues = IssueState.None, - - }; - if (notify) - { - model.AddUserToNotification(Username); - } + }; Log.Trace(settings.DumpJson()); if (ShouldAutoApprove(RequestType.Movie, settings)) @@ -500,15 +497,17 @@ namespace PlexRequests.UI.Modules RequestService.AddRequest(model); - if (ShouldSendNotification()) { - var notificationModel = new NotificationModel { - Title = model.Title, - User = Username, - DateTime = DateTime.Now, - NotificationType = NotificationType.NewRequest - }; - NotificationService.Publish (notificationModel); - } + 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 @@ -525,15 +524,17 @@ namespace PlexRequests.UI.Modules 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); - } + 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!" }); } @@ -564,7 +565,7 @@ namespace PlexRequests.UI.Modules /// The seasons. /// if set to true [notify]. /// - private Response RequestTvShow(int showId, string seasons, bool notify) + private Response RequestTvShow(int showId, string seasons) { var tvApi = new TvMazeApi(); @@ -584,10 +585,6 @@ namespace PlexRequests.UI.Modules // check if the current user is already marked as a requester for this show, if not, add them if (!existingRequest.UserHasRequested(Username)) { - if (notify) - { - existingRequest.AddUserToNotification(Username); - } existingRequest.RequestedUsers.Add(Username); RequestService.UpdateRequest(existingRequest); } @@ -625,10 +622,7 @@ namespace PlexRequests.UI.Modules ImdbId = showInfo.externals?.imdb ?? string.Empty, SeasonCount = showInfo.seasonCount }; - if (notify) - { - model.AddUserToNotification(Username); - } + var seasonsList = new List(); switch (seasons) { @@ -660,15 +654,17 @@ namespace PlexRequests.UI.Modules 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); - } + 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!" }); } @@ -686,22 +682,24 @@ namespace PlexRequests.UI.Modules 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); - } + 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 ? "Message From SickRage: " + 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."}); + return Response.AsJson(new JsonResponseModel { Result = false, Message = "The request of TV Shows is not correctly set up. Please contact your admin." }); } @@ -713,19 +711,22 @@ namespace PlexRequests.UI.Modules return Response.AsJson(new JsonResponseModel { Result = true, Message = $"{fullShowName} was successfully added!" }); } - private bool ShouldSendNotification(){ - var sendNotification = true; - var claims = Context.CurrentUser?.Claims; - if (claims != null) { - if (claims.Contains (UserClaims.Admin) || claims.Contains (UserClaims.PowerUser)) { - sendNotification = false; // Don't bother sending a notification if the user is an admin - } - } - return sendNotification; - } + private bool ShouldSendNotification() + { + var sendNotification = true; + var claims = Context.CurrentUser?.Claims; + if (claims != null) + { + if (claims.Contains(UserClaims.Admin) || claims.Contains(UserClaims.PowerUser)) + { + sendNotification = false; // Don't bother sending a notification if the user is an admin + } + } + return sendNotification; + } - private Response RequestAlbum(string releaseId, bool notify) + private Response RequestAlbum(string releaseId) { var settings = PrService.GetSettings(); var existingRequest = RequestService.CheckRequest(releaseId); @@ -736,10 +737,7 @@ namespace PlexRequests.UI.Modules Log.Debug("We do have an existing album request"); if (!existingRequest.UserHasRequested(Username)) { - if (notify) - { - existingRequest.AddUserToNotification(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); @@ -797,10 +795,6 @@ namespace PlexRequests.UI.Modules ArtistId = artist.id }; - if (notify) - { - model.AddUserToNotification(Username); - } if (ShouldAutoApprove(RequestType.Album, settings)) { Log.Debug("We don't require approval OR the user is in the whitelist"); @@ -825,15 +819,17 @@ namespace PlexRequests.UI.Modules 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); - } + 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 @@ -843,15 +839,17 @@ namespace PlexRequests.UI.Modules }); } - if (ShouldSendNotification ()) { - var notify2 = new NotificationModel { - Title = model.Title, - User = Username, - DateTime = DateTime.Now, - NotificationType = NotificationType.NewRequest - }; - NotificationService.Publish (notify2); - } + 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 { @@ -892,5 +890,56 @@ namespace PlexRequests.UI.Modules return false; } } + + private Response NotifyUser(bool notify) + { + var auth = Auth.GetSettings().UserAuthentication; + if (!auth) + { + return Response.AsJson(new JsonResponseModel { Result = false, Message = "Sorry, but this functionality is currently only for users with Plex accounts"}); + } + var username = Username; + var originalList = UsersToNotifyRepo.GetAll(); + if (!notify) + { + if (originalList == null) + { + return Response.AsJson(new JsonResponseModel { Result = false, Message = "We could not remove this notification because you never had it!" }); + } + var userToRemove = originalList.FirstOrDefault(x => x.Username == username); + if (userToRemove != null) + { + UsersToNotifyRepo.Delete(userToRemove); + } + return Response.AsJson(new JsonResponseModel { Result = true }); + } + + + if (originalList == null) + { + var userModel = new UsersToNotify { Username = username }; + var insertResult = UsersToNotifyRepo.Insert(userModel); + return Response.AsJson(insertResult != -1 ? new JsonResponseModel { Result = true } : new JsonResponseModel { Result = false, Message = "Could not save, please try again" }); + } + + var existingUser = originalList.FirstOrDefault(x => x.Username == username); + if (existingUser != null) + { + return Response.AsJson(new JsonResponseModel { Result = true }); // It's already enabled + } + else + { + var userModel = new UsersToNotify { Username = username }; + var insertResult = UsersToNotifyRepo.Insert(userModel); + return Response.AsJson(insertResult != -1 ? new JsonResponseModel { Result = true } : new JsonResponseModel { Result = false, Message = "Could not save, please try again" }); + } + + } + + public Response GetUserNotificationSettings() + { + var retval = UsersToNotifyRepo.GetAll().FirstOrDefault(x => x.Username == Username); + return Response.AsJson(retval != null); + } } } diff --git a/PlexRequests.UI/Views/Search/Index.cshtml b/PlexRequests.UI/Views/Search/Index.cshtml index 3d26aab63..20a1251b9 100644 --- a/PlexRequests.UI/Views/Search/Index.cshtml +++ b/PlexRequests.UI/Views/Search/Index.cshtml @@ -128,7 +128,7 @@
- +