2016-07-09 08:06:21 +08:00
|
|
|
|
|
|
|
class ContactProcessor {
|
|
|
|
|
2016-07-12 09:30:08 +08:00
|
|
|
verified(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)
|
|
|
|
|
2016-07-12 15:59:41 +08:00
|
|
|
if (!contact.email) {
|
|
|
|
return false;
|
|
|
|
}
|
2016-07-09 08:06:21 +08:00
|
|
|
if (regex.test(contact.email) || contact.email.length > 60) {
|
|
|
|
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-13 09:31:30 +08:00
|
|
|
processMessage({db, message}) {
|
2016-07-09 08:06:21 +08:00
|
|
|
const {Contact} = db;
|
|
|
|
|
|
|
|
let allContacts = []
|
|
|
|
const fields = ['to', 'from', 'bcc', 'cc']
|
|
|
|
fields.forEach((field) => {
|
|
|
|
allContacts = allContacts.concat(message[field])
|
|
|
|
})
|
2016-07-12 09:30:08 +08:00
|
|
|
const filtered = allContacts.filter(this.verified)
|
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),
|
|
|
|
}
|