This repository has been archived by the owner on Oct 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
85 lines (77 loc) · 3.08 KB
/
server.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 express = require('express');
const app = express();
const ping = require('ping');
const say = require('say');
const https = require('https');
const fs = require('fs');
const STATIONS = JSON.parse(fs.readFileSync('./stations.json', 'utf8'));
let lastStatus = {}
STATIONS.forEach((n) => {
lastStatus[n.address] = true
});
app.get('/api', (req, res) => {
let promises = [];
STATIONS.forEach((host) => {
if (host.pingOnly) {
promises.push(ping.promise.probe(host.address).then((val) => {
return {
"name": host.name,
"host": host.address,
"alive": val.alive,
"canvasX": host.canvasX,
"canvasY": host.canvasY,
"color": host.color,
"host": host.address
};
}));
} else {
promises.push(new Promise((resolve, reject) => {
let req = https.get(host.address, (res) => {
res.on("error", reject);
resolve({
"name": host.name,
"host": host.address,
"alive": res.statusCode == 200,
"canvasX": host.canvasX,
"canvasY": host.canvasY,
"color": host.color,
"host": host.address
});
});
req.end();
}).catch());
}
});
Promise.all(promises).then((values) => {
let response = [];
values.forEach((val) => {
const name = val.name || val.host;
const stationStatus = {
"name": name,
"alive": val.alive,
"canvasX": val.canvasX,
"canvasY": val.canvasY,
"color": val.color,
"host": val.host
};
response.push(stationStatus);
if (!val.alive && lastStatus[val.host]) {
text = name + " is down"
console.log(text);
say.speak(text);
lastStatus[val.host] = false;
}
if (val.alive && !lastStatus[val.host]) {
text = name + " is up"
console.log(text);
say.speak(text);
lastStatus[val.host] = true;
}
});
res.send(response);
}).catch(console.err);
});
app.use(express.static("public"));
app.listen(3000, () => {
console.log('listening on port 3000!')
});