-
Notifications
You must be signed in to change notification settings - Fork 29
/
index.js
180 lines (155 loc) · 4.36 KB
/
index.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
var request = require('request')
, Parser = require('./lib/parser')
, split = require('split')
, multiparty = require('multiparty')
, ss = require('stream-stream')
, through = require('through2')
, querystring = require('querystring')
, api = 'https://www.googleapis.com'
var Gmail = function (key) {
if (!key) {
throw new Error('Access key required')
}
this.key = key
}
var retrieveCount = function (key, q, endpoint, opts, next) {
request({
url: api + '/gmail/v1/users/me/' + endpoint,
json: true,
timeout: opts.timeout,
qs: {
q: q,
fields: 'resultSizeEstimate'
},
headers: {
'Authorization': 'Bearer ' + key
}
}, function (err, response, body) {
if (err) {
return next(err)
}
if (body.error) {
return next(new Error(body.error.message))
}
return next(null, body.resultSizeEstimate)
})
}
var formQuery = function (query) {
var formedQuery = '?'
, params = {}
Object.keys(query).forEach(function(key) {
if(query[key]) {
params[key] = query[key] instanceof Array ? query[key].join(',') : query[key]
}
})
formedQuery += querystring.stringify(params)
return formedQuery
}
var retrieve = function (key, q, endpoint, opts) {
var result = new Parser({objectMode: true})
, combined = ss()
, opts = opts || {}
, i = opts.max
, partsFound = 0
var loop = function(page) {
var reqOpts = {
url: api + '/gmail/v1/users/me/' + endpoint,
json: true,
timeout: opts.timeout,
qs: {
q: q,
maxResults: i < 100 ? i : 100
},
headers: {
'Authorization': 'Bearer ' + key
}
}
var query = formQuery({fields : opts.fields, format : opts.format})
if (page) reqOpts.qs.pageToken = page
request(reqOpts, function (err, response, body) {
if (err) {
return result.emit('error', err)
}
if (body.error) {
return result.emit('error', new Error(body.error.message))
}
result.resultSizeEstimate = body.resultSizeEstimate
if (!result.resultSizeEstimate) {
return result.end()
}
var messages = body[endpoint].map(function (m) {
return {
'Content-Type': 'application/http',
body: 'GET ' + api + '/gmail/v1/users/me/' + endpoint + '/' + m.id + query + '\n'
}
})
var r = request({
method: 'POST',
url: api + '/batch/gmail/v1',
multipart: messages,
timeout: opts.timeout,
headers: {
'Authorization': 'Bearer ' + key,
'content-type': 'multipart/mixed'
}
})
r.on('error', function (e) {
result.emit('error', e)
})
r.on('response', function (res) {
var type = res.headers['content-type']
, form = new multiparty.Form
res.headers['content-type'] = type.replace('multipart/mixed', 'multipart/related')
form.on('part', function (part) {
partsFound++;
combined.write(part.pipe(split('\r\n')).pipe(new Parser))
}).parse(res)
form.on('close', function () {
if (opts.max !== partsFound && body.nextPageToken) return loop(body.nextPageToken)
combined.end()
})
})
})
}
loop()
var counter = through(function(obj, enc, cb) {
i--
cb(null, obj)
})
return combined.pipe(counter).pipe(result)
}
/*
* Fetches the number of estimated messages matching the query
* Invokes callback with err and estimated number
*/
Gmail.prototype.estimatedMessages = function (q, opts, next) {
if (!next) {
next = opts
opts = {}
}
return retrieveCount(this.key, q, 'messages', opts, next)
}
/*
* Fetches email that matches the query. Returns a stream of messages with a max of 100 messages
* since the batch api sets a limit of 100.
*
* e.g. to search an inbox: gmail.messages('label:inbox')
*/
Gmail.prototype.messages = function (q, opts) {
return retrieve(this.key, q, 'messages', opts)
}
/*
* Fetches the number of estimated threads matching the query
* Invokes callback with err and estimated number
*/
Gmail.prototype.estimatedThreads = function (q, opts, next) {
if (!next) {
next = opts
opts = {}
}
return retrieveCount(this.key, q, 'threads', opts, next)
}
Gmail.prototype.threads = function (q, opts) {
return retrieve(this.key, q, 'threads', opts)
}
module.exports = Gmail