-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
69 lines (56 loc) · 1.8 KB
/
index.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
let http = require('http');
let express = require('express');
let cors = require('cors')
let fs = require('fs');
let io = require('socket.io');
let crypto = require('crypto');
let app = express();
let staticDir = express.static;
app.use(cors()); // enable cors for all origins
let server = http.createServer(app);
let socketsIO = io(server, {
cors: {
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS" ]
}
});
let opts = {
port: process.env.PORT || 1948,
baseDir : process.cwd()
};
socketsIO.on( 'connection', socket => {
console.debug('Connection opened');
socket.on('multiplex-statechanged', data => {
if (typeof data.secret == 'undefined' || data.secret == null || data.secret === '') return;
if (createHash(data.secret) === data.socketId) {
console.debug('Broadcasting state change');
data.secret = null;
socket.broadcast.emit(data.socketId, data);
} else {
console.warn('Secret and socketId do not match');
}
});
});
app.use( express.static( opts.baseDir ) );
app.get("/", ( req, res ) => {
res.writeHead(200, {'Content-Type': 'text/html'});
let stream = fs.createReadStream( opts.baseDir + '/index.html' );
stream.on('error', error => {
res.write('<style>body{font-family: sans-serif;}</style><h2>reveal.js multiplex server.</h2><a href="/token">Generate token</a>');
res.end();
});
stream.on('open', () => {
stream.pipe( res );
});
});
app.get("/token", ( req, res ) => {
let secret = crypto.randomBytes(16).toString('hex');
res.send({secret: secret, socketId: createHash(secret)});
});
let createHash = (secret) => {
let hash = crypto.createHash('sha256').update(secret);
return hash.digest('hex');
};
// Open the listening port
server.listen( opts.port || null );
console.log(`reveal.js: Multiplex running on port: ${opts.port}`);