2016-07-09 08:06:21 +08:00
|
|
|
|
|
|
|
class ContactProcessor {
|
|
|
|
|
2016-07-12 04:48:00 +08:00
|
|
|
verified(logger, contact) {
|
2016-07-09 08:06:21 +08:00
|
|
|
// some suggestions: http://stackoverflow.com/questions/6317714/apache-camel-mail-to-identify-auto-generated-messages
|
|
|
|
const regex = new RegExp(/^(noreply|no-reply|donotreply|mailer|support|webmaster|news(letter)?@)/ig)
|
|
|
|
|
|
|
|
if (regex.test(contact.email) || contact.email.length > 60) {
|
2016-07-12 04:48:00 +08:00
|
|
|
logger.info('Email address doesn\'t seem to be areal person')
|
2016-07-09 08:06:21 +08:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
emptyContact(Contact, options = {}, accountId) {
|
|
|
|
options.accountId = accountId
|
|
|
|
return Contact.create(options)
|
|
|
|
}
|
|
|
|
|
|
|
|
findOrCreateByContactId(Contact, contact, accountId) {
|
|
|
|
return Contact.find({where: {email: contact.email}})
|
|
|
|
.then((contactDb) => {
|
|
|
|
return contactDb || this.emptyContact(Contact, contact, accountId)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2016-07-12 04:48:00 +08:00
|
|
|
processMessage({db, message, logger}) {
|
2016-07-09 08:06:21 +08:00
|
|
|
const {Contact} = db;
|
2016-07-12 04:48:00 +08:00
|
|
|
this.logger = logger
|
2016-07-09 08:06:21 +08:00
|
|
|
|
|
|
|
let allContacts = []
|
|
|
|
const fields = ['to', 'from', 'bcc', 'cc']
|
|
|
|
fields.forEach((field) => {
|
|
|
|
allContacts = allContacts.concat(message[field])
|
|
|
|
})
|
2016-07-12 04:48:00 +08:00
|
|
|
const filtered = allContacts.filter(this.verified(logger))
|
2016-07-09 08:06:21 +08:00
|
|
|
const contactPromises = filtered.map((contact) => {
|
|
|
|
return this.findOrCreateByContactId(Contact, contact, message.accountId)
|
|
|
|
})
|
|
|
|
|
|
|
|
return Promise.all(contactPromises)
|
|
|
|
.then(() => {
|
|
|
|
return message
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const processor = new ContactProcessor()
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
order: 3,
|
|
|
|
processMessage: processor.processMessage.bind(processor),
|
|
|
|
}
|