-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbackground.js
3123 lines (2913 loc) · 104 KB
/
background.js
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
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Class for abstracting the idea that a message is locked and can't be sent
// again. Uses local storage as the persistent lock cache. The key of each
// value in the cache is a message idea and a date. The value is an array
// containing a lock type and an x-send-later-at date value. Search for
// ".lock(" below to find out the lock types that are used. The lock type
// "true" is the generic "This message was sent successfully so if we see it
// again the Drafts folder is probably corrupt" lock type; others indicate
// different errors which do NOT mean that the Drafts folder is corrupt.
//
// Because we enforce not delivering messages with x-send-later-at values more
// than 180 days in the past, we can prune any lock cache entries with dates
// older than that. This prevents the lock cache from growing without bound
// forever.
class Locker {
static locks;
static newLocks;
constructor() {
if (!Locker.locks) {
return (async () => {
let changed = false;
let storage = await messenger.storage.local.get({ lock: {} });
Locker.locks = storage.lock;
// Convert old style lock cache to new one.
if (!Locker.locks["migrated"]) {
for (let lock of Object.keys(Locker.locks)) {
Locker.locks[lock] = [Locker.locks[lock], new Date()];
}
Locker.locks["migrated"] = 1;
changed = true;
}
let cutoff = new Date(Date.now() - 180 * 24 * 60 * 60 * 1000);
for (let lockId of Object.keys(Locker.locks)) {
let value = Locker.locks[lockId];
if (typeof value != "object") {
// "migrated" key
continue;
}
if (value[1] < cutoff) {
changed = true;
delete Locker.locks[lockId];
}
}
if (changed) {
await messenger.storage.local.set({ lock: Locker.locks });
}
return this;
})();
}
}
async lock(hdr, full, reason) {
let msgId = hdr.headerMessageId;
let date = hdr.date;
let id = `${msgId}/${date}`;
let sendAt = full.headers["x-send-later-at"][0];
Locker.locks[id] = [reason || true, new Date(sendAt)];
if (Locker.newLocks) {
Locker.newLocks[id] = Locker.locks[id];
}
return await messenger.storage.local.set({ lock: Locker.locks });
}
isLocked(hdr, full) {
let msgId = hdr.headerMessageId;
let date = hdr.date;
let id = `${msgId}/${date}`;
let it = Locker.locks[id];
if (it) {
if (Locker.newLocks) {
Locker.newLocks[id] = Locker.locks[id];
}
return it[0];
}
return false;
}
}
async function* getMessages(list) {
let page = await list;
for (let message of page.messages) {
yield message;
}
while (page.id) {
page = await messenger.messages.continueList(page.id);
for (let message of page.messages) {
yield message;
}
}
}
async function* getMessageIds(list) {
for await (let message of getMessages(list)) yield message.id;
}
// Pseudo-namespace encapsulation for global-ish variables.
const SendLater = {
prefCache: {},
windowCreatedResolver: null,
// Track the status of Send Later's main loop. This helps
// resolve sub-minute accuracy for very short scheduled times
// (e.g. "Send in 38 seconds" ...). Only affects UI
// elements in which a relative time is displayed.
previousLoop: null,
loopMinutes: 1,
// Time for each loop over and above the interval time
loopExcessTimes: [],
// Cause current compose window to send immediately
// (after some pre-send checks)
async checkDoSendNow(options) {
if (options.first) {
let messageArgs = [
messenger.i18n.getMessage("sendNowLabel"),
messenger.i18n.getMessage("sendAtLabel"),
];
let preferences = await SLTools.getPrefs();
if (preferences.showSendNowAlert) {
const result = await SLTools.confirmCheck(
messenger.i18n.getMessage("AreYouSure"),
messenger.i18n.getMessage("SendNowConfirmMessage", messageArgs),
messenger.i18n.getMessage("ConfirmAgain"),
true,
).catch((err) => {
SLStatic.trace(err);
});
if (result.check === false) {
preferences.showSendNowAlert = false;
await messenger.storage.local.set({ preferences });
}
if (!result.ok) {
SLStatic.debug(`User canceled send now.`);
return false;
}
} else if (options.changed && preferences.showChangedAlert) {
const result = await SLTools.confirmCheck(
messenger.i18n.getMessage("AreYouSure"),
messenger.i18n.getMessage("PopupChangedConfirmMessage", messageArgs),
messenger.i18n.getMessage("ConfirmAgain"),
true,
).catch((err) => {
SLStatic.trace(err);
});
if (result.check === false) {
preferences.showChangedAlert = false;
await messenger.storage.local.set({ preferences });
}
if (!result.ok) {
SLStatic.debug(`User canceled send now.`);
return false;
}
}
}
return true;
},
async doSendNow(tabId, options, fromMenuCommand) {
await messenger.compose.sendMessage(tabId, { mode: "sendNow" });
return true;
},
// Use built-in send later function (after some pre-send checks)
async checkDoPlaceInOutbox(options) {
if (options.first) {
let messageArgs = [
messenger.i18n.getMessage("sendlater.prompt.sendlater.label"),
messenger.i18n.getMessage("sendAtLabel"),
];
let preferences = await SLTools.getPrefs();
if (preferences.showOutboxAlert) {
const result = await SLTools.confirmCheck(
messenger.i18n.getMessage("AreYouSure"),
messenger.i18n.getMessage("OutboxConfirmMessage", messageArgs),
messenger.i18n.getMessage("ConfirmAgain"),
true,
).catch((err) => {
SLStatic.trace(err);
});
if (result.check === false) {
preferences.showOutboxAlert = false;
await messenger.storage.local.set({ preferences });
}
if (!result.ok) {
SLStatic.debug(`User canceled put in outbox.`);
return false;
}
} else if (options.changed && preferences.showChangedAlert) {
const result = await SLTools.confirmCheck(
messenger.i18n.getMessage("AreYouSure"),
messenger.i18n.getMessage("PopupChangedConfirmMessage", messageArgs),
messenger.i18n.getMessage("ConfirmAgain"),
true,
).catch((err) => {
SLStatic.trace(err);
});
if (result.check === false) {
preferences.showChangedAlert = false;
await messenger.storage.local.set({ preferences });
}
if (!result.ok) {
SLStatic.debug(`User canceled put in outbox.`);
return false;
}
}
}
return true;
},
async doPlaceInOutbox(tabId, options, fromMenuCommand) {
await messenger.compose.sendMessage(tabId, { mode: "sendLater" });
return true;
},
// Sends composed message according to user function (specified
// by name), and arguments (specified as an "unparsed" string).
async quickSendWithUfunc(funcName, funcArgs, tabId) {
if (!tabId) {
let tab = await SLTools.getActiveComposeTab();
if (tab) {
tabId = tab.id;
}
}
if (!(await SendLater.schedulePrecheck())) {
return false;
}
if (tabId) {
let { ufuncs } = await messenger.storage.local.get({ ufuncs: {} });
let funcBody = ufuncs[funcName].body;
let schedule = SLStatic.parseUfuncToSchedule(
funcName,
funcBody,
null,
funcArgs,
);
let options = {
sendAt: schedule.sendAt,
recurSpec: SLStatic.unparseRecurSpec(schedule.recur),
args: schedule.recur.args,
cancelOnReply: false,
};
await SendLater.scheduleSendLater(tabId, options);
}
},
async schedulePrecheck() {
if (!(await SLStatic.tb128(true, false))) {
let tab = await SLTools.getActiveComposeTab();
let composeDetails = await messenger.compose.getComposeDetails(tab.id);
if (composeDetails.deliveryStatusNotification) {
let extensionName = messenger.i18n.getMessage("extensionName");
let dsnName = messenger.i18n.getMessage("DSN");
let title = messenger.i18n.getMessage("noDsnTitle", [
dsnName,
extensionName,
]);
let text = messenger.i18n.getMessage("noDsnText", [
dsnName,
extensionName,
]);
SLTools.alert(title, text);
return false;
}
}
return true;
},
// Go through the process of handling pre-send checks, assigning custom
// header fields, and saving the message to Drafts.
async scheduleSendLater(tabId, options, fromMenuCommand) {
let now = new Date();
SLStatic.debug(`Pre-send check initiated at ${now}`);
let encryptionStatus =
await messenger.SL3U.signingOrEncryptingMessage(tabId);
SLStatic.telemetrySend({
event: "encryptionStatus",
encryptionStatus: encryptionStatus,
});
if (encryptionStatus.endsWith("-error")) {
let name = messenger.i18n.getMessage("extensionName");
let title = messenger.i18n.getMessage("IncompatibleEncryptionTitle", [
name,
]);
let errorKey = `IncompatibleEncryption-${encryptionStatus}-Text`;
let text = messenger.i18n.getMessage(errorKey, [name]);
SLTools.alert(title, text);
return false;
}
let check = await messenger.SL3U.GenericPreSendCheck();
if (!check) {
SLStatic.warn(
`Canceled via pre-send checks (check initiated at ${now})`,
);
return;
}
// let windowId = await messenger.tabs.get(tabId).then(
// tab => tab.windowId);
// let originalDraftMsg = await messenger.SL3U.findAssociatedDraft(
// windowId);
const preferences = await SLTools.getPrefs();
SLStatic.info(`Scheduling send later: ${tabId} with options`, options);
// Expand mailing lists into individual recipients
await SLTools.expandRecipients(tabId);
let customHeaders = [
{ name: "X-Send-Later-Uuid", value: preferences.instanceUUID },
];
// Determine time at which this message should be sent
let sendAt;
if (options.sendAt !== undefined) {
sendAt = new Date(options.sendAt);
} else if (options.delay !== undefined) {
sendAt = new Date(Date.now() + options.delay * 60000);
} else {
SLStatic.error("scheduleSendLater requires scheduling information");
return;
}
sendAt = SLStatic.parseableDateTimeFormat(sendAt);
customHeaders.push({ name: "X-Send-Later-At", value: sendAt });
if (preferences.scheduledDateField) {
customHeaders.push({ name: "Date", value: sendAt });
}
if (options.recurSpec) {
customHeaders.push({
name: "X-Send-Later-Recur",
value: options.recurSpec,
});
if (options.cancelOnReply) {
customHeaders.push({
name: "X-Send-Later-Cancel-On-Reply",
value: "yes",
});
}
}
if (options.args) {
customHeaders.push({ name: "X-Send-Later-Args", value: options.args });
}
// When Thunderbird saves an existing draft, it preserves its message ID
// (the RFC message ID, not the internal TB message ID). This causes
// problems, especially with Gmail. Setting Message-ID to an empty value
// here forces Thunderbird to generate a new Message ID when saving the
// message.
customHeaders.push({ name: "message-id", value: "" });
let composeDetails = await messenger.compose.getComposeDetails(tabId);
// // // Merge the new custom headers into the original headers
// // // Note: this shouldn't be necessary, but it appears that
// // // `setComposeDetails` does not preserve existing headers.
// // for (let hdr of composeDetails.customHeaders) {
// // if (!hdr.name.toLowerCase().startsWith("x-send-later")) {
// // customHeaders.push(hdr);
// // }
// // }
// // composeDetails.customHeaders = customHeaders;
// // SLStatic.info("Saving message with details:", composeDetails);
// // await messenger.compose.setComposeDetails(tabId, composeDetails);
//
// The setComposeDetails method seems to drop all unsupported headers
// (which is most of the headers). This breaks things like replies
// which need to retain the "in-reply-to" header (for example).
for (let hdr of customHeaders) {
await messenger.SL3U.setHeader(tabId, hdr.name, hdr.value);
}
// Save the message as a draft
let saveProperties = await messenger.compose.saveMessage(tabId, {
mode: "draft",
});
if (!saveProperties.messages.length) {
throw new Error(
"Failed to save draft, no exception thrown by Thunderbird",
);
}
// The "real" draft, as opposed to the FCC, is always first.
let msg = saveProperties.messages[0];
// Optionally mark the saved message as "read"
if (preferences.markDraftsRead) {
await messenger.messages.update(msg.id, { read: true });
}
// Some servers, most notably Gmail but perhaps others as well, don't
// refresh the content of the saved message properly when the new message
// is saved and the old one is deleted. This seems to be true even when
// we replace the Message-ID in the message as we do above. This also seems
// to be different from the bug which sometimes causes the local Thunderbird
// to display the old content for a message even though the server has the
// new content; in this case it appears that even the server doesn't show
// the new content, as evidenced by looking at the draft on mail.google.com.
// Cleaning the Drafts folder after saving the message seems to solve this.
SendLater.addToDraftsToClean(msg.folder, true);
let targetFolder = await SLTools.getTargetSubfolder(preferences, msg);
if (targetFolder) {
await messenger.messages.move([msg.id], targetFolder);
// Message ID has changed so we want to make sure not to use the old one!
// If we forget and try to later on in the function this should cause an
// error.
msg.id = null;
msg.folder = targetFolder;
SendLater.addToDraftsToClean(msg.folder, true);
}
SendLater.cleanDrafts();
if (preferences.ignoredAccounts && preferences.ignoredAccounts.length) {
let identity = await messenger.identities.get(composeDetails.identityId);
let accountId = identity.accountId;
if (preferences.ignoredAccounts.includes(accountId)) {
preferences.ignoredAccounts = preferences.ignoredAccounts.filter(
(a) => a != accountId,
);
await messenger.storage.local.set({ preferences });
SLStatic.info(
`Reactivating ${accountId} because message scheduled in it`,
);
}
}
// Close the composition tab
await messenger.tabs.remove(tabId);
// If message was a reply or forward, update the original message
// to show that it has been replied to or forwarded.
if (!fromMenuCommand && composeDetails.relatedMessageId) {
if (composeDetails.type == "reply") {
SLStatic.debug("This is a reply message. Setting original 'replied'");
await messenger.SL3U.setDispositionState(
composeDetails.relatedMessageId,
"replied",
);
} else if (composeDetails.type == "forward") {
SLStatic.debug("This is a fwd message. Setting original 'forwarded'");
await messenger.SL3U.setDispositionState(
composeDetails.relatedMessageId,
"forwarded",
);
}
}
// If the message was already saved as a draft (and made it into the
// unscheduledMsgCache while being composed), then it will be ignored when
// checking for scheduled messages. We should be able to remove it from the
// unscheduledMsgCache here, but there seems to be a bug in Thunderbird
// where the message ID reported to us is not the actual saved message.
// Also, if the user is using a drafts folder then we no longer have the
// actual message ID of the draft because it changed when we moved it and
// we haven't searched and found the new ID.
// Best option right now seems to be invalidating and regenerating the
// entire unscheduledMsgCache.
if (!fromMenuCommand) {
SLTools.unscheduledMsgCache.clear();
// It seems that a delay is required for messages.getFull to successfully
// access the recently saved message.
setTimeout(SendLater.updateStatusIndicator, 1000);
}
// // Different workaround:
// function touchDraftMsg(draftId) {
// SLTools.unscheduledMsgCache.delete(draftId);
// SLTools.scheduledMsgCache.add(draftId);
// if (preferences.markDraftsRead)
// await messenger.messages.update(draftId, { read: true });
// }
// if (originalDraftMsg)
// touchDraftMsg(originalDraftMsg.id);
// if (composeDetails.type == "draft" && composeDetails.relatedMessageId)
// touchDraftMsg(composeDetails.relatedMessageId);
// await messenger.SL3U.findAssociatedDraft(windowId).then(
// newDraftMsg => touchDraftMsg(newDraftMsg.id)
// );
return true;
},
draftsToClean: [],
addToDraftsToClean(folder, force) {
if (
!SendLater.draftsToClean.some(
(f) => f.accountId == folder.accountId && f.path == folder.path,
)
) {
SLStatic.debug("Adding folder to draftsToClean:", folder);
SendLater.draftsToClean.push(folder);
} else {
SLStatic.debug("Clean is already queued for:", folder);
}
if (force) SendLater.draftsToClean.slforce = true;
},
// There are two different race conditions we're concerned about here. First,
// while we're waiting for all of the drafts folders we're cleaning to become
// idle, someone else could call cleanDrafts a second time. Second, while
// we're awaiting for something in the loop of cleaning all the folders,
// someone could add another folder to the list.
// To address the first, any time cleanDrafts is invoked it needs to await
// for the prior running invocation to finish. We set this up in a loop that
// keeps awaiting until there's nothing to wait for, because if multiple
// invocations are awaiting for it to finish before they start, one of them
// could regain control before we do and start another clean cycle.
// To address the second, we make the list of drafts to clean local before we
// start the cleaning process, and reinitialize the shared list to an empty
// array, so if someone else adds a folder to the list once we've started
// cleaning it'll get picked up in the next invocation of cleanDrafts.
// This is just used so that different invocations of cleanDrafts can be
// distinguished from each other in the logs.
cdid: 0,
cleanDraftsPromise: null,
async cleanDrafts() {
let _id = SendLater.cdid++;
SLStatic.trace(`cleanDrafts[${_id}]: start`);
let waited;
while (SendLater.cleanDraftsPromise) {
waited = true;
SLStatic.debug(
`cleanDrafts[${_id}]: waiting for previous clean to finish`,
);
await SendLater.cleanDraftsPromise;
}
if (waited) SLStatic.debug(`cleanDrafts[${_id}]: finished waiting`);
SendLater.cleanDraftsPromise = SendLater.cleanDraftsReal();
await SendLater.cleanDraftsPromise;
SendLater.cleanDraftsPromise = null;
SLStatic.trace(`cleanDrafts[${_id}]: end`);
},
async cleanDraftsReal() {
draftsToClean = SendLater.draftsToClean;
SendLater.draftsToClean = [];
if (!draftsToClean.length) return;
if (draftsToClean.slforce || SendLater.prefCache.compactDrafts) {
await messenger.SL3U.waitUntilIdle(draftsToClean);
for (let folder of draftsToClean) {
SLStatic.debug("Cleaning folder:", folder);
await messenger.SL3U.expungeOrCompactFolder(folder);
}
} else {
SLStatic.debug("Not cleaning folders, preference is disabled");
}
},
async deleteMessage(hdr) {
SendLater.addToDraftsToClean(hdr.folder);
let account = await messenger.accounts.get(hdr.folder.accountId, false);
let accountType = account.type;
let succeeded;
if (!accountType.startsWith("owl")) {
try {
await messenger.messages.delete([hdr.id], true).then(() => {
succeeded = true;
SLStatic.info("Deleted message", hdr.id);
SLTools.scheduledMsgCache.delete(hdr.id);
SLTools.unscheduledMsgCache.delete(hdr.id);
});
} catch (ex) {
SLStatic.error(`Error deleting message ${hdr.id}`, ex);
}
} else {
// When we're talking to an Owl Exchange account, the code simply
// above... stops. Neither the code inside the `then` block nor the code
// inside the `catch` block is called. In fact, the code flow just stops
// and nothing after it gets executed. Basically, the extension is hung
// at that point. I have no idea what's going on here. Since it's likely
// to be a problem inside the Owl code, I've asked the author of Owl for
// assistance figuring it out. He may have no idea either :shrug:. In the
// meantime we just have to do delete asynchronously, and we can't log
// "Deleted message" because we don't know for certain that the message
// was in fact deleted.
try {
await messenger.messages.delete([hdr.id], true).then(() => {
succeeded = true;
});
} catch (ex) {
SLStatic.error(`Error deleting message ${hdr.id}`, ex);
}
SLTools.scheduledMsgCache.delete(hdr.id);
SLTools.unscheduledMsgCache.delete(hdr.id);
}
return succeeded;
},
checkEncryption(contentType, originalMsgId, msgHdr) {
if (/encrypted/i.test(contentType)) {
SLStatic.debug(
`Message ${originalMsgId} is encrypted, and will not ` +
`be processed by Send Later.`,
);
SLTools.unscheduledMsgCache.add(msgHdr.id);
return false;
}
return true;
},
async checkLocked(
preferences,
locker,
originalMsgId,
msgHdr,
msgLockId,
fullMsg,
) {
let locked = locker.isLocked(msgHdr, fullMsg);
if (!locked) return true;
const msgSubject = msgHdr.subject;
if (locked === true) {
if (preferences.optOutResendWarning === true) {
SLStatic.debug(
`Encountered previously sent message ` +
`"${msgSubject}" ${msgLockId}.`,
);
} else {
SLStatic.error(
`Attempted to resend message "${msgSubject}" ${msgLockId}.`,
);
const result = await SLTools.alertCheck(
null,
messenger.i18n.getMessage("CorruptFolderError", [
msgHdr.folder.path,
]) +
"\n\n" +
messenger.i18n.getMessage("CorruptFolderErrorDetails", [
msgSubject,
originalMsgId,
]),
null,
true,
);
if (result.check === false) {
preferences.optOutResendWarning = true;
await messenger.storage.local.set({ preferences });
}
}
}
return false;
},
async checkLate(preferences, locker, nextSend, msgHdr, fullMsg) {
// Respect late message blocker
// We enforce a maximum grace period of six months even when one isn't
// specified in the user's preferences, for safety.
let maxGracePeriod = 60 * 24 * 180; // minutes
let lateGracePeriod;
if (preferences.blockLateMessages) {
lateGracePeriod = Math.min(preferences.lateGracePeriod, maxGracePeriod);
} else {
lateGracePeriod = maxGracePeriod;
}
let lateness = (Date.now() - nextSend.getTime()) / 60000;
if (lateness <= lateGracePeriod) return true;
SLStatic.warn(`Grace period exceeded for message ${msgHdr.id}`);
if (locker.isLocked(msgHdr, fullMsg) != "late") {
let units, newLateness;
if (lateness / 60 / 24 / 365 > 1) {
lateness = Math.floor(lateness / 60 / 24 / 365);
units = "year";
} else if (lateness / 60 / 24 / 30 > 1) {
lateness = Math.floor(lateness / 60 / 24 / 30);
units = "month";
} else if (lateness / 60 / 24 / 7 > 1) {
lateness = Math.floor(lateness / 60 / 24 / 7);
units = "week";
} else if (lateness / 60 / 24 > 1) {
lateness = Math.floor(lateness / 60 / 24);
units = lateness == 1 ? "day" : "dai"; // ugh
} else {
lateness = Math.floor(lateness);
units = "minute";
}
units = SLStatic.i18n.getMessage(
lateness == 1 ? `single_${units}` : `plural_${units}ly`,
);
const msgSubject = msgHdr.subject;
const warningMsg = messenger.i18n.getMessage("BlockedLateMessage2", [
msgSubject,
msgHdr.folder.path,
lateness,
units,
]);
const warningTitle = messenger.i18n.getMessage(
"ScheduledMessagesWarningTitle",
);
SLTools.alert(warningTitle, warningMsg);
await locker.lock(msgHdr, fullMsg, "late");
}
return false;
},
async checkTimeRestrictions(
preferences,
recur,
skipping,
originalMsgId,
msgHdr,
) {
if (!preferences.enforceTimeRestrictions) return true;
// Respect "until" preference
if (recur.until) {
if (SLStatic.compareTimes(Date.now(), ">", recur.until)) {
(skipping ? SLStatic.error : SLStatic.debug)(
`Message ${msgHdr.id} ${originalMsgId} past ` +
`"until" restriction. Skipping.`,
);
return false;
}
}
// Respect "send between" preference
if (!skipping && recur.between) {
if (
SLStatic.compareTimes(Date.now(), "<", recur.between.start) ||
SLStatic.compareTimes(Date.now(), ">", recur.between.end)
) {
// Skip message this time, but don't explicitly reschedule it.
SLStatic.debug(
`Message ${msgHdr.id} ${originalMsgId} outside of ` +
`sendable time range. Skipping.`,
recur.between,
);
return false;
}
}
// Respect "only on days of week" preference
if (!skipping && recur.days) {
const today = new Date().getDay();
if (!recur.days.includes(today)) {
// Reschedule for next valid time.
const start_time = recur.between && recur.between.start;
const end_time = recur.between && recur.between.end;
let nextRecurAt = SLStatic.adjustDateForRestrictions(
new Date(),
start_time,
end_time,
recur.days,
false,
);
while (nextRecurAt < new Date()) {
nextRecurAt = new Date(nextRecurAt.getTime() + 60000);
}
const this_wkday = new Intl.DateTimeFormat("default", {
weekday: "long",
});
SLStatic.info(
`Message ${msgHdr.id} not scheduled to send on ` +
`${this_wkday.format(new Date())}. Rescheduling ` +
`for ${nextRecurAt}`,
);
let newMsgContent = await messenger.messages.getRaw(msgHdr.id);
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"X-Send-Later-At",
SLStatic.parseableDateTimeFormat(nextRecurAt),
false,
);
if (preferences.scheduledDateField) {
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"Date",
SLStatic.parseableDateTimeFormat(nextRecurAt),
false /* replaceAll */,
true /* addIfMissing */,
);
}
let success = await SLStatic.tb115(
async () => {
let file = SLStatic.getFileFromRaw(newMsgContent);
return await SLStatic.messageImport(file, msgHdr.folder, {
new: false,
read: preferences.markDraftsRead,
});
},
async () => {
return await messenger.SL3U.saveMessage(
newMsgContent,
msgHdr.folder,
preferences.markDraftsRead,
);
},
);
if (success) {
SLStatic.debug(
`Rescheduled message ${originalMsgId}. Deleting original.`,
);
await SendLater.deleteMessage(msgHdr);
} else {
SLStatic.error("Unable to schedule next recurrence.");
}
return false;
}
}
return true;
},
async doSendMessage(
preferences,
options,
locker,
originalMsgId,
msgHdr,
msgLockId,
fullMsg,
) {
// Initiate send from draft message
SLStatic.info(`Sending message ${originalMsgId}.`);
// "Why do we have to iterate through local accounts?" you ask. "Isn't
// there just one Local Folders account?" Well, sure, that's normally the
// case, but it's apparently possible to have multiple local accounts. See,
// for example, https://addons.thunderbird.net/thunderbird/addon/
// localfolder/. So we need to find the local account that has the Outbox
// in it.
let outboxFolder;
let localAccounts = (await messenger.accounts.list(false)).filter(
(account) => account.type == "none",
);
for (let localAccount of localAccounts) {
let localFolders = await messenger.folders.getSubFolders(
await SLStatic.tb128(localAccount.id, localAccount),
);
for (let localFolder of localFolders) {
if (localFolder.type == "outbox") {
outboxFolder = localFolder;
break;
}
}
if (outboxFolder) break;
}
if (!outboxFolder) {
SLStatic.error("Could not find outbox folder to deliver message");
return false;
}
let content = await SLTools.prepNewMessageHeaders(
await messenger.messages.getRaw(msgHdr.id),
);
const identityId =
options.identityId ?? (await findBestIdentity(msgHdr, fullMsg));
content = SLStatic.replaceHeader(
content,
"X-Identity-Key",
identityId,
true,
true,
);
let success;
await SLStatic.tb115(undefined, async () => {
// See https://github.com/Extended-Thunder/send-later/issues/643
// Thunderbird will get sick if we try to deliver a message through the
// outbox larger than mailnews.message_warning_size.
let messageSizeLimit = await messenger.SL3U.getLegacyPref(
"mailnews.message_warning_size",
"int",
"0",
true,
);
if (messageSizeLimit && content.length > messageSizeLimit) {
let title = SLStatic.i18n.getMessage("messageTooLargeTitle");
let extensionName = SLStatic.i18n.getMessage("extensionName");
let numberFormatter = new Intl.NumberFormat();
let text = SLStatic.i18n.getMessage("messageTooLargeText", [
extensionName,
msgHdr.subject,
numberFormatter.format(content.length),
numberFormatter.format(messageSizeLimit),
]);
await locker.lock(msgHdr, fullMsg, "too large");
SLStatic.debug(
`Locked too-large message <${msgLockId}> from re-sending.`,
);
SLTools.alert(title, text);
SLStatic.telemetrySend({
event: "tooLargeForOutbox",
});
success = false;
}
});
if (success === undefined) {
success = await SLStatic.tb115(
async () => {
let file = SLStatic.getFileFromRaw(content);
return await SLStatic.messageImport(file, outboxFolder, {
new: false,
read: true,
});
},
async () => {
return await messenger.SL3U.saveMessage(content, outboxFolder, true);
},
);
}
SLStatic.telemetrySend({
event: "delivery",
successful: success,
});
if (success) {
if (preferences.sendUnsentMsgs) {
setTimeout(messenger.SL3U.queueSendUnsentMessages, 1000);
}
await locker.lock(msgHdr, fullMsg, true);
SLStatic.debug(`Locked message <${msgLockId}> from re-sending.`);
} else {
SLStatic.error(
`Something went wrong while sending message ${originalMsgId}`,
);
}
return success;
},
async doNextRecur(
preferences,
locker,
originalMsgId,
msgHdr,
recur,
nextSend,
msgRecurSpec,
args,
) {
let nextRecur;
if (recur.type !== "none") {
nextRecur = await SLStatic.nextRecurDate(
nextSend,
msgRecurSpec,
new Date(),
args,
);
}
if (!nextRecur) return false;
try {
let nextRecurAt = nextRecur.sendAt;
let nextRecurSpec = nextRecur.nextspec;
let nextRecurArgs = nextRecur.nextargs;
while (nextRecurAt < new Date()) {
nextRecurAt = new Date(nextRecurAt.getTime() + 60000);
}
SLStatic.info(`Scheduling next recurrence of message ${originalMsgId}`, {
nextRecurAt,
nextRecurSpec,
nextRecurArgs,
});
let newMsgContent = await messenger.messages.getRaw(msgHdr.id);
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"Date",
SLStatic.parseableDateTimeFormat(
SendLater.prefCache.scheduledDateField ? nextRecurAt : Date.now(),
),
false /* replaceAll */,
true /* addIfMissing */,
);
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"X-Send-Later-At",
SLStatic.parseableDateTimeFormat(nextRecurAt),
false,
);
if (typeof nextRecurSpec === "string") {
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"X-Send-Later-Recur",
nextRecurSpec,
false,
true,
);
}
if (typeof nextRecurArgs === "object") {
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"X-Send-Later-Args",
SLStatic.unparseArgs(nextRecurArgs),
false,