This repository has been archived by the owner on Jun 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
compose.js
527 lines (493 loc) · 16.5 KB
/
compose.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
/**
* @fileoverview Composition-related utils: quoting, wrapping text before
* sending a message, converting back and forth between HTML and plain text...
* @author Jonathan Protzenko
*/
var EXPORTED_SYMBOLS = [
"composeInIframe",
"getEditorForIframe",
"quoteMsgHdr",
"citeString",
"htmlToPlainText",
"simpleWrap",
"plainTextToHtml",
"replyAllParams",
"determineComposeHtml",
"composeMessageTo",
"getSignatureContentsForAccount",
"parse",
];
const { XPCOMUtils } = ChromeUtils.import(
"resource://gre/modules/XPCOMUtils.jsm"
);
XPCOMUtils.defineLazyModuleGetters(this, {
MailServices: "resource:///modules/MailServices.jsm",
NetUtil: "resource://gre/modules/NetUtil.jsm",
Services: "resource://gre/modules/Services.jsm",
});
function importRelative(that, path) {
return ChromeUtils.import(new URL(path, that.__URI__), null);
}
const {
escapeHtml,
getDefaultIdentity,
getIdentities,
systemCharset,
} = importRelative(this, "misc.js");
const { msgHdrGetUri, getMail3Pane, msgHdrGetHeaders } = importRelative(
this,
"msgHdrUtils.js"
);
/**
* Use the mailnews component to stream a message, and process it in a way
* that's suitable for quoting (strip signature, remove images, stuff like
* that).
* @param {nsIMsgDBHdr} aMsgHdr The message header that you want to quote
* @return {Promise}
* Returns a quoted string suitable for insertion in an HTML editor.
* You can pass this to htmlToPlainText if you're running a plaintext editor
*/
function quoteMsgHdr(aMsgHdr) {
return new Promise(resolve => {
let chunks = [];
const decoder = new TextDecoder();
let listener = {
/** @ignore*/
setMimeHeaders() {},
/** @ignore*/
onStartRequest(aRequest) {},
/** @ignore*/
onStopRequest(aRequest, aStatusCode) {
let data = chunks.join("");
resolve(data);
},
/** @ignore*/
onDataAvailable(aRequest, aStream, aOffset, aCount) {
// Fortunately, we have in Gecko 2.0 a nice wrapper
let data = NetUtil.readInputStreamToString(aStream, aCount);
// Now each character of the string is actually to be understood as a byte
// of a UTF-8 string.
// So charCodeAt is what we want here...
let array = [];
for (let i = 0; i < data.length; ++i) {
array[i] = data.charCodeAt(i);
}
// Yay, good to go!
chunks.push(decoder.decode(Uint8Array.from(array)));
},
QueryInterface: ChromeUtils.generateQI([
Ci.nsIStreamListener,
Ci.nsIMsgQuotingOutputStreamListener,
Ci.nsIRequestObserver,
]),
};
// Here's what we want to stream...
let msgUri = msgHdrGetUri(aMsgHdr);
/**
* Quote a particular message specified by its URI.
*
* @param charset optional parameter - if set, force the message to be
* quoted using this particular charset
*/
// void quoteMessage(in string msgURI, in boolean quoteHeaders,
// in nsIMsgQuotingOutputStreamListener streamListener,
// in string charset, in boolean headersOnly);
let quoter = Cc["@mozilla.org/messengercompose/quoting;1"].createInstance(
Ci.nsIMsgQuote
);
quoter.quoteMessage(msgUri, false, listener, "", false, aMsgHdr);
});
}
function getEditorForIframe(aIframe) {
let w = aIframe.contentWindow;
let s = w
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIEditingSession);
return s.getEditorForWindow(w);
}
function composeInIframe(aIframe, { msgHdr, compType, identity }) {
let fields = Cc[
"@mozilla.org/messengercompose/composefields;1"
].createInstance(Ci.nsIMsgCompFields);
let params = Cc[
"@mozilla.org/messengercompose/composeparams;1"
].createInstance(Ci.nsIMsgComposeParams);
params.identity = identity;
if (msgHdr) {
params.origMsgHdr = msgHdr;
params.originalMsgURI = msgHdrGetUri(msgHdr);
}
params.composeFields = fields;
params.type = compType;
let compose = MailServices.compose.initCompose(
params,
getMail3Pane(),
aIframe.docShell
);
compose.initEditor(getEditorForIframe(aIframe), aIframe.contentWindow);
}
/**
* A function that properly quotes a plaintext email.
* @param {String} aStr The mail body that we're expected to quote.
* @return {String} The quoted mail body with >'s properly taken care of.
*/
function citeString(aStr) {
let l = aStr.length;
return aStr.replace(
"\n",
function(match, offset, str) {
// http://mxr.mozilla.org/comm-central/source/mozilla/editor/libeditor/text/nsInternetCiter.cpp#96
if (offset < l - 1) {
if (
str[offset + 1] != ">" &&
str[offset + 1] != "\n" &&
str[offset + 1] != "\r"
) {
return "\n> ";
}
return "\n>";
}
return match;
},
"g"
);
}
/**
* Wrap some text. Beware, that function doesn't do rewrapping, and only
* operates on non-quoted lines. This is only useful in our very specific case
* where the quoted lines have been properly wrapped for format=flowed already,
* and the non-quoted lines are the only ones that need wrapping for
* format=flowed.
* Beware, this function will treat all lines starting with >'s as quotations,
* even user-inserted ones. We would need support from the editor to proceed
* otherwise, and the current textarea doesn't provide this.
* This function, when breaking lines, will do space-stuffing per the RFC if
* after the break the text starts with From or >.
* @param {String} txt The text that should be wrapped.
* @param {Number} width (optional) The width we should wrap to. Default to 72.
* @return {String} The text with non-quoted lines wrapped. This is suitable for
* sending as format=flowed.
*/
function simpleWrap(txt, width) {
if (!width) {
width = 72;
}
function maybeEscape(line) {
if (line.indexOf("From") === 0 || line.indexOf(">") === 0) {
return " " + line;
}
return line;
}
/**
* That function takes a (long) line, and splits it into many lines.
* @param soFar {Array String} an accumulator of the lines we've wrapped already
* @param remaining {String} the remaining string to wrap
*/
function splitLongLine(soFar, remaining) {
if (remaining.length > width) {
// Start at the end of the line, and move back until we find a word
// boundary.
let i = width - 1;
while (remaining[i] != " " && i > 0) {
i--;
}
// We found a word boundary, break there
if (i > 0) {
// This includes the trailing space that indicates that we are wrapping
// a long line with format=flowed.
soFar.push(maybeEscape(remaining.substring(0, i + 1)));
return splitLongLine(
soFar,
remaining.substring(i + 1, remaining.length)
);
}
// No word boundary, break at the first space
let j = remaining.indexOf(" ");
if (j > 0) {
// Same remark about the trailing space.
soFar.push(maybeEscape(remaining.substring(0, j + 1)));
return splitLongLine(
soFar,
remaining.substring(j + 1, remaining.length)
);
}
// Make sure no one interprets this as a line continuation.
soFar.push(remaining.trimRight());
return soFar.join("\n");
}
// Same remark about the trailing space.
soFar.push(maybeEscape(remaining.trimRight()));
return soFar.join("\n");
}
let lines = txt.split(/\r?\n/);
lines.forEach(function(line, i) {
if (line.length > width && line[0] != ">") {
lines[i] = splitLongLine([], line);
}
});
return lines.join("\n");
}
/**
* Convert HTML into text/plain suitable for insertion right away in the mail
* body. If there is text with >'s at the beginning of lines, these will be
* space-stuffed, and the same goes for Froms. <blockquote>s will be converted
* with the suitable >'s at the beginning of the line, and so on...
* This function also takes care of rewrapping at 72 characters, so your quoted
* lines will be properly wrapped too. This means that you can add some text of
* your own, and then pass this to simpleWrap, it should "just work" (unless
* the user has edited a quoted line and made it longer than 990 characters, of
* course).
* @param {String} aHtml A string containing the HTML that's to be converted.
* @return {String} A text/plain string suitable for insertion in a mail body.
*/
function htmlToPlainText(aHtml) {
// Yes, this is ridiculous, we're instanciating composition fields just so
// that they call ConvertBufPlainText for us. But ConvertBufToPlainText
// really isn't easily scriptable, so...
let fields = Cc[
"@mozilla.org/messengercompose/composefields;1"
].createInstance(Ci.nsIMsgCompFields);
fields.body = aHtml;
fields.forcePlainText = true;
fields.ConvertBodyToPlainText();
return fields.body;
}
/**
* @ignore
*/
function citeLevel(line) {
let i;
for (i = 0; line[i] == ">" && i < line.length; ++i) {
// nop
}
return i;
}
/**
* Just try to convert quoted lines back to HTML markup (<blockquote>s).
* @param {String} txt
* @return {String}
*/
function plainTextToHtml(txt) {
let lines = txt.split(/\r?\n/);
let newLines = [];
let level = 0;
for (let line of lines) {
let newLevel = citeLevel(line);
if (newLevel > level) {
for (let i = level; i < newLevel; ++i) {
newLines.push('<blockquote type="cite">');
}
}
if (newLevel < level) {
for (let i = newLevel; i < level; ++i) {
newLines.push("</blockquote>");
}
}
let newLine =
line[newLevel] == " "
? escapeHtml(line.substring(newLevel + 1, line.length))
: escapeHtml(line.substring(newLevel, line.length));
newLines.push(newLine);
level = newLevel;
}
return newLines.join("\n");
}
function parse(mimeLine) {
if (!mimeLine) {
return [[], []];
}
// The null here copes with pre-Thunderbird 71 compatibility.
let addresses = MailServices.headerParser.parseEncodedHeader(mimeLine, null);
if (addresses[0]) {
return [addresses[0].name, addresses[0].email];
}
return [[], []];
}
/**
* Analyze a message header, and then return all the compose parameters for the
* reply-all case.
* @param {nsIIdentity} The identity you've picked for the reply.
* @param {nsIMsgDbHdr} The message header.
* @param {k} The function to call once we've determined all parameters. Take an
* argument like
* {{ to: [[name, email]], cc: [[name, email]], bcc: [[name, email]]}}
*/
function replyAllParams(aIdentity, aMsgHdr, k) {
// Do the whole shebang to find out who to send to...
let [[author], [authorEmailAddress]] = parse(aMsgHdr.author);
let [recipients, recipientsEmailAddresses] = parse(aMsgHdr.recipients);
let [ccList, ccListEmailAddresses] = parse(aMsgHdr.ccList);
let [bccList, bccListEmailAddresses] = parse(aMsgHdr.bccList);
authorEmailAddress = authorEmailAddress.toLowerCase();
recipientsEmailAddresses = recipientsEmailAddresses.map(x => x.toLowerCase());
ccListEmailAddresses = ccListEmailAddresses.map(x => x.toLowerCase());
bccListEmailAddresses = bccListEmailAddresses.map(x => x.toLowerCase());
let identity = aIdentity;
let identityEmail = identity.email.toLowerCase();
let to = [],
cc = [],
bcc = [];
let isReplyToOwnMsg = false;
for (let currentIdentity of getIdentities()) {
let email = currentIdentity.identity.email.toLowerCase();
if (email == authorEmailAddress) {
isReplyToOwnMsg = true;
}
if (recipientsEmailAddresses.some(x => x == email)) {
isReplyToOwnMsg = false;
}
if (ccListEmailAddresses.some(x => x == email)) {
isReplyToOwnMsg = false;
}
}
// Actually we are implementing the "Reply all" logic... that's better, no one
// wants to really use reply anyway ;-)
if (isReplyToOwnMsg) {
to = recipients.map((r, i) => [r, recipientsEmailAddresses[i]]);
} else {
to = [[author, authorEmailAddress]];
}
cc = ccList
.map((cc, i) => [cc, ccListEmailAddresses[i]])
.filter((e, i) => e[1] != identityEmail);
if (!isReplyToOwnMsg) {
cc = cc.concat(
recipients
.map((r, i) => [r, recipientsEmailAddresses[i]])
.filter((e, i) => e[1] != identityEmail)
);
}
bcc = bccList.map((bcc, i) => [bcc, bccListEmailAddresses]);
let finish = function(to, cc, bcc) {
let hashMap = {};
for (let [, email] of to) {
hashMap[email] = null;
}
cc = cc.filter(function([name, email]) {
let r = email in hashMap;
hashMap[email] = null;
return !r;
});
bcc = bcc.filter(function([name, email]) {
let r = email in hashMap;
hashMap[email] = null;
return !r;
});
k({ to, cc, bcc });
};
// Do we have a Reply-To header?
msgHdrGetHeaders(aMsgHdr, function(aHeaders) {
if (aHeaders.has("reply-to")) {
let [names, emails] = parse(aHeaders.get("reply-to"));
emails = emails.map(email => email.toLowerCase());
if (emails.length) {
// Invariant: at this stage, we only have one item in to.
cc = cc.concat([to[0]]); // move the to in cc
to = names.map((n, i) => [n, emails[i]]);
}
}
finish(to, cc, bcc);
});
}
/**
* This function replaces nsMsgComposeService::determineComposeHTML, which is
* marked as [noscript], just to make our lives complicated. [insert random rant
* here].
*
* @param aIdentity (optional) You can specify the identity which you would like
* to get the preference for.
* @return a bool which is true if you should compose in HTML
*/
function determineComposeHtml(aIdentity) {
if (!aIdentity) {
aIdentity = getDefaultIdentity().identity;
}
if (aIdentity) {
return aIdentity.composeHtml == Ci.nsIMsgCompFormat.HTML;
}
return Services.prefs.getBoolPref("mail.compose_html");
}
/**
* Open a composition window for the given email address.
* @param aEmail {String}
* @param aDisplayedFolder {nsIMsgFolder} pass gFolderDisplay.displayedFolder
*/
function composeMessageTo(aEmail, aDisplayedFolder) {
let fields = Cc[
"@mozilla.org/messengercompose/composefields;1"
].createInstance(Ci.nsIMsgCompFields);
let params = Cc[
"@mozilla.org/messengercompose/composeparams;1"
].createInstance(Ci.nsIMsgComposeParams);
fields.to = aEmail;
params.type = Ci.nsIMsgCompType.New;
params.format = Ci.nsIMsgCompFormat.Default;
if (aDisplayedFolder) {
params.identity = MailServices.accounts.getFirstIdentityForServer(
aDisplayedFolder.server
);
}
params.composeFields = fields;
MailServices.compose.OpenComposeWindowWithParams(null, params);
}
/**
* Returns signature contents depending on account settings of the identity.
* HTML signature is converted to plain text.
* @param {nsIIdentity} The identity you've picked for the reply.
* @return {String} plain text signature
*/
function getSignatureContentsForAccount(aIdentity) {
let signature = "";
if (!aIdentity) {
return signature;
}
if (aIdentity.attachSignature && aIdentity.signature) {
let charset = systemCharset();
const replacementChar =
Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
let fstream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
Ci.nsIFileInputStream
);
let cstream = Cc[
"@mozilla.org/intl/converter-input-stream;1"
].createInstance(Ci.nsIConverterInputStream);
try {
fstream.init(aIdentity.signature, -1, 0, 0);
try {
cstream.init(fstream, charset, 1024, replacementChar);
} catch (e) {
console.error(
"ConverterInputStream init error: " +
e +
"\n charset: " +
charset +
"\n"
);
cstream.init(fstream, "UTF-8", 1024, replacementChar);
}
let str = {};
while (cstream.readString(4096, str) != 0) {
signature += str.value;
}
if (aIdentity.signature.path.match(/\.html?$/)) {
signature = htmlToPlainText(signature);
}
} catch (e) {
console.error("Signature file stream error: " + e + "\n");
}
cstream.close();
fstream.close();
// required for stripSignatureIfNeeded working properly
signature = signature.replace(/\r?\n/g, "\n");
} else {
signature = aIdentity.htmlSigFormat
? htmlToPlainText(aIdentity.htmlSigText)
: aIdentity.htmlSigText;
}
return signature;
}