-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.js
160 lines (132 loc) · 5.42 KB
/
handler.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
'use strict';
const AWS = require('aws-sdk');
const axios = require('axios');
const EmailReplyParser = require("email-reply-parser");
const TurndownService = require("turndown");
const turndownService = new TurndownService();
const {getChannel} = require("./mappers");
const simpleParser = require('mailparser').simpleParser;
const MailParser = require('mailparser').MailParser;
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
region: process.env.AWSREGION,
});
const s3AttachmentBucketName = 'your_unique_s3_file_bucket'; // create a S3 bucket and provide the name. This will be used to store the email attachment.
function parseEmailTo(data) {
return data.value[0];
}
function getNow() {
const date = new Date();
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
module.exports.postprocess = async (event) => {
const record = event.Records[0];
const request = {
Bucket: record.s3.bucket.name,
Key: record.s3.object.key,
};
try {
const data = await s3.getObject(request).promise();
// console.log('Raw email:' + data.Body);
const email = await simpleParser(data.Body);
const to = parseEmailTo(email.to);
const mimeName = record.s3.object.key;
const webhookUrl = getChannel(to.address, email.headers.get('x-forwarded-to'));
if (!webhookUrl) {
console.log('No Webhook URL found for email Mime: ' + mimeName + '; Email Address: ' + to.address);
return false; // Webhook URL could not be found from your mappers.js file
}
const now = getNow();
let isMarkDown = false;
if (!email.text && email.html) {
const head = email.html.match(/<head>.*<\/head>/s);
if (head) {
email.html = email.html.replace(head[0], '');
}
email.text = turndownService.turndown(email.html);
isMarkDown = true;
}
const emailReplyParser = new EmailReplyParser().read(email.text);
let visibleText = emailReplyParser.getVisibleText();
// Handle Forwarded Message
const matches = visibleText.match(/From:.+?(?=To:)[^>]*>/sg);
let forwarded = null;
if (matches) {
let forwardedParts = visibleText.match(/(?<=From:\s+)(.*?)(?=>)/);
if (forwardedParts) {
forwardedParts = forwardedParts[0].split('<');
forwarded = {
name: forwardedParts[0].trim(),
address: forwardedParts[1].trim()
};
}
matches.forEach(match => visibleText = visibleText.replace(match, ''));
visibleText = visibleText.replace(/---------- Forwarded message ---------/g, '');
}
const formattedData = {
date: email.date,
subject: email.subject,
body_text: (new MailParser()).textToHtml(visibleText),
messageId: email.messageId,
from: email.from,
to: email.to,
forwarded,
attachments: [],
isMarkDown
};
const processPayload = async _ => {
for (let i = 0; i < email.attachments.length; i++) {
const attachment = email.attachments[i];
const key = attachment.filename.split('.').join('_' + Date.now() + '.');
await s3.putObject({
Bucket: s3AttachmentBucketName,
Key: key,
Body: attachment.content
}).promise();
await s3.getSignedUrlPromise('getObject', {
Bucket: s3AttachmentBucketName,
Key: key,
}).then(url => {
formattedData.attachments.push({
url,
cid: attachment.cid,
filename: attachment.filename,
contentType: attachment.contentType,
contentDisposition: attachment.contentDisposition,
});
})
}
const postedData = JSON.stringify(formattedData);
await axios.post(webhookUrl, {payload: postedData})
.then((res) => {
// it's a success
})
.catch((error) => {
let log = {
type: 'failed',
payload: postedData,
mime: record.s3.object.key,
created_at: now,
updated_at: now,
id: channel.log_id,
};
if (error.response) {
log.response_status = error.response.status;
log.message = 'Probably plugin deactivated.';
} else if (error.request) {
log.response_status = 400;
log.message = 'Domain not available.';
} else {
log.response_status = 500;
log.message = 'Axios setup error.';
}
console.log(log);
})
.finally(() => {});
}
await processPayload();
} catch (Error) {
console.log(Error, Error.stack);
return Error;
}
};