-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (62 loc) · 2.07 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//Import NPM Packages
const express = require('express');
const fs = require('fs');
//Import Config
const config = require('./config.js');
//Init Express
const app = express();
const port = config.port;
const http = require('http').Server(app);
//Init Websocket
const wsport = config.WSport;
const WebSocket = require('ws');
const wss = new WebSocket.Server({port: wsport});
console.log('[INFO]\tWebsocket has opened on port ' + wsport + '.');
wss.on('connection', function connection(ws) {
console.log("[INFO]\tClient connected.");
ws.on('close', () => {
console.log('[INFO]\tClient disconnected.')
});
});
//Get Auth Info
const keys = config.keys;
//Import Sendou.ink
const sendou = require('./sendou.js');
//Function to save data to .json file
const saveData = async (data) => {
if (data && data.currentMatch && data.currentMatch.teamA && data.currentMatch.teamB) {
data['sink'] = {};
data['sink']['teamA'] = await sendou.getFullDataFromTeam(data.currentMatch.teamA);
data['sink']['teamB'] = await sendou.getFullDataFromTeam(data.currentMatch.teamB);
}
data = JSON.stringify(data, null, 2);
fs.writeFileSync('./data/data.json', data);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
})
};
//Webserver
app.use(express.json());
app.post('/update/:auth', (req, res) => {
let auth = req.params.auth;
if (auth && keys.includes(auth)) {
if (!req.body) return res.sendStatus(400);
console.log("[INFO]\tRequest from NodeCG was acknowledged and recorded.");
res.sendStatus(200);
saveData(req.body);
}
else {
console.warn("[WARN]\tA request was forbidden.")
return res.sendStatus(403);
}
});
app.get('/data', (req, res) => {
res.type('json');
res.send(fs.readFileSync('./data/data.json'));
});
app.use(express.static('public'));
http.listen(port, () => {
console.log("[INFO]\tInfo Middleman service has been started on port " + port + ".");
});