1var http        = require('http');
2var express		= require('express');
3var fs			= require('fs');
4var io			= require('socket.io');
5var crypto		= require('crypto');
6
7var app       	= express();
8var staticDir 	= express.static;
9var server    	= http.createServer(app);
10
11io = io(server);
12
13var opts = {
14	port: process.env.PORT || 1948,
15	baseDir : __dirname + '/../../'
16};
17
18io.on( 'connection', function( socket ) {
19	socket.on('multiplex-statechanged', function(data) {
20		if (typeof data.secret == 'undefined' || data.secret == null || data.secret === '') return;
21		if (createHash(data.secret) === data.socketId) {
22			data.secret = null;
23			socket.broadcast.emit(data.socketId, data);
24		};
25	});
26});
27
28[ 'css', 'js', 'plugin', 'lib' ].forEach(function(dir) {
29	app.use('/' + dir, staticDir(opts.baseDir + dir));
30});
31
32app.get("/", function(req, res) {
33	res.writeHead(200, {'Content-Type': 'text/html'});
34
35	var stream = fs.createReadStream(opts.baseDir + '/index.html');
36	stream.on('error', function( error ) {
37		res.write('<style>body{font-family: sans-serif;}</style><h2>reveal.js multiplex server.</h2><a href="/token">Generate token</a>');
38		res.end();
39	});
40	stream.on('readable', function() {
41		stream.pipe(res);
42	});
43});
44
45app.get("/token", function(req,res) {
46	var ts = new Date().getTime();
47	var rand = Math.floor(Math.random()*9999999);
48	var secret = ts.toString() + rand.toString();
49	res.send({secret: secret, socketId: createHash(secret)});
50});
51
52var createHash = function(secret) {
53	var cipher = crypto.createCipher('blowfish', secret);
54	return(cipher.final('hex'));
55};
56
57// Actually listen
58server.listen( opts.port || null );
59
60var brown = '\033[33m',
61	green = '\033[32m',
62	reset = '\033[0m';
63
64console.log( brown + "reveal.js:" + reset + " Multiplex running on port " + green + opts.port + reset );