Fully finished #27 just need to test it!

pull/226/head
tidusjar 8 years ago
parent db00326a9c
commit e49b160500

@ -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> plexSettings, ISettingsService<AuthenticationSettings> auth, IRequestService request, IPlexApi plex, ICacheProvider cache,
INotificationService notify, IJobRecord rec)
INotificationService notify, IJobRecord rec, IRepository<UsersToNotify> users)
{
Plex = plexSettings;
Auth = auth;
@ -56,6 +58,7 @@ namespace PlexRequests.Services.Jobs
Cache = cache;
Notification = notify;
Job = rec;
UserNotifyRepo = users;
}
private ISettingsService<PlexSettings> Plex { get; }
@ -66,7 +69,7 @@ namespace PlexRequests.Services.Jobs
private ICacheProvider Cache { get; }
private INotificationService Notification { get; }
private IJobRecord Job { get; }
private IRepository<UsersToNotify> 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)

@ -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; }
}
}

@ -60,6 +60,7 @@
<Compile Include="DbConfiguration.cs" />
<Compile Include="Entity.cs" />
<Compile Include="Models\ScheduledJobs.cs" />
<Compile Include="Models\UsersToNotify.cs" />
<Compile Include="Repository\IRequestRepository.cs" />
<Compile Include="Repository\ISettingsRepository.cs" />
<Compile Include="ISqliteConfiguration.cs" />

@ -40,7 +40,6 @@ namespace PlexRequests.Store
public List<string> RequestedUsers { get; set; }
public string ArtistName { get; set; }
public string ArtistId { get; set; }
public List<string> UsersToNotify { get; private set; }
[JsonIgnore]
public List<string> 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<string>();
}
if (UsersToNotify.FirstOrDefault(x => x == username) != null)
{
// User already exists in the notification list
return;
}
UsersToNotify.Add(username);
}
}
public enum RequestType

@ -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);
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);

@ -86,6 +86,7 @@ namespace PlexRequests.UI
// Repo's
container.Register<IRepository<LogEntity>, GenericRepository<LogEntity>>();
container.Register<IRepository<UsersToNotify>, GenericRepository<UsersToNotify>>();
container.Register<IRepository<ScheduledJobs>, GenericRepository<ScheduledJobs>>();
container.Register<IRequestService, JsonRequestService>();
container.Register<ISettingsRepository, SettingsJsonRepository>();

@ -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 + "&notify=" + $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 + "&notify=" + $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 + "&notify=" + $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();

@ -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");
});
}
}

@ -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);

@ -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<PlexRequestSettings> prSettings, IAvailabilityChecker checker,
IRequestService request, ISonarrApi sonarrApi, ISettingsService<SonarrSettings> sonarrSettings,
ISettingsService<SickRageSettings> sickRageService, ICouchPotatoApi cpApi, ISickRageApi srApi,
INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService<HeadphonesSettings> hpService,
ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi,
ISettingsService<PlexSettings> plexService, ISettingsService<AuthenticationSettings> auth) : base("search", prSettings)
INotificationService notify, IMusicBrainzApi mbApi, IHeadphonesApi hpApi, ISettingsService<HeadphonesSettings> hpService,
ICouchPotatoCacher cpCacher, ISonarrCacher sonarrCacher, ISickRageCacher sickRageCacher, IPlexApi plexApi,
ISettingsService<PlexSettings> plexService, ISettingsService<AuthenticationSettings> auth, IRepository<UsersToNotify> 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<UsersToNotify> UsersToNotifyRepo { get; }
private static Logger Log = LogManager.GetCurrentClassLogger();
private Negotiator RequestLoad()
@ -157,7 +163,7 @@ namespace PlexRequests.UI.Modules
var apiMovies = new List<MovieResult>();
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<Task>();
var taskList = new List<Task>();
var apiTv = new List<TvMazeSearch>();
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<string> { 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
/// <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, 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<int>();
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 ? "<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."});
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);
}
}
}

@ -128,7 +128,7 @@
</div>
<div class="form-group">
<div>
<button id="saveNotificationSettings" type="submit" class="btn btn-primary-outline">Save</button>
<button id="saveNotificationSettings" class="btn btn-primary-outline">Save</button>
</div>
</div>
</fieldset>

Loading…
Cancel
Save