xonecas.io
49
Do

dotter / files

dotter / server.js

2.3 KB
1
2var io = require('socket.io'),
3   _ = require('underscore'),
4   connect = require('connect'),
5   http = require('http'),
6   Twitter = require('twitter');
7
8function getPoint(twiit) {
9   var geo = twiit.geo,
10      coords = twiit.coordinates;
11
12   if (typeof coords === 'object' && coords !== null) {
13      var point = {lat: coords.coordinates[0],
14         lng: coords.coordinates[1]};
15   }
16   else if (typeof geo === 'object' && geo !== null) {
17      var point = {lat: geo.coordinates[1],
18         lng: geo.coordinates[0]};
19   }
20
21   if (point !== undefined)
22      return point;
23}
24
25var twitter = new Twitter({
26   consumer_key: '',
27   consumer_secret: '',
28   access_token_key: '',
29   access_token_secret: ''
30});
31
32var server = connect.createServer(
33   connect.static(__dirname)
34);
35server.listen(1234);
36
37var stream = false;
38var socket = io.listen(server);
39
40var stats = {
41   streams: 0,
42   clients: 0
43};
44
45socket.on('connection', function (client) {
46   if (!stream) {
47      twitter.stream('statuses/filter', 
48         {locations: '-180,-90,180,90', track: 'RT'}, 
49         function (newStream) {
50
51         stream = newStream;
52
53         console.log('===== New stream started ');
54         stats.streams++;
55
56         stream.on('data', function (twiit) {
57            var point = getPoint(twiit);
58               retweet = twiit.retweeted_status;
59
60            if (typeof retweet === 'object' && retweet !== null) {
61               var repoint = getPoint(retweet)
62            }
63
64            if (point !== undefined && repoint !== undefined) {
65               point.repoint = repoint;
66               console.log('===== Point and Repoint ');
67            }
68            else if (point === undefined && repoint !== undefined)
69               var point = repoint;
70               
71            if (point !== undefined) 
72               socket.broadcast(JSON.stringify(point));
73
74         });
75      });
76   }
77
78   client.on('message', function (data) {
79      if (data === 'track') {
80         stats.clients++;
81         console.log('===== Client count (page requests): '+ stats.clients);
82      }
83   });
84
85   client.on('disconnect', function () {
86      if (_.size(socket.clients) === 1) {
87         stream.destroy();
88         stream = false;
89         console.log('===== Stream destroyed, idle \n===== Stream count: '+ stats.streams);
90      }
91   });
92});
93