-
Notifications
You must be signed in to change notification settings - Fork 47
/
server.js
86 lines (71 loc) · 2.91 KB
/
server.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
//Setup web server and socket
var twitter = require('twitter'),
express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
//Setup twitter stream api
var twit = new twitter({
consumer_key: '<ENTER>',
consumer_secret: '<ENTER>',
access_token_key: '<ENTER>',
access_token_secret: '<ENTER>'
}),
stream = null;
//Use the default port (for beanstalk) or default to 8081 locally
server.listen(process.env.PORT || 8081);
//Setup rotuing for app
app.use(express.static(__dirname + '/public'));
//Create web sockets connection.
io.sockets.on('connection', function (socket) {
socket.on("start tweets", function() {
if(stream === null) {
//Connect to twitter stream passing in filter for entire world.
twit.stream('statuses/filter', {'locations':'-180,-90,180,90'}, function(stream) {
stream.on('data', function(data) {
// Does the JSON result have coordinates
if (data.coordinates){
if (data.coordinates !== null){
//If so then build up some nice json and send out to web sockets
var outputPoint = {"lat": data.coordinates.coordinates[0],"lng": data.coordinates.coordinates[1]};
socket.broadcast.emit("twitter-stream", outputPoint);
//Send out to web sockets channel.
socket.emit('twitter-stream', outputPoint);
}
else if(data.place){
if(data.place.bounding_box === 'Polygon'){
// Calculate the center of the bounding box for the tweet
var coord, _i, _len;
var centerLat = 0;
var centerLng = 0;
for (_i = 0, _len = coords.length; _i < _len; _i++) {
coord = coords[_i];
centerLat += coord[0];
centerLng += coord[1];
}
centerLat = centerLat / coords.length;
centerLng = centerLng / coords.length;
// Build json object and broadcast it
var outputPoint = {"lat": centerLat,"lng": centerLng};
socket.broadcast.emit("twitter-stream", outputPoint);
}
}
}
stream.on('limit', function(limitMessage) {
return console.log(limitMessage);
});
stream.on('warning', function(warning) {
return console.log(warning);
});
stream.on('disconnect', function(disconnectMessage) {
return console.log(disconnectMessage);
});
});
});
}
});
// Emits signal to the client telling them that the
// they are connected and can start receiving Tweets
socket.emit("connected");
});