forked from Extended-Thunder/send-later
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
1475 lines (1330 loc) · 55.7 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
// Pseudo-namespace encapsulation for global-ish variables.
const SendLater = {
prefCache: {},
watchAndMarkRead: new Set(),
// The user should be alerted about messages which are
// beyond their late grace period once per session.
warnedAboutLateMessageBlocked: new Set(),
loopTimeout: null,
notify(title, text) {
SLStatic.warn(`Alert: ${title}- ${text}`);
browser.notifications.create(null, {
"type": "basic",
"title": title,
"message": text
});
},
async printVersionInfo() {
const extensionName = browser.i18n.getMessage("extensionName");
const thisVersion = browser.runtime.getManifest().version;
const browserInfo = await browser.runtime.getBrowserInfo();
const platformInfo = await browser.runtime.getPlatformInfo();
console.info(`${extensionName} version ${thisVersion} on ` +
`${browserInfo.name} ${browserInfo.version} (${browserInfo.buildID}) ` +
`[${platformInfo.os} ${platformInfo.arch}]`);
},
async preSendCheck() {
return await browser.SL3U.preSendCheck();
},
async isEditing(msgId) {
// Look through each of the compose windows, check for this message UUID.
return await browser.SL3U.editingMessage(msgId);
},
async forAllDraftFolders(callback) {
const that = this;
try {
let results = [];
let accounts = await browser.accounts.list();
for (let acct of accounts) {
let draftFolders = await getDraftFolders(acct);
for (let folder of draftFolders) {
results.push(callback(folder));
}
}
return await Promise.all(results);
} catch (ex) {
SLStatic.error(ex);
}
},
async forAllDrafts(callback) {
const that = this;
try {
let results = [];
let accounts = await browser.accounts.list();
for (let acct of accounts) {
let draftFolders = await getDraftFolders(acct);
for (let folder of draftFolders) {
let page = await browser.messages.list(folder);
do {
let pageResults = page.messages.map(
message => callback.call(that, message)
);
results = results.concat(pageResults);
if (page.id) {
page = await browser.messages.continueList(page.id);
}
} while (page.id);
}
}
return await Promise.all(results);
} catch (ex) {
SLStatic.error(ex);
}
},
async expandRecipients(tabId) {
let details = {};
for (let type of ["to", "cc", "bcc"]) {
details[type] = await browser.SL3U.expandRecipients(type);
}
await browser.compose.setComposeDetails(tabId, details);
},
async scheduleSendLater(tabId, options) {
SLStatic.info(`Scheduling send later: ${tabId} with options`,options);
const { preferences } = await browser.storage.local.get({ preferences: {} });
const customHeaders = {
"x-send-later-uuid": preferences.instanceUUID
};
// Determine time at which this message should be sent
if (options.sendAt !== undefined) {
const sendAt = new Date(options.sendAt);
customHeaders["x-send-later-at"] = SLStatic.parseableDateTimeFormat(sendAt);
} else if (options.delay !== undefined) {
const sendAt = new Date(Date.now() + options.delay*60000);
customHeaders["x-send-later-at"] = SLStatic.parseableDateTimeFormat(sendAt);
} else {
SLStatic.error("scheduleSendLater requires scheduling information");
return;
}
if (options.recurSpec) {
customHeaders['x-send-later-recur'] = options.recurSpec;
if (options.cancelOnReply) {
customHeaders['x-send-later-cancel-on-reply'] = "yes";
}
}
if (options.args) {
customHeaders['x-send-later-args'] = options.args;
}
const inserted = Object.keys(customHeaders).map(name =>
browser.SL3U.setHeader(name, (""+customHeaders[name]))
);
await this.expandRecipients(tabId);
await Promise.all(inserted);
SLStatic.debug('headers',customHeaders);
const composeDetails = await browser.compose.getComposeDetails(tabId);
const newMessageId = await browser.SL3U.generateMsgId(composeDetails.identityId);
if (preferences.markDraftsRead) {
this.watchAndMarkRead.add(newMessageId);
}
const success = await browser.SL3U.saveAsDraft(newMessageId);
if (!success) {
SLStatic.error("Something went wrong while scheduling this message.");
}
setTimeout(() => {
this.setStatusBarIndicator.call(this, false);
}, 1000);
},
async possiblySendMessage(msgHdr, rawContent) {
// Determines whether or not a particular draft message is due to be sent
SLStatic.debug(`Checking message ${msgHdr.uri}.`);
// const rawContent = await browser.messages.getRaw(msgHdr.id).catch(err => {
// SLStatic.warn(`Unable to fetch message ${msgHdr.id}.`, err);
// });
if (!rawContent) {
SLStatic.warn("possiblySendMessage failed. Unable to get raw message contents.", msgHdr);
return;
}
const msgSendAt = SLStatic.getHeader(rawContent, 'x-send-later-at');
const msgUUID = SLStatic.getHeader(rawContent, 'x-send-later-uuid');
const msgRecurSpec = SLStatic.getHeader(rawContent, 'x-send-later-recur');
const msgRecurArgs = SLStatic.getHeader(rawContent, 'x-send-later-args');
const originalMsgId = SLStatic.getHeader(rawContent, 'message-id');
const contentType = SLStatic.getHeader(rawContent, 'content-type');
if (msgSendAt === undefined) {
return;
}
const nextSend = new Date(msgSendAt);
if ((/encrypted/i).test(contentType)) {
SLStatic.warn(`Message ${originalMsgId} is encrypted, and will not be processed by Send Later.`);
return;
}
const { preferences, lock } = await browser.storage.local.get({
preferences: {}, lock: {}
});
if (!preferences.sendWhileOffline && !window.navigator.onLine) {
SLStatic.debug(`Send Later is configured to disable sending while offline. Skipping.`);
return;
}
if (!msgUUID) {
SLStatic.debug(`Message <${originalMsgId}> has no uuid header.`);
return;
}
if (msgUUID !== preferences.instanceUUID) {
SLStatic.debug(`Message <${originalMsgId}> is scheduled by a different Thunderbird isntance.`);
return;
}
if (lock[originalMsgId]) {
const msgSubject = SLStatic.getHeader(rawContent, 'subject');
if (preferences.optOutResendWarning === true) {
SLStatic.debug(`Encountered previously sent message "${msgSubject}" ${originalMsgId}.`);
} else {
SLStatic.error(`Attempted to resend message "${msgSubject}" ${originalMsgId}.`);
const result = await browser.SL3U.alertCheck(
"",
browser.i18n.getMessage("CorruptFolderError", [msgHdr.folder.path]) + "\n\n" +
browser.i18n.getMessage("CorruptFolderErrorDetails", [msgSubject, originalMsgId]),
browser.i18n.getMessage("ConfirmAgain"),
true
);
preferences.optOutResendWarning = (result.check === false);
await browser.storage.local.set({ preferences });
}
return;
}
if (!(Date.now() >= nextSend.getTime())) {
SLStatic.debug(`Message ${msgHdr.id} not due for send until ${SLStatic.humanDateTimeFormat(nextSend)}`);
return;
}
if (await this.isEditing(originalMsgId)) {
SLStatic.debug(`Skipping message ${originalMsgId} while it is being edited`);
return;
}
const recur = SLStatic.parseRecurSpec(msgRecurSpec);
const args = msgRecurArgs ? SLStatic.parseArgs(msgRecurArgs) : null;
// Respect late message blocker
if (preferences.blockLateMessages) {
const lateness = (Date.now() - nextSend.getTime()) / 60000;
if (lateness > preferences.lateGracePeriod) {
SLStatic.warn(`Grace period exceeded for message ${msgHdr.id}`);
if (!this.warnedAboutLateMessageBlocked.has(originalMsgId)) {
const msgSubject = SLStatic.getHeader(rawContent, "subject");
const warningMsg = browser.i18n.getMessage(
"BlockedLateMessage",
[msgSubject, msgHdr.folder.path, preferences.lateGracePeriod]
);
const warningTitle = browser.i18n.getMessage("ScheduledMessagesWarningTitle");
this.warnedAboutLateMessageBlocked.add(originalMsgId);
browser.SL3U.alert(warningTitle, warningMsg)
}
return;
}
}
if (preferences.enforceTimeRestrictions) {
// Respect "send between" preference
if (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;
}
}
// Respect "only on days of week" preference
if (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;
const nextRecurAt = SLStatic.adjustDateForRestrictions(
new Date(), start_time, end_time, recur.days, false
);
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 = rawContent;
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"X-Send-Later-At",
SLStatic.parseableDateTimeFormat(nextRecurAt),
false
);
const idkey = SLStatic.getHeader(rawContent, "X-Identity-Key");
const newMessageId = await browser.SL3U.generateMsgId(idkey);
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"Message-ID",
newMessageId,
false
);
if (preferences.markDraftsRead) {
this.watchAndMarkRead.add(newMessageId);
}
const success = await browser.SL3U.saveMessage(
msgHdr.folder.accountId,
msgHdr.folder.path,
newMsgContent
);
if (success) {
SLStatic.debug(`Rescheduled message ${originalMsgId}. Deleting original.`);
return "delete_original";
} else {
SLStatic.error("Unable to schedule next recuurrence.");
return;
}
}
}
}
// Initiate send from draft message
SLStatic.info(`Sending message ${originalMsgId}.`);
const success = await browser.SL3U.sendRaw(
SLStatic.prepNewMessageHeaders(rawContent),
preferences.sendUnsentMsgs
).catch((ex) => {
SLStatic.error(`Error sending raw message from drafts`, ex);
return null;
});
if (success) {
lock[originalMsgId] = true;
browser.storage.local.set({ lock }).then(() => {
SLStatic.debug(`Locked message <${originalMsgId}> from re-sending.`);
});
if (preferences.throttleDelay) {
SLStatic.debug(`Throttling send rate: ${preferences.throttleDelay/1000}s`);
await new Promise(resolve =>
setTimeout(resolve, preferences.throttleDelay)
);
}
} else {
SLStatic.error(`Something went wrong while sending message ${originalMsgId}`);
return;
}
let nextRecur;
if (recur.type !== "none") {
nextRecur = await SLStatic.nextRecurDate(
nextSend,
msgRecurSpec,
new Date(),
args
);
}
if (nextRecur) {
let nextRecurAt, nextRecurSpec, nextRecurArgs;
if (nextRecur.getTime) {
nextRecurAt = nextRecur;
} else {
nextRecurAt = nextRecur.sendAt;
nextRecurSpec = nextRecur.nextspec;
nextRecurArgs = nextRecur.nextargs;
}
SLStatic.info(`Scheduling next recurrence of message ${originalMsgId}`,
{nextRecurAt, nextRecurSpec, nextRecurArgs});
let newMsgContent = rawContent;
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"Date",
SLStatic.parseableDateTimeFormat(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,
true
);
}
newMsgContent = SLStatic.appendHeader(
newMsgContent,
"References",
originalMsgId
);
const idkey = SLStatic.getHeader(rawContent, "X-Identity-Key");
const newMessageId = await browser.SL3U.generateMsgId(idkey);
newMsgContent = SLStatic.replaceHeader(
newMsgContent,
"Message-ID",
newMessageId,
false
);
if (preferences.markDraftsRead) {
this.watchAndMarkRead.add(newMessageId);
}
const success = await browser.SL3U.saveMessage(
msgHdr.folder.accountId,
msgHdr.folder.path,
newMsgContent
);
if (success) {
SLStatic.info(`Scheduled next occurrence of message ` +
`<${originalMsgId}>. Deleting original.`);
// browser.messages.delete([msgHdr.id], true);
return "delete_original";
} else {
SLStatic.error("Unable to schedule next recuurrence.");
}
} else {
SLStatic.info(`No recurrences for message ${originalMsgId} (${msgHdr.id}). Deleting original.`);
//browser.messages.delete([msgHdr.id], true);
return "delete_original";
}
},
async migratePreferences() {
// Migrate legacy preferences to local storage.
const { ufuncs, preferences } = await browser.storage.local.get({
preferences: {},
ufuncs: {},
});
const currentMigrationNumber = preferences.migratedLegacy|0;
// Load the default user functions.
const isComplete = (v) => v && v.body && v.help;
if (
!isComplete(ufuncs.ReadMeFirst) ||
!isComplete(ufuncs.BusinessHours) ||
!isComplete(ufuncs.DaysInARow) ||
!isComplete(ufuncs.Delay)
) {
ufuncs.ReadMeFirst = {
help: browser.i18n.getMessage("EditorReadMeHelp"),
body: browser.i18n.getMessage("EditorReadMeCode"),
};
ufuncs.BusinessHours = {
help: browser.i18n.getMessage("BusinessHoursHelp"),
body: browser.i18n.getMessage("_BusinessHoursCode"),
};
ufuncs.DaysInARow = {
help: browser.i18n.getMessage("DaysInARowHelp"),
body: browser.i18n.getMessage("DaysInARowCode"),
};
ufuncs.Delay = {
help: browser.i18n.getMessage("DelayFunctionHelp"),
body: "next = new Date(Date.now() + args[0]*60000);",
};
}
const prefDefaults = await fetch(
"/utils/defaultPrefs.json"
).then((ptxt) => ptxt.json());
// Load legacy preferences
if (currentMigrationNumber === 0) {
// Merge any existing legacy preferences into the new storage system
let prefKeys = [];
let legacyValuePromises = [];
// Load values from legacy storage, substitute defaults if not defined.
for (let prefName of Object.getOwnPropertyNames(prefDefaults)) {
prefKeys.push(prefName);
let dtype = prefDefaults[prefName][0];
let defVal = prefDefaults[prefName][1];
let legacyKey = prefDefaults[prefName][2];
let pp; // Promise that resolves to this preference value.
const isquickopt = prefName.match(/quickOptions(\d)Label/);
if (isquickopt) {
const delayMins = (+prefDefaults[`quickOptions${isquickopt[1]}Args`][1])|0;
const localizedDelayLabel =
`${(new Sugar.Date(Date.now() + 60000 * delayMins)).relative()}`;
pp = new Promise((resolve, reject) => {
resolve(localizedDelayLabel)
});
} else if (legacyKey === null) {
pp = new Promise((resolve, reject) => resolve(defVal));
} else {
pp = browser.SL3U.getLegacyPref(
legacyKey,
dtype,
defVal.toString()
);
}
legacyValuePromises.push(pp);
}
// Combine keys and legacy/default values back into a single object.
let legacyPrefs = await Promise.all(legacyValuePromises).then(
(legacyVals) => {
return legacyVals.reduce((r, f, i) => {
r[prefKeys[i]] = f;
return r;
}, {});
}
);
SLStatic.info("SendLater: migrating legacy/default preferences.");
// Merge legacy preferences into undefined preference keys
prefKeys.forEach((key) => {
if (preferences[key] === undefined) {
preferences[key] = legacyPrefs[key];
}
});
}
SLStatic.logConsoleLevel = (preferences.logConsoleLevel||"info").toLowerCase();
// Pick up any new properties from defaults
for (let prefName of Object.getOwnPropertyNames(prefDefaults)) {
if (preferences[prefName] === undefined) {
const prefValue = prefDefaults[prefName][1];
SLStatic.debug(`Added new preference ${prefName}: ${prefValue}`);
preferences[prefName] = prefValue;
}
}
//if (currentMigrationNumber < 4)
if (preferences.instanceUUID) {
SLStatic.info(`This instance's UUID: ${preferences.instanceUUID}`);
} else {
let instance_uuid = await browser.SL3U.getLegacyPref(
"instance.uuid", "string", "");
if (instance_uuid) {
SLStatic.info(`Using migrated UUID: ${instance_uuid}`);
} else {
instance_uuid = SLStatic.generateUUID();
SLStatic.info(`Generated new UUID: ${instance_uuid}`);
}
preferences.instanceUUID = instance_uuid;
browser.SL3U.setLegacyPref("instance.uuid", "string", instance_uuid);
}
if (currentMigrationNumber < SLStatic.CURRENT_LEGACY_MIGRATION) {
preferences.migratedLegacy = SLStatic.CURRENT_LEGACY_MIGRATION;
}
if (preferences.migratedLegacy !== SLStatic.CURRENT_LEGACY_MIGRATION) {
SLStatic.error("Something has gone wrong with migrating preferences. " +
"The migration number is currently set to an " +
"invalid value:", preferences.migratedLegacy);
}
await browser.storage.local.set({ preferences, ufuncs });
return currentMigrationNumber;
},
async getActiveSchedules(matchUUID) {
const allSchedulePromises = await browser.accounts.list().then(async accounts => {
let folderSchedules = [];
for (let acct of accounts) {
let draftFolders = await getDraftFolders(acct);
if (draftFolders && draftFolders.length > 0) {
for (let draftFolder of draftFolders) {
if (draftFolder) {
try {
SLStatic.debug(`Checking for messages in folder ${draftFolder.path}`);
const accountId = draftFolder.accountId, path = draftFolder.path;
const thisFoldersSchedulePromise = browser.SL3U.getAllScheduledMessages(
accountId, path, false, true
).then(messages => {
let schedules = [];
for (let message of messages) {
const msgSendAt = message["x-send-later-at"];
const msgUUID = message["x-send-later-uuid"];
if (msgSendAt === undefined) {
//return null;
} else if (matchUUID && msgUUID != matchUUID) {
//return null;
} else {
const nextSend = new Date(msgSendAt).getTime();
schedules.push(nextSend);
}
}
return schedules;
});
folderSchedules.push(thisFoldersSchedulePromise);
} catch (ex0) {
SLStatic.error(ex0);
}
}
}
} else {
SLStatic.debug(`getActiveSchedules: Unable to find drafts folder for account`, acct);
}
}
return SLStatic.flatten(folderSchedules);
}).catch(SLStatic.error);
const allSchedules = await Promise.all(allSchedulePromises);
return SLStatic.flatten(allSchedules);
},
async doSanityCheck() {
const { preferences } = await browser.storage.local.get({ preferences: {} });
let message = "";
try { // Compact Drafts folders and Outbox folder
const compactedDrafts = await this.forAllDraftFolders(
async folder => {
const accountId = folder.accountId, path = folder.path;
SLStatic.log(`Compacting folder <${path}> in account ${accountId}`);
return browser.SL3U.compactFolder(accountId, path);
});
const compactedOutbox = await browser.SL3U.compactFolder("", "outbox");
if (compactedDrafts.every(v => v === true)) {
SLStatic.debug("Successfully compacted Drafts.");
} else {
let errMsg = browser.i18n.getMessage("CompactionFailureNoError", ["Drafts"]);
message += "\n\n"+errMsg;
}
if (compactedOutbox) {
SLStatic.debug("Successfully compacted Outbox.");
} else {
let errMsg = browser.i18n.getMessage("CompactionFailureNoError", ["Outbox"]);
message += "\n\n"+errMsg;
}
} catch (e) {
SLStatic.error("Compacting Outbox and/or Drafts folders failed with error",e);
let errMsg = browser.i18n.getMessage("CompactionFailureWithError");
message += `\n\n${errMsg}\n${e}`;
}
const activeSchedules = await this.getActiveSchedules(preferences.instanceUUID);
const nActive = activeSchedules.length;
if (nActive > 0) {
const soonest = new Date(Math.min(...activeSchedules));
const nextActiveText = SLStatic.humanDateTimeFormat(soonest) +
` (${(new Sugar.Date(soonest)).relative()})`;
message += "\n\n" + browser.i18n.getMessage("SanityCheckDrafts", [nActive, nextActiveText]);
}
const nUnsentMessages = await browser.SL3U.countUnsentMessages();
if (nUnsentMessages > 0 && preferences.sendUnsentMsgs) {
message += "\n\n" + browser.i18n.getMessage("SanityCheckOutbox", [nUnsentMessages]);
}
if (message !== "") {
const title = browser.i18n.getMessage("extensionName");
message += "\n\n" + browser.i18n.getMessage("SanityCheckCorruptFolderWarning");
message += `\n\n` + browser.i18n.getMessage("SanityCheckConfirmOptionMessage");
const okay = await browser.SL3U.confirm(title, message.trim());
if (!okay) {
SLStatic.info("Disabling Send Later per user selection.");
preferences.checkTimePref = 0;
// We dont need to do the whole migration again next time, but
// we should run the sanity check once more until the user hits
// 'okay' to close it. Hard code back to legacy migration 2, because
// this sanity check was implemented in migration 3.
preferences.migratedLegacy = 2;
await browser.storage.local.set({ preferences });
return false;
}
}
return true;
},
async claimDrafts() {
/*
* Because the x-send-later-uuid header was omitted in beta
* releases <= 8.0.15, there may be some scheduled drafts
* which do not have an associated instance id.
*
* This function will scan all drafts for messages with an
* x-send-later-at header but no x-send-later-uuid header.
* It will create a new message with this instance's uuid,
* and delete the existing draft.
*
* This should only happen once, and only for users who
* have been following the beta releases.
*/
let claimed = await this.forAllDrafts(async (msg) => {
const rawContent = await browser.messages.getRaw(msg.id).catch(err => {
SLStatic.warn(`Unable to fetch message ${msg.id}.`, err);
});
if (!rawContent) {
SLStatic.warn("claimDrafts.forAllDrafts failed. Unable to get raw message contents.",msg);
return;
}
const sendAt = SLStatic.getHeader(rawContent, "x-send-later-at");
const uuid = SLStatic.getHeader(rawContent, 'x-send-later-uuid');
if (sendAt && !uuid) {
const msgId = SLStatic.getHeader(rawContent, 'message-id');
const subject = SLStatic.getHeader(rawContent, 'subject');
SLStatic.info(`Adding UUID to message ${msgId} (${subject})`);
const { preferences } =
await browser.storage.local.get({ preferences: {} });
const idkey = SLStatic.getHeader(rawContent, "X-Identity-Key");
const newMessageId = await browser.SL3U.generateMsgId(idkey);
let newMsgContent = rawContent;
newMsgContent = SLStatic.replaceHeader(
newMsgContent, "Message-ID", newMessageId, false);
newMsgContent = SLStatic.replaceHeader(
newMsgContent, "X-Send-Later-Uuid", preferences.instanceUUID,
false, true);
newMsgContent = SLStatic.appendHeader(
newMsgContent, "References", msgId);
if (msg.read) {
this.watchAndMarkRead.add(newMessageId);
}
const success = await browser.SL3U.saveMessage(
msg.folder.accountId,
msg.folder.path,
newMsgContent
);
if (success) {
SLStatic.log(`Saved new message id: ${newMessageId}. ` +
`Deleting original.`);
browser.messages.delete([msg.id], true);
return newMessageId;
} else {
SLStatic.error("Unable to claim message");
}
}
});
claimed = claimed.filter(v => v !== null && v !== undefined);
SLStatic.info(`Claimed ${claimed.length} scheduled messages.`);
},
async setStatusBarIndicator(isActive) {
let statusMsg;
if (isActive) {
statusMsg = browser.i18n.getMessage("CheckingMessage");
} else {
const { preferences } = await browser.storage.local.get({ preferences: {} });
const activeSchedules = await this.getActiveSchedules(preferences.instanceUUID);
const nActive = activeSchedules.length;
browser.SL3U.setSendLaterVar("messages_pending", nActive);
if (nActive > 0) {
statusMsg = browser.i18n.getMessage("PendingMessage", [nActive]);
} else {
statusMsg = browser.i18n.getMessage("IdleMessage");
}
}
const extName = browser.i18n.getMessage("extensionName");
return await browser.SL3U.showStatus(`${extName} [${statusMsg}]`);
},
async init() {
await this.printVersionInfo();
// Set custom DB headers preference, if not already set.
await browser.SL3U.setCustomDBHeaders();
// Before preferences are available, let's set logging
// to the default level.
SLStatic.logConsoleLevel = "info";
// Clear the current message settings cache
browser.storage.local.set({ scheduleCache: {} });
// Perform any pending preference migrations.
const previousMigration = await this.migratePreferences();
if (previousMigration < 3) {
// This really shouldn't be necessary, but we should check
// whether the outbox and drafts folders might be corrupted.
await this.doSanityCheck();
}
if (previousMigration > 0 && previousMigration < 4) {
await this.claimDrafts();
}
const { preferences } =
await browser.storage.local.get({ preferences: {} });
this.prefCache = preferences;
// This listener should be added *after* all of the storage-related
// setup is complete. It makes sure that subsequent changes to storage
// are propagated to their respective
browser.storage.onChanged.addListener(async (changes, areaName) => {
if (areaName === "local") {
SLStatic.debug("Propagating changes from local storage");
const { preferences } =
await browser.storage.local.get({ preferences: {} });
this.prefCache = preferences;
SLStatic.logConsoleLevel = preferences.logConsoleLevel.toLowerCase();
const prefString = JSON.stringify(preferences);
await browser.SL3U.notifyStorageLocal(prefString, false);
}
});
await browser.SL3U.injectScripts([
"utils/sugar-custom.js",
"utils/static.js",
"experiments/headerView.js",
"experiments/statusBar.js"
]);
setTimeout(() => {
const prefString = JSON.stringify(preferences);
browser.SL3U.notifyStorageLocal(prefString, true);
}, 1000);
SLStatic.debug("Registering window listeners");
await browser.SL3U.startObservers();
await browser.SL3U.bindKeyCodes();
await this.setStatusBarIndicator(false);
}
}; // SendLater
browser.SL3U.onKeyCode.addListener(keyid => {
SLStatic.info(`Received keycode ${keyid}`);
switch (keyid) {
case "key_altShiftEnter": {
if (SendLater.prefCache.altBinding) {
browser.composeAction.openPopup();
} else {
SLStatic.info("Ignoring Alt+Shift+Enter on account of user preferences");
}
break;
}
case "key_sendLater":
{ // User pressed ctrl+shift+enter
SLStatic.debug("Received Ctrl+Shift+Enter.");
if (SendLater.prefCache.altBinding) {
SLStatic.info("Passing Ctrl+Shift+Enter along to builtin send later " +
"because user bound alt+shift+enter instead.");
browser.SL3U.builtInSendLater().catch((ex) => {
SLStatic.error("Error during builtin send later",ex);
});
} else {
SLStatic.info("Opening popup");
browser.composeAction.openPopup();
}
break;
}
case "cmd_sendLater":
{ // User clicked the "Send Later" menu item, which should always
// open the Send Later popup.
browser.composeAction.openPopup();
break;
}
case "cmd_sendNow":
case "cmd_sendButton":
case "key_send":
{
if (SendLater.prefCache.sendDoesSL) {
SLStatic.debug("Opening scheduler dialog.");
browser.composeAction.openPopup();
} else if (SendLater.prefCache.sendDoesDelay) {
//Schedule with delay
const sendDelay = SendLater.prefCache.sendDelay;
SLStatic.info(`Scheduling Send Later ${sendDelay} minutes from now.`);
browser.windows.getAll({
populate: true,
windowTypes: ["messageCompose"]
}).then((allWindows) => {
// Current compose windows
const ccWins = allWindows.filter((cWindow) => (cWindow.focused === true));
if (ccWins.length === 1) {
const ccTabs = ccWins[0].tabs.filter(tab => (tab.active === true));
if (ccTabs.length !== 1) { // No tabs?
throw new Error(`Unexpected situation: no tabs found in current window`);
}
const tabId = ccTabs[0].id;
SendLater.preSendCheck.call(SendLater).then(dosend => {
if (dosend) {
SendLater.scheduleSendLater.call(SendLater, tabId, { delay: sendDelay });
} else {
SLStatic.info("User cancelled send via pre-send check.");
}
});
} else if (ccWins.length === 0) {
// No compose window is opened
SLStatic.warn(`The currently active window is not a messageCompose window`);
} else {
// Whaaaat!?!?
throw new Error(`Unexpected situation: multiple active windows found?`);
}
});
} else {
// Just pass along to the builtin command
let command = keyid;
if (command === "key_send")
command = "cmd_sendWithCheck";
browser.SL3U.goDoCommand(command).catch((ex) => {
SLStatic.error("Error during builtin send operation",ex);
});
}
break;
}
default: {
SLStatic.error(`Unrecognized keycode ${keyid}`);
}
}
});
browser.runtime.onMessageExternal.addListener(
(message, sender, sendResponse) => {
if (message["action"] === "getPreferences") {
browser.storage.local.get({"preferences":{}}).then(storage => {
for (const prop in storage["preferences"]) {
if (!SLStatic.prefInputIds.includes(prop)) {
delete storage.preferences[prop];
}
}
sendResponse(storage.preferences);
});
return true;
}
else if (message["action"] === "setPreferences") {
new_prefs = message.preferences;
browser.storage.local.get({"preferences":{}}).then(storage => {
old_prefs = storage.preferences;
for (const prop in new_prefs) {
if (!SLStatic.prefInputIds.includes(prop)) {
throw `Property ${prop} is not a valid Send Later preference.`;
}
if (prop in old_prefs && typeof(old_prefs[prop]) != "undefined" &&
typeof(new_prefs[prop]) != "undefined" &&
typeof(old_prefs[prop]) != typeof(new_prefs[prop])) {
throw `Type of ${prop} is invalid: new ` +
`${typeof(new_prefs[prop])} vs. current ` +
`${typeof(old_prefs[prop])}.`;
}
old_prefs[prop] = new_prefs[prop];
}
browser.storage.local.set(storage).then((result) => {
sendResponse(old_prefs)
});
});
return true;
}
else if (message["action"] === "parseDate") {
try {
const date = SLStatic.convertDate(message["value"], true);
if (date) {
const dateStr = SLStatic.parseableDateTimeFormat(date.getTime());
sendResponse(dateStr);
return;
}
} catch (ex) {
SLStatic.debug("Unable to parse date/time",ex);
}
sendResponse(null);
}
});
browser.runtime.onMessage.addListener(async (message) => {
const response = {};
switch (message.action) {
case "alert": {
SendLater.notify(message.title, message.text);
break;
}
case "doSendNow": {
SLStatic.debug("User requested send immediately.");
const { preferences } = await browser.storage.local.get({ preferences: {} });
if (preferences.showSendNowAlert) {
const result = await browser.SL3U.confirmCheck(
browser.i18n.getMessage("AreYouSure"),
browser.i18n.getMessage("SendNowConfirmMessage"),
browser.i18n.getMessage("ConfirmAgain"),
true
).catch((err) => {
SLStatic.trace(err);
});
if (result.check === false) {
preferences.showSendNowAlert = false;
browser.storage.local.set({ preferences });