const Imap = require('imap'); module.exports = Self => { Self.remoteMethod('checkInbox', { description: 'Check an email inbox and process it', accessType: 'READ', returns: { arg: 'body', type: 'file', root: true }, http: { path: `/checkInbox`, verb: 'GET' } }); Self.checkInbox = async() => { let imapConfig = await Self.app.models.WorkerTimeControlParams.findOne(); let imap = new Imap({ user: imapConfig.mailUser, password: imapConfig.mailPass, host: imapConfig.mailHost, port: 993, tls: true }); let isEmailOk; let emailText = ''; function openInbox(cb) { imap.openBox('INBOX', true, cb); } imap.once('ready', function() { openInbox(function(err, box) { if (err) throw err; let f = imap.seq.fetch('1:3', { bodies: ['HEADER.FIELDS (FROM SUBJECT)', '1'], struct: true }); f.on('message', function(msg, seqno) { isEmailOk = false; msg.on('body', function(stream, info) { let buffer = ''; stream.on('data', function(chunk) { buffer = chunk.toString('utf8'); if (info.which === '1') { emailText = buffer.split('\n')[0]; emailText = emailText.toUpperCase(); emailText = emailText.replace(/\s/g, ''); if (emailText === 'OK') isEmailOk = true; // isEmailOk } }); stream.once('end', function() { if (info.which === 'HEADER.FIELDS (FROM SUBJECT)') { console.log('isEmailOk', isEmailOk); if (isEmailOk) { emailConfirm(buffer); imap.seq.move(seqno, 'exito', function(err) { console.log('Move correcte: ' + err); console.log('Move error: ' + seqno); }); } else { emailReply(buffer); imap.seq.move(seqno, 'error', function(err) { console.log('Move error: ' + err); console.log('Move error: ' + seqno); }); } } }); }); }); // msg.on('attributes', function(attrs) { // console.log('ATRIBUTO', attrs.struct[0]); // console.log('ATRIBUTO', attrs.struct[0].params); // }); }); }); imap.connect(); return 'pepinillos'; }; async function getUser(workerEmail) { let firstPosition = workerEmail.search('<') + 1; let lastPosition = workerEmail.search('@') - firstPosition; let userName = workerEmail.substr(firstPosition, lastPosition); let user = await Self.app.models.Account.findOne({where: {name: userName}}); return user; } async function getEmailDate(subject) { let date = subject.match(/\d+/g); return date; } async function emailConfirm(buffer) { let now = new Date(); let from = JSON.stringify(Imap.parseHeader(buffer).from); let subject = JSON.stringify(Imap.parseHeader(buffer).subject); let timeControlDate = await getEmailDate(subject); let week = timeControlDate[0]; let year = timeControlDate[1]; let user = await getUser(from); let workerMail = await Self.app.models.WorkerTimeControlMail.findOne({ where: { week: week, year: year, worker: user.id } }); await workerMail.updateAttributes({ updated: now, state: 'CONFIRMED' }); // MOVER A CARPETA EXITO } async function emailReply(subject, workerEmail) { console.log('bbbbb'); // INSERT EN VN.MAIL // UPDATE EN WORKERTIMECONTROLMAIL // MOVER A CARPETA ERROR } };