-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmailNotifier.cs
392 lines (345 loc) · 14.7 KB
/
EmailNotifier.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Streamer.bot.Plugin.Interface;
using Microsoft.Toolkit.Uwp.Notifications;
using System.Text;
using System.Windows;
using System.Drawing.Imaging;
using System.Windows.Threading;
using Newtonsoft.Json;
namespace EmailBot
{
public class EmailNotifier : IDisposable
{
private static readonly string[] Scopes = { GmailService.Scope.GmailReadonly };
private readonly string LogoPath;
internal readonly IInlineInvokeProxy BotProxy;
private GmailService EmailService;
private readonly HashSet<string> PastIds = new HashSet<string>();
private long? NotBefore = null;
private Timer PollerTimer = null;
private bool Paused = false;
private Application App;
private Dispatcher UiDispatch;
internal readonly EmailConfig Config;
public EmailNotifier(IInlineInvokeProxy botProxy)
{
BotProxy = botProxy;
BotProxy.LogDebug("[Email.bot] Email Notifier started. Loading config...");
Config = EmailConfig.Load(botProxy);
BotProxy.LogDebug("[Email.bot] Config loaded.");
BotProxy.RegisterCustomTrigger("New email received", "NewEmailReceived", new string[] { "Email" });
// Extract Logo
LogoPath = Path.GetTempPath() + "EmailBot_GLogo.png";
Resources.GmailLogo.Save(LogoPath, ImageFormat.Png);
// UI Management
AppContext.SetSwitch("Switch.System.Windows.Input.Stylus.DisableStylusAndTouchSupport", true); // This prevents a nasty bug (hanging thread on AppDomain unload)
var handle = new AutoResetEvent(false);
var uiThread = new System.Threading.Thread(() => {
UiDispatch = Dispatcher.CurrentDispatcher;
UiDispatch.Invoke(() =>
{
App = new Application()
{
ShutdownMode = ShutdownMode.OnExplicitShutdown
};
handle.Set();
App.Run();
});
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
handle.WaitOne();
// Start Service
Initialize().Wait();
}
public void Dispose()
{
UiDispatch?.Invoke(() => {
App?.Shutdown();
App = null;
});
}
~EmailNotifier()
{
StopPoller();
EmailService = null;
Config?.Persist();
BotProxy?.LogDebug("[Email.bot] Module is shuting down, notifications are interrupted.");
}
protected async Task<bool> Initialize()
{
try
{
if (Config.GoogleCredentials == null || Config.GoogleCredentials == "")
await OpenConfigEditor();
if (Config.GoogleCredentials == null || Config.GoogleCredentials == "")
{
MessageBox.Show("You must have valid API credentials to use this module.", "Gmail - Missing credentials");
return false;
}
await Authenticate();
return true;
}
catch (Exception e)
{
BotProxy.LogDebug("[Email.bot] Module initialization failed : " + e);
MessageBox.Show(e.Message, "Email.bot - Init failed");
return false;
}
}
internal async Task Authenticate()
{
try
{
UserCredential credential;
using (var stream = new MemoryStream(Encoding.Default.GetBytes(Config.GoogleCredentials)))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new GmailDataStore(BotProxy));
}
BotProxy.LogDebug("[Email.bot] Authentication successful.");
EmailService = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Email plugin for Streamer.bot"
});
}
catch
{
EmailService = null;
}
}
public async void Configure()
{
await OpenConfigEditor();
if (PollerTimer != null)
{
PollerTimer.Dispose();
PollerTimer = null;
Paused = false;
}
if(await Initialize())
StartPoller();
}
protected async Task OpenConfigEditor()
{
await Task.Run(() => {
UiDispatch.Invoke(() => {
var config = new EmailConfigWindow(this);
config.ShowDialog();
Config.Persist();
});
});
}
public void StartPoller()
{
if(EmailService == null || PollerTimer != null)
{
return;
}
try
{
if (!Paused)
{
NotBefore = DateTimeOffset.Now.ToUnixTimeMilliseconds();
var messages = ListEmails();
if (messages != null)
{
foreach (var message in messages)
{
PastIds.Add(message.Id);
}
}
}
}
catch (Exception e)
{
BotProxy.LogDebug("[Email.bot] Unable to prefetch existing matching emails : " + e);
}
try
{
var delay = Config.PollerInterval;
PollerTimer = new Timer(CheckEmails, null, TimeSpan.FromSeconds(delay), TimeSpan.FromSeconds(delay));
BotProxy.LogDebug($"[Email.bot] Poller enabled. Polling every {delay} seconds.");
new ToastContentBuilder()
.AddText("Gmail - Notifications enabled")
.AddText($"Checking for new emails every {delay} seconds.")
.AddAppLogoOverride(new Uri(LogoPath))
.SetToastDuration(ToastDuration.Short)
.Show();
}
catch(Exception e)
{
BotProxy.LogDebug("[Email.bot] Unable to start the poller : " + e);
}
}
public void StopPoller(bool pause = false)
{
if(PollerTimer != null)
{
PollerTimer.Dispose();
PollerTimer = null;
Paused = pause;
BotProxy.LogDebug("[Email.bot] Poller stopped.");
new ToastContentBuilder()
.AddText("Gmail - Notifications " + (pause ? "ON HOLD" : "DISABLED"))
.AddText("No new notification will be received.")
.AddAppLogoOverride(new Uri(LogoPath))
.SetToastDuration(ToastDuration.Short)
.Show();
}
}
public void FetchEmailBody(string messageId, bool asHtml = false)
{
try
{
Message email = EmailService.Users.Messages.Get("me", messageId).Execute();
// Check Body for non-multipart content
var bodyPart = email.Payload.Body;
// Body can be provided as an attachment, so check that first
if (bodyPart?.AttachmentId != null && bodyPart?.AttachmentId != string.Empty)
bodyPart = EmailService.Users.Messages.Attachments.Get("me", messageId, bodyPart.AttachmentId).Execute();
// If the body is clear, decode it and we're done
string body = bodyPart.Data?.DecodeBase64Url();
if (body != null && body != string.Empty)
{
var payloadContentTypeL = from header in email.Payload.Headers
where header.Name.ToLower() == "content-type" && (header.Value.StartsWith("text/html") || header.Value.StartsWith("text/plain"))
select (IsHtml: header.Value.StartsWith("text/html"), Body: bodyPart.Data.DecodeBase64Url());
// If Content-Type is "text/html" or "text/plain", we should have exactly 1 result.
if (payloadContentTypeL.Count() > 0)
{
var contentType = payloadContentTypeL.First();
if(!(contentType.IsHtml ^ asHtml))
{
BotProxy.SetArgument("emailBody", contentType.Body);
}
return;
}
// Or we'll try our luck elsewhere
}
if (email.Payload.Parts.Count > 0)
{
var parts = from emailPart in email.Payload.Parts
from header in emailPart.Headers
where header.Name.ToLower() == "content-type" && (header.Value.StartsWith("text/html") || header.Value.StartsWith("text/plain"))
select (IsHtml: header.Value.StartsWith("text/html"), emailPart.Body);
foreach (var (IsHtml, Body) in parts)
{
bodyPart = Body;
if (!(IsHtml ^ asHtml))
{
// Part body can be provided as an attachment, so check that first
if (bodyPart.AttachmentId != null && bodyPart.AttachmentId != string.Empty)
bodyPart = EmailService.Users.Messages.Attachments.Get("me", messageId, bodyPart.AttachmentId).Execute();
if(bodyPart.Data != null && bodyPart.Data != string.Empty)
{
BotProxy.SetArgument("emailBody", bodyPart.Data.DecodeBase64Url());
return;
}
}
}
}
} catch (Exception e) {
BotProxy.LogDebug("[Email.bot] Failed to fetch email body : " + e);
}
}
private void CheckEmails(object state)
{
BotProxy.LogVerbose("[Email.bot] Checking emails ...");
IList<Message> messages = ListEmails();
long latestDate = NotBefore.GetValueOrDefault(0);
if (messages != null)
{
foreach (Message message in messages)
{
try
{
Message email = EmailService.Users.Messages.Get("me", message.Id).Execute();
if (!PastIds.Contains(email.Id))
{
try
{
if(email.InternalDate != null)
{
if (email.InternalDate < NotBefore)
continue;
latestDate = Math.Max(email.InternalDate.GetValueOrDefault(0), latestDate);
}
BotProxy.LogDebug("[Email.bot] New email found Id=" + email.Id + " InternalDate=" + email.InternalDate);
BotProxy.TriggerCodeEvent("NewEmailReceived", new Dictionary<string, object>() {
{ "emailId", email.Id },
{ "emailDate", DateTimeOffset.FromUnixTimeMilliseconds(email.InternalDate.GetValueOrDefault(DateTimeOffset.Now.ToUnixTimeMilliseconds())).DateTime },
{ "emailFrom", (from header in email.Payload.Headers where header.Name.ToLower() == "from" select header.Value).FirstOrDefault() },
{ "emailSubject", (from header in email.Payload.Headers where header.Name.ToLower() == "subject" select header.Value).FirstOrDefault() }
});
PastIds.Add(email.Id);
}
catch (Exception e)
{
BotProxy.LogDebug("[Email.bot] Unable to read email data : " + e);
}
}
}
catch (Exception e)
{
BotProxy.LogDebug("[Email.bot] Unable to read emails from Gmail : " + e);
}
}
NotBefore = latestDate;
}
}
private IList<Message> ListEmails()
{
try
{
UsersResource.MessagesResource.ListRequest request = EmailService.Users.Messages.List("me");
request.LabelIds = Config.GmailLabel;
request.Q = Config.GmailQueryFilter;
request.MaxResults = 20;
ListMessagesResponse response = request.Execute();
return response.Messages;
}
catch(Exception e)
{
BotProxy.LogDebug("[Email.bot] An error occured while fetching emails : " + e);
}
return null;
}
}
internal class EmailConfig
{
[JsonIgnore]
private IInlineInvokeProxy BotProxy;
public string GoogleCredentials { get; set; }
public string GmailLabel { get; set; } = "INBOX";
public string GmailQueryFilter { get; set; } = "is:unread";
public int PollerInterval { get; set; } = 60;
public static EmailConfig Load(IInlineInvokeProxy botProxy)
{
var data = botProxy.GetGlobalVar<string>("EmailBotConfig");
var config = data?.ToUnprotectedObject<EmailConfig>();
if (config == null)
config = new EmailConfig();
config.BotProxy = botProxy;
return config;
}
public void Persist()
{
BotProxy.SetGlobalVar("EmailBotConfig", this.ToProtectedData());
}
}
}