This repository has been archived by the owner on Apr 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
71 lines (55 loc) · 1.68 KB
/
app.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
70
71
/* app.js - Porchwire Copyright 2018 by Brett Fraley */
const express = require('express');
const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 4200;
// Peerjs server definition
const PeerServer = require('peer').ExpressPeerServer;
app.use(express.static(path.join(__dirname, 'dist')));
app.use(bodyParser.json());
app.set('port', port);
let USERS_ONLINE = [];
if (port !== 4200) {
// Redirect http => https on production
app.all('*', function(req, res, next) {
if (req.headers['x-forwarded-proto'] != 'https') {
res.redirect('https://' + req.headers.host + req.url);
}
else {
next();
}
});
}
// Home route - page routing handled by Angular
app.get('/', (req, res, next) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
// Gets list of online users
app.get('/online', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(USERS_ONLINE));
});
// HTTP server
const server = http.createServer(app);
// Peerjs server option values
const options = {
debug: true,
allow_discovery: true,
path: '/peerjs',
key: 'porchwiredev2018'
}
// Peerjs server
var Peer = PeerServer(server, options);
app.use('/peerjs', Peer);
// Init server
server.listen(port);
// Push new user to USERS_ONLINE array
Peer.on('connection', (id) => USERS_ONLINE.push({name:id}));
// Removes disconnected user from USERS_ONLINE array
Peer.on('disconnect', function(id) {
USERS_ONLINE = USERS_ONLINE.filter(function(USERS_ONLINE) {
return USERS_ONLINE.name !== id;
});
})