forked from orcasound/aifororcas-livesystem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SendSubscriberEmail.cs
70 lines (62 loc) · 2.53 KB
/
SendSubscriberEmail.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Azure.Storage.Queue;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NotificationSystem.Template;
using NotificationSystem.Utilities;
using SendGrid.Helpers.Mail;
namespace NotificationSystem
{
[StorageAccount("OrcaNotificationStorageSetting")]
public static class SendSubscriberEmail
{
[FunctionName("SendSubscriberEmail")]
// TODO: change timer to once per hour (0 0 * * * *)
public static async Task Run(
[TimerTrigger("0 */1 * * * *")] TimerInfo myTimer,
[Queue("srkwfound")] CloudQueue cloudQueue,
[Table("EmailList")] CloudTable cloudTable,
[SendGrid(ApiKey = "SendGridKey")] IAsyncCollector<SendGridMessage> messageCollector,
ILogger log)
{
log.LogInformation("Checking if there are items in queue");
await cloudQueue.FetchAttributesAsync();
if (cloudQueue.ApproximateMessageCount == 0)
{
log.LogInformation("No items in queue");
return;
}
log.LogInformation("Creating email message");
var body = await CreateBody(cloudQueue);
log.LogInformation("Retrieving email list and sending notifications");
foreach (var emailEntity in EmailHelpers.GetEmailEntities(cloudTable, "Subscriber"))
{
var email = EmailHelpers.CreateEmail(Environment.GetEnvironmentVariable("SenderEmail"),
emailEntity.Email, "Notification: Orca detected!", body);
await messageCollector.AddAsync(email);
}
}
// TODO: make emails more pretty
public static async Task<string> CreateBody(CloudQueue cloudQueue)
{
var bodyBuilder = new StringBuilder("<h1>Confirmed SRKW detections:</h1>\n<ul>");
CloudQueueMessage message;
List<JObject> messagesJson = new List<JObject>();
while (true)
{
message = await cloudQueue.GetMessageAsync();
if (message == null)
break;
messagesJson.Add(JsonConvert.DeserializeObject<JObject>(message.AsString));
await cloudQueue.DeleteMessageAsync(message);
}
return EmailTemplate.GetSubscriberEmailBody(messagesJson);
}
}
}