This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
mailbridge.js
1202 lines (1073 loc) · 36.4 KB
/
mailbridge.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
/**
*
**/
define(
[
'rdcommon/log',
'./util',
'./mailchew-strings',
'./date',
'./slice_bridge_proxy',
'require',
'module',
'exports'
],
function(
$log,
$imaputil,
$mailchewStrings,
$date,
$sliceBridgeProxy,
require,
$module,
exports
) {
var bsearchForInsert = $imaputil.bsearchForInsert,
bsearchMaybeExists = $imaputil.bsearchMaybeExists,
SliceBridgeProxy = $sliceBridgeProxy.SliceBridgeProxy;
function toBridgeWireOn(x) {
return x.toBridgeWire();
}
var FOLDER_TYPE_TO_SORT_PRIORITY = {
account: 'a',
inbox: 'c',
starred: 'e',
important: 'f',
drafts: 'g',
localdrafts: 'h',
queue: 'i',
sent: 'j',
junk: 'k',
trash: 'm',
archive: 'o',
normal: 'z',
// nomail folders are annoying since they are basically just hierarchy,
// but they are also rare and should only happen amongst normal folders.
nomail: 'z',
};
/**
* Make a folder sorting function that groups folders by account, puts the
* account header first in that group, maps priorities using
* FOLDER_TYPE_TO_SORT_PRIORITY, then sorts by path within that.
*
* This is largely necessitated by localeCompare being at the mercy of glibc's
* locale database and failure to fallback to unicode code points for
* comparison purposes.
*/
function makeFolderSortString(account, folder) {
if (!folder)
return account.id;
var parentFolder = account.getFolderMetaForFolderId(folder.parentId);
return makeFolderSortString(account, parentFolder) + '!' +
FOLDER_TYPE_TO_SORT_PRIORITY[folder.type] + '!' +
folder.name.toLocaleLowerCase();
}
function strcmp(a, b) {
if (a < b)
return -1;
else if (a > b)
return 1;
return 0;
}
function checkIfAddressListContainsAddress(list, addrPair) {
if (!list)
return false;
var checkAddress = addrPair.address;
for (var i = 0; i < list.length; i++) {
if (list[i].address === checkAddress)
return true;
}
return false;
}
/**
* There is exactly one `MailBridge` instance for each `MailAPI` instance.
* `same-frame-setup.js` is the only place that hooks them up together right
* now.
*/
function MailBridge(universe, name) {
this.universe = universe;
this.universe.registerBridge(this);
this._LOG = LOGFAB.MailBridge(this, universe._LOG, name);
/** @dictof[@key[handle] @value[BridgedViewSlice]]{ live slices } */
this._slices = {};
/** @dictof[@key[namespace] @value[@listof[BridgedViewSlice]]] */
this._slicesByType = {
accounts: [],
identities: [],
folders: [],
headers: [],
matchedHeaders: [],
};
/**
* Observed bodies in the format of:
*
* @dictof[
* @key[suid]
* @value[@dictof[
* @key[handleId]
* @value[@oneof[Function null]]
* ]]
* ]
*
* Similar in concept to folder slices but specific to bodies.
*/
this._observedBodies = {};
// outstanding persistent objects that aren't slices. covers: composition
this._pendingRequests = {};
//
this._lastUndoableOpPair = null;
}
exports.MailBridge = MailBridge;
MailBridge.prototype = {
__sendMessage: function(msg) {
throw new Error('This is supposed to get hidden by an instance var.');
},
__receiveMessage: function mb___receiveMessage(msg) {
var implCmdName = '_cmd_' + msg.type;
if (!(implCmdName in this)) {
this._LOG.badMessageType(msg.type);
return;
}
var rval = this._LOG.cmd(msg.type, this, this[implCmdName], msg);
},
_cmd_ping: function mb__cmd_ping(msg) {
this.__sendMessage({
type: 'pong',
handle: msg.handle,
});
},
_cmd_modifyConfig: function mb__cmd_modifyConfig(msg) {
this.universe.modifyConfig(msg.mods);
},
/**
* Public api to verify if body has observers.
*
*
* MailBridge.bodyHasObservers(header.id) // => true/false.
*
*/
bodyHasObservers: function(suid) {
return !!this._observedBodies[suid];
},
notifyConfig: function(config) {
this.__sendMessage({
type: 'config',
config: config,
});
},
_cmd_debugSupport: function mb__cmd_debugSupport(msg) {
switch (msg.cmd) {
case 'setLogging':
this.universe.modifyConfig({ debugLogging: msg.arg });
break;
case 'dumpLog':
switch (msg.arg) {
case 'storage':
this.universe.dumpLogToDeviceStorage();
break;
}
break;
}
},
_cmd_setInteractive: function mb__cmd_setInteractive(msg) {
this.universe.setInteractive();
},
_cmd_localizedStrings: function mb__cmd_localizedStrings(msg) {
$mailchewStrings.set(msg.strings);
},
_cmd_tryToCreateAccount: function mb__cmd_tryToCreateAccount(msg) {
var self = this;
this.universe.tryToCreateAccount(msg.details, msg.domainInfo,
function(error, account, errorDetails) {
self.__sendMessage({
type: 'tryToCreateAccountResults',
handle: msg.handle,
account: account ? account.toBridgeWire() : null,
error: error,
errorDetails: errorDetails,
});
});
},
_cmd_clearAccountProblems: function mb__cmd_clearAccountProblems(msg) {
var account = this.universe.getAccountForAccountId(msg.accountId),
self = this;
account.checkAccount(function(err) {
// If we succeeded or the problem was not an authentication, assume
// everything went fine and clear the problems. This includes the case
// we're offline.
if (!err || (
err !== 'bad-user-or-pass' &&
err !== 'bad-address' &&
err !== 'needs-app-pass' &&
err !== 'imap-disabled'
)) {
self.universe.clearAccountProblems(account);
}
// The login information is still bad; re-send the bad login notification.
else {
// This is only being sent over this, the same bridge the clear request
// came from rather than sent via the mailuniverse. No point having the
// notifications stack up on inactive UIs.
self.notifyBadLogin(account, err);
}
self.__sendMessage({
type: 'clearAccountProblems',
handle: msg.handle,
});
});
},
_cmd_modifyAccount: function mb__cmd_modifyAccount(msg) {
var account = this.universe.getAccountForAccountId(msg.accountId),
accountDef = account.accountDef;
for (var key in msg.mods) {
var val = msg.mods[key];
switch (key) {
case 'name':
accountDef.name = val;
break;
case 'username':
accountDef.credentials.username = val;
break;
case 'password':
accountDef.credentials.password = val;
break;
case 'identities':
// TODO: support identity mutation
// we expect a list of identity mutation objects, namely an id and the
// rest are attributes to change
break;
case 'servers':
// TODO: support server mutation
// we expect a list of server mutation objects; namely, the type names
// the server and the rest are attributes to change
break;
case 'syncRange':
accountDef.syncRange = val;
break;
case 'syncInterval':
accountDef.syncInterval = val;
break;
case 'notifyOnNew':
accountDef.notifyOnNew = val;
break;
case 'setAsDefault':
// Weird things can happen if the device's clock goes back in time,
// but this way, at least the user can change their default if they
// cycle through their accounts.
if (val)
accountDef.defaultPriority = $date.NOW();
break;
}
}
this.universe.saveAccountDef(accountDef, null);
},
_cmd_deleteAccount: function mb__cmd_deleteAccount(msg) {
this.universe.deleteAccount(msg.accountId);
},
notifyBadLogin: function mb_notifyBadLogin(account, problem) {
this.__sendMessage({
type: 'badLogin',
account: account.toBridgeWire(),
problem: problem
});
},
_cmd_viewAccounts: function mb__cmd_viewAccounts(msg) {
var proxy = this._slices[msg.handle] =
new SliceBridgeProxy(this, 'accounts', msg.handle);
proxy.markers = this.universe.accounts.map(function(x) { return x.id; });
this._slicesByType['accounts'].push(proxy);
var wireReps = this.universe.accounts.map(toBridgeWireOn);
// send all the accounts in one go.
proxy.sendSplice(0, 0, wireReps, true, false);
},
notifyAccountAdded: function mb_notifyAccountAdded(account) {
var accountWireRep = account.toBridgeWire();
var i, proxy, slices, wireSplice = null, markersSplice = null;
// -- notify account slices
slices = this._slicesByType['accounts'];
for (i = 0; i < slices.length; i++) {
proxy = slices[i];
proxy.sendSplice(proxy.markers.length, 0, [accountWireRep], false, false);
proxy.markers.push(account.id);
}
// -- notify folder slices
accountWireRep = account.toBridgeFolder();
slices = this._slicesByType['folders'];
var startMarker = makeFolderSortString(account, accountWireRep),
idxStart;
for (i = 0; i < slices.length; i++) {
proxy = slices[i];
// If it's filtered to an account, it can't care about us. (You can't
// know about an account before it's created.)
if (proxy.mode === 'account')
continue;
idxStart = bsearchForInsert(proxy.markers, startMarker, strcmp);
wireSplice = [accountWireRep];
markersSplice = [startMarker];
for (var iFolder = 0; iFolder < account.folders.length; iFolder++) {
var folder = account.folders[iFolder],
folderMarker = makeFolderSortString(account, folder),
idxFolder = bsearchForInsert(markersSplice, folderMarker, strcmp);
wireSplice.splice(idxFolder, 0, folder);
markersSplice.splice(idxFolder, 0, folderMarker);
}
proxy.sendSplice(idxStart, 0, wireSplice, false, false);
proxy.markers.splice.apply(proxy.markers,
[idxStart, 0].concat(markersSplice));
}
},
/**
* Generate modifications for an account. We only generate this for account
* queries proper and not the folder representations of accounts because we
* define that there is nothing interesting mutable for the folder
* representations.
*/
notifyAccountModified: function(account) {
var slices = this._slicesByType['accounts'],
accountWireRep = account.toBridgeWire();
for (var i = 0; i < slices.length; i++) {
var proxy = slices[i];
var idx = proxy.markers.indexOf(account.id);
if (idx !== -1) {
proxy.sendUpdate([idx, accountWireRep]);
}
}
},
notifyAccountRemoved: function(accountId) {
var i, proxy, slices;
// -- notify account slices
slices = this._slicesByType['accounts'];
for (i = 0; i < slices.length; i++) {
proxy = slices[i];
var idx = proxy.markers.indexOf(accountId);
if (idx !== -1) {
proxy.sendSplice(idx, 1, [], false, false);
proxy.markers.splice(idx, 1);
}
}
// -- notify folder slices
slices = this._slicesByType['folders'];
var startMarker = accountId + '!!',
endMarker = accountId + '!|';
for (i = 0; i < slices.length; i++) {
proxy = slices[i];
var idxStart = bsearchForInsert(proxy.markers, startMarker,
strcmp),
idxEnd = bsearchForInsert(proxy.markers, endMarker,
strcmp);
if (idxEnd !== idxStart) {
proxy.sendSplice(idxStart, idxEnd - idxStart, [], false, false);
proxy.markers.splice(idxStart, idxEnd - idxStart);
}
}
},
_cmd_viewSenderIdentities: function mb__cmd_viewSenderIdentities(msg) {
var proxy = this._slices[msg.handle] =
new SliceBridgeProxy(this, identities, msg.handle);
this._slicesByType['identities'].push(proxy);
var wireReps = this.universe.identities;
// send all the identities in one go.
proxy.sendSplice(0, 0, wireReps, true, false);
},
_cmd_requestBodies: function(msg) {
var self = this;
this.universe.downloadBodies(msg.messages, msg.options, function() {
self.__sendMessage({
type: 'requestBodiesComplete',
handle: msg.handle,
requestId: msg.requestId
});
});
},
notifyFolderAdded: function(account, folderMeta) {
var newMarker = makeFolderSortString(account, folderMeta);
var slices = this._slicesByType['folders'];
for (var i = 0; i < slices.length; i++) {
var proxy = slices[i];
var idx = bsearchForInsert(proxy.markers, newMarker, strcmp);
proxy.sendSplice(idx, 0, [folderMeta], false, false);
proxy.markers.splice(idx, 0, newMarker);
}
},
notifyFolderModified: function(account, folderMeta) {
var marker = makeFolderSortString(account, folderMeta);
var slices = this._slicesByType['folders'];
for (var i = 0; i < slices.length; i++) {
var proxy = slices[i];
var idx = bsearchMaybeExists(proxy.markers, marker, strcmp);
if (idx === null)
continue;
proxy.sendUpdate([idx, folderMeta]);
}
},
notifyFolderRemoved: function(account, folderMeta) {
var marker = makeFolderSortString(account, folderMeta);
var slices = this._slicesByType['folders'];
for (var i = 0; i < slices.length; i++) {
var proxy = slices[i];
var idx = bsearchMaybeExists(proxy.markers, marker, strcmp);
if (idx === null)
continue;
proxy.sendSplice(idx, 1, [], false, false);
proxy.markers.splice(idx, 1);
}
},
/**
* Sends a notification of a change in the body. Because FolderStorage is
* the authoritative store of body representations and access is currently
* mediated through mutexes, this method should really only be called by
* FolderStorage.updateMessageBody.
*
* @param suid {SUID}
* The message whose body representation has been updated
* @param detail {Object}
* See {{#crossLink "FolderStorage/updateMessageBody"}{{/crossLink}} for
* more information on the structure of this object.
* @param body {BodyInfo}
* The current representation of the body.
*/
notifyBodyModified: function(suid, detail, body) {
var handles = this._observedBodies[suid];
var defaultHandler = this.__sendMessage;
if (handles) {
for (var handle in handles) {
// the suid may have an existing handler which captures the output of
// the notification instead of dispatching here... This allows us to
// aggregate pending notifications while fetching the bodies so updates
// never come before the actual body.
var emit = handles[handle] || defaultHandler;
emit.call(this, {
type: 'bodyModified',
handle: handle,
bodyInfo: body,
detail: detail
});
}
}
},
_cmd_viewFolders: function mb__cmd_viewFolders(msg) {
var proxy = this._slices[msg.handle] =
new SliceBridgeProxy(this, 'folders', msg.handle);
this._slicesByType['folders'].push(proxy);
proxy.mode = msg.mode;
proxy.argument = msg.argument;
var markers = proxy.markers = [];
var wireReps = [];
function pushAccountFolders(acct) {
for (var iFolder = 0; iFolder < acct.folders.length; iFolder++) {
var folder = acct.folders[iFolder];
var newMarker = makeFolderSortString(acct, folder);
var idx = bsearchForInsert(markers, newMarker, strcmp);
wireReps.splice(idx, 0, folder);
markers.splice(idx, 0, newMarker);
}
}
if (msg.mode === 'account') {
pushAccountFolders(
this.universe.getAccountForAccountId(msg.argument));
}
else {
var accounts = this.universe.accounts.concat();
// sort accounts by their id's
accounts.sort(function (a, b) {
return a.id.localeCompare(b.id);
});
for (var iAcct = 0; iAcct < accounts.length; iAcct++) {
var acct = accounts[iAcct], acctBridgeRep = acct.toBridgeFolder(),
acctMarker = makeFolderSortString(acct, acctBridgeRep),
idxAcct = bsearchForInsert(markers, acctMarker, strcmp);
wireReps.splice(idxAcct, 0, acctBridgeRep);
markers.splice(idxAcct, 0, acctMarker);
pushAccountFolders(acct);
}
}
proxy.sendSplice(0, 0, wireReps, true, false);
},
_cmd_createFolder: function mb__cmd_createFolder(msg) {
this.universe.createFolder(
msg.accountId,
msg.parentFolderId,
msg.containOnlyOtherFolders);
},
_cmd_viewFolderMessages: function mb__cmd_viewFolderMessages(msg) {
var proxy = this._slices[msg.handle] =
new SliceBridgeProxy(this, 'headers', msg.handle);
this._slicesByType['headers'].push(proxy);
var account = this.universe.getAccountForFolderId(msg.folderId);
account.sliceFolderMessages(msg.folderId, proxy);
},
_cmd_searchFolderMessages: function mb__cmd_searchFolderMessages(msg) {
var proxy = this._slices[msg.handle] =
new SliceBridgeProxy(this, 'matchedHeaders', msg.handle);
this._slicesByType['matchedHeaders'].push(proxy);
var account = this.universe.getAccountForFolderId(msg.folderId);
account.searchFolderMessages(
msg.folderId, proxy, msg.phrase, msg.whatToSearch);
},
_cmd_refreshHeaders: function mb__cmd_refreshHeaders(msg) {
var proxy = this._slices[msg.handle];
if (!proxy) {
this._LOG.badSliceHandle(msg.handle);
return;
}
if (proxy.__listener)
proxy.__listener.refresh();
},
_cmd_growSlice: function mb__cmd_growSlice(msg) {
var proxy = this._slices[msg.handle];
if (!proxy) {
this._LOG.badSliceHandle(msg.handle);
return;
}
if (proxy.__listener)
proxy.__listener.reqGrow(msg.dirMagnitude, msg.userRequestsGrowth);
},
_cmd_shrinkSlice: function mb__cmd_shrinkSlice(msg) {
var proxy = this._slices[msg.handle];
if (!proxy) {
this._LOG.badSliceHandle(msg.handle);
return;
}
if (proxy.__listener)
proxy.__listener.reqNoteRanges(
msg.firstIndex, msg.firstSuid, msg.lastIndex, msg.lastSuid);
},
_cmd_killSlice: function mb__cmd_killSlice(msg) {
var proxy = this._slices[msg.handle];
if (!proxy) {
this._LOG.badSliceHandle(msg.handle);
return;
}
delete this._slices[msg.handle];
var proxies = this._slicesByType[proxy._ns],
idx = proxies.indexOf(proxy);
proxies.splice(idx, 1);
proxy.die();
this.__sendMessage({
type: 'sliceDead',
handle: msg.handle,
});
},
_cmd_getBody: function mb__cmd_getBody(msg) {
var self = this;
// map the message id to the folder storage
var folderStorage = this.universe.getFolderStorageForMessageSuid(msg.suid);
// when requesting the body we also create a observer to notify the client
// of events... We never want to send the updates before fetching the body
// so we buffer them here with a temporary handler.
var pendingUpdates = [];
var catchPending = function catchPending(msg) {
pendingUpdates.push(msg);
};
if (!this._observedBodies[msg.suid])
this._observedBodies[msg.suid] = {};
this._observedBodies[msg.suid][msg.handle] = catchPending;
var handler = function(bodyInfo) {
self.__sendMessage({
type: 'gotBody',
handle: msg.handle,
bodyInfo: bodyInfo
});
// if all body reps where requested we verify that all are present
// otherwise we begin the request for more body reps.
if (
msg.downloadBodyReps &&
!folderStorage.messageBodyRepsDownloaded(bodyInfo)
) {
self.universe.downloadMessageBodyReps(
msg.suid,
msg.date,
function() { /* we don't care it will send update events */ }
);
}
// dispatch pending updates...
pendingUpdates.forEach(self.__sendMessage, self);
pendingUpdates = null;
// revert to default handler. Note! this is intentionally
// set to null and not deleted if deleted the observer is removed.
self._observedBodies[msg.suid][msg.handle] = null;
};
if (msg.withBodyReps)
folderStorage.getMessageBodyWithReps(msg.suid, msg.date, handler);
else
folderStorage.getMessageBody(msg.suid, msg.date, handler);
},
_cmd_killBody: function(msg) {
var handles = this._observedBodies[msg.id];
if (handles) {
delete handles[msg.handle];
var purgeHandles = true;
for (var key in handles) {
purgeHandles = false;
break;
}
if (purgeHandles) {
delete this._observedBodies[msg.id];
}
}
this.__sendMessage({
type: 'bodyDead',
handle: msg.handle
});
},
_cmd_downloadAttachments: function mb__cmd__downloadAttachments(msg) {
var self = this;
this.universe.downloadMessageAttachments(
msg.suid, msg.date, msg.relPartIndices, msg.attachmentIndices,
function(err) {
self.__sendMessage({
type: 'downloadedAttachments',
handle: msg.handle
});
});
},
//////////////////////////////////////////////////////////////////////////////
// Message Mutation
//
// All mutations are told to the universe which breaks the modifications up on
// a per-account basis.
_cmd_modifyMessageTags: function mb__cmd_modifyMessageTags(msg) {
// XXXYYY
// - The mutations are written to the database for persistence (in case
// we fail to make the change in a timely fashion) and so that we can
// know enough to reverse the operation.
// - Speculative changes are made to the headers in the database locally.
var longtermIds = this.universe.modifyMessageTags(
msg.opcode, msg.messages, msg.addTags, msg.removeTags);
this.__sendMessage({
type: 'mutationConfirmed',
handle: msg.handle,
longtermIds: longtermIds,
});
},
_cmd_deleteMessages: function mb__cmd_deleteMessages(msg) {
var longtermIds = this.universe.deleteMessages(
msg.messages);
this.__sendMessage({
type: 'mutationConfirmed',
handle: msg.handle,
longtermIds: longtermIds,
});
},
_cmd_moveMessages: function mb__cmd_moveMessages(msg) {
var longtermIds = this.universe.moveMessages(
msg.messages, msg.targetFolder);
this.__sendMessage({
type: 'mutationConfirmed',
handle: msg.handle,
longtermIds: longtermIds,
});
},
_cmd_undo: function mb__cmd_undo(msg) {
this.universe.undoMutation(msg.longtermIds);
},
//////////////////////////////////////////////////////////////////////////////
// Composition
_cmd_beginCompose: function mb__cmd_beginCompose(msg) {
require(['mailapi/drafts/composer'], function ($composer) {
var req = this._pendingRequests[msg.handle] = {
type: 'compose',
active: 'begin',
account: null,
persistedNamer: null,
die: false
};
// - figure out the identity to use
var account, identity, folderId;
if (msg.mode === 'new' && msg.submode === 'folder')
account = this.universe.getAccountForFolderId(msg.refSuid);
else
account = this.universe.getAccountForMessageSuid(msg.refSuid);
req.account = account;
identity = account.identities[0];
// not doing something that needs a body just return an empty composer.
if (msg.mode !== 'reply' && msg.mode !== 'forward') {
return this.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
error: null,
identity: identity,
subject: '',
body: { text: '', html: null },
to: [],
cc: [],
bcc: [],
references: null,
attachments: [],
});
}
var folderStorage =
this.universe.getFolderStorageForMessageSuid(msg.refSuid);
var self = this;
folderStorage.getMessage(
msg.refSuid, msg.refDate, { withBodyReps: true }, function(res) {
if (!res) {
// cannot compose a reply/fwd message without a header/body
return console.warn(
'Cannot compose message missing header/body: ',
msg.refSuid
);
}
var header = res.header;
var bodyInfo = res.body;
if (msg.mode === 'reply') {
var rTo, rCc, rBcc;
// clobber the sender's e-mail with the reply-to
var effectiveAuthor = {
name: msg.refAuthor.name,
address: (header.replyTo && header.replyTo.address) ||
msg.refAuthor.address,
};
switch (msg.submode) {
case 'list':
// XXX we can't do this without headers we're not retrieving,
// fall through for now.
case null:
case 'sender':
rTo = [effectiveAuthor];
rCc = rBcc = [];
break;
case 'all':
// No need to change the lists if the author is already on the
// reply lists.
//
// nb: Our logic here is fairly simple; Thunderbird's
// nsMsgCompose.cpp does a lot of checking that we should
// audit, although much of it could just be related to its
// much more extensive identity support.
if (checkIfAddressListContainsAddress(header.to,
effectiveAuthor) ||
checkIfAddressListContainsAddress(header.cc,
effectiveAuthor)) {
rTo = header.to;
}
// add the author as the first 'to' person
else {
if (header.to && header.to.length)
rTo = [effectiveAuthor].concat(header.to);
else
rTo = [effectiveAuthor];
}
rCc = header.cc;
rBcc = header.bcc;
break;
}
var referencesStr;
if (bodyInfo.references) {
referencesStr = bodyInfo.references.concat([msg.refGuid])
.map(function(x) { return '<' + x + '>'; })
.join(' ');
}
else if (msg.refGuid) {
referencesStr = '<' + msg.refGuid + '>';
}
// ActiveSync does not thread so good
else {
referencesStr = '';
}
req.active = null;
self.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
error: null,
identity: identity,
subject: $composer.mailchew
.generateReplySubject(msg.refSubject),
// blank lines at the top are baked in
body: $composer.mailchew.generateReplyBody(
bodyInfo.bodyReps, effectiveAuthor, msg.refDate,
identity, msg.refGuid),
to: rTo,
cc: rCc,
bcc: rBcc,
referencesStr: referencesStr,
attachments: [],
});
}
else {
req.active = null;
self.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
error: null,
identity: identity,
subject: $composer.mailchew
.generateForwardSubject(msg.refSubject),
// blank lines at the top are baked in by the func
body: $composer.mailchew.generateForwardMessage(
msg.refAuthor, msg.refDate, msg.refSubject,
header, bodyInfo, identity),
// forwards have no assumed envelope information
to: [],
cc: [],
bcc: [],
// XXX imitate Thunderbird current or previous behaviour; I
// think we ended up linking forwards into the conversation
// they came from, but with an extra header so that it was
// possible to detect it was a forward.
references: null,
attachments: [],
});
}
});
}.bind(this));
},
_cmd_attachBlobToDraft: function(msg) {
// for ordering consistency reasons with other draft logic, this needs to
// require composer as a dependency too.
require(['mailapi/drafts/composer'], function ($composer) {
var draftReq = this._pendingRequests[msg.draftHandle];
if (!draftReq)
return;
this.universe.attachBlobToDraft(
draftReq.account,
draftReq.persistedNamer,
msg.attachmentDef,
function (err) {
this.__sendMessage({
type: 'attachedBlobToDraft',
// Note! Our use of 'msg' here means that our reference to the Blob
// will be kept alive slightly longer than the job keeps it alive,
// but just slightly.
handle: msg.handle,
draftHandle: msg.draftHandle,
err: err
});
}.bind(this));
}.bind(this));
},
_cmd_detachAttachmentFromDraft: function(msg) {
// for ordering consistency reasons with other draft logic, this needs to
// require composer as a dependency too.
require(['mailapi/drafts/composer'], function ($composer) {
var req = this._pendingRequests[msg.draftHandle];
if (!req)
return;
this.universe.detachAttachmentFromDraft(
req.account,
req.persistedNamer,
msg.attachmentIndex,
function (err) {
this.__sendMessage({
type: 'detachedAttachmentFromDraft',
handle: msg.handle,
draftHandle: msg.draftHandle,
err: err
});
}.bind(this));
}.bind(this));
},
_cmd_resumeCompose: function mb__cmd_resumeCompose(msg) {
var req = this._pendingRequests[msg.handle] = {
type: 'compose',
active: 'resume',
account: null,
persistedNamer: msg.messageNamer,
die: false
};
// NB: We are not acquiring the folder mutex here because
var account = req.account =
this.universe.getAccountForMessageSuid(msg.messageNamer.suid);
var folderStorage = this.universe.getFolderStorageForMessageSuid(
msg.messageNamer.suid);
var self = this;
folderStorage.runMutexed('resumeCompose', function(callWhenDone) {
function fail() {
self.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
error: 'no-message'
});
callWhenDone();
}
folderStorage.getMessage(msg.messageNamer.suid, msg.messageNamer.date,
function(res) {