-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmail-fetcher.js
102 lines (93 loc) · 2.61 KB
/
mail-fetcher.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
var util = require('util'),
conf = require('./config'),
nodemailer = require('nodemailer'),
ImapConnection = require('imap').ImapConnection,
mailparser = require('mailparser'),
imap,
spawn = require('child_process').spawn,
xoauthProcess,
xoauthParams = {
user: conf.emailParams.email,
oauth_token: conf.emailParams.oauthToken,
oauth_token_secret: conf.emailParams.oauthTokenSecret
},
xoauthEncoded,
redis = require('redis'),
pubsub = redis.createClient(),
fetchInterval = 2000;
function imapWatch(xoauthEncoded, logger) {
imap = new ImapConnection({
host: 'imap.gmail.com',
port: 993,
secure: true,
xoauth: xoauthEncoded
// , debug: function(msg) { console.log(msg); }
});
imap.on('error', function(err) {
logger.error(err);
});
imap.on('close', function(err) {
logger.info('IMAP connection closed. Reconnect...');
imapWatch(xoauthEncoded, logger);
});
imap.connect(function(err) {
if (err) {
logger.error(err);
process.exit(1);
}
logger.info('IMAP connected.');
imap.openBox('INBOX', false, watchInbox);
});
function watchInbox(err, box) {
imap.search(['UNSEEN'], function(err, results) {
var fetch;
if (!results || !results.length) {
// logger.info('No unread messages. Retry...');
setTimeout(watchInbox, fetchInterval);
return;
}
fetch = imap.fetch(results, {
markSeen: true,
request: {
body: 'full',
headers: false,
struct: false
}
});
fetch.on('message', function(msg) {
newMessage(msg);
});
fetch.on('end', function() {
logger.info('Fetching messages ended.');
setTimeout(watchInbox, fetchInterval);
});
});
}
function newMessage(message) {
var parser = new mailparser.MailParser();
parser.on('end', function(mail) {
logger.info('[mail-fetcher] New mail: ' + mail.subject);
pubsub.publish('game:emails', JSON.stringify(mail));
});
message.on('data', function(data) {
parser.write(data.toString());
});
message.on('end', function() {
parser.end();
});
}
}
function main(logger) {
var xoauthEncoded = nodemailer.createXOAuthGenerator({
requestUrl: 'https://mail.google.com/mail/b/' + xoauthParams.user + '/imap/',
user: xoauthParams.user,
token: xoauthParams.oauth_token,
tokenSecret: xoauthParams.oauth_token_secret
}).generate();
imapWatch(xoauthEncoded, logger);
}
if (require.main === module) {
main(require('winston'));
} else {
module.exports = main;
}