Skip to content

Commit

Permalink
Merge pull request #452 from poppastring/email-alert-comment
Browse files Browse the repository at this point in the history
Daily Email alert
  • Loading branch information
poppastring authored Aug 29, 2020
2 parents 54c808a + fc275b8 commit 39852ba
Show file tree
Hide file tree
Showing 13 changed files with 305 additions and 443 deletions.
2 changes: 1 addition & 1 deletion source/DasBlog.CLI/DasBlog.CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Xml" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.6" />
<PackageReference Include="Microsoft.Extensions.Options" Version="3.0.0" />
</ItemGroup>

Expand Down
5 changes: 4 additions & 1 deletion source/DasBlog.Services/ActivityLogs/EventCodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ public enum EventCodes : int
EditUser,
DeleteUser,
RSS = 7000,
Site,
Site = 8000,
HttpReferrer = 10000,
HttpUserAgent = 10001,
HttpUserDomain = 10002,
ApplicationStartup = 32000,

}
Expand Down
1 change: 1 addition & 0 deletions source/DasBlog.Services/DasBlog.Services.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageReference Include="Kveer.XmlRPC" Version="1.1.1" />
<PackageReference Include="MailKit" Version="2.4.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="3.0.0" />
<PackageReference Include="Quartz.AspNetCore" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
Expand Down
2 changes: 2 additions & 0 deletions source/DasBlog.Services/IDasBlogSettings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Net.Mail;
using DasBlog.Core.Security;
using DasBlog.Services.ConfigFile.Interfaces;
using newtelligence.DasBlog.Runtime;
Expand Down Expand Up @@ -44,5 +45,6 @@ public interface IDasBlogSettings
string CompressTitle(string title);
bool IsAdmin(string gravatarhash);
string GeneratePostUrl(Entry entry);
SendMailInfo GetMailInfo(MailMessage emailmessage);
}
}
173 changes: 173 additions & 0 deletions source/DasBlog.Services/Scheduler/SiteReport.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
using System;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using DasBlog.Services.ActivityLogs;
using Microsoft.Extensions.Logging;
using newtelligence.DasBlog.Runtime;
using Quartz;

