index.js 1.8 KB

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