1 |
|
2 |
|
3 |
|
4 | var EventEmitter = require('events').EventEmitter
|
5 | , querystring = require('querystring')
|
6 | , util = require('util')
|
7 | , Parser = require('./parser')
|
8 | , Auth = require('./auth')
|
9 |
|
10 |
|
11 | var STATUS_CODES_TO_ABORT_ON = [ 400, 401, 403, 404, 406, 410, 422 ];
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | function OARequest (oauth, method, path, params) {
|
22 | if (method !== 'GET' && method !== 'POST') {
|
23 | throw new Error('method `'+method+'` not supported.\n')
|
24 | }
|
25 | this.oauth = oauth
|
26 | this.method = method
|
27 |
|
28 | this.twit_options = {}
|
29 |
|
30 | if (params && params.twit_options && typeof params.twit_options !== 'object') {
|
31 |
|
32 | throw new Error('Invalid twit_options supplied: '+params.twit_options)
|
33 | } else if (params.twit_options) {
|
34 |
|
35 | this.twit_options = JSON.parse(JSON.stringify(params.twit_options))
|
36 | delete params.twit_options
|
37 | }
|
38 |
|
39 | if (method === 'GET') {
|
40 | this.path = path + (params ? '?' + querystring.stringify(params) : '')
|
41 | this.params = null
|
42 | } else if (method === 'POST') {
|
43 | this.path = path
|
44 | this.params = params
|
45 | }
|
46 |
|
47 | EventEmitter.call(this)
|
48 | }
|
49 |
|
50 | util.inherits(OARequest, EventEmitter)
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | OARequest.prototype.persist = function () {
|
57 | var self = this
|
58 |
|
59 | this.parser = new Parser()
|
60 |
|
61 |
|
62 | this.parser.on('element', function (msg) {
|
63 |
|
64 | self.connectInterval = 0
|
65 | if (msg.delete) { self.emit('delete', msg) }
|
66 | else if (msg.disconnect) { self.handleDisconnect(msg) }
|
67 | else if (msg.limit) { self.emit('limit', msg) }
|
68 | else if (msg.scrub_geo) { self.emit('scrub_geo', msg) }
|
69 | else if (msg.warning) { self.emit('warning', msg) }
|
70 | else if (msg.status_withheld) { self.emit('status_withheld', msg) }
|
71 | else if (msg.user_withheld) { self.emit('user_withheld', msg) }
|
72 | else if (msg.friends) { self.emit('friends', msg) }
|
73 | else if (msg.direct_message) { self.emit('direct_message', msg) }
|
74 | else if (msg.event) {
|
75 | self.emit('user_event', msg)
|
76 |
|
77 | var ev = msg.event
|
78 |
|
79 | if (ev === 'blocked') { self.emit('blocked', msg) }
|
80 | else if (ev === 'unblocked') { self.emit('unblocked', msg) }
|
81 | else if (ev === 'favorite') { self.emit('favorite', msg) }
|
82 | else if (ev === 'unfavorite') { self.emit('unfavorite', msg) }
|
83 | else if (ev === 'follow') { self.emit('follow', msg) }
|
84 | else if (ev === 'unfollow') { self.emit('unfollow', msg) }
|
85 | else if (ev === 'user_update') { self.emit('user_update', msg) }
|
86 | else if (ev === 'list_created') { self.emit('list_created', msg) }
|
87 | else if (ev === 'list_destroyed') { self.emit('list_destroyed', msg) }
|
88 | else if (ev === 'list_updated') { self.emit('list_updated', msg) }
|
89 | else if (ev === 'list_member_added') { self.emit('list_member_added', msg) }
|
90 | else if (ev === 'list_member_removed') { self.emit('list_member_removed', msg) }
|
91 | else if (ev === 'list_user_subscribed') { self.emit('list_user_subscribed', msg) }
|
92 | else if (ev === 'list_user_unsubscribed') { self.emit('list_user_unsubscribed', msg) }
|
93 | else { self.emit('unknown_user_event', msg) }
|
94 | } else { self.emit('tweet', msg) }
|
95 | })
|
96 |
|
97 | this.parser.on('error', function (err) {
|
98 | self.emit('error', err)
|
99 | })
|
100 |
|
101 |
|
102 |
|
103 | process.nextTick(function () {
|
104 |
|
105 |
|
106 | self.keepAlive()
|
107 | })
|
108 |
|
109 | return this
|
110 | }
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 | OARequest.prototype.start = function () {
|
117 | this.abortedBy = null;
|
118 | this.keepAlive()
|
119 | return this
|
120 | }
|
121 |
|
122 |
|
123 |
|
124 |
|
125 |
|
126 | OARequest.prototype.stop = function () {
|
127 | this.abortedBy = 'twit-client'
|
128 |
|
129 | if (this.request) {
|
130 | this.request.abort()
|
131 | this.request.removeAllListeners()
|
132 | delete this.request
|
133 | }
|
134 |
|
135 | if (this.response) {
|
136 | this.response.removeAllListeners()
|
137 | }
|
138 |
|
139 | return this
|
140 | }
|
141 |
|
142 |
|
143 |
|
144 |
|
145 |
|
146 |
|
147 | OARequest.prototype.keepAlive = function () {
|
148 |
|
149 | var self = this;
|
150 |
|
151 | this.request = this.makeRequest(null);
|
152 |
|
153 | this.response = null;
|
154 |
|
155 | this.request.once('response', function (response) {
|
156 |
|
157 |
|
158 | self.usedFirstReconnect = false;
|
159 | self.response = response;
|
160 | self.response.setEncoding('utf8');
|
161 |
|
162 |
|
163 | self.response.on('data', function (chunk) {
|
164 | self.emit('connected', self.response);
|
165 |
|
166 | self.resetStallAbortTimeout();
|
167 | self.parser.parse(chunk);
|
168 | });
|
169 |
|
170 | self.response.once('close', function () {
|
171 | self.handleCloseEvent()
|
172 | })
|
173 |
|
174 | self.response.on('error', function (err) {
|
175 |
|
176 | self.emit('error', err)
|
177 | })
|
178 |
|
179 | if (STATUS_CODES_TO_ABORT_ON.indexOf(response.statusCode) !== -1) {
|
180 | self.abortedBy = 'twit-client'
|
181 | self.stop()
|
182 |
|
183 | var error = new Error('Bad Twitter streaming request: ' + response.statusCode)
|
184 | error.response = response
|
185 | self.emit('error', error);
|
186 | }
|
187 | });
|
188 |
|
189 | this.request.once('close', function () {
|
190 | self.handleCloseEvent()
|
191 | });
|
192 |
|
193 | this.request.once('error', function (err) {
|
194 | self.stopStallAbortTimeout();
|
195 | self.emit('error', err);
|
196 | });
|
197 |
|
198 | this.request.end();
|
199 | this.emit('connect', this.request);
|
200 | return this;
|
201 | }
|
202 |
|
203 |
|
204 |
|
205 |
|
206 |
|
207 |
|
208 |
|
209 |
|
210 | OARequest.prototype.handleCloseEvent = function () {
|
211 | var self = this;
|
212 |
|
213 | self.stopStallAbortTimeout();
|
214 |
|
215 |
|
216 | if (self.abortedBy === 'twit-client')
|
217 | return
|
218 |
|
219 |
|
220 | self.abortedBy = 'twitter';
|
221 |
|
222 | if (self.scheduledReconnect) {
|
223 |
|
224 |
|
225 | return
|
226 | }
|
227 |
|
228 | if (self.response && self.response.statusCode === 420) {
|
229 |
|
230 |
|
231 | if (!self.connectInterval) {
|
232 | self.connectInterval = 60000;
|
233 | } else {
|
234 | self.connectInterval *= 2;
|
235 | }
|
236 | } else if (self.response && String(self.response.statusCode).charAt(0) === '5') {
|
237 |
|
238 |
|
239 | if (!self.connectInterval) {
|
240 | self.connectInterval = 5000;
|
241 | } else if (self.connectInterval < 320000) {
|
242 | self.connectInterval *= 2;
|
243 | } else {
|
244 | self.connectInterval = 320000;
|
245 | }
|
246 | } else {
|
247 |
|
248 | if (!self.usedFirstReconnect) {
|
249 |
|
250 | self.connectInterval = 0;
|
251 | self.usedFirstReconnect = true;
|
252 | } else if (self.connectInterval < 16000) {
|
253 |
|
254 | self.connectInterval += 250;
|
255 | } else {
|
256 |
|
257 | self.connectInterval = 16000;
|
258 | }
|
259 | }
|
260 |
|
261 | self.emit('reconnect', self.request, self.response, self.connectInterval);
|
262 |
|
263 |
|
264 | self.scheduledReconnect = setTimeout(function () {
|
265 | self.start();
|
266 | delete self.scheduledReconnect;
|
267 | }, self.connectInterval);
|
268 | }
|
269 |
|
270 |
|
271 |
|
272 |
|
273 |
|
274 |
|
275 |
|
276 |
|
277 | OARequest.prototype.handleDisconnect = function (msg) {
|
278 | this.emit('disconnect', msg)
|
279 | this.stop()
|
280 | return this
|
281 | }
|
282 |
|
283 |
|
284 |
|
285 |
|
286 |
|
287 |
|
288 |
|
289 |
|
290 | OARequest.prototype.end = function (callback) {
|
291 | var self = this
|
292 |
|
293 |
|
294 | var responseHandler = function (err, raw, response) {
|
295 | if (err instanceof Error) {
|
296 |
|
297 |
|
298 | err.twitterReply = raw || null
|
299 |
|
300 | err.code = null;
|
301 | err.allErrors = [];
|
302 |
|
303 | return callback(err, err.twitterReply, response)
|
304 | }
|
305 |
|
306 |
|
307 | if (err && !(err instanceof Error) && err.statusCode) {
|
308 | if (
|
309 | self.twit_options.retry &&
|
310 | STATUS_CODES_TO_ABORT_ON.indexOf(err.statusCode) === -1
|
311 | ) {
|
312 |
|
313 | self.makeRequest(responseHandler)
|
314 | return
|
315 | }
|
316 |
|
317 | var error = new Error()
|
318 |
|
319 | error.message = 'Unknown Twitter API Error';
|
320 | error.statusCode = err.statusCode
|
321 |
|
322 | error.twitterReply = err.data
|
323 |
|
324 | error.code = null;
|
325 |
|
326 | error.allErrors = [];
|
327 |
|
328 |
|
329 | try {
|
330 | var parsedError = JSON.parse(err.data)
|
331 |
|
332 | if (parsedError.errors && parsedError.errors.length) {
|
333 |
|
334 | error.message = parsedError.errors[0].message
|
335 | error.code = parsedError.errors[0].code
|
336 |
|
337 |
|
338 | error.allErrors = parsedError.errors;
|
339 | }
|
340 | } catch (e) {
|
341 |
|
342 | }
|
343 |
|
344 | return callback(error, undefined, response)
|
345 | } else if (err) {
|
346 |
|
347 | err.twitterReply = raw
|
348 | return callback(err, undefined, response)
|
349 | }
|
350 |
|
351 |
|
352 |
|
353 |
|
354 | var parsed = null
|
355 | , parseError = null
|
356 |
|
357 | try {
|
358 | parsed = JSON.parse(raw)
|
359 | } catch(e) {
|
360 | parseError = new Error('twitter reply is not a valid JSON string.')
|
361 | parseError.twitterReply = raw
|
362 | }
|
363 |
|
364 |
|
365 | if (parseError) {
|
366 | return callback(parseError, undefined, response)
|
367 | } else if (!parsed) {
|
368 |
|
369 | var badReplyError = new Error('twitter sent bad reply: `'+parsed+'`.')
|
370 | badReplyError.twitterReply = raw
|
371 |
|
372 | return callback(badReplyError, undefined, response)
|
373 | }
|
374 |
|
375 | return callback(null, parsed, response)
|
376 | }
|
377 |
|
378 |
|
379 | this.makeRequest(responseHandler)
|
380 |
|
381 | return this
|
382 | }
|
383 |
|
384 |
|
385 |
|
386 |
|
387 |
|
388 |
|
389 |
|
390 |
|
391 |
|
392 |
|
393 | OARequest.prototype.makeRequest = function (cb) {
|
394 | var action = this.method.toLowerCase()
|
395 | var self = this
|
396 |
|
397 | if (action !== 'get' && action !== 'post')
|
398 | throw new Error('method `'+action+'` not supported')
|
399 |
|
400 |
|
401 | if (action === 'get') {
|
402 | return self.oauth.oa.get(
|
403 | self.path
|
404 | , self.oauth.config.access_token
|
405 | , self.oauth.config.access_token_secret
|
406 | , cb
|
407 | )
|
408 | }
|
409 |
|
410 | return self.oauth.oa.post(
|
411 | self.path
|
412 | , self.oauth.config.access_token
|
413 | , self.oauth.config.access_token_secret
|
414 | , self.params
|
415 | , cb
|
416 | )
|
417 | }
|
418 |
|
419 |
|
420 |
|
421 |
|
422 |
|
423 |
|
424 |
|
425 | OARequest.prototype.resetStallAbortTimeout = function () {
|
426 | var self = this;
|
427 |
|
428 | this.stopStallAbortTimeout();
|
429 |
|
430 | this.stallAbortTimeout = setTimeout(function () {
|
431 | if (typeof self.request !== 'undefined') {
|
432 | self.request.abort();
|
433 | delete self.request;
|
434 | }
|
435 | }, 90000);
|
436 | return this;
|
437 | }
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 | OARequest.prototype.stopStallAbortTimeout = function () {
|
444 | if (this.stallAbortTimeout) clearTimeout(this.stallAbortTimeout);
|
445 | return this;
|
446 | }
|
447 |
|
448 | module.exports = OARequest
|
449 |
|