This repository has been archived by the owner on Jul 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
socket.js
90 lines (78 loc) · 2.64 KB
/
socket.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
var debug = require('debug')('scc:socket');
var backoff = require('backoff');
var processTweet = require('./util/process-tweet');
var topic = process.env.TWITTER_TOPIC || '<topic>';
var preloadedTweets = [];
module.exports = function(io, twitter) {
// existing sessions
var sessions = {};
var connectTwitter = function() {
twitter.stream({ track: topic, filter_level: 'medium', language: 'en' }, function(stream) {
debug('Connected to twitter.stream, topic: %s', topic);
stream.on('data', function(tweet) {
fibonacciBackoff.reset();
processTweet(tweet, function (error, processedTweet) {
if (error) {
debug(error);
debug('Ignore tweet: %s', tweet.text);
return;
}
preloadedTweets.push(processedTweet);
if(preloadedTweets.length > 5) {
preloadedTweets.shift();
}
Object.keys(sessions).forEach(function(id) {
sessions[id].socket.emit('message', processedTweet);
});
});
});
stream.on('error', function(error) {
debug('Error connecting to twitter.stream: %s', error);
fibonacciBackoff.backoff();
});
stream.on('close', function(error) {
debug('Error connecting to twitter.stream: %s', error);
fibonacciBackoff.backoff();
});
});
};
// Create a session on socket connection
io.use(function(socket, next) {
sessions[socket.id] = { socket: socket };
debug('Total sessions: %s sessions', Object.keys(sessions).length);
socket.emit('session', socket.id);
next();
});
io.on('connection', function(socket) {
preloadedTweets.forEach(function(tweet){
socket.emit('message', tweet);
});
socket.on('message', function() {
// send initial tweets
socket.emit('message', 'hello!');
});
// Delete the session on disconnect
socket.on('disconnect', function() {
delete sessions[socket.id];
debug('Disconnect: %s', socket.id);
});
});
var fibonacciBackoff = backoff.fibonacci({
randomisationFactor: 0,
initialDelay: 10,
maxDelay: 30000
});
fibonacciBackoff.failAfter(10);
fibonacciBackoff.on('backoff', function(number, delay) {
// Do something when backoff starts, e.g. show to the
// user the delay before next reconnection attempt.
debug('Attempting to reconect to twitter. Attempts: ' + number + ' ' + delay + 'ms');
});
fibonacciBackoff.on('ready', function() {
connectTwitter();
});
fibonacciBackoff.on('fail', function() {
debug('Failed to connect to twitter after multiple attempts.');
});
fibonacciBackoff.backoff();
};