This repository has been archived by the owner on Apr 13, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
85 lines (76 loc) · 3.02 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const config = require('./src/config.js');
const WebSocketServer = require('websocket').server;
const http = require('http');
const websocketLogic = require('./src/websockets');
const express = require('express');
const httpApi = require('./src/httpApi.js');
const mysql = require('mysql');
const mysqlTools = require('./src/mysql.js');
// Initiate Database
const pool = mysql.createPool(Object.assign({multipleStatements:true}, config.database));
if(!pool) console.error(new Date() + "Failed to establish database connection!");
mysqlTools.query(pool, "SELECT * FROM `user_room` LIMIT 1;SELECT * FROM `user` LIMIT 1;SELECT * FROM `room` LIMIT 1;").then(function(){
console.log(new Date() + " Database available.");
// HTTP Api init
const app = express();
httpApi.setDatabaseConnectionPool(pool);
httpApi.initialiseApp(app);
const server = http.createServer(app);
server.listen(config.http.port, function() {
const host = server.address().address;
const port = server.address().port;
console.log((new Date()) + ' Server is running on ' + host + ' and listening on port ' + port);
});
// Websocket initiation
websocketLogic.setDatabaseConnectionPool(pool);
const wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
/**
* Tests if the origin of the request can be accepted
* @param request
* @returns {boolean}
*/
function isRequestAllowed(request) {
const toAccept = config.websocket.acceptOrigin;
if(toAccept){
if(!request.order) return false;
if(toAccept.length){ // Go through array of origins
for(let i = 0; i < toAccept.length; i++){
if(toAccept[i] === request.origin){
return true;
}
}
return false; //No acceptable origin found
} else {
return toAccept === request.origin;
}
} else {
console.log(new Date() + ' Origin auto accepted: ', request.origin);
return true;
}
}
wsServer.on('request', function(request) {
if (!isRequestAllowed(request)) { //Deny non allowed origins
request.reject();
console.log((new Date()) + ' Connection from ', request.origin, ' rejected.');
return;
}
let connection = request.accept(null, request.origin); //specify protocol with none
console.log((new Date()) + ' Connection accepted.');
websocketLogic.setupConnection(connection);
});
}).catch(function(err){
if(err.fatal){
console.error(new Date() + " Failed to connect to Database", err);
} else {
mysqlTools.resetDatabase(pool, function(err, result){
if(err){
console.error(new Date() + "Failed to reset Database", err);
} else {
console.log(new Date() + " Reset Database because it was empty.", result);
}
});
}
});