index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 = Math.floor(Math.random()*9999999);
  40. var secret = ts.toString() + rand.toString();
  41. res.send({secret: secret, socketId: createHash(secret)});
  42. });
  43. var createHash = function(secret) {
  44. var cipher = crypto.createCipher('blowfish', secret);
  45. return(cipher.final('hex'));
  46. };
  47. // Actually listen
  48. server.listen( opts.port || null );
  49. var brown = '\033[33m',
  50. green = '\033[32m',
  51. reset = '\033[0m';
  52. console.log( brown + "reveal.js:" + reset + " Multiplex running on port " + green + opts.port + reset );