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
|
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
|
-
-
+
+
-
+
+
+
+
+
+
-
+
|
{
GithubFlavored = true,
RemoveComments = false,
SmartHrefHandling = true,
TableWithoutHeaderRowHandling = ReverseMarkdown.Config.TableWithoutHeaderRowHandlingOption.Default,
UnknownTags = ReverseMarkdown.Config.UnknownTagsOption.Bypass,
};
private Dictionary<(string, bool), long> _keywords;
private Dictionary<string, long> _participants;
private Dictionary<(string, bool), long> _keywords = new Dictionary<(string, bool), long>();
private Dictionary<string, long> _participants = new Dictionary<string, long>();
private int _totalCountAllFolders;
private int _countAllFolders;
private DateTime _startAccount;
private bool _haveDeleted = false;
public MailSynchronizer(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
}
public async Task SynchronizeAccount(string host, short port, NetworkCredential credentials,
Func<IMailFolder,bool> folderFilter = null,
Func<IMailFolder,bool>? folderFilter = null,
bool vacuumDatabase = false)
{
if (credentials is null)
{
throw new ArgumentNullException(nameof(credentials));
}
Account account;
using (var work = new UnitOfWork(_cancellationToken))
{
account = await work.Accounts.GetOrCreateAsync(host, port, credentials.UserName);
_participants = await work.Participants.GetDictionaryAsync(p => p.Address ?? p.Name, p => p.ID, StringComparer.InvariantCultureIgnoreCase);
_participants = await work.Participants.GetDictionaryAsync(p => p.Address ?? p.Name ?? "", p => p.ID, StringComparer.InvariantCultureIgnoreCase);
_keywords = await work.Keywords.GetDictionaryAsync(kw => (kw.Name, kw.IsLabel), kw => kw.ID, KeywordEqualityComparer.InvariantCultureIgnoreCase);
}
using (var client = new MailKit.Net.Imap.ImapClient())
{
Con.WriteLine("Connecting to server...", TraceLevel.Verbose);
await client.ConnectAsync(host, port, true, _cancellationToken);
|
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
|
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
|
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
-
-
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
-
-
+
+
-
-
+
+
-
-
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
-
+
-
+
|
}
}
}
private async Task SynchronizeMessage(IMessageSummary summary, IMailFolder mailFolder,
long folderID, long? folderMsgID, long? messageID)
{
using (var work = new UnitOfWork(_cancellationToken))
using var work = new UnitOfWork(_cancellationToken);
{
try
{
// Deleted message: don't download it; delete it from the database instead
if (summary.Flags.Value.HasFlag(MessageFlags.Deleted))
{
if (folderMsgID != null)
{
work.FolderMessages.DeleteByID(folderMsgID.Value);
await work.SaveChangesAsync();
_haveDeleted = true;
}
return;
}
try
{
// Deleted message: don't download it; delete it from the database instead
if (summary.Flags.Value.HasFlag(MessageFlags.Deleted))
{
if (folderMsgID != null)
{
work.FolderMessages.DeleteByID(folderMsgID.Value);
await work.SaveChangesAsync();
_haveDeleted = true;
}
return;
}
// Otherwise, check out the existing message
Message dbMessage = null;
if (messageID != null)
{
dbMessage = await work.Messages.GetByIdAsync(messageID.Value);
}
FolderMessage folderMessage = null;
if (folderMsgID == null
&& dbMessage != null
&& summary.Flags == dbMessage.Flags
&& summary.InternalDate == dbMessage.DateReceived
&& string.Join(", ", summary.Keywords) == dbMessage.Keywords)
{
folderMessage = new FolderMessage
{
FolderID = folderID,
UniqueId = summary.UniqueId,
Message = dbMessage,
};
await work.FolderMessages.AddAsync(folderMessage);
}
else if (dbMessage == null
|| summary.Flags != dbMessage.Flags
|| summary.InternalDate != dbMessage.DateReceived
|| string.Join(", ", summary.Keywords) != dbMessage.Keywords)
{
MimeMessage mailMessage = await GetMailMessageAsync(summary, mailFolder);
// save message to database
if (folderMsgID != null)
{
folderMessage = await work.DB.FolderMessages
.Where(fm => fm.ID == folderMsgID)
.Include(fm => fm.Message)
.ThenInclude(m => m.Participants)
.SingleOrDefaultAsync(_cancellationToken);
}
if (folderMessage == null)
{
folderMessage = new FolderMessage
{
FolderID = folderID,
UniqueId = summary.UniqueId,
Message = dbMessage ?? new Message
{
Participants = new List<MessageParticipant>(),
},
};
await work.FolderMessages.AddAsync(folderMessage);
}
dbMessage = folderMessage.Message;
dbMessage.GlobalID = summary.GMailMessageId;
dbMessage.DateRetrievedUTC = DateTime.UtcNow;
dbMessage.Flags = summary.Flags ?? MessageFlags.None;
dbMessage.DateReceived = summary.InternalDate;
TimerCollection.Global.Start("PopulateMessageAsync");
try
{
await PopulateMessageAsync(dbMessage, mailMessage, summary.Keywords);
}
finally
{
TimerCollection.Global.Stop("PopulateMessageAsync");
}
// Otherwise, check out the existing message
Message? dbMessage = null;
if (messageID != null)
{
dbMessage = await work.Messages.GetByIdAsync(messageID.Value);
}
FolderMessage? folderMessage = null;
if (folderMsgID == null
&& dbMessage != null
&& summary.Flags == dbMessage.Flags
&& summary.InternalDate == dbMessage.DateReceived
&& string.Join(", ", summary.Keywords) == dbMessage.Keywords)
{
folderMessage = new FolderMessage
{
FolderID = folderID,
UID = summary.UniqueId.Id,
Message = dbMessage,
};
await work.FolderMessages.AddAsync(folderMessage);
}
else if (dbMessage == null
|| summary.Flags != dbMessage.Flags
|| summary.InternalDate != dbMessage.DateReceived
|| string.Join(", ", summary.Keywords) != dbMessage.Keywords)
{
MimeMessage mailMessage = await GetMailMessageAsync(summary, mailFolder);
// save message to database
if (folderMsgID != null)
{
folderMessage = await work.DB.FolderMessages
.Where(fm => fm.ID == folderMsgID)
.Include(fm => fm.Message)
.ThenInclude(m => m.Participants)
.SingleOrDefaultAsync(_cancellationToken);
}
if (folderMessage == null)
{
folderMessage = new FolderMessage
{
FolderID = folderID,
UID = summary.UniqueId.Id,
Message = dbMessage ?? new Message
{
Participants = new List<MessageParticipant>(),
},
};
await work.FolderMessages.AddAsync(folderMessage);
}
dbMessage = folderMessage.Message;
dbMessage.GlobalID = summary.GMailMessageId;
dbMessage.DateRetrievedUTC = DateTime.UtcNow;
dbMessage.Flags = summary.Flags ?? MessageFlags.None;
dbMessage.DateReceived = summary.InternalDate;
TimerCollection.Global.Start("PopulateMessageAsync");
try
{
await PopulateMessageAsync(dbMessage, mailMessage, summary.Keywords);
}
finally
{
TimerCollection.Global.Stop("PopulateMessageAsync");
}
// Store all separate entities contained in the mail message
TimerCollection.Global.Start("PopulateParticipants");
await PopulateParticipantsAsync(work, dbMessage, mailMessage); // from headers
TimerCollection.Global.Stop("PopulateParticipants");
TimerCollection.Global.Start("PopulateKeywords");
await PopulateKeywordsAsync(work, dbMessage, summary.Keywords, summary.GMailLabels); // from summary
TimerCollection.Global.Stop("PopulateKeywords");
TimerCollection.Global.Start("PopulateReferences");
await PopulateReferencesAsync(work, dbMessage, mailMessage); // from summary + headers
TimerCollection.Global.Stop("PopulateReferences");
}
await work.SaveChangesAsync();
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
// Store all separate entities contained in the mail message
TimerCollection.Global.Start("PopulateParticipants");
await PopulateParticipantsAsync(work, dbMessage, mailMessage); // from headers
TimerCollection.Global.Stop("PopulateParticipants");
TimerCollection.Global.Start("PopulateKeywords");
await PopulateKeywordsAsync(work, dbMessage, summary.Keywords, summary.GMailLabels); // from summary
TimerCollection.Global.Stop("PopulateKeywords");
TimerCollection.Global.Start("PopulateReferences");
await PopulateReferencesAsync(work, dbMessage, mailMessage); // from summary + headers
TimerCollection.Global.Stop("PopulateReferences");
}
await work.SaveChangesAsync();
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
}
}
}
private async Task<MimeMessage> GetMailMessageAsync(IMessageSummary summary, IMailFolder mailFolder)
{
MimeMessage mailMessage;
try
{
TimerCollection.Global.Start("mailFolder.GetMessageAsync");
try {
mailMessage = await mailFolder.GetMessageAsync(summary.UniqueId, _cancellationToken);
} finally {
TimerCollection.Global.Stop("mailFolder.GetMessageAsync");
}
}
catch (FormatException)
{
var mailEncoding = Encoding.GetEncoding("ISO-8859-1");
// Upon failure to parse the message, try to download the entire message stream
using (Stream mailStream = await mailFolder.GetStreamAsync(summary.UniqueId, 0, (int)summary.Size.Value, _cancellationToken))
using (StreamReader reader = new StreamReader(mailStream, mailEncoding, true))
using Stream mailStream = await mailFolder.GetStreamAsync(summary.UniqueId, 0, (int)summary.Size.Value, _cancellationToken);
using StreamReader reader = new StreamReader(mailStream, mailEncoding, true);
{
using (var fs = new FileStream($"{summary.GMailMessageId}.eml", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
await mailStream.CopyToAsync(fs, _cancellationToken);
mailStream.Position = 0;
}
// Now, attempt to fix the mail message, by skipping lines until one doesn't start with a spacing character
var sbSource = new StringBuilder((int)mailStream.Length);
while (!reader.EndOfStream)
{
string line = await reader.ReadLineAsync();
if (line.Length == 0 || !char.IsWhiteSpace(line[0]))
{
sbSource.Append(line);
sbSource.Append("\r\n");
sbSource.Append(await reader.ReadToEndAsync());
}
}
using (var fixedStream = new MemoryStream((int)mailStream.Length))
using (var fs = new FileStream($"{summary.GMailMessageId}.eml", FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
{
await mailStream.CopyToAsync(fs, _cancellationToken);
mailStream.Position = 0;
}
// Now, attempt to fix the mail message, by skipping lines until one doesn't start with a spacing character
var sbSource = new StringBuilder((int)mailStream.Length);
while (!reader.EndOfStream)
{
string line = await reader.ReadLineAsync() ?? "";
if (line.Length == 0 || !char.IsWhiteSpace(line[0]))
{
sbSource.Append(line);
sbSource.Append("\r\n");
sbSource.Append(await reader.ReadToEndAsync());
}
}
using var fixedStream = new MemoryStream((int)mailStream.Length);
{
await fixedStream.WriteAsync(reader.CurrentEncoding.GetBytes(sbSource.ToString()), _cancellationToken);
fixedStream.Position = 0;
var options = new ParserOptions
{
AddressParserComplianceMode = RfcComplianceMode.Loose,
AllowAddressesWithoutDomain = true,
AllowUnquotedCommasInAddresses = false,
CharsetEncoding = mailEncoding,
MaxAddressGroupDepth = 3,
ParameterComplianceMode = RfcComplianceMode.Loose,
RespectContentLength = true,
Rfc2047ComplianceMode = RfcComplianceMode.Loose,
};
mailMessage = await MimeMessage.LoadAsync(options, fixedStream, _cancellationToken);
await fixedStream.WriteAsync(reader.CurrentEncoding.GetBytes(sbSource.ToString()), _cancellationToken);
fixedStream.Position = 0;
var options = new ParserOptions
{
AddressParserComplianceMode = RfcComplianceMode.Loose,
AllowAddressesWithoutDomain = true,
AllowUnquotedCommasInAddresses = false,
CharsetEncoding = mailEncoding,
MaxAddressGroupDepth = 3,
ParameterComplianceMode = RfcComplianceMode.Loose,
RespectContentLength = true,
Rfc2047ComplianceMode = RfcComplianceMode.Loose,
};
mailMessage = await MimeMessage.LoadAsync(options, fixedStream, _cancellationToken);
}
}
}
return mailMessage;
}
public async Task ClearUnunsedObjectsAsync(bool vacuumDatabase = false)
{
using (var work = new UnitOfWork(_cancellationToken))
using var work = new UnitOfWork(_cancellationToken);
{
await Con.WriteLineAsync("Cleaning up database...", TraceLevel.Verbose);
await Con.WriteLineAsync("Cleaning up database...", TraceLevel.Verbose);
// Delete any messages not linked to a folder
work.Messages.DeleteByIDs(m => !m.Folders.Any(), m => m.ID);
int numDeleted = await work.SaveChangesAsync();
// Delete any messages not linked to a folder
work.Messages.DeleteByIDs(m => !m.Folders.Any(), m => m.ID);
int numDeleted = await work.SaveChangesAsync();
// Delete any participants not linked to a message
work.Participants.DeleteByIDs(p => !p.Messages.Any(), p => p.ID);
numDeleted += await work.SaveChangesAsync();
// Delete any participants not linked to a message
work.Participants.DeleteByIDs(p => !p.Messages.Any(), p => p.ID);
numDeleted += await work.SaveChangesAsync();
if (vacuumDatabase && (_haveDeleted || numDeleted > 0))
{
await work.DB.Database.ExecuteSqlCommandAsync("VACUUM", _cancellationToken);
if (vacuumDatabase && (_haveDeleted || numDeleted > 0))
{
await work.DB.Database.ExecuteSqlRawAsync("VACUUM", _cancellationToken);
}
}
}
private async Task PopulateMessageAsync(Message targetMsg, MimeMessage sourceMsg, IEnumerable<string> keywords)
{
try
{
targetMsg.RfcMessageID = sourceMsg.ResentMessageId ?? sourceMsg.MessageId; // TODO: reverse these?
targetMsg.Subject = sourceMsg.Subject;
targetMsg.Date = sourceMsg.Date;
targetMsg.From = new InternetAddressList(sourceMsg.From.Concat(sourceMsg.ResentFrom)).ToString();
targetMsg.To = new InternetAddressList(sourceMsg.To.Concat(sourceMsg.ResentTo)).ToString();
targetMsg.Cc = new InternetAddressList(sourceMsg.Cc.Concat(sourceMsg.ResentCc)).ToString();
targetMsg.Bcc = new InternetAddressList(sourceMsg.Bcc.Concat(sourceMsg.ResentBcc)).ToString();
targetMsg.Keywords = string.Join(", ", keywords);
targetMsg.RfcMessageID = sourceMsg.ResentMessageId ?? sourceMsg.MessageId; // TODO: reverse these?
targetMsg.Subject = sourceMsg.Subject;
targetMsg.Date = sourceMsg.Date;
targetMsg.From = new InternetAddressList(sourceMsg.From.Concat(sourceMsg.ResentFrom)).ToString();
targetMsg.To = new InternetAddressList(sourceMsg.To.Concat(sourceMsg.ResentTo)).ToString();
targetMsg.Cc = new InternetAddressList(sourceMsg.Cc.Concat(sourceMsg.ResentCc)).ToString();
targetMsg.Bcc = new InternetAddressList(sourceMsg.Bcc.Concat(sourceMsg.ResentBcc)).ToString();
targetMsg.Keywords = string.Join(", ", keywords);
// TODO: only do this if we've downloaded more than just the headers
// store text (if present) and ALSO extract text from HTML (if present); they might not contain the same text.
TimerCollection.Global.Start("ExtractBodyText");
try {
targetMsg.Body = await ExtractBodyText(sourceMsg);
} finally {
TimerCollection.Global.Stop("ExtractBodyText");
}
// TODO: only do this if we've downloaded more than just the headers
// store text (if present) and ALSO extract text from HTML (if present); they might not contain the same text.
TimerCollection.Global.Start("ExtractBodyText");
try {
targetMsg.Body = await ExtractBodyText(sourceMsg);
} finally {
TimerCollection.Global.Stop("ExtractBodyText");
}
if (sourceMsg.Attachments.Any())
{
targetMsg.AttachmentSummary = string.Join(Environment.NewLine,
sourceMsg.Attachments.Select((a, i) => $"{i + 1}. {(a is MimePart part ? part.FileName : null)} [{a.ContentType.MimeType}] " + a.Headers[HeaderId.ContentDescription]));
}
else
{
targetMsg.AttachmentSummary = null;
}
if (sourceMsg.Attachments.Any())
{
targetMsg.AttachmentSummary = string.Join(Environment.NewLine,
sourceMsg.Attachments.Select((a, i) => $"{i + 1}. {(a is MimePart part ? part.FileName : null)} [{a.ContentType.MimeType}] " + a.Headers[HeaderId.ContentDescription]));
}
else
{
targetMsg.AttachmentSummary = null;
}
TimerCollection.Global.Start("ZipArchive");
using (var zipStream = new MemoryStream())
TimerCollection.Global.Start("ZipArchive");
using var zipStream = new MemoryStream();
{
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Update))
{
string filename = CreateMessageFilename(sourceMsg);
var entry = zip.CreateEntry(filename, CompressionLevel.Optimal);
try
{
entry.LastWriteTime = sourceMsg.Date;
}
catch {
catch
{
// ignore errors; just use today's date instead
}
using (var compressedStream = entry.Open())
await sourceMsg.WriteToAsync(compressedStream);
using var compressedStream = entry.Open();
await sourceMsg.WriteToAsync(compressedStream);
}
targetMsg.Original = zipStream.ToArray();
}
TimerCollection.Global.Stop("ZipArchive");
// TODO: skip the above if we only have the headers
TimerCollection.Global.Stop("ZipArchive");
// TODO: skip the above if we only have the headers
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
}
} // PopulateMessageAsync
private static string CreateMessageFilename(MimeMessage sourceMsg, string extension = ".eml")
{
string subject = MakeSafe(sourceMsg.Subject);
string? subject = MakeSafe(sourceMsg.Subject);
InternetAddress sender = sourceMsg.From.FirstOrDefault();
string senderName = MakeSafe(sender?.Name ?? sender?.ToString());
string? senderName = MakeSafe(sender?.Name ?? sender?.ToString());
string fileName = $"{subject}{(subject != null && senderName != null ? " - " : "")}{senderName}";
// If there's nothing left, just use a default name
if (fileName.Length <= 3)
return "message" + extension;
else if (fileName.Length > 250)
return MakeSafe(fileName.Substring(0, 250)) + extension;
else
return fileName + extension;
}
private static readonly char[] _forbiddenChars = new char[] { '<', '>', '|', '?', '*', ':', '/', '\\', '"' };
private static readonly UnicodeCategory[] _spacingCategories = new UnicodeCategory[]
{
UnicodeCategory.LineSeparator,
UnicodeCategory.ParagraphSeparator,
UnicodeCategory.SpaceSeparator,
};
private static string MakeSafe(string text)
private static string? MakeSafe(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return null;
// First, trim spaces and strip all diacritics; replace all spacing by a normal space
char[] chars = text.Trim().Normalize(NormalizationForm.FormD)
.Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
.Select(c => _spacingCategories.Contains(CharUnicodeInfo.GetUnicodeCategory(c)) ? ' ' : c)
.ToArray();
// Then, get rid of all remaining non-ascii characters (will get converted to '?')
var ascii = Encoding.ASCII;
chars = ascii.GetChars(ascii.GetBytes(chars));
// Finally remove all forbidden characters from the file name (including '?')
return new string(chars.Where(c => c >= ' ' && !_forbiddenChars.Contains(c)).ToArray())
.Normalize(NormalizationForm.FormC)
.Trim();
}
private async Task<string> ExtractBodyText(MimeMessage sourceMsg)
private async Task<string?> ExtractBodyText(MimeMessage sourceMsg)
{
string bodyText = sourceMsg.TextBody?.Trim();
string? bodyText = sourceMsg.TextBody?.Trim();
if (sourceMsg.HtmlBody != null)
{
if (bodyText != null)
bodyText += Environment.NewLine + Environment.NewLine;
else
bodyText = "";
var errors = new List<Exception>();
|
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
|
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
|
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
-
-
+
-
+
|
}
}
return bodyText;
}
private async Task PopulateParticipantsAsync(UnitOfWork work, Message targetMsg, MimeMessage sourceMsg)
{
try
{
var participantList = new List<(ParticipantField Field, string Address, string Name)>();
GatherParticipants(ref participantList, sourceMsg.From, ParticipantField.From);
GatherParticipants(ref participantList, sourceMsg.To, ParticipantField.To);
GatherParticipants(ref participantList, sourceMsg.Cc, ParticipantField.Cc);
GatherParticipants(ref participantList, sourceMsg.Bcc, ParticipantField.Bcc);
GatherParticipants(ref participantList, sourceMsg.ReplyTo, ParticipantField.ReplyTo);
GatherParticipants(ref participantList, sourceMsg.Sender, ParticipantField.Sender);
GatherParticipants(ref participantList, sourceMsg.ResentFrom, ParticipantField.ResentFrom);
GatherParticipants(ref participantList, sourceMsg.ResentTo, ParticipantField.ResentTo);
GatherParticipants(ref participantList, sourceMsg.ResentCc, ParticipantField.ResentCc);
GatherParticipants(ref participantList, sourceMsg.ResentBcc, ParticipantField.ResentBcc);
GatherParticipants(ref participantList, sourceMsg.ResentReplyTo, ParticipantField.ResentReplyTo);
GatherParticipants(ref participantList, sourceMsg.ResentSender, ParticipantField.ResentSender);
var participantList = new List<(ParticipantField Field, string? Address, string Name)>();
GatherParticipants(ref participantList, sourceMsg.From, ParticipantField.From);
GatherParticipants(ref participantList, sourceMsg.To, ParticipantField.To);
GatherParticipants(ref participantList, sourceMsg.Cc, ParticipantField.Cc);
GatherParticipants(ref participantList, sourceMsg.Bcc, ParticipantField.Bcc);
GatherParticipants(ref participantList, sourceMsg.ReplyTo, ParticipantField.ReplyTo);
GatherParticipants(ref participantList, sourceMsg.Sender, ParticipantField.Sender);
GatherParticipants(ref participantList, sourceMsg.ResentFrom, ParticipantField.ResentFrom);
GatherParticipants(ref participantList, sourceMsg.ResentTo, ParticipantField.ResentTo);
GatherParticipants(ref participantList, sourceMsg.ResentCc, ParticipantField.ResentCc);
GatherParticipants(ref participantList, sourceMsg.ResentBcc, ParticipantField.ResentBcc);
GatherParticipants(ref participantList, sourceMsg.ResentReplyTo, ParticipantField.ResentReplyTo);
GatherParticipants(ref participantList, sourceMsg.ResentSender, ParticipantField.ResentSender);
int order = 0;
foreach (var (field, mailAddress, mailName) in participantList)
{
string address = mailAddress == "" ? null : mailAddress;
string name = mailName == "" ? null : mailName;
if (name != null && name.Trim(' ', '\'', '"', '<', '>', '(', ')') == address)
name = null;
int order = 0;
foreach (var (field, mailAddress, mailName) in participantList)
{
string? address = mailAddress == "" ? null : mailAddress;
string? name = mailName == "" ? null : mailName;
if (name != null && name.Trim(' ', '\'', '"', '<', '>', '(', ')') == address)
name = null;
var msgParticipant = new MessageParticipant
{
Message = targetMsg,
Field = field,
Order = ++order,
Name = name,
};
var msgParticipant = new MessageParticipant
{
Message = targetMsg,
Field = field,
Order = ++order,
Name = name,
};
var key = address ?? name;
if (_participants.TryGetValue(key, out long participantID))
{
msgParticipant.ParticipantID = participantID;
/* TODO: when cleaning up the database? Put the most used name for this address in the participant.
UPDATE Participants p
SET Name = (SELECT mp.Name
FROM MessageParticipants mp
WHERE ParticipantID = p.ID
AND mp.Name IS NOT NULL
GROUP BY mp.Name
ORDER BY count(*) DESC
, ID ASC
LIMIT 1)
WHERE p.ID IN ({string.Join(', ', participantIDs)});
*/
}
else
{
var participant = new Participant
{
Address = address,
Name = name,
};
await work.Participants.AddAsync(participant);
// We only know the IDs after saving the entities
await work.SaveChangesAsync();
_participants.TryAdd(key, participant.ID);
string key = address ?? name ?? "";
if (_participants.TryGetValue(key, out long participantID))
{
msgParticipant.ParticipantID = participantID;
/* TODO: when cleaning up the database? Put the most used name for this address in the participant.
UPDATE Participants p
SET Name = (SELECT mp.Name
FROM MessageParticipants mp
WHERE ParticipantID = p.ID
AND mp.Name IS NOT NULL
GROUP BY mp.Name
ORDER BY count(*) DESC
, ID ASC
LIMIT 1)
WHERE p.ID IN ({string.Join(', ', participantIDs)});
*/
}
else
{
var participant = new Participant
{
Address = address,
Name = name,
};
await work.Participants.AddAsync(participant);
// We only know the IDs after saving the entities
await work.SaveChangesAsync();
_participants.TryAdd(key, participant.ID);
msgParticipant.ParticipantID = participant.ID;
}
msgParticipant.ParticipantID = participant.ID;
}
await work.DB.MessageParticipants.AddAsync(msgParticipant, _cancellationToken);
}
await work.SaveChangesAsync();
await work.DB.MessageParticipants.AddAsync(msgParticipant, _cancellationToken);
}
await work.SaveChangesAsync();
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
}
} // PopulateParticipantsAsync
private async Task PopulateKeywordsAsync(UnitOfWork work, Message targetMsg,
IEnumerable<string> keywords, IEnumerable<string> labels)
{
try
{
// Store the keywords separately, and link them to this message
var allKeywords = keywords.Select(k => (Name: k, IsLabel: false))
.Concat(labels.Select(l => (Name: l, IsLabel: true)));
var triplets = allKeywords.Select(mailKeyword => (Name: mailKeyword.Name,
// Store the keywords separately, and link them to this message
var allKeywords = keywords.Select(k => (Name: k, IsLabel: false))
.Concat(labels.Select(l => (Name: l, IsLabel: true)));
var triplets = allKeywords.Select(mailKeyword => (mailKeyword.Name, mailKeyword.IsLabel,
IsLabel: mailKeyword.IsLabel,
ID: _keywords.GetValueOrDefault(mailKeyword, 0)));
var keywordSets = from triplet in triplets
join dbMsgKeyword in work.DB.MessageKeywords.Where(mk => mk.Message == targetMsg)
on triplet.ID equals dbMsgKeyword.KeywordID
into msgKeywordSet
from dbMsgKeyword in msgKeywordSet.DefaultIfEmpty()
select (triplet.Name,
triplet.IsLabel,
msgKeywordID: dbMsgKeyword == null ? (long?)null : dbMsgKeyword.ID,
keywordID: triplet.ID);
int index = 0;
foreach ((string mailKeyword, bool isLabel, long? msgKeywordID, long kwID) in keywordSets)
{
index++;
if (msgKeywordID == null)
{
long keywordID = kwID;
if (keywordID == 0)
{
var keyword = new Keyword
{
Name = mailKeyword,
IsLabel = isLabel
};
await work.Keywords.AddAsync(keyword);
await work.SaveChangesAsync();
keywordID = keyword.ID;
_keywords.Add((mailKeyword, isLabel), keywordID);
}
await work.DB.MessageKeywords.AddAsync(new MessageKeyword
{
Message = targetMsg,
Order = index,
KeywordID = keywordID,
}, _cancellationToken);
}
ID: _keywords.GetValueOrDefault(mailKeyword, 0)));
var keywordSets = from triplet in triplets
join dbMsgKeyword in work.DB.MessageKeywords.Where(mk => mk.Message == targetMsg)
on triplet.ID equals dbMsgKeyword.KeywordID
into msgKeywordSet
from dbMsgKeyword in msgKeywordSet.DefaultIfEmpty()
select (triplet.Name,
triplet.IsLabel,
msgKeywordID: dbMsgKeyword == null ? (long?)null : dbMsgKeyword.ID,
keywordID: triplet.ID);
int index = 0;
foreach ((string mailKeyword, bool isLabel, long? msgKeywordID, long kwID) in keywordSets)
{
index++;
if (msgKeywordID == null)
{
long keywordID = kwID;
if (keywordID == 0)
{
var keyword = new Keyword
{
Name = mailKeyword,
IsLabel = isLabel
};
await work.Keywords.AddAsync(keyword);
await work.SaveChangesAsync();
keywordID = keyword.ID;
_keywords.Add((mailKeyword, isLabel), keywordID);
}
await work.DB.MessageKeywords.AddAsync(new MessageKeyword
{
Message = targetMsg,
Order = index,
KeywordID = keywordID,
}, _cancellationToken);
}
}
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
}
}
/// <summary>
/// Store any references between messages.
/// </summary>
/// <param name="work">The <see cref="UnitOfWork"/> to use when storing the references.</param>
/// <param name="targetMsg">The (newly stored) <see cref="Message"/> that should link to the references.</param>
/// <param name="sourceMsg">The <see cref="MimeMessage"/> containing the references.</param>
private async Task PopulateReferencesAsync(UnitOfWork work, Message targetMsg, MimeMessage sourceMsg)
private static async Task PopulateReferencesAsync(UnitOfWork work, Message targetMsg, MimeMessage sourceMsg)
{
try
{
// Include the In-Reply-To header in the list of references
var sourceReferences = new List<string>(sourceMsg.References);
if (!string.IsNullOrWhiteSpace(sourceMsg.InReplyTo) && !sourceReferences.Contains(sourceMsg.InReplyTo))
sourceReferences.Insert(0, sourceMsg.InReplyTo);
// Include the In-Reply-To header in the list of references
var sourceReferences = new List<string>(sourceMsg.References);
if (!string.IsNullOrWhiteSpace(sourceMsg.InReplyTo) && !sourceReferences.Contains(sourceMsg.InReplyTo))
sourceReferences.Insert(0, sourceMsg.InReplyTo);
var dbMessageRefs = await work.MessageReferences
.GetDictionaryAsync(mr => mr.Message == targetMsg,
mr => mr.ReferencedRfcMessageID,
mr => mr);
var dbReferencedMessageIDs = work.Messages
.GetLookup(m => sourceReferences.Contains(m.RfcMessageID),
m => m.RfcMessageID,
m => m?.ID); // make this a nullable long, so FirstOrDefault will return a null.
int index = 0;
foreach (string mailRef in sourceReferences)
{
index++;
MessageReference dbReference = dbMessageRefs.GetValueOrDefault(mailRef, null);
long? dbMessageID = null;
if (dbReferencedMessageIDs.Contains(mailRef))
{
dbMessageID = dbReferencedMessageIDs[mailRef].FirstOrDefault(id => id.HasValue);
}
if (dbReference == null)
{
await work.MessageReferences.AddAsync(new MessageReference
{
Message = targetMsg,
ReferencedRfcMessageID = mailRef,
InReplyTo = mailRef == sourceMsg.InReplyTo,
Order = index,
ReferencedMessageID = dbMessageID,
});
}
else
{
dbReference.Order = index;
dbReference.ReferencedMessageID = dbMessageID;
dbMessageRefs.Remove(mailRef);
}
}
var dbMessageRefs = await work.MessageReferences
.GetDictionaryAsync(mr => mr.Message == targetMsg,
mr => mr.ReferencedRfcMessageID,
mr => mr);
var dbReferencedMessageIDs = work.Messages
.GetLookup(m => sourceReferences.Contains(m.RfcMessageID ?? ""),
m => m.RfcMessageID,
m => m?.ID); // make this a nullable long, so FirstOrDefault will return a null.
int index = 0;
foreach (string mailRef in sourceReferences)
{
index++;
MessageReference? dbReference = dbMessageRefs.GetValueOrDefault(mailRef, null);
long? dbMessageID = null;
if (dbReferencedMessageIDs.Contains(mailRef))
{
dbMessageID = dbReferencedMessageIDs[mailRef].FirstOrDefault(id => id.HasValue);
}
if (dbReference == null)
{
await work.MessageReferences.AddAsync(new MessageReference
{
Message = targetMsg,
ReferencedRfcMessageID = mailRef,
InReplyTo = mailRef == sourceMsg.InReplyTo,
Order = index,
ReferencedMessageID = dbMessageID,
});
}
else
{
dbReference.Order = index;
dbReference.ReferencedMessageID = dbMessageID;
dbMessageRefs.Remove(mailRef);
}
}
// Any remaining references are no longer in use, so delete them
work.MessageReferences.Delete(dbMessageRefs.Values);
// Any remaining references are no longer in use, so delete them
work.MessageReferences.Delete(dbMessageRefs.Values);
// Find any existing references to targetMsg, and fill them in
if (targetMsg.RfcMessageID != null)
{
var previousReferences = work.MessageReferences
.GetList(mr => mr.ReferencedRfcMessageID == targetMsg.RfcMessageID && mr.Message == null);
foreach (var dbReference in previousReferences)
{
dbReference.Message = targetMsg;
}
}
// Find any existing references to targetMsg, and fill them in
if (targetMsg.RfcMessageID != null)
{
var previousReferences = work.MessageReferences
.GetList(mr => mr.ReferencedRfcMessageID == targetMsg.RfcMessageID && mr.Message == null);
foreach (var dbReference in previousReferences)
{
dbReference.Message = targetMsg;
}
}
await work.SaveChangesAsync();
await work.SaveChangesAsync();
}
catch (Exception ex)
{
if (ex is TaskCanceledException || ex is OperationCanceledException || ex is ServiceNotConnectedException)
{
throw; // those need to fall through
}
await Con.WriteLineAsync();
await Con.WriteLineAsync(ex);
}
} // PopulateReferencesAsync
private static void GatherParticipants(ref List<(ParticipantField Field, string Address, string Name)> participantList, InternetAddress ia, ParticipantField field)
private static void GatherParticipants(ref List<(ParticipantField Field, string? Address, string Name)> participantList, InternetAddress ia, ParticipantField field)
{
if (ia == null) return;
var list = new InternetAddressList(new InternetAddress[] { ia });
GatherParticipants(ref participantList, list, field);
}
private static void GatherParticipants(ref List<(ParticipantField Field, string Address, string Name)> participantList, InternetAddressList list, ParticipantField field)
private static void GatherParticipants(ref List<(ParticipantField Field, string? Address, string Name)> participantList, InternetAddressList list, ParticipantField field)
{
foreach (var ia in list)
{
if (ia is GroupAddress group)
{
if (group.Members.Count > 0)
{
participantList.AddRange(group.Members
.Select(ma => ma as MailboxAddress)
.Select(ma => (field, ma.Address, ma.Name)));
.Select(ma => (field, ma?.Address, ma?.Name ?? "")));
}
else
{
participantList.Add((field, null, group.Name));
}
}
else if (ia is MailboxAddress mailbox)
{
participantList.Add((field, mailbox.Address, mailbox.Name));
}
else
{
participantList.Add((field, null, ia.Name));
}
}
}
private class KeywordEqualityComparer : IEqualityComparer<(string Name, bool IsLabel)>
{
private static readonly KeywordEqualityComparer _default = new KeywordEqualityComparer();
public static KeywordEqualityComparer InvariantCultureIgnoreCase { get => _default; }
public static KeywordEqualityComparer InvariantCultureIgnoreCase { get; } = new KeywordEqualityComparer();
public bool Equals((string Name, bool IsLabel) x, (string Name, bool IsLabel) y)
{
return x.IsLabel == y.IsLabel
&& x.Name.Equals(y.Name, StringComparison.InvariantCultureIgnoreCase);
}
public int GetHashCode((string Name, bool IsLabel) obj)
{
return obj.Name.GetHashCode() ^ obj.IsLabel.GetHashCode();
return obj.Name.GetHashCode(StringComparison.InvariantCultureIgnoreCase) ^ obj.IsLabel.GetHashCode();
}
}
}
}
|