#96 Email notification test button (others to come)

This commit is contained in:
Drewster727 2016-03-27 23:45:52 -05:00
parent 085c46ce43
commit 4b3f79b4a8
9 changed files with 134 additions and 18 deletions

View file

@ -27,6 +27,7 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using PlexRequests.Services.Notification; using PlexRequests.Services.Notification;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.Services.Interfaces namespace PlexRequests.Services.Interfaces
{ {
@ -35,5 +36,7 @@ namespace PlexRequests.Services.Interfaces
string NotificationName { get; } string NotificationName { get; }
Task NotifyAsync(NotificationModel model); Task NotifyAsync(NotificationModel model);
Task NotifyAsync(NotificationModel model, EmailNotificationSettings settings);
} }
} }

View file

@ -27,12 +27,14 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using PlexRequests.Services.Notification; using PlexRequests.Services.Notification;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.Services.Interfaces namespace PlexRequests.Services.Interfaces
{ {
public interface INotificationService public interface INotificationService
{ {
Task Publish(NotificationModel model); Task Publish(NotificationModel model);
Task Publish(NotificationModel model, EmailNotificationSettings settings);
void Subscribe(INotification notification); void Subscribe(INotification notification);
void UnSubscribe(INotification notification); void UnSubscribe(INotification notification);

View file

@ -46,13 +46,19 @@ namespace PlexRequests.Services.Notification
private static readonly 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 async Task NotifyAsync(NotificationModel model) public async Task NotifyAsync(NotificationModel model)
{ {
var configuration = GetConfiguration(); var configuration = GetConfiguration();
if (!ValidateConfiguration(configuration)) await NotifyAsync(model, configuration);
}
public async Task NotifyAsync(NotificationModel model, EmailNotificationSettings settings)
{
if (settings == null) await NotifyAsync(model);
if (!ValidateConfiguration(settings))
{ {
return; return;
} }
@ -60,10 +66,10 @@ namespace PlexRequests.Services.Notification
switch (model.NotificationType) switch (model.NotificationType)
{ {
case NotificationType.NewRequest: case NotificationType.NewRequest:
await EmailNewRequest(model); await EmailNewRequest(model, settings);
break; break;
case NotificationType.Issue: case NotificationType.Issue:
await EmailIssue(model); await EmailIssue(model, settings);
break; break;
case NotificationType.RequestAvailable: case NotificationType.RequestAvailable:
throw new NotImplementedException(); throw new NotImplementedException();
@ -74,6 +80,10 @@ namespace PlexRequests.Services.Notification
case NotificationType.AdminNote: case NotificationType.AdminNote:
throw new NotImplementedException(); throw new NotImplementedException();
case NotificationType.Test:
await EmailTest(model, settings);
break;
default: default:
throw new ArgumentOutOfRangeException(); throw new ArgumentOutOfRangeException();
} }
@ -100,23 +110,23 @@ namespace PlexRequests.Services.Notification
return true; return true;
} }
private async Task EmailNewRequest(NotificationModel model) private async Task EmailNewRequest(NotificationModel model, EmailNotificationSettings settings)
{ {
var message = new MailMessage var message = new MailMessage
{ {
IsBodyHtml = true, IsBodyHtml = true,
To = { new MailAddress(Settings.RecipientEmail) }, 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")}", 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.EmailSender), From = new MailAddress(settings.EmailSender),
Subject = $"Plex Requests: New request for {model.Title}!" Subject = $"Plex Requests: New request for {model.Title}!"
}; };
try try
{ {
using (var smtp = new SmtpClient(Settings.EmailHost, Settings.EmailPort)) using (var smtp = new SmtpClient(settings.EmailHost, settings.EmailPort))
{ {
smtp.Credentials = new NetworkCredential(Settings.EmailUsername, Settings.EmailPassword); smtp.Credentials = new NetworkCredential(settings.EmailUsername, settings.EmailPassword);
smtp.EnableSsl = Settings.Ssl; smtp.EnableSsl = settings.Ssl;
await smtp.SendMailAsync(message).ConfigureAwait(false); await smtp.SendMailAsync(message).ConfigureAwait(false);
} }
} }
@ -130,23 +140,53 @@ namespace PlexRequests.Services.Notification
} }
} }
private async Task EmailIssue(NotificationModel model) private async Task EmailIssue(NotificationModel model, EmailNotificationSettings settings)
{ {
var message = new MailMessage var message = new MailMessage
{ {
IsBodyHtml = true, IsBodyHtml = true,
To = { new MailAddress(Settings.RecipientEmail) }, To = { new MailAddress(settings.RecipientEmail) },
Body = $"Hello! The user '{model.User}' has reported a new issue {model.Body} for the title {model.Title}!", Body = $"Hello! The user '{model.User}' has reported a new issue {model.Body} for the title {model.Title}!",
From = new MailAddress(Settings.RecipientEmail), From = new MailAddress(settings.RecipientEmail),
Subject = $"Plex Requests: New issue for {model.Title}!" Subject = $"Plex Requests: New issue for {model.Title}!"
}; };
try try
{ {
using (var smtp = new SmtpClient(Settings.EmailHost, Settings.EmailPort)) using (var smtp = new SmtpClient(settings.EmailHost, settings.EmailPort))
{ {
smtp.Credentials = new NetworkCredential(Settings.EmailUsername, Settings.EmailPassword); smtp.Credentials = new NetworkCredential(settings.EmailUsername, settings.EmailPassword);
smtp.EnableSsl = Settings.Ssl; smtp.EnableSsl = settings.Ssl;
await smtp.SendMailAsync(message).ConfigureAwait(false);
}
}
catch (SmtpException smtp)
{
Log.Error(smtp);
}
catch (Exception e)
{
Log.Error(e);
}
}
private async Task EmailTest(NotificationModel model, EmailNotificationSettings settings)
{
var message = new MailMessage
{
IsBodyHtml = true,
To = { new MailAddress(settings.RecipientEmail) },
Body = "This is just a test! Success!",
From = new MailAddress(settings.RecipientEmail),
Subject = "Plex Requests: Test Message!"
};
try
{
using (var smtp = new SmtpClient(settings.EmailHost, settings.EmailPort))
{
smtp.Credentials = new NetworkCredential(settings.EmailUsername, settings.EmailPassword);
smtp.EnableSsl = settings.Ssl;
await smtp.SendMailAsync(message).ConfigureAwait(false); await smtp.SendMailAsync(message).ConfigureAwait(false);
} }
} }

View file

@ -32,6 +32,7 @@ using System.Threading.Tasks;
using NLog; using NLog;
using PlexRequests.Services.Interfaces; using PlexRequests.Services.Interfaces;
using PlexRequests.Core.SettingModels;
namespace PlexRequests.Services.Notification namespace PlexRequests.Services.Notification
{ {
@ -47,6 +48,13 @@ namespace PlexRequests.Services.Notification
await Task.WhenAll(notificationTasks).ConfigureAwait(false); await Task.WhenAll(notificationTasks).ConfigureAwait(false);
} }
public async Task Publish(NotificationModel model, EmailNotificationSettings settings)
{
var notificationTasks = Observers.Values.Select(notification => NotifyAsync(notification, model, settings));
await Task.WhenAll(notificationTasks).ConfigureAwait(false);
}
public void Subscribe(INotification notification) public void Subscribe(INotification notification)
{ {
Observers.TryAdd(notification.NotificationName, notification); Observers.TryAdd(notification.NotificationName, notification);
@ -58,10 +66,17 @@ namespace PlexRequests.Services.Notification
} }
private static async Task NotifyAsync(INotification notification, NotificationModel model) private static async Task NotifyAsync(INotification notification, NotificationModel model)
{
await NotifyAsync(notification, model, null);
}
private static async Task NotifyAsync(INotification notification, NotificationModel model, EmailNotificationSettings settings)
{ {
try try
{ {
await notification.NotifyAsync(model).ConfigureAwait(false); await notification.NotifyAsync(model, settings).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {

View file

@ -33,5 +33,6 @@ namespace PlexRequests.Services.Notification
RequestAvailable, RequestAvailable,
RequestApproved, RequestApproved,
AdminNote, AdminNote,
Test
} }
} }

View file

@ -128,5 +128,10 @@ namespace PlexRequests.Services.Notification
Log.Error(e); Log.Error(e);
} }
} }
public Task NotifyAsync(NotificationModel model, EmailNotificationSettings settings)
{
throw new NotImplementedException();
}
} }
} }