namespace DasBlog.Services.Scheduler
{
public class SiteEmailReport : IJob
{
private readonly ILogger<SiteEmailReport> logger;
private readonly IActivityService activityService;
private readonly IDasBlogSettings dasBlogSettings;
private readonly DateTime midnight;

private const string MAIN_HEADER_TABLE = "<html><table><tbody><tr><td class='x_mainheader' width='100%'>{0}</td></tr></tbody></table>";
private const string TABLE = "<table width='100%'><tbody>{0}</tbody></table>";
private const string TABLE_HEADER_ROW = "<tr><td class='x_data' width='90%'><b>{0}</b></td><td class='x_data' width='10%'><b>{1}</b></td></tr>";
private const string TABLE_BODY_ROW = "<tr><td class='x_data'>{0}</td><td class='x_data'>{1}</td></tr>";
private const string HTML_CLOSE_TAG = "</html>";
private readonly string EMAIL_TITLE = string.Empty;

public SiteEmailReport(ILogger<SiteEmailReport> logger, IActivityService activityService, IDasBlogSettings dasBlogSettings)
{
this.logger = logger;
this.activityService = activityService;
this.dasBlogSettings = dasBlogSettings;
midnight = DateTime.Now.Date;
EMAIL_TITLE = string.Format("Weblog Daily Activity Report for {0}, {1}", midnight.DayOfWeek, midnight.ToString("MMMM dd, yyyy"));
}

public async Task Execute(IJobExecutionContext context)
{
if(dasBlogSettings.SiteConfiguration.EnableDailyReportEmail)
{
logger.LogInformation(context.JobDetail.Key + " job executing, triggered by " + context.Trigger.Key);

var emailbody = FormatEmail();

var emailinfo = ComposeMail(emailbody);

try
{
emailinfo?.SendMyMessage();
}
catch (Exception ex)
{
logger.LogError(new ActivityLogs.EventDataItem(ActivityLogs.EventCodes.SmtpError,
new Uri(dasBlogSettings.SiteConfiguration.Root),
string.Format("Weblog Daily Activity Report Failed: {0}", ex.Message)));
}
}

await Task.Delay(TimeSpan.FromMilliseconds(1));
}

private string FormatEmail()
{
var body = new StringBuilder();
var table = new StringBuilder();
var events = activityService.GetEventsForDay(midnight);

//header
body.Append(string.Format(MAIN_HEADER_TABLE, EMAIL_TITLE));

//summary header
table.Append(string.Format(TABLE_HEADER_ROW, "Summary", "Hits"));
table.Append(string.Format(TABLE_BODY_ROW, "Referrer", events.Count(e => e.EventCode == ActivityLogs.EventCodes.HttpReferrer)));
table.Append(string.Format(TABLE_BODY_ROW, "User Agents", events.Count(e => e.EventCode == ActivityLogs.EventCodes.HttpUserAgent)));
table.Append(string.Format(TABLE_BODY_ROW, "Domain", events.Count(e => e.EventCode == ActivityLogs.EventCodes.HttpUserDomain)));

body.Append(string.Format(TABLE, table.ToString()));

//Referrer
table.Clear();
table.Append(string.Format(TABLE_HEADER_ROW, "Referrer", "Count"));

var referrer = events.Where(x => x.EventCode == ActivityLogs.EventCodes.HttpReferrer)
.GroupBy(info => info.HtmlMessage)
.Select(group => new { Referrer = group.Key, Count = group.Count() })
.OrderBy(y => y.Count);

foreach (var row in referrer)
{
table.Append(string.Format(TABLE_BODY_ROW, row.Referrer, row.Count));
}

body.Append(string.Format(TABLE, table.ToString()));

//User Agents
table.Clear();
table.Append(string.Format(TABLE_HEADER_ROW, "User Agents", "Count"));

var useragent = events.Where(x => x.EventCode == ActivityLogs.EventCodes.HttpUserAgent)
.GroupBy(info => info.HtmlMessage)
.Select(group => new { Referrer = group.Key, Count = group.Count() })
.OrderBy(y => y.Count);

foreach (var row in useragent)
{
table.Append(string.Format(TABLE_BODY_ROW, row.Referrer, row.Count));
}

body.Append(string.Format(TABLE, table.ToString()));

//Domain
table.Clear();
table.Append(string.Format(TABLE_HEADER_ROW, "Domain", "Count"));

var domain = events.Where(x => x.EventCode == ActivityLogs.EventCodes.HttpUserDomain)
.GroupBy(info => info.HtmlMessage)
.Select(group => new { Referrer = group.Key, Count = group.Count() })
.OrderBy(y => y.Count);

foreach (var row in domain)
{
table.Append(string.Format(TABLE_BODY_ROW, row.Referrer, row.Count));
}

body.Append(string.Format(TABLE, table.ToString()));

body.Append(HTML_CLOSE_TAG);

return body.ToString();
}

private SendMailInfo ComposeMail(string body)
{
var emailMessage = new MailMessage();

if (!string.IsNullOrWhiteSpace(dasBlogSettings.SiteConfiguration.NotificationEMailAddress))
{
emailMessage.To.Add(dasBlogSettings.SiteConfiguration.NotificationEMailAddress);
}
else
{
if (!string.IsNullOrWhiteSpace(dasBlogSettings.SiteConfiguration.Contact))
{
emailMessage.To.Add(dasBlogSettings.SiteConfiguration.Contact);
}
else
{
return null;
}
}

emailMessage.Subject = string.Format("Weblog Daily Activity Report for {0}, {1}", midnight.DayOfWeek, midnight.ToString("MMMM dd, yyyy"));

emailMessage.Body = body;

emailMessage.IsBodyHtml = true;
emailMessage.BodyEncoding = Encoding.UTF8;

if (!string.IsNullOrWhiteSpace(dasBlogSettings.SiteConfiguration.SmtpUserName))
{
emailMessage.From = new MailAddress(dasBlogSettings.SiteConfiguration.SmtpUserName);
}
else
{
return null;
}

return dasBlogSettings.GetMailInfo(emailMessage);
}


}
}
6 changes: 6 additions & 0 deletions source/DasBlog.Tests/UnitTests/DasBlogSettingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Xml.Serialization;
using DasBlog.Services;
using newtelligence.DasBlog.Runtime;
using System.Net.Mail;

