-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
441 lines (367 loc) · 10.5 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
/**
* Express config
*/
var express = require('express'),
app = module.exports = express(),
http = require('http'),
bodyParser = require('body-parser'),
logger = require('morgan'),
errorHandler = require('errorhandler'),
basicAuth = require('basic-auth'),
fs = require('fs');
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
app.set('port', process.env.PORT || 3000);
if('development' == app.get('env')) {
app.use(errorHandler());
}
/**
* Configure self
*/
var config = function() {
var json, config = {};
try {
json = JSON.parse(fs.readFileSync(__dirname + '/config.json', 'utf8'));
}
catch(e) {
console.log("** Error while reading config.json: " + e);
}
if(typeof(json.twitter) !== undefined) {
config.twitter = {
consumer_key : json.twitter.consumer_key
, consumer_secret : json.twitter.consumer_secret
, access_token_key : json.twitter.access_token_key
, access_token_secret : json.twitter.access_token_secret
, track : json.twitter.track
}
};
if(typeof(json.schedule) !== undefined) {
config.schedule = {
host : json.schedule.host
, port : json.schedule.port
, path : json.schedule.path
, time_slots: []
, event_date : json.schedule.event_date
, tz : json.schedule.tz
}
}
if(typeof(json.admin) !== undefined) {
config.admin = {
user : json.admin.user
, pass : json.admin.pass
}
}
return config;
}();
/**
* Utils
*/
var adminAuth = function (req, res, next ) {
function unauthorized(res) {
res.set('WWW-Authenticate', 'Basic realm=BCB Admin');
return res.send(401);
};
var user = basicAuth(req);
if ( !user || !user.name || !user.pass) {
return unauthorized(res);
};
if (user.name == config.admin.user && config.admin.pass ) {
return next();
}
else {
return unauthorized(res);
};
}
function strencode( data ) {
return unescape( encodeURIComponent( JSON.stringify( data ) ) );
}
/**
* Routing
*
* /schedule
* /wall
* /admin
* /push
* GET /update
* POST /update
* /
*/
app.get('/schedule', function(req, res) {
res.sendFile(__dirname + '/public/schedule.html');
});
app.get('/wall', function(req, res) {
res.sendFile(__dirname + '/public/wall.html');
});
app.get('/admin', adminAuth, function(req, res) {
res.sendFile(__dirname + '/public/admin.html');
});
app.get('/push', adminAuth, function(req, res) {
updateJSON(req, res);
});
app.get('/update', adminAuth, function(req, res) {
res.sendFile(__dirname + '/public/update.html');
});
app.post('/update', adminAuth, function(req, res) {
handleUpdatePost(req,res);
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/wall.html');
})
var server = app.listen(app.get('port'), function(){
console.log(' | Server listening on port ' + app.get('port'));
})
/**
* Twitter functions
*
* set up connection
* push to client
* handle disconnects from twitter
*/
var twitter = require('ntwitter'),
twitter_stream = '',
tweet_buffer = new Array(),
tweet_buffer_length = 30;
var t = new twitter({
consumer_key: config.twitter.consumer_key,
consumer_secret: config.twitter.consumer_secret,
access_token_key: config.twitter.access_token_key,
access_token_secret: config.twitter.access_token_secret
});
function connectStream(){
t.stream('statuses/filter', {track: config.twitter.track}, function(stream) {
twitter_stream = stream;
console.log(' | Stream start');
stream.on('data', function(data){
json = strencode(data);
if(json.length > 0) {
try {
updates.emit('tweet', json);
tweet_buffer.push(data);
}
catch(e) {
console.log("** Error sending Tweet: " + e);
console.log("** Tweet: " + json);
}
}
});
stream.on('end', function(data) {
twitter_stream = '';
pruneTweetBuffer();
console.log(' | Stream end');
});
stream.on('error', function(error) {
twitter_stream = '';
console.log('** Error in Twitter Stream: ' + error);
connectStream();
});
});
}
function pruneTweetBuffer() {
if(tweet_buffer.length > tweet_buffer_length) {
console.log(' | Pruning Tweet Buffer: START - ' + tweet_buffer.length);
tweet_buffer.splice(0, (tweet_buffer.length - tweet_buffer_length));
console.log(' | Pruning Tweet Buffer: END - ' + tweet_buffer.length);
}
}
/**
* Schedule functions
*
* update schedule json
* push updated schedule to client
* update currently running session
*/
var schJSON = {},
updJSON = {};
function readJSON() {
try{
console.log(' | Reading JSON');
fs.readFile(__dirname + '/android_bcb15.json', 'utf8', function(error, data) {
schJSON = JSON.parse(data);
config.schedule.time_slots = []
schJSON.slots.forEach(function(slot){
config.schedule.time_slots.push( config.schedule.event_date + " " + slot.startTime + " " + config.schedule.tz );
});
//console.log(config.schedule.time_slots);
});
fs.readFile(__dirname + '/updates.json', 'utf8', function(err, data) {
updJSON = JSON.parse(data);
})
}
catch(e) {
console.log('** Error reading JSON: ' + e);
}
}
readJSON();
function pushSchedule() {
schedules.json.send(schJSON);
console.log(' | Schedule pushed to clients');
}
function updateJSON(req, res) {
// get JSON from barcampbangalore.org
var schRequest = http.request({
host: config.schedule.host,
port: config.schedule.port,
path: config.schedule.path,
method: 'GET'
}, function(resp){
if(resp.statusCode == 200 ) {
var outfile = fs.createWriteStream(__dirname+'/android_bcb15.json');
var buff = '';
resp.setEncoding('utf8');
resp.on('data', function(chunk) {
outfile.write(chunk);
buff += chunk;
});
outfile.on('close', function() {
console.log(' | Schedule retreived successfully');
try {
schJSON = JSON.parse(buff);
pushSchedule();
}
catch(e) {
console.log("Error: " + e);
};
});
resp.on('end', function() {
outfile.end();
res.write('JSON updated!<br />');
res.end();
});
}
else {
console.log('** Error in retrieving schedule JSON ' + resp.statusCode);
};
});
console.log(' | Retrieving schedule from '+config.schedule.host);
schRequest.end();
}
/**
* Updates functions
*
* handle post of an update
*/
function handleUpdatePost(request, response) {
if(request.body.update_cancel == undefined && request.body.update_submit == "true") {
// handle post
var update_string = request.body.update_text;
updates.json.emit("new_update", { ata : update_string });
response.write("Update pushed<br />");
try {
var updateJSON = JSON.parse(fs.readFileSync(__dirname +'/updates.json', 'utf8'));
updateJSON.updates.push(update_string);
fs.writeFileSync(__dirname+'/updates.json', JSON.stringify(updateJSON), 'utf8');
updJSON.updates.push(update_string);
}
catch(e) {
console.log("Error storing update: " + e);
}
response.write("Update stored<br />");
response.end();
}
else if(request.body.update_submit == undefined && request.body.update_cancel == "true") {
response.redirect('/update');
}
else {
response.write("Incorrect request<br />");
response.end();
}
}
var moment = require('moment');
function setCurrentSession() {
var now = moment();
var current_slot_index = 0;
var slots_length = config.schedule.time_slots.length
if( 0 == slots_length )
{
console.log(" # time slots not available yet");
return;
}
while(now.isAfter(config.schedule.time_slots[current_slot_index], 'minute')) {
current_slot_index += 1;
if(current_slot_index >= slots_length) {
break;
}
}
var output = {};
// we haven't yet started the day
if(current_slot_index <= 0) {
output.type = 'special';
output.string = "Barcamp Bangalore Monsoon 2014 begins at 08:00 AM on 12th October 2014, hope to see you there!";
}
else if (current_slot_index >= slots_length) { // the day has ended
output.type = 'special';
output.string = "Barcamp Bangalore Monsoon 2014 is over. Thanks for coming by.";
}
else { // we are in some session
if(typeof(schJSON.slots) === "undefined") {
// Argh! We don't yet have a schedule! Fill up all the slots and generate it
output.type = 'special';
output.string = 'Barcamp Bangalore Spring 2014 is go! Where is the schedule yo?';
}
else {
output.type = schJSON.slots[current_slot_index-1].type;
output.tracks = schJSON.tracks;
output.slot = schJSON.slots[current_slot_index-1];
}
}
updates.emit( "current_session", { ata: output } );
}
/**
* Websockets
*
* set up updates+twitter socket, populate initial updates
* set up schedule socket, populate initial schedule
*/
var io = require('socket.io')(server),
totWallUsers = 0,
totScheduleUsers = 0;
// io.configure(function() {
// io.enable('browser client minification');
// io.enable('browser client etag');
// io.enable('browser client gzip');
// io.set('log level', 1);
// io.set('transports', [
// 'websocket',
// // 'flashsocket',
// 'htmlfile',
// 'xhr-polling',
// 'jsonp-polling'
// ]);
// });
var updates = io.of('/updates').on('connection', function(client) {
totWallUsers++;
console.log(' | User '+ client.id +' connected, total wall users: ' + totWallUsers)
if ((totWallUsers > 0) && (twitter_stream == '')) {
connectStream();
}
client.json.emit('init_updates', { ata : updJSON } );
setCurrentSession();
if(tweet_buffer.length > 0) {
tweet_buffer.forEach(function(element){
client.json.emit('tweet', strencode(element));
})
}
client.on('disconnect', function() {
totWallUsers--;
console.log(' | User '+ client.id +' disconnected, total wall users: '+ totWallUsers);
if (totWallUsers == 0) {
console.log(' | 0 Users, disconnecting Twitter stream');
twitter_stream.destroy();
twitter_stream = '';
}
});
});
var currentSessionInterval = setInterval(setCurrentSession, 300000);
var pruneTweetBufferInterval = setInterval(pruneTweetBuffer, 60000);
var pushScheduleInterval = setInterval(pushSchedule, 300000);
var schedules = io.of('/schedule').on('connection', function(client) {
// push the current json to the new socket
totScheduleUsers++;
console.log(' | User ' + client.id + 'connected, total schedule users: ' + totScheduleUsers);
client.json.send(schJSON);
client.on('disconnect', function() {
totScheduleUsers--;
console.log(' | User '+ client.id + ' disconnected, total schedule users: ' + totScheduleUsers);
});
});