-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcentral-server.js
100 lines (66 loc) · 2.57 KB
/
central-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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const Express = require('express');
var server = Express();
server.listen(1338, '0.0.0.0');
const MAX_ELEMENTS_PER_IP = 10;
const MAX_TIME_TO_KEEP_MS = 1000 * 60 * 3;
const CLEANUP_INTERVAL_MS = 1000 * 60 * 1;
server.use(Express.json({
strict: false,
type: 'application/x-www-form-urlencoded'
}));
const respondWithJSON = (request, response, data) => {
if (arguments.length < 3) data = 0;
response.header('Access-Control-Allow-Origin', '*');
response.end(JSON.stringify(data));
};
const mappingTable = {
}
server.post('/getHosts', (request, response) => {
// const remoteAddress = request.socket.remoteAddress;
// if (typeof remoteAddress !== 'string' || !remoteAddress) return respondWithJSON(request, response);
const browserId = request.body.browserId;
if (typeof browserId !== 'string' || !browserId) return;
if (!mappingTable.hasOwnProperty(browserId)) return respondWithJSON(request, response);
if (!mappingTable[browserId].length) return respondWithJSON(request, response);
respondWithJSON(request, response, mappingTable[browserId].map(x => x.deviceIp));
});
server.post('/retropie', (request, response) => {
response.end();
console.info(request.socket.remoteAddress, request.socket.remotePort)
const browserId = request.body.browserId;
if (typeof browserId !== 'string' || !browserId) return;
const deviceIp = request.body.deviceIp;
if (typeof deviceIp !== 'string' || !deviceIp) return;
const addresses = (
mappingTable.hasOwnProperty(browserId) ?
mappingTable[browserId] :
mappingTable[browserId] = []
);
const existingIndex = addresses.findIndex(item => item.deviceIp === deviceIp);
const when = Date.now();
if (existingIndex !== -1) {
const existingAddress = addresses[existingIndex];
addresses.splice(existingIndex, 1);
addresses.push({ ...existingAddress, when });
} else {
addresses.push({ when, deviceIp });
}
mappingTable[browserId] = addresses.slice(-MAX_ELEMENTS_PER_IP);
});
const checkExpiredAddresses = () => {
console.info('checkExpiredAddresses:start');
for (const browserId in mappingTable) {
mappingTable[browserId] = mappingTable[browserId].filter(address => {
const isExpired = (Date.now() - address.when >= MAX_TIME_TO_KEEP_MS);
if (isExpired) console.info(`expired ${browserId} -> ${JSON.stringify(address)}`);
return !isExpired;
});
if (!mappingTable[browserId].length) {
console.info(`remove ${browserId} from table`);
delete mappingTable[browserId];
}
}
console.info('checkExpiredAddresses:finish');
setTimeout(checkExpiredAddresses, CLEANUP_INTERVAL_MS);
};
checkExpiredAddresses();