namespace DasBlog.Tests.UnitTests
{
Expand Down Expand Up @@ -244,5 +245,10 @@ public string GeneratePostUrl(Entry entry)

return link;
}

public SendMailInfo GetMailInfo(MailMessage emailmessage)
{
throw new NotImplementedException();
}
}
}
12 changes: 2 additions & 10 deletions source/DasBlog.Web.Repositories/BlogManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ public bool SendTestEmail()
emailMessage.Subject = string.Format("SMTP email from {0}", dasBlogSettings.SiteConfiguration.Title);
emailMessage.Body = "Test ";

var sendMailInfo = GetMailInfo(emailMessage);
var sendMailInfo = dasBlogSettings.GetMailInfo(emailMessage);

try
{
Expand Down Expand Up @@ -531,15 +531,7 @@ private SendMailInfo ComposeMail(Comment c)

emailMessage.From = new MailAddress(dasBlogSettings.SiteConfiguration.SmtpUserName);

return GetMailInfo(emailMessage);
}

private SendMailInfo GetMailInfo(MailMessage emailmessage)
{
return new SendMailInfo(emailmessage, dasBlogSettings.SiteConfiguration.SmtpServer,
dasBlogSettings.SiteConfiguration.EnableSmtpAuthentication, dasBlogSettings.SiteConfiguration.UseSSLForSMTP,
dasBlogSettings.SiteConfiguration.SmtpUserName, dasBlogSettings.SiteConfiguration.SmtpPassword,
dasBlogSettings.SiteConfiguration.SmtpPort);
return dasBlogSettings.GetMailInfo(emailMessage);
}
}
}
Expand Down
1 change: 1 addition & 0 deletions source/DasBlog.Web.UI/DasBlog.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.10" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="NetEscapades.Extensions.Logging.RollingFile" Version="2.2.0" />
<PackageReference Include="Quartz.AspNetCore" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DasBlog.CLI\DasBlog.CLI.csproj" />
Expand Down
62 changes: 62 additions & 0 deletions source/DasBlog.Web.UI/Services/LoggingAgent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DasBlog.Services;
using DasBlog.Services.ActivityLogs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Quartz.Util;

namespace DasBlog.Web.Services
{
public class LoggingAgent
{
private readonly ILogger<LoggingAgent> logger;
private readonly RequestDelegate _next;

public LoggingAgent(RequestDelegate next, ILogger<LoggingAgent> logger)
{
_next = next;
this.logger = logger;
}

public async Task Invoke(HttpContext context)
{
try
{
if (!context.Request.Headers["User-Agent"].ToString().IsNullOrWhiteSpace())
{
logger.LogInformation(new EventDataItem(EventCodes.HttpUserAgent, null, context.Request.Headers["User-Agent"].ToString()));
}

if (!context.Request.Headers["Referrer"].ToString().IsNullOrWhiteSpace())
{
logger.LogInformation(new EventDataItem(EventCodes.HttpReferrer, null, context.Request.Headers["Referrer"].ToString()));
}

if (!context.Request.HttpContext.Connection.RemoteIpAddress.ToString().IsNullOrWhiteSpace())
{
logger.LogInformation(new EventDataItem(EventCodes.HttpReferrer, null, context.Request.HttpContext.Connection.RemoteIpAddress.ToString()));
}
}
catch (Exception ex)
{
logger.LogError(new EventDataItem(EventCodes.Error, null, string.Format("Logging Agent Exception:{0}", ex.Message)));
}

await _next.Invoke(context);
}
}

public static class MiddlewareExtensions
{
public static IApplicationBuilder UseLoggingAgent(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggingAgent>();
}
}


}
Loading

0 comments on commit 39852ba

Please sign in to comment.