Advertisement
Guest User

Untitled

a guest
Sep 23rd, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. const models = require('../models');
  4. const _ = require('lodash');
  5. const Promise = require('bluebird');
  6. const Imap = require('imap');
  7. const MailParser = require('mailparser').MailParser;
  8. const async = require('async');
  9.  
  10.  
  11. var getEmailAccounts = function () {
  12.   var criteria = {
  13.     where: {
  14.       removed: false,
  15.       imapUser: {$ne: null},
  16.       imapPassword: {$ne: null},
  17.       imapHost: {$ne: null},
  18.       imapPort: {$ne: null},
  19.       imapTls: {$ne: null}
  20.     }
  21.   };
  22.   return models.emailAccounts.findAll(criteria);
  23. };
  24.  
  25.  
  26. var getMailsFromAccount = function (emailAccount) {
  27.   return new Promise(function (resolve, reject) {
  28.     var results = [];
  29.  
  30.     var userData = {
  31.       user: emailAccount.imapUser,
  32.       password: emailAccount.imapPassword,
  33.       host: emailAccount.imapHost,
  34.       port: emailAccount.imapPort,
  35.       tls: emailAccount.imapTls
  36.     };
  37.  
  38.     var imap = new Imap(userData);
  39.  
  40.     function openInbox(cb) {
  41.       imap.openBox('INBOX', true, cb);
  42.     }
  43.  
  44.  
  45.     imap.once('error', function (err) {
  46.       sails.log.error('Connection error: ' + err.message + '  For: ' + JSON.stringify(userData));
  47.       return reject(err.message);
  48.     });
  49.  
  50.     imap.once('ready', function () {
  51.       openInbox(function (err) {
  52.         if (err) reject(err);
  53.         imap.search(['ALL', ['SINCE', '20 Sep, 2016']], function(err, messages) {
  54.           var f = imap.fetch(messages, {bodies: ''});
  55.  
  56.           f.on('message', function (msg) {
  57.             var parser = new MailParser();
  58.  
  59.             parser.on('end', function (msg) {
  60.               msg.agencyId = emailAccount.agencyId;
  61.               results.push(msg);
  62.               if (results.length == messages.length) {
  63.                 imap.end();
  64.               }
  65.             });
  66.  
  67.             msg.on('body', function (stream) {
  68.               stream.on('data', function (chunk) {
  69.                 parser.write(chunk.toString('utf8'));
  70.               });
  71.             });
  72.  
  73.             msg.once('end', function () {
  74.               parser.end();
  75.             });
  76.           });
  77.  
  78.           f.once('error', function (err) {
  79.             console.log('Fetch error: ' + err);
  80.           });
  81.  
  82.         });
  83.       });
  84.     });
  85.  
  86.     imap.once('error', function (error) {
  87.       resolve(error);
  88.     });
  89.  
  90.     imap.once('end', function () {
  91.       resolve(results);
  92.     });
  93.  
  94.     imap.connect();
  95.   });
  96. };
  97.  
  98.  
  99. var createEventIfNotExists = function (email) {
  100.   return models.events.findOne({
  101.     where: {
  102.       removed: false,
  103.       messageId: email.messageId,
  104.       agencyId: email.agencyId
  105.     }
  106.   })
  107.   .then(function(event) {
  108.     if (event) {
  109.       return {
  110.         email: email,
  111.         event: event
  112.       };
  113.     }
  114.     return models.events.create({
  115.       eventTypeId: 1,
  116.       content: email.text,
  117.       title: email.subject,
  118.       date: email.date,
  119.       agencyId: email.agencyId,
  120.       messageId: email.messageId
  121.     })
  122.     .then(function(event) {
  123.       return {
  124.         email: email,
  125.         event: event
  126.       };
  127.     });
  128.   });
  129. };
  130.  
  131.  
  132. var createContactIfNotExists = function(agencyId, emailAddress) {
  133.   return models.contacts.findOne({
  134.     where: {
  135.       removed: false,
  136.       agencyId: agencyId,
  137.       email: emailAddress
  138.     }
  139.   })
  140.   .then(function (contact) {
  141.     if (contact) {
  142.       return contact;
  143.     }
  144.     return models.contacts.create({
  145.       agencyId: agencyId,
  146.       email: emailAddress
  147.     });
  148.   });
  149. };
  150.  
  151.  
  152. var attachContactToEvent = function(typeId, contactId, eventId) {
  153.   return models.eventForContacts.findOne({
  154.     where: {
  155.       contactId: contactId,
  156.       eventId: eventId
  157.     }
  158.   })
  159.   .then(function(result) {
  160.     if (result) {
  161.       return result;
  162.     }
  163.     return models.eventForContacts.create({
  164.       eventForContactTypeId: typeId,
  165.       contactId: contactId,
  166.       eventId: eventId
  167.     });
  168.   });
  169. };
  170.  
  171.  
  172. var attachContactsToEvent = function(data) {
  173.   var email = data.email;
  174.   var event = data.event;
  175.   var fields = ['from', 'cc', 'bcc'];
  176.  
  177.   return _.map(fields, (field) => {
  178.     return _.map(email[field], function (item) {
  179.         createContactIfNotExists(event.agencyId, item.address)
  180.         .then(function (contact) {
  181.           return attachContactToEvent(
  182.             EventForContactType[field.toUpperCase()],
  183.             contact.id,
  184.             event.id
  185.           );
  186.         });
  187.     });
  188.   });
  189. };
  190.  
  191. var parseEmail = function (email) {
  192.   return createEventIfNotExists(email)
  193.     .then(attachContactsToEvent);
  194. };
  195.  
  196. var processEmailAccount = function (emailAccount) {
  197.   return getMailsFromAccount(emailAccount)
  198.     .then(function (emails) {
  199.       return Promise.all(_.map(emails, parseEmail));
  200.     })
  201.     .catch(function (err) {
  202.       sails.log.error(err);
  203.     });
  204. };
  205.  
  206.  
  207. var getMails = function () {
  208.   return getEmailAccounts()
  209.     .then(function (emailAccounts) {
  210.       return new Promise(function(resolve) {
  211.         async.eachLimit(emailAccounts, sails.config.app.emailParseLimit, processEmailAccount, function() {
  212.           resolve();
  213.         });
  214.       });
  215.     })
  216.     .catch(function (err) {
  217.       sails.log.error(err);
  218.     });
  219. };
  220.  
  221. module.exports = {
  222.   getMails: getMails
  223. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement