-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
521 lines (427 loc) · 9.9 KB
/
index.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
let AWS = require('aws-sdk');
let mime = require('mime');
let parser = require("mailparser").simpleParser;
//
// Initialize S3.
//
let s3 = new AWS.S3({
apiVersion: '2006-03-01'
});
//
// This lambda will read RAW emails and convert them in easy to read formats
// like: HTML and Text.
//
exports.handler = (event) => {
//
// 1. We need to process the path received by S3 since AWS dose escape
// the string in a special way. They escape the string in a HTML style
// but for whatever reason they convert spaces in to +ses.
//
let s3_key = event.Records[0].s3.object.key;
//
// 2. So first we convert the + in to spaces.
//
let plus_to_space = s3_key.replace(/\+/g, ' ');
//
// 3. And then we unescape the string, other wise we lose
// real + characters.
//
let unescaped_key = decodeURIComponent(plus_to_space);
//
// 4. This JS object will contain all the data within the chain.
//
let container = {
bucket: event.Records[0].s3.bucket.name,
key: unescaped_key,
parsed: {
html: "",
text: "",
attachments: []
}
}
//
// -> Start the chain.
//
load_the_email(container)
.then(function(container) {
return remove_extension(container);
}).then(function(container) {
return parse_the_email(container);
}).then(function(container) {
return save_text(container);
}).then(function(container) {
return save_html(container);
}).then(function(container) {
return save_attachments(container);
}).then(function(container) {
return true;
}).catch(function(error) {
console.error(error);
return false;
});
};
// _____ _____ ____ __ __ _____ _____ ______ _____
// | __ \ | __ \ / __ \ | \/ | |_ _| / ____| | ____| / ____|
// | |__) | | |__) | | | | | | \ / | | | | (___ | |__ | (___
// | ___/ | _ / | | | | | |\/| | | | \___ \ | __| \___ \
// | | | | \ \ | |__| | | | | | _| |_ ____) | | |____ ____) |
// |_| |_| \_\ \____/ |_| |_| |_____| |_____/ |______| |_____/
//
//
// Load the email that triggered the function from S3.
//
function load_the_email(container)
{
return new Promise(function(resolve, reject) {
console.info("load_the_email");
//
// 1. Set the query.
//
let params = {
Bucket: container.bucket,
Key: container.key
};
//
// -> Execute the query.
//
s3.getObject(params, function(error, data) {
//
// 1. Check for internal errors.
//
if(error)
{
return reject(error);
}
//
// 2. Save the email for the next promise
//
container.raw_email = data.Body
//
// -> Move to the next chain.
//
return resolve(container);
});
});
}
//
// Since the raw email is saved with an extension we need to remove it
// before we can save other converted versions.
//
function remove_extension(container)
{
return new Promise(function(resolve, reject) {
console.info("remove_extension");
//
// 1. Split the string.
//
let tmp = container.key.split('.');
//
// 2. Remove the last element from the array which is `eml`.
//
tmp.pop();
//
// 2. Join the array back to how it was, minus the extension.
// We need to do this, since we don't know how many dots were in
// the email title for example.
//
container.key = tmp.join('.');
//
// -> Move to the next chain.
//
return resolve(container);
});
}
//
// Convert the raw email in to HTML and Text, and extract also the
// attachments.
//
function parse_the_email(container)
{
return new Promise(function(resolve, reject) {
//
// 1. Parse the email and extract all the it necessary.
//
parser(container.raw_email, function(error, parsed) {
//
// 1. Check for internal errors.
//
if(error)
{
return reject(error);
}
//
// 2. Save the parsed email for the next promise.
//
container.parsed.html = parsed.html;
container.parsed.text = parsed.text;
container.parsed.attachments = parsed.attachments;
//
// -> Move to the next chain.
//
return resolve(container);
});
});
}
//
// After the conversion we save the Text version to S3.
//
function save_text(container)
{
return new Promise(function(resolve, reject) {
console.info("save_text");
//
// 1. Set the query.
//
let params = {
Bucket: container.bucket,
Key: container.key + ".txt",
Body: container.parsed.text
};
//
// -> Execute the query.
//
s3.putObject(params, function(error, data) {
//
// 1. Check for internal errors.
//
if(error)
{
return reject(error);
}
//
// -> Move to the next chain.
//
return resolve(container);
});
});
}
//
// Then if we have a HTML version we try to save that.
//
function save_html(container)
{
return new Promise(function(resolve, reject) {
//
// <>> When the body of an email have only one version, meaning it
// dose have only the pure text version and no HTML.
//
// Nodemailer won't generate the HTML for you, it just grabs
// what is in the Email body.
//
// So, this value will be false, when there is no HTML content in
// the email, and thus we skip this step.
//
if(!container.parsed.html)
{
console.info("save_html - skipped");
//
// -> Move to the next chain.
//
return resolve(container);
}
console.info("save_html");
//
// 1. Set the query.
//
let params = {
Bucket: container.bucket,
Key: container.key + ".html",
Body: container.parsed.html
};
//
// -> Execute the query.
//
s3.putObject(params, function(error, data) {
//
// 1. Check for internal errors.
//
if(error)
{
return reject(error);
}
//
// -> Move to the next chain.
//
return resolve(container);
});
});
}
//
// Last thing to do is to save the attachments if there are any. If the
// array is empty the loop will skip itself.
//
function save_attachments(container)
{
return new Promise(function(resolve, reject) {
console.info("save_attachments");
//
// Start the loop which save all the attachments.
//
loop(1, function(error) {
//
// <<> Check if there was an error.
//
if(error)
{
//
// -> Stop everything and surface the error.
//
return reject(container);
}
//
// -> Move to the next chain.
//
return resolve(container);
});
//
// This loop will upload all the individual attachments found
// in a email.
//
function loop(count, callback)
{
//
// 1. Pop the last element in the array if any.
//
let file = container.parsed.attachments.pop()
//
// 2. If there is nothing left then we stop the loop.
//
if(!file)
{
return callback();
}
//
// 3. Get the file name which also contain the file extension.
//
file_name = file.filename
//
// 4. An email attachment is not required to have a name, this
// mean we need to check if we have a file name and, if not
// we create a general name, so all attachments can be saved
// and accounted for.
//
if(!file_name)
{
//
// 1. Set the generic name with the count name so we give
// unique names to each attachment.
//
file_name = "Mail Attachment " + count;
//
// 2. We only count the times we had to set a generic name.
//
count++;
}
//
// 5. Split the string to and get the last element of the array
// which should be the file extension.
//
let extension = file_name.split('.').pop();
//
// 6. Then we check if the last element is an extension.
//
let is_extension = mime.getType(extension);
//
// 7. If it isn't, we get one from the content-type header.
//
if(!is_extension)
{
//
// 1. Make sure we have a content type, since I'm sure
// some emails won't have it if they were malformed.
//
if(file.contentType)
{
//
// 1. Try to find out the file extension from the
// content-type found in the email message.
//
let file_type = mime.getExtension(file.contentType);
//
// 2. If the extension was not found, then we set a
// default one which will let the user know
// that we don't know the type of the file, while
// also setting the type to txt (for convenience)
// so it can be open by any editor and inspected.
//
if(!file_type)
{
file_type = 'unknown_extension.txt';
}
//
// 3. Attach the extension to the file.
//
file_name += "." + file_type;
}
}
//
// 8. Then save the buffer of the attachment.
//
file_body = file.content
//
// 9. Split the S3 Key (path) so we can remove the last element.
// since we don't want the object name, we care only about
// the path.
//
let tmp = container.key.split('/');
//
// 10. Now remove the last element from the array which is the
// file name that contains the raw email, which we don't want.
//
tmp.pop();
//
// 11. After all this, we recombine the array in to a single
// string which becomes again the S3 Key minus the file name.
//
let path = tmp.join('/');
//
// 12. This variable is used if there are two files of the same
// name.
//
let cid = "";
//
// 13. If the CID is set then it means that two files have the
// same names.
//
if(file.cid)
{
//
// 1. Add the CID in front of the name of the file so they
// won't be overwritten.
//
cid = file.cid + " - "
}
//
// 14. Create the full key path with the object at the end.
//
let key = path
+ "/attachments/"
+ cid
+ file_name
//
// 15. Set the query.
//
let params = {
Bucket: container.bucket,
Key: key,
Body: file_body
};
//
// -> Execute the query.
//
s3.putObject(params, function(error, data) {
//
// 1. Check for internal errors.
//
if(error)
{
return callback(error);
}
//
// -> Move to the next chain.
//
return loop(count, callback);
});
}
});
}