57
Fi
firelaunch / files
firelaunch / server.js
2.5 KB
1 2var util = require('util'), 3 io = require('socket.io'), 4 _ = require('underscore'), 5 connect = require('connect'), 6 http = require('http'), 7 url = require('url'), 8 fs = require('fs'), 9 inspect = require('util').inspect, 10 Twitter = require('twitter'); 11 12var twitter = new Twitter({ 13 consumer_key: 'qRnYzQj3dxTkxaFwkkiw', 14 consumer_secret: 'CGcMlTKdP9HKVelHijPzvSb4EfmJxzHxEccuXENs', 15 access_token_key: '59268061-xuB5Wo0b9kGewqP3pGxbstTDCZTKQ9RxRofwotqD5', 16 access_token_secret: 'qWJkB3kHyP9vdRW7zQcXShsjGazbWxK4GuwFsFrlQIE' 17}); 18 19var cache = 1000 * 60 * 60 * 24 * 5; 20var server = connect.createServer( 21 connect.logger(), 22 connect.router(function (app) { 23 24 app.get('/paul', function (req, res, next) { 25 var reqUrl = url.parse(req.url, true); 26// res.end(util.inspect(reqUrl)); 27 if (reqUrl.query.s === 'log') { 28 req.url = '/log.txt'; 29 next(); 30 } 31 }); 32 33 }), 34 connect.static(__dirname, {maxAge: cache}) 35); 36 37server.listen(321); 38var socket = io.listen(server); 39 40var stats = { 41 clients: 0, 42 count: 0, 43 perMin: 0, 44 perHour: 0, 45 perDay : 0, 46 start: new Date().getTime() 47 }, 48 cache = []; 49 50 51socket.on('connection', function (client) { 52 if (cache.length > 0) 53 client.send(JSON.stringify(cache)); 54 55 client.on('message', function (data) { 56 if (data === 'track') { 57 stats.clients++; 58 console.log('===== Page requests: '+ stats.clients); 59 } 60 }); 61}); 62 63var file = fs.createWriteStream( 64 "./log.txt", 65 { flags: 'w', enconding: 'utf8' } 66); 67 68twitter.stream('statuses/filter', {track: 'firefox 4, ff4, firefox4, fx4, ffx4'}, 69 function (hose) { 70 71 hose.on('data', function (twiit) { 72 stats.count++; 73 74 // calculate rates 75 var now = new Date().getTime(), 76 time = now - stats.start, 77 timeMinutes = time / (1000 * 60), 78 timeHours = time / (1000 * 60 * 60), 79 timeDays = time / (1000 * 60 * 60 * 24), 80 count = stats.count, 81 rateMin = count / timeMinutes, 82 rateHour = count / timeHours, 83 rateDays = count / timeDays; 84 85 stats.perMin = rateMin.toFixed(3); 86 stats.perHour = rateHour.toFixed(3); 87 stats.perDay = rateDays.toFixed(3); 88 89 90 twiit.stats = stats; 91 socket.broadcast(JSON.stringify(twiit)); 92 cache.unshift(twiit); 93 cache = cache.slice(0, 25); // save the cache 94 cache.reverse(); // latest at the top 95 96 console.log('===== Twits containing firefox: '+ stats.count); 97 98 file.write("\n\n"+ inspect(twiit) +"\n\n"); 99 }); 100}); 101