-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathNotificationServices.cs
256 lines (221 loc) · 9.61 KB
/
NotificationServices.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ServiceStack;
using ServiceStack.Configuration;
using ServiceStack.DataAnnotations;
using ServiceStack.Logging;
using ServiceStack.OrmLite;
using ServiceStack.Templates;
using TechStacks.ServiceInterface.DataModel;
using TechStacks.ServiceInterface.Notifications;
using TechStacks.ServiceModel;
using TechStacks.ServiceModel.Types;
namespace TechStacks.ServiceInterface.Admin
{
[ExcludeMetadata]
[Route("/notifications/{Id}/send")]
public class SendNotification : IReturnVoid
{
public long Id { get; set; }
}
[ExcludeMetadata]
[Route("/email/system")]
public class SendSystemEmail : IReturnVoid
{
public string Subject { get; set; }
public string Body { get; set; }
}
[ExcludeMetadata]
[Route("/notifications/retry-pending")]
public class RetryPendingNotifications {}
public class RetryPendingNotificationsResponse
{
public long[] ResentIds { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
[RequiredRole("Admin")]
public partial class NotificationServices : Service
{
private static ILog log = LogManager.GetLogger(typeof(NotificationServices));
public EmailProvider Email { get; set; }
public IAppSettings AppSettings { get; set; }
public object Any(RetryPendingNotifications request)
{
var pendingNotificationIds = Db.Column<long>(Db.From<Notification>()
.Where(x => x.Completed == null && x.Failed == null)
.Select(x => x.Id))
.ToArray();
if (pendingNotificationIds.Length > 0)
{
log.Info($"Resending {pendingNotificationIds.Length} pending notifications: {pendingNotificationIds}");
foreach (var notificationId in pendingNotificationIds)
{
PublishMessage(new SendNotification { Id = notificationId });
}
}
return new RetryPendingNotificationsResponse {
ResentIds = pendingNotificationIds
};
}
Func<Notification, Task> GetEventHandler(string eventName)
{
switch (eventName)
{
case nameof(CreatePost):
return SendNewPostEmail;
case nameof(UserPostReport):
return SendReportPostEmail;
case nameof(UserPostCommentReport):
return SendReportCommentEmail;
}
return null;
}
public void Any(SendSystemEmail request)
{
Email.Send(new EmailMessage {
To = new MailTo {
Email = AppSettings.GetString("SystemToEmail"),
},
From = new MailTo {
Email = AppSettings.GetString("NotificationsFromEmail"),
},
Subject = $"[SYSTEM] {request.Subject}",
Body = request.Body,
});
}
public async Task Any(SendNotification request)
{
var notification = AssertNotification(request.Id);
var eventHandler = GetEventHandler(notification.Event);
if (eventHandler != null)
{
try
{
await eventHandler(notification);
await Db.UpdateOnlyAsync(() => new Notification {
Completed = DateTime.Now
},
where: x => x.Id == notification.Id);
}
catch (Exception ex)
{
await Db.UpdateOnlyAsync(() => new Notification {
Failed = DateTime.Now,
Error = ex.Message + Environment.NewLine + ex
},
where:x => x.Id == notification.Id);
throw;
}
}
else
{
log.Warn($"Received notification of unknown Event Type: {notification.Event}");
}
}
private async Task SendNewPostEmail(Notification notification)
{
EmailTemplate template = null;
if (notification.EmailTemplateId == null)
{
var post = await AssertPost(notification.RefId);
var org = await Db.SingleByIdAsync<Organization>(post.OrganizationId);
var user = await Db.SingleByIdAsync<CustomUserAuth>(post.UserId);
var q = Db.From<OrganizationSubscription>()
.Where(x => x.OrganizationId == post.OrganizationId)
.And("ARRAY[{0}] && post_types", post.Type)
.Select(x => x.UserId);
var postTypeSubscriberUserIds = await Db.ColumnAsync<int>(q);
var context = CreateEmailTemplateContext();
var templatePath = "emails/post-new";
var page = context.GetPage(templatePath);
var result = new PageResult(page) {
Args = {
["baseUrl"] = AppSettings.GetString("PublicBaseUrl"),
["post"] = post,
["organization"] = org,
}
};
template = await CreateAndSaveEmailTemplate(notification, nameof(SendNewPostEmail), templatePath,
toUserIds: postTypeSubscriberUserIds,
fromName: user.DisplayName ?? user.UserName,
ccName: org.Name + " Subscribed",
subject: $"[{post.Type}] {post.Title}",
html: await result.RenderToStringAsync());
}
else
{
template = await Db.SingleByIdAsync<EmailTemplate>(notification.EmailTemplateId);
}
await SendEmailsToRemainingUsers(notification, template);
}
async Task SendReportPostEmail(Notification notification)
{
EmailTemplate template = null;
if (notification.EmailTemplateId == null)
{
var report = await Db.SingleByIdAsync<PostReport>(notification.RefId);
var post = await AssertPost(report.PostId);
var org = await Db.SingleByIdAsync<Organization>(post.OrganizationId);
var moderatorUserIds = await GetOrganizationModeratorIds(org.Id);
var context = CreateEmailTemplateContext();
var templatePath = "emails/post-report";
var page = context.GetPage(templatePath);
var result = new PageResult(page) {
Args = {
["baseUrl"] = AppSettings.GetString("PublicBaseUrl"),
["report"] = report,
["post"] = post,
["organization"] = org,
}
};
var reportType = report.FlagType == FlagType.Other ? "Report" : report.FlagType.ToString();
template = await CreateAndSaveEmailTemplate(notification, nameof(SendReportPostEmail), templatePath,
toUserIds: moderatorUserIds,
fromName: report.UserName,
ccName: org.Name + " Moderators",
subject: $"[{reportType}] {post.Title}",
html: await result.RenderToStringAsync());
}
else
{
template = await Db.SingleByIdAsync<EmailTemplate>(notification.EmailTemplateId);
}
await SendEmailsToRemainingUsers(notification, template);
}
async Task SendReportCommentEmail(Notification notification)
{
EmailTemplate template = null;
if (notification.EmailTemplateId == null)
{
var report = await Db.SingleByIdAsync<PostCommentReport>(notification.RefId);
var comment = await Db.SingleByIdAsync<PostComment>(report.PostCommentId);
var org = await Db.SingleByIdAsync<Organization>(report.OrganizationId);
var moderatorUserIds = await GetOrganizationModeratorIds(org.Id);
var context = CreateEmailTemplateContext();
var templatePath = "emails/comment-report";
var page = context.GetPage(templatePath);
var result = new PageResult(page) {
Args = {
["baseUrl"] = AppSettings.GetString("PublicBaseUrl"),
["report"] = report,
["comment"] = comment,
["organization"] = org,
}
};
var reportType = report.FlagType == FlagType.Other ? "Report" : report.FlagType.ToString();
template = await CreateAndSaveEmailTemplate(notification, nameof(SendReportPostEmail), templatePath,
toUserIds: moderatorUserIds,
fromName: report.UserName,
ccName: org.Name + " Moderators",
subject: $"[{reportType}] Comment",
html: await result.RenderToStringAsync());
}
else
{
template = await Db.SingleByIdAsync<EmailTemplate>(notification.EmailTemplateId);
}
await SendEmailsToRemainingUsers(notification, template);
}
}
}