This repository has been archived by the owner on Nov 3, 2021. It is now read-only.
/
mailbridge.js
914 lines (815 loc) · 27.8 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
/**
*
**/
define(
[
'rdcommon/log',
'mailcomposer',
'./mailchew',
'./util',
'module',
'exports'
],
function(
$log,
$mailcomposer,
$mailchew,
$imaputil,
$module,
exports
) {
const bsearchForInsert = $imaputil.bsearchForInsert,
bsearchMaybeExists = $imaputil.bsearchMaybeExists;
function toBridgeWireOn(x) {
return x.toBridgeWire();
}
const FOLDER_TYPE_TO_SORT_PRIORITY = {
account: 'a',
inbox: 'c',
starred: 'e',
important: 'f',
drafts: 'g',
queue: 'h',
sent: 'i',
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(acctId, folder) {
// '!' is before alphanum, so is a good separator for variable length id's
return acctId + '!' + FOLDER_TYPE_TO_SORT_PRIORITY[folder.type] + '!' +
folder.path.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) {
this.universe = universe;
this.universe.registerBridge(this);
this._LOG = LOGFAB.MailBridge(this, universe._LOG, null);
/** @dictof[@key[handle] @value[BridgedViewSlice]]{ live slices } */
this._slices = {};
/** @dictof[@key[namespace] @value[@listof[BridgedViewSlice]]] */
this._slicesByType = {
accounts: [],
identities: [],
folders: [],
headers: [],
matchedHeaders: [],
};
// 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);
},
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_localizedStrings: function mb__cmd_localizedStrings(msg) {
$mailchew.setLocalizedStrings(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,
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.
if (!err || (
err !== 'bad-user-or-pass' &&
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);
}
});
},
_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;
}
}
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.id, 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.id, 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);
},
notifyFolderAdded: function(accountId, folderMeta) {
var newMarker = makeFolderSortString(accountId, 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(accountId, folderMeta) {
var marker = makeFolderSortString(accountId, 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(accountId, folderMeta) {
var marker = makeFolderSortString(accountId, 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);
}
},
_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.id, 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.id, 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);
folderStorage.getMessageBody(msg.suid, msg.date, function(bodyInfo) {
self.__sendMessage({
type: 'gotBody',
handle: msg.handle,
bodyInfo: bodyInfo,
});
});
},
_cmd_downloadAttachments: function mb__cmd__downloadAttachments(msg) {
var self = this;
this.universe.downloadMessageAttachments(
msg.suid, msg.date, msg.relPartIndices, msg.attachmentIndices,
function(err, bodyInfo) {
self.__sendMessage({
type: 'downloadedAttachments',
handle: msg.handle,
bodyInfo: err ? null : bodyInfo
});
});
},
//////////////////////////////////////////////////////////////////////////////
// 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) {
var req = this._pendingRequests[msg.handle] = {
type: 'compose',
// XXX draft persistence/saving to-do/etc.
persistedFolder: null,
persistedUID: null,
};
// - 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);
identity = account.identities[0];
if (msg.mode === 'reply' ||
msg.mode === 'forward') {
var folderStorage = this.universe.getFolderStorageForMessageSuid(
msg.refSuid);
var self = this;
folderStorage.getMessageBody(
msg.refSuid, msg.refDate,
function(bodyInfo) {
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: (bodyInfo.replyTo && bodyInfo.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(bodyInfo.to,
effectiveAuthor) ||
checkIfAddressListContainsAddress(bodyInfo.cc,
effectiveAuthor)) {
rTo = bodyInfo.to;
}
// add the author as the first 'to' person
else {
if (bodyInfo.to && bodyInfo.to.length)
rTo = [effectiveAuthor].concat(bodyInfo.to);
else
rTo = [effectiveAuthor];
}
rCc = bodyInfo.cc;
rBcc = bodyInfo.bcc;
break;
}
var referencesStr;
if (bodyInfo.references) {
referencesStr = bodyInfo.references.concat([msg.refGuid])
.map(function(x) { return '<' + x + '>'; })
.join(' ');
}
else {
referencesStr = '<' + msg.refGuid + '>';
}
self.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
identity: identity,
subject: $mailchew.generateReplySubject(msg.refSubject),
// blank lines at the top are baked in
body: $mailchew.generateReplyBody(
bodyInfo.bodyReps, effectiveAuthor, msg.refDate,
identity, msg.refGuid),
to: rTo,
cc: rCc,
bcc: rBcc,
referencesStr: referencesStr,
attachments: [],
});
}
else {
self.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
identity: identity,
subject: 'Fwd: ' + msg.refSubject,
// blank lines at the top are baked in by the func
body: $mailchew.generateForwardMessage(
msg.refAuthor, msg.refDate, msg.refSubject,
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: [],
});
}
});
return;
}
this.__sendMessage({
type: 'composeBegun',
handle: msg.handle,
identity: identity,
subject: '',
body: { text: '', html: null },
to: [],
cc: [],
bcc: [],
references: null,
attachments: [],
});
},
_cmd_doneCompose: function mb__cmd_doneCompose(msg) {
if (msg.command === 'delete') {
// XXX if we have persistedFolder/persistedUID, enqueue a delete of that
// message and try and execute it.
return;
}
var composer = new $mailcomposer.MailComposer(),
wireRep = msg.state;
var identity = this.universe.getIdentityForSenderIdentityId(
wireRep.senderId),
account = this.universe.getAccountForSenderIdentityId(
wireRep.senderId);
var body = wireRep.body;
var messageOpts = {
from: $imaputil.formatAddresses([identity]),
subject: wireRep.subject,
};
if (body.html) {
messageOpts.html = $mailchew.mergeUserTextWithHTML(body.text, body.html);
}
else {
messageOpts.body = body.text;
}
if (identity.replyTo)
messageOpts.replyTo = identity.replyTo;
if (wireRep.to && wireRep.to.length)
messageOpts.to = $imaputil.formatAddresses(wireRep.to);
if (wireRep.cc && wireRep.cc.length)
messageOpts.cc = $imaputil.formatAddresses(wireRep.cc);
if (wireRep.bcc && wireRep.bcc.length)
messageOpts.bcc = $imaputil.formatAddresses(wireRep.bcc);
composer.setMessageOption(messageOpts);
if (wireRep.customHeaders) {
for (var iHead = 0; iHead < wireRep.customHeaders.length; iHead += 2){
composer.addHeader(wireRep.customHeaders[iHead],
wireRep.customHeaders[iHead+1]);
}
}
composer.addHeader('User-Agent', 'Mozilla Gaia Email Client 0.1alpha');
var sentDate = new Date();
composer.addHeader('Date', sentDate.toUTCString());
// we're copying nodemailer here; we might want to include some more...
var messageId =
'<' + Date.now() + Math.random().toString(16).substr(1) + '@mozgaia>';
composer.addHeader('Message-Id', messageId);
if (wireRep.references)
composer.addHeader('References', wireRep.references);
if (msg.command === 'send') {
var self = this, asyncPending = 0;
if (wireRep.attachments) {
wireRep.attachments.forEach(function(attachmentDef) {
var reader = new FileReader();
reader.onload = function onloaded() {
composer.addAttachment({
filename: attachmentDef.name,
contentType: attachmentDef.blob.type,
contents: new Uint8Array(reader.result),
});
if (--asyncPending === 0)
initiateSend();
};
try {
reader.readAsArrayBuffer(attachmentDef.blob);
asyncPending++;
}
catch (ex) {
console.error('Problem attaching attachment:', ex, '\n', ex.stack);
}
});
}
var initiateSend = function() {
account.sendMessage(composer, function(err, badAddresses) {
self.__sendMessage({
type: 'sent',
handle: msg.handle,
err: err,
badAddresses: badAddresses,
messageId: messageId,
sentDate: sentDate.valueOf(),
});
});
};
if (asyncPending === 0)
initiateSend();
}
else { // (msg.command === draft)
// XXX save drafts!
}
},
//////////////////////////////////////////////////////////////////////////////
};
function SliceBridgeProxy(bridge, ns, handle) {
this._bridge = bridge;
this._ns = ns;
this._handle = handle;
this.__listener = null;
this.status = 'synced';
this.progress = 0.0;
this.atTop = false;
this.atBottom = false;
this.userCanGrowDownwards = false;
}
SliceBridgeProxy.prototype = {
/**
* Issue a splice to add and remove items.
*/
sendSplice: function sbp_sendSplice(index, howMany, addItems, requested,
moreExpected) {
this._bridge.__sendMessage({
type: 'sliceSplice',
handle: this._handle,
index: index,
howMany: howMany,
addItems: addItems,
requested: requested,
moreExpected: moreExpected,
status: this.status,
progress: this.progress,
atTop: this.atTop,
atBottom: this.atBottom,
userCanGrowDownwards: this.userCanGrowDownwards,
});
},
/**
* Issue an update for existing items.
*/
sendUpdate: function sbp_sendUpdate(indexUpdatesRun) {
this._bridge.__sendMessage({
type: 'sliceUpdate',
handle: this._handle,
updates: indexUpdatesRun,
});
},
sendStatus: function sbp_sendStatus(status, requested, moreExpected,
progress) {
this.status = status;
if (progress != null)
this.progress = progress;
this.sendSplice(0, 0, [], requested, moreExpected);
},
sendSyncProgress: function(progress) {
this.progress = progress;
this.sendSplice(0, 0, [], true, true);
},
die: function sbp_die() {
if (this.__listener)
this.__listener.die();
},
};
var LOGFAB = exports.LOGFAB = $log.register($module, {
MailBridge: {
type: $log.DAEMON,
events: {
// NB: under unit test, this is not used and bridgeSnoop is used instead.
send: { type: true },
},
TEST_ONLY_events: {
send: { msg: false },
},
errors: {
badMessageType: { type: true },
badSliceHandle: { handle: true },
},
calls: {
cmd: { command: true },
},
TEST_ONLY_calls: {
},
},
});
}); // end define