Added a notification model to the notifiers.

Added the backend work for sending a notification for an issue report #75
This commit is contained in:
tidusjar 2016-03-22 17:13:14 +00:00
parent 5b90fa9089
commit 0585ff73ec
11 changed files with 245 additions and 66 deletions

View file

@ -97,7 +97,7 @@ namespace PlexRequests.Services.Tests
{ {
Assert.DoesNotThrow( Assert.DoesNotThrow(
() => () =>
{ NotificationService.Publish(string.Empty, string.Empty); }); { NotificationService.Publish(new NotificationModel()); });
} }
[Test] [Test]
@ -112,11 +112,11 @@ namespace PlexRequests.Services.Tests
NotificationService.Subscribe(notificationMock2.Object); NotificationService.Subscribe(notificationMock2.Object);
Assert.That(NotificationService.Observers.Count, Is.EqualTo(2)); Assert.That(NotificationService.Observers.Count, Is.EqualTo(2));
var model = new NotificationModel {Title = "abc", Body = "test"};
NotificationService.Publish(model);
NotificationService.Publish("a","b"); notificationMock1.Verify(x => x.Notify(model), Times.Once);
notificationMock2.Verify(x => x.Notify(model), Times.Once);
notificationMock1.Verify(x => x.Notify("a","b"), Times.Once);
notificationMock2.Verify(x => x.Notify("a","b"), Times.Once);
} }
} }
} }

View file

@ -42,10 +42,12 @@ namespace PlexRequests.Services.Notification
EmailNotificationSettings = settings; EmailNotificationSettings = settings;
} }
private static Logger Log = LogManager.GetCurrentClassLogger(); private static readonly Logger Log = LogManager.GetCurrentClassLogger();
private ISettingsService<EmailNotificationSettings> EmailNotificationSettings { get; } private ISettingsService<EmailNotificationSettings> EmailNotificationSettings { get; }
private EmailNotificationSettings Settings => GetConfiguration();
public string NotificationName => "EmailMessageNotification"; public string NotificationName => "EmailMessageNotification";
public bool Notify(string title, string requester)
public bool Notify(NotificationModel model)
{ {
var configuration = GetConfiguration(); var configuration = GetConfiguration();
if (!ValidateConfiguration(configuration)) if (!ValidateConfiguration(configuration))
@ -53,33 +55,22 @@ namespace PlexRequests.Services.Notification
return false; return false;
} }
var message = new MailMessage switch (model.NotificationType)
{ {
IsBodyHtml = true, case NotificationType.NewRequest:
To = { new MailAddress(configuration.RecipientEmail) }, return EmailNewRequest(model);
Body = $"User {requester} has requested {title}!", case NotificationType.Issue:
From = new MailAddress(configuration.EmailUsername), return EmailIssue(model);
Subject = $"New Request for {title}!" case NotificationType.RequestAvailable:
}; break;
case NotificationType.RequestApproved:
break;
case NotificationType.AdminNote:
break;
default:
throw new ArgumentOutOfRangeException();
}
try
{
using (var smtp = new SmtpClient(configuration.EmailHost, configuration.EmailPort))
{
smtp.Credentials = new NetworkCredential(configuration.EmailUsername, configuration.EmailPassword);
smtp.EnableSsl = configuration.Ssl;
smtp.Send(message);
return true;
}
}
catch (SmtpException smtp)
{
Log.Fatal(smtp);
}
catch (Exception e)
{
Log.Fatal(e);
}
return false; return false;
} }
@ -95,14 +86,76 @@ namespace PlexRequests.Services.Notification
{ {
return false; return false;
} }
if (string.IsNullOrEmpty(settings.EmailHost) || string.IsNullOrEmpty(settings.EmailUsername) if (string.IsNullOrEmpty(settings.EmailHost) || string.IsNullOrEmpty(settings.EmailUsername) || string.IsNullOrEmpty(settings.EmailPassword) || string.IsNullOrEmpty(settings.RecipientEmail) || string.IsNullOrEmpty(settings.EmailPort.ToString()))
|| string.IsNullOrEmpty(settings.EmailPassword) || string.IsNullOrEmpty(settings.RecipientEmail)
|| string.IsNullOrEmpty(settings.EmailPort.ToString()))
{ {
return false; return false;
} }
return true; return true;
} }
private bool EmailNewRequest(NotificationModel model)
{
var message = new MailMessage
{
IsBodyHtml = true,
To = { new MailAddress(Settings.RecipientEmail) },
Body = $"Hello! The user '{model.User}' has requested {model.Title}! Please log in to approve this request. Request Date: {model.DateTime.ToString("f")}",
From = new MailAddress(Settings.EmailUsername),
Subject = $"Plex Requests: New request for {model.Title}!"
};
try
{
using (var smtp = new SmtpClient(Settings.EmailHost, Settings.EmailPort))
{
smtp.Credentials = new NetworkCredential(Settings.EmailUsername, Settings.EmailPassword);
smtp.EnableSsl = Settings.Ssl;
smtp.Send(message);
return true;
}
}
catch (SmtpException smtp)
{
Log.Fatal(smtp);
}
catch (Exception e)
{
Log.Fatal(e);
}
return false;
}
private bool EmailIssue(NotificationModel model)
{
var message = new MailMessage
{
IsBodyHtml = true,
To = { new MailAddress(Settings.RecipientEmail) },
Body = $"Hello! The user '{model.User}' has reported a new issue {model.Body} for the title {model.Title}!",
From = new MailAddress(Settings.EmailUsername),
Subject = $"Plex Requests: New issue for {model.Title}!"
};
try
{
using (var smtp = new SmtpClient(Settings.EmailHost, Settings.EmailPort))
{
smtp.Credentials = new NetworkCredential(Settings.EmailUsername, Settings.EmailPassword);
smtp.EnableSsl = Settings.Ssl;
smtp.Send(message);
return true;
}
}
catch (SmtpException smtp)
{
Log.Fatal(smtp);
}
catch (Exception e)
{
Log.Fatal(e);
}
return false;
}
} }
} }

