JJ Allaire | efa6ad4 | 2016-01-30 13:12:05 -0500 | [diff] [blame] | 1 | var http = require('http'); |
| 2 | var express = require('express'); |
| 3 | var fs = require('fs'); |
| 4 | var io = require('socket.io'); |
| 5 | var crypto = require('crypto'); |
| 6 | |
| 7 | var app = express(); |
| 8 | var staticDir = express.static; |
| 9 | var server = http.createServer(app); |
| 10 | |
| 11 | io = io(server); |
| 12 | |
| 13 | var opts = { |
| 14 | port: process.env.PORT || 1948, |
| 15 | baseDir : __dirname + '/../../' |
| 16 | }; |
| 17 | |
| 18 | io.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 | |
| 32 | app.get("/", function(req, res) { |
| 33 | res.writeHead(200, {'Content-Type': 'text/html'}); |
Bruce's Thinkpad | 8b73dcf | 2016-07-14 00:12:43 +0800 | [diff] [blame] | 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 | }); |
JJ Allaire | efa6ad4 | 2016-01-30 13:12:05 -0500 | [diff] [blame] | 43 | }); |
| 44 | |
| 45 | app.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 | |
| 52 | var createHash = function(secret) { |
| 53 | var cipher = crypto.createCipher('blowfish', secret); |
| 54 | return(cipher.final('hex')); |
| 55 | }; |
| 56 | |
| 57 | // Actually listen |
| 58 | server.listen( opts.port || null ); |
| 59 | |
| 60 | var brown = '\033[33m', |
| 61 | green = '\033[32m', |
| 62 | reset = '\033[0m'; |
| 63 | |
| 64 | console.log( brown + "reveal.js:" + reset + " Multiplex running on port " + green + opts.port + reset ); |