This repository has been archived by the owner on Sep 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 195
/
Copy pathemailSend.js
306 lines (275 loc) · 9.1 KB
/
emailSend.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
const fs = require('fs')
const template = require('lodash/template')
const sendgridMail = require('@sendgrid/mail')
const Sequelize = require('sequelize')
const mjml2html = require('mjml')
const Identity = require('@origin/identity/src/models').Identity
const { messageTemplates } = require('../templates/messageTemplates')
const { getNotificationMessage } = require('./notification')
const logger = require('./logger')
const {
getMessageFingerprint,
isNotificationDupe,
logNotificationSent
} = require('./dupeTools')
// Configure SendGrid.
sendgridMail.setApiKey(process.env.SENDGRID_API_KEY)
if (!process.env.SENDGRID_API_KEY) {
logger.warn('Warning: SENDGRID_API_KEY env var is not set')
}
if (!process.env.SENDGRID_FROM_EMAIL) {
logger.warn('Warning: SENDGRID_FROM_EMAIL env var is not set')
}
class EmailSender {
/**
* Constructor
* @param {Object} config: Notification server config.
*/
constructor(config) {
this.config = config
}
/**
* Write the content of an email to a file. Useful during development.
* @param {Object} email
* @param {Object} config: Notification server config.
* @private
*/
_writeEmailToFile(email) {
const now = new Date()
fs.writeFile(
`${this.config.emailFileOut}_${now.getTime()}_${email.to}.html`,
email.html,
error => {
logger.error(error)
}
)
fs.writeFile(
`${this.config.emailFileOut}_${now.getTime()}_${email.to}.txt`,
email.text,
error => {
logger.error(error)
}
)
}
/**
* Sends an email to a user.
*
* @param {string} ethAddress: Eth address of the receiver.
* @param {Object} email: SendGrid email object
* @returns {Promise<void>}
* @private
*/
async _send(ethAddress, email) {
// Optional writing of email contents to files
if (this.config.emailFileOut) {
this._writeEmailToFile(email)
}
// Check we are not spamming the user.
const messageFingerprint = getMessageFingerprint(email)
if ((await isNotificationDupe(messageFingerprint, this.config)) > 0) {
logger.warn(`Duplicate. Notification already recently sent. Skipping.`)
return
}
// Send the email and record the action in the notification_log table.
// Note: do not send the email if we are in test mode.
if (process.env.NODE_ENV !== 'test') {
await sendgridMail.send(email)
}
await logNotificationSent(messageFingerprint, ethAddress, 'email')
logger.log(`Email sent to ${ethAddress} at ${email.to}`)
}
/**
* Sends an email to a list of users to let them know they
* have a new Message in Origin messaging.
*
* @param {Array<string>} receivers: List of Eth address an email should be sent to.
* @param {string} sender: Eth address of the user that sent the Origin message.
* @param {string} messageHash: Origin message hash.
* @returns {Promise<void>}
*/
async sendMessageEmail(receivers, sender, messageHash) {
if (!receivers) throw new Error('receivers not defined')
if (!sender) throw new Error('sender not defined')
// Force lowercase
sender = sender.toLowerCase()
receivers = receivers.map(r => r.toLowerCase())
logger.info(
`Messsage email: attempting to email addresses ${receivers.join(',')}`
)
// Load email template
const templateDir = `${__dirname}/../templates`
// Standard template for MJML emails
const emailTemplateMjml = template(
fs.readFileSync(`${templateDir}/emailTemplate.mjml`).toString()
)
// Standard template for text emails
const emailTemplateTxt = template(
fs.readFileSync(`${templateDir}/emailTemplate.txt`).toString()
)
// Load the sender's identity and construct the best human readable
// version of sender name.
const senderIdentity = await Identity.findOne({
where: {
ethAddress: sender
}
})
const senderName =
senderIdentity !== null &&
senderIdentity.firstName &&
senderIdentity.lastName
? `${senderIdentity.firstName || ''} ${senderIdentity.lastName || ''}`
: null
// Dynamic variables used when evaluating the template.
const templateVars = {
config: this.config,
sender,
senderName,
dappUrl: this.config.dappUrl,
ipfsGatewayUrl: this.config.ipfsGatewayUrl,
messageHash
}
// Load the identities of all the receivers.
const identities = await Identity.findAll({
where: { ethAddress: { [Sequelize.Op.or]: receivers } }
})
// Send an email to each receiver.
for (const identity of identities) {
if (!identity.email && !this.config.overrideEmail) {
logger.info(`${identity.ethAddress} has no email address. Skipping.`)
continue
}
try {
const message = messageTemplates.message['email']['messageReceived']
const email = {
to: this.config.overrideEmail || identity.email,
from: this.config.fromEmail,
subject: message.subject(templateVars),
text: emailTemplateTxt({
message: message.text(templateVars),
messageHash
}),
html: mjml2html(
emailTemplateMjml({
message: message.mjml(templateVars),
messageHash
})
).html,
asm: {
groupId: this.config.asmGroupId
},
__messageHash: messageHash // Not part of SendGrid spec, here prevent different messages from being counted as duplicates.
}
await this._send(identity.ethAddress, email)
} catch (error) {
logger.error(
`Could not email ${identity.ethAddress} via Sendgrid: ${error}`
)
}
}
}
/**
* Sends an email to a buyer or seller to notify them
* that the state of one of their offer changed.
*
* @param {string} eventName: Name of the event. Example: OfferCreated, OfferAccepted, ...
* @param {string} party: Either the buyer or the seller Eth address.
* @param {string} buyerAddress: Buyer's Eth address.
* @param {string} sellerAddress: Seller's Eth address.
* @param {Object} offer: Offer object.
* @param {Object} listing: Listing object.
* @returns {Promise<void>}
*/
async sendMarketplaceEmail(
eventName,
party,
buyerAddress,
sellerAddress,
offer,
listing
) {
if (!eventName) throw new Error('eventName not defined')
if (!party) throw new Error('party not defined')
if (!buyerAddress) throw new Error('buyerAddress not defined')
if (!sellerAddress) throw new Error('sellerAddress not defined')
if (!offer) throw new Error('offer not defined')
if (!listing) throw new Error('listing not defined')
// Force lowercase
buyerAddress = buyerAddress.toLowerCase()
sellerAddress = sellerAddress.toLowerCase()
party = party.toLowerCase()
logger.info(
`Transaction Email: party:${party} buyerAddress:${buyerAddress} sellerAddress:${sellerAddress}`
)
// Load email template
const templateDir = `${__dirname}/../templates`
// Standard template for MJML emails
const emailTemplateMjml = template(
fs.readFileSync(`${templateDir}/emailTemplate.mjml`).toString()
)
// Standard template for text emails
const emailTemplateTxt = template(
fs.readFileSync(`${templateDir}/emailTemplate.txt`).toString()
)
const templateVars = {
listing,
offer,
config: this.config,
dappUrl: this.config.dappUrl,
ipfsGatewayUrl: this.config.ipfsGatewayUrl
}
const identities = await Identity.findAll({
where: {
ethAddress: {
[Sequelize.Op.or]: [buyerAddress, sellerAddress, party]
}
}
})
// Send an email to each recipient.
for (const identity of identities) {
if (!identity.email && !this.config.overrideEmail) {
logger.info(`${identity.ethAddress} has no email address. Skipping.`)
continue
}
try {
const recipient = identity.ethAddress.toLowerCase()
const recipientRole = recipient === sellerAddress ? 'seller' : 'buyer'
logger.info(
`Sending email for ${identity.ethAddress} as ${recipientRole}`
)
const message = getNotificationMessage(
eventName,
party,
recipient,
recipientRole,
'email'
)
if (!message) {
logger.info(
`No template defined for ${eventName} as a ${recipientRole}. Skipping.`
)
continue
}
const email = {
to: this.config.overrideEmail || identity.email,
from: this.config.fromEmail,
subject: message.subject(templateVars),
text: emailTemplateTxt({
message: message.text(templateVars)
}),
html: mjml2html(
emailTemplateMjml({
message: message.mjml(templateVars)
})
).html,
asm: {
groupId: this.config.asmGroupId
}
}
await this._send(identity.ethAddress, email)
} catch (error) {
logger.error(`Could not email via Sendgrid: ${error}`)
}
}
}
}
module.exports = EmailSender