View file

@ -38,9 +38,8 @@ namespace PlexRequests.Services.Notification
/// <summary> /// <summary>
/// Notifies the specified title. /// Notifies the specified title.
/// </summary> /// </summary>
/// <param name="title">The title.</param> /// <param name="model">The model.</param>
/// <param name="requester">The requester.</param>
/// <returns></returns> /// <returns></returns>
bool Notify(string title, string requester); bool Notify(NotificationModel model);
} }
} }

View file

@ -0,0 +1,39 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: NotificationModel.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 System;
namespace PlexRequests.Services.Notification
{
public class NotificationModel
{
public string Title { get; set; }
public string Body { get; set; }
public DateTime DateTime { get; set; }
public NotificationType NotificationType { get; set; }
public string User { get; set; }
}
}

View file

@ -44,7 +44,7 @@ namespace PlexRequests.Services.Notification
Observers = new Dictionary<string, INotification>(); Observers = new Dictionary<string, INotification>();
} }
public static void Publish(string title, string requester) public static void Publish(NotificationModel model)
{ {
Log.Trace("Notifying all observers: "); Log.Trace("Notifying all observers: ");
Log.Trace(Observers.DumpJson()); Log.Trace(Observers.DumpJson());
@ -55,7 +55,7 @@ namespace PlexRequests.Services.Notification
new Thread(() => new Thread(() =>
{ {
Thread.CurrentThread.IsBackground = true; Thread.CurrentThread.IsBackground = true;
notification.Notify(title, requester); notification.Notify(model);
}).Start(); }).Start();
} }
} }

View file

@ -0,0 +1,37 @@
#region Copyright
// /************************************************************************
// Copyright (c) 2016 Jamie Rees
// File: NotificationType.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
namespace PlexRequests.Services.Notification
{
public enum NotificationType
{
NewRequest,
Issue,
RequestAvailable,
RequestApproved,
AdminNote,
}
}

View file

@ -39,27 +39,59 @@ namespace PlexRequests.Services.Notification
public PushbulletNotification(IPushbulletApi pushbulletApi, ISettingsService<PushbulletNotificationSettings> settings) public PushbulletNotification(IPushbulletApi pushbulletApi, ISettingsService<PushbulletNotificationSettings> settings)
{ {
PushbulletApi = pushbulletApi; PushbulletApi = pushbulletApi;
Settings = settings; SettingsService = settings;
} }
private IPushbulletApi PushbulletApi { get; } private IPushbulletApi PushbulletApi { get; }
private ISettingsService<PushbulletNotificationSettings> Settings { get; } private ISettingsService<PushbulletNotificationSettings> SettingsService { get; }
private PushbulletNotificationSettings Settings => GetSettings();
private static Logger Log = LogManager.GetCurrentClassLogger(); private static Logger Log = LogManager.GetCurrentClassLogger();
public string NotificationName => "PushbulletNotification"; public string NotificationName => "PushbulletNotification";
public bool Notify(string title, string requester) public bool Notify(NotificationModel model)
{ {
var settings = GetSettings(); if (!ValidateConfiguration())
if (!settings.Enabled)
{ {
return false; return false;
} }
var message = $"{title} has been requested by {requester}"; switch (model.NotificationType)
var pushTitle = $"Plex Requests: {title}"; {
case NotificationType.NewRequest:
return PushNewRequest(model);
case NotificationType.Issue:
return PushIssue(model);
case NotificationType.RequestAvailable:
break;
case NotificationType.RequestApproved:
break;
case NotificationType.AdminNote:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private bool ValidateConfiguration()
{
return !Settings.Enabled && !string.IsNullOrEmpty(Settings.AccessToken);
}
private PushbulletNotificationSettings GetSettings()
{
return SettingsService.GetSettings();
}
private bool PushNewRequest(NotificationModel model)
{
var message = $"{model.Title} has been requested by user: {model.User}";
var pushTitle = $"Plex Requests: {model.Title} has been requested!";
try try
{ {
var result = PushbulletApi.Push(settings.AccessToken, pushTitle, message, settings.DeviceIdentifier); var result = PushbulletApi.Push(Settings.AccessToken, pushTitle, message, Settings.DeviceIdentifier);
if (result != null) if (result != null)
{ {
return true; return true;
@ -72,9 +104,23 @@ namespace PlexRequests.Services.Notification
return false; return false;
} }
private PushbulletNotificationSettings GetSettings() private bool PushIssue(NotificationModel model)
{ {
return Settings.GetSettings(); var message = $"A new issue: {model.Title} has been reported by user: {model.User} for the title: {model.Body}";
var pushTitle = $"Plex Requests: A new issue has been reported for {model.Body}";
try
{
var result = PushbulletApi.Push(Settings.AccessToken, pushTitle, message, Settings.DeviceIdentifier);
if (result != null)
{
return true;
}
}
catch (Exception e)
{
Log.Fatal(e);
}
return false;
} }
} }
} }

View file

@ -79,7 +79,9 @@
<Compile Include="Interfaces\IIntervals.cs" /> <Compile Include="Interfaces\IIntervals.cs" />
<Compile Include="Notification\INotification.cs" /> <Compile Include="Notification\INotification.cs" />
<Compile Include="Notification\EmailMessageNotification.cs" /> <Compile Include="Notification\EmailMessageNotification.cs" />
<Compile Include="Notification\NotificationModel.cs" />
<Compile Include="Notification\NotificationService.cs" /> <Compile Include="Notification\NotificationService.cs" />
<Compile Include="Notification\NotificationType.cs" />
<Compile Include="Notification\PushbulletNotification.cs" /> <Compile Include="Notification\PushbulletNotification.cs" />
<Compile Include="PlexAvailabilityChecker.cs" /> <Compile Include="PlexAvailabilityChecker.cs" />
<Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Properties\AssemblyInfo.cs" />

View file

@ -182,7 +182,7 @@ namespace PlexRequests.UI.Modules
var movieInfo = movieApi.GetMovieInformation(movieId).Result; var movieInfo = movieApi.GetMovieInformation(movieId).Result;
Log.Trace("Getting movie info from TheMovieDb"); Log.Trace("Getting movie info from TheMovieDb");
Log.Trace(movieInfo.DumpJson); Log.Trace(movieInfo.DumpJson);
//#if !DEBUG //#if !DEBUG
try try
{ {
if (CheckIfTitleExistsInPlex(movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString())) if (CheckIfTitleExistsInPlex(movieInfo.Title, movieInfo.ReleaseDate?.Year.ToString()))
@ -194,7 +194,7 @@ namespace PlexRequests.UI.Modules
{ {
return Response.AsJson(new JsonResponseModel { Result = false, Message = $"We could not check if {movieInfo.Title} is in Plex, are you sure it's correctly setup?" }); return Response.AsJson(new JsonResponseModel { Result = false, Message = $"We could not check if {movieInfo.Title} is in Plex, are you sure it's correctly setup?" });
} }
//#endif //#endif
var model = new RequestedModel var model = new RequestedModel
{ {
@ -241,7 +241,8 @@ namespace PlexRequests.UI.Modules
Log.Debug("Adding movie to database requests"); Log.Debug("Adding movie to database requests");
var id = RequestService.AddRequest(model); var id = RequestService.AddRequest(model);
NotificationService.Publish(model.Title, model.RequestedBy); var notificationModel = new NotificationModel { Title = model.Title, User = model.RequestedBy, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest };
NotificationService.Publish(notificationModel);
return Response.AsJson(new JsonResponseModel { Result = true }); return Response.AsJson(new JsonResponseModel { Result = true });
} }
@ -269,7 +270,7 @@ namespace PlexRequests.UI.Modules
var tvApi = new TvMazeApi(); var tvApi = new TvMazeApi();
var showInfo = tvApi.ShowLookupByTheTvDbId(showId); var showInfo = tvApi.ShowLookupByTheTvDbId(showId);
//#if !DEBUG //#if !DEBUG
try try
{ {
if (CheckIfTitleExistsInPlex(showInfo.name, showInfo.premiered?.Substring(0, 4))) // Take only the year Format = 2014-01-01 if (CheckIfTitleExistsInPlex(showInfo.name, showInfo.premiered?.Substring(0, 4))) // Take only the year Format = 2014-01-01
@ -281,7 +282,7 @@ namespace PlexRequests.UI.Modules
{ {
return Response.AsJson(new JsonResponseModel { Result = false, Message = $"We could not check if {showInfo.name} is in Plex, are you sure it's correctly setup?" }); return Response.AsJson(new JsonResponseModel { Result = false, Message = $"We could not check if {showInfo.name} is in Plex, are you sure it's correctly setup?" });
} }
//#endif //#endif
DateTime firstAir; DateTime firstAir;
DateTime.TryParse(showInfo.premiered, out firstAir); DateTime.TryParse(showInfo.premiered, out firstAir);
@ -344,7 +345,9 @@ namespace PlexRequests.UI.Modules
} }
RequestService.AddRequest(model); RequestService.AddRequest(model);
NotificationService.Publish(model.Title, model.RequestedBy);
var notificationModel = new NotificationModel { Title = model.Title, User = model.RequestedBy, DateTime = DateTime.Now, NotificationType = NotificationType.NewRequest };
NotificationService.Publish(notificationModel);
return Response.AsJson(new { Result = true }); return Response.AsJson(new { Result = true });
} }

View file

@ -13,21 +13,22 @@
layout="${date} ${logger} ${level}: ${message}" /> layout="${date} ${logger} ${level}: ${message}" />
<!--<target name="Database" xsi:type="Database" <target name="Database" xsi:type="Database"
dbProvider="Mono.Data.Sqlite,Mono.Data.Sqlite" keepConnection="false" dbProvider="Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756" keepConnection="false"
connectionString="Data Source=PlexRequests.sqlite" connectionString="Data Source=PlexRequests.sqlite, version=3"
commandText="INSERT into Log(Date, Level, Logger, Callsite, Message) commandText="INSERT into Logs(Date, Level, Logger, Callsite, Message, Exception)
values(@Date, @Loglevel, @Logger, @Callsite, @Message)"> values(@Date, @Loglevel, @Logger, @Callsite, @Message, @Exception)">
<parameter name="@Date" layout="${longdate}"/> <parameter name="@Date" layout="${longdate}"/>
<parameter name="@Loglevel" layout="${level:uppercase=true}"/> <parameter name="@Loglevel" layout="${level:uppercase=true}"/>
<parameter name="@Logger" layout="${logger}"/> <parameter name="@Logger" layout="${logger}"/>
<parameter name="@Callsite" layout="${callsite:filename=true}"/> <parameter name="@Callsite" layout="${callsite:filename=true}"/>
<parameter name="@Message" layout="${message}"/> <parameter name="@Message" layout="${message}"/>
</target>--> <parameter name="@Exception" layout="${exception:format=tostring}"/>
</target>
</targets> </targets>
<rules> <rules>
<logger name="*" minlevel="Trace" writeTo="filelog" /> <logger name="*" minlevel="Trace" writeTo="filelog" />
<!--<logger name="*" minlevel="Trace" writeTo="Database" />--> <logger name="*" minlevel="Trace" writeTo="Database" />
</rules> </rules>
</nlog> </nlog>

View file

@ -61,7 +61,6 @@ namespace PlexRequests.UI
} }
port = portResult; port = portResult;
} }
Log.Trace("Getting product version"); Log.Trace("Getting product version");
WriteOutVersion(); WriteOutVersion();
@ -126,7 +125,7 @@ namespace PlexRequests.UI
{ {
CommandType = CommandType.Text, CommandType = CommandType.Text,
ConnectionString = connectionString, ConnectionString = connectionString,
DBProvider = "Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756", DBProvider = "Mono.Data.Sqlite.SqliteConnection, Mono.Data.Sqlite, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756",
Name = "database" Name = "database"
}; };