-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitter-stream-service.js
52 lines (43 loc) · 1.39 KB
/
twitter-stream-service.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
'use strict';
var NTwitter = require('ntwitter');
function TwitterStreamService(config) {
this.twit = new NTwitter(config);
this.sampleStream = null;
this.sampleStreamIdleTimer = null;
this.idleTimeout = 1000 * 60 * 10;
setInterval((function () {
if (this.sampleStream && this.sampleStream.listeners('data').length === 0) {
console.log('everyone left, destroy()');
this.sampleStream.destroy();
this.sampleStream = null;
}
}).bind(this), 1000);
}
TwitterStreamService.prototype.getSampleStream = function getSampleStream(callback) {
if (this.sampleStream) {
callback(this.sampleStream);
return;
}
console.log('connect to streaming server.');
this.twit.stream('statuses/sample', (function (stream) {
this.sampleStream = stream;
stream.on('missedHeartbeat', (function () {
console.log('missedHeartbeat, destroy()');
stream.destroy();
this.sampleStream = null;
}).bind(this));
callback(stream);
}).bind(this));
};
TwitterStreamService.prototype.updateIdleTimer = function updateIdleTimer() {
clearTimeout(this.sampleStreamIdleTimer);
this.sampleStreamIdleTimer = setTimeout((function () {
if (!this.sampleStream) { return; }
console.log('sampleStreamIdleTimer timeout, destroy()');
this.sampleStream.destroy();
this.sampleStream = null;
}).bind(this), this.idleTimeout);
};
module.exports = function create(config) {
return new TwitterStreamService(config);
};