View file

@ -126,5 +126,10 @@ namespace PlexRequests.Services.Notification
Log.Error(e); Log.Error(e);
} }
} }
public Task NotifyAsync(NotificationModel model, EmailNotificationSettings settings)
{
throw new NotImplementedException();
}
} }
} }

View file

@ -51,6 +51,7 @@ using PlexRequests.Store.Models;
using PlexRequests.Store.Repository; using PlexRequests.Store.Repository;
using PlexRequests.UI.Helpers; using PlexRequests.UI.Helpers;
using PlexRequests.UI.Models; using PlexRequests.UI.Models;
using System;
namespace PlexRequests.UI.Modules namespace PlexRequests.UI.Modules
{ {
@ -139,6 +140,7 @@ namespace PlexRequests.UI.Modules
Get["/emailnotification"] = _ => EmailNotifications(); Get["/emailnotification"] = _ => EmailNotifications();
Post["/emailnotification"] = _ => SaveEmailNotifications(); Post["/emailnotification"] = _ => SaveEmailNotifications();
Post["/testemailnotification"] = _ => TestEmailNotifications();
Get["/status"] = _ => Status(); Get["/status"] = _ => Status();
Get["/pushbulletnotification"] = _ => PushbulletNotifications(); Get["/pushbulletnotification"] = _ => PushbulletNotifications();
@ -372,6 +374,19 @@ namespace PlexRequests.UI.Modules
return View["EmailNotifications", settings]; return View["EmailNotifications", settings];
} }
private Response TestEmailNotifications()
{
var settings = this.Bind<EmailNotificationSettings>();
var notificationModel = new NotificationModel
{
NotificationType = NotificationType.Test,
DateTime = DateTime.Now
};
NotificationService.Publish(notificationModel, settings);
Log.Info("Sent email notification test");
return Response.AsJson(new JsonResponseModel { Result = true, Message = "Successfully sent a test Email Notification!" });
}
private Response SaveEmailNotifications() private Response SaveEmailNotifications()
{ {
var settings = this.Bind<EmailNotificationSettings>(); var settings = this.Bind<EmailNotificationSettings>();

View file

@ -88,6 +88,11 @@
</div> </div>
</div> </div>
<div class="form-group">
<div>
<button id="testEmail" type="submit" class="btn btn-primary-outline">Test</button>
</div>
</div>
<div class="form-group"> <div class="form-group">
<div> <div>
@ -128,7 +133,32 @@
}); });
}); });
$('#testEmail').click(function (e) {
e.preventDefault();
var port = $('#EmailPort').val();
if (isNaN(port)) {
generateNotify("You must specify a valid Port.", "warning");
return;
}
var $form = $("#mainForm");
$.ajax({
type: $form.prop("method"),
data: $form.serialize(),
url: '/admin/testemailnotification',
dataType: "json",
success: function (response) {
if (response.result === true) {
generateNotify(response.message, "success");
} else {
generateNotify(response.message, "warning");
}
},
error: function (e) {
console.log(e);
generateNotify("Something went wrong!", "danger");
}
});
});
}); });