forked from SpiderStrategies/node-gmail-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
219 lines (190 loc) · 5.26 KB
/
index.js
File metadata and controls
219 lines (190 loc) · 5.26 KB
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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',
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 email with specific message Id. Returns a message.
*
* e.g. to get single message: gmail.attachment('1884771040010', '')
*/
Gmail.prototype.attachment = function (messageId, attachmentId, opts, next) {
if (!next) {
next = opts
opts = {}
}
var r = request({
url: api + '/gmail/v1/users/me/messages/' + messageId + '/attachments/' + attachmentId,
json: true,
timeout: opts.timeout,
timeout: opts.timeout,
headers: {
'Authorization': 'Bearer ' + this.key
}
}, function (err, res, body) {
if (err) {
return next && next(err)
}
if (res.statusCode === 404) {
return next && next(new Error('Message Not Found'))
}
if (res.statusCode !== 200) {
return next && next(new Error('Failed with status: ' + res.statusCode))
}
try {
return next && next(err, JSON.parse(body))
} catch (e) {
return next && next(err, body)
}
})
}
/*
* 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