-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
259 lines (233 loc) · 7.1 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
const https = require("https");
const http = require("http");
const fs = require("fs");
const dns = require("dns");
const subjectsConfig = require("./config/subjects.js");
const config = require("./config/server_config.js");
const utils = require("./utils.js");
const providers = {};
const LOG_SIZE = 30;
const COMMANDS_PRESENT = "arrived";
const COMMANDS_DEPARTED = "departed";
const subjects = Object.keys(subjectsConfig.subjects).reduce((acc, name) => {
acc[name] = {
...subjectsConfig.subjects[name],
present: null
}
return acc;
}, {});
const srvOptions = {
key: fs.readFileSync("./certs/keyFile.key"),
cert: fs.readFileSync("./certs/crtFile.crt")
}
const srv = https.createServer(srvOptions, (req, res) => {
res.setHeader("Content-Type", "application/json");
});
function callDevice(subject, newState){
const path = `${config.path}/${subjects[subject].deviceId}/${newState ? COMMANDS_PRESENT : COMMANDS_DEPARTED}?access_token=${config.ACCESS_TOKEN}`;
http.get(`${config.host}${path}`, (res) => {
utils.log(path.split("?")[0], ` - ${res.statusCode}`);
});
}
function updatePresence(data){
if(subjects[data.subject].present !== data.newState || data.newState === null){
const newState = Object.keys(providers).reduce((acc, ip) => {
return acc || providers[ip].isPresent(data.subject);
}, false);
if(newState !== subjects[data.subject].present){
subjects[data.subject].present = newState;
utils.log(`Update presence for ${data.subject} to ${newState}`);
callDevice(data.subject, newState);
}
}
}
const checkAuth = (auth, user, pass) => {
const userpass = Buffer.from((auth || '').split(' ')[1] || '', 'base64').toString();
if (userpass !== `${user}:${pass}`) {
utils.log("invalid registration: invlid cedentials");
return Promise.resolve(false);
}
return Promise.resolve(true)
}
const handler = {
register(req, res){
const ip = req.connection.remoteAddress;
return new Promise((resolve, reject) => {
checkAuth(req.headers.authorization, config.credentials[0], config.credentials[1]).then((result) => {
if(!result){
reject(401);
return;
}
if(providers[ip]){
providers[ip].removeEventListeners();
}
providers[ip] = new PresenceProvider();
providers[ip].addEventListener(PresenceProvider.EVT_UPDATE_PRESENCE, updatePresence);
utils.log(`Registered ${ip} as presence provider`);
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(subjectsConfig));
resolve();
});
});
},
update(req){
const path = req.url.split("?");
const ip = req.connection.remoteAddress;
const query = path[1] ? path[1].split("&").reduce((acc, value) => {
const parsed = value.split("=");
acc[parsed[0]] = parsed.slice(1).join("=");
return acc;
}, {}) : null;
return new Promise((resolve, reject) => {
if(!providers[ip]){
reject(401);
return;
}
if(!query){
reject(400);
}
providers[ip].setPresence(query.subject, query.present).then((updated) => {
resolve(updated ? 200 : 202);
});
});
},
status(req, res){
return checkAuth(req.headers.authorization, config.credentials[0], config.credentials[1]).then((authResult) => {
if(!authResult){
res.setHeader("WWW-Authenticate", "basic realm=status page");
reject(401);
return;
}
const result = Object.keys(subjects).reduce((acc, name) => {
acc[name] = {
present: subjects[name].present,
lastSeen: Object.keys(providers).reduce((acc, ip) => {
const lastSeen = providers[ip].lastSeen(name) ? new Date(providers[ip].lastSeen(name)) : null;
if(acc === null){
if(lastSeen === null){
return null;
}
return {
time: lastSeen,
provider: ip
}
}
return acc < lastSeen ? {time: lastSeen, provider: ip} : acc;
}, null)
}
return acc;
}, {});
res.setHeader("Content-Type", "application/json");
res.write(JSON.stringify(result));
return Promise.resolve(200);
});
}
}
class PresenceProvider {
constructor(){
this.log = [];
this.listeners = {};
this.currentState = {};
}
setPresence(subject, newPresence){
const oldState = !!this.currentState[subject];
if(newPresence !== "null"){
this.log.push({
time: new Date(),
value: newPresence,
subject: subject,
});
this.logRotate();
}
this.currentState[subject] = newPresence === "null" ? null : newPresence === "true";
if(oldState !== this.currentState[subject]){
this.dispatchEvent(this.constructor.EVT_UPDATE_PRESENCE, {
provider: this,
subject: subject,
oldState: oldState,
newState: this.currentState[subject]
});
return Promise.resolve(true);
}
return Promise.resolve(false);
}
isPresent(subject){
return !!this.currentState[subject];
}
lastSeen(subject){
const tmp = [...this.log.reverse()];
const len = tmp.length;
for(let i = 0; i < len; i++){
if(tmp[i].subject === subject){
return tmp[i].time;
}
}
return null;
}
logRotate(){
const len = this.log.length;
if(len > LOG_SIZE){
this.log = this.log.slice(len - LOG_SIZE);
}
}
addEventListener(evtName, callback){
this.listeners[evtName] = this.listeners[evtName] || new Set();
this.listeners[evtName].add(callback);
}
removeEventListener(evtName, callback){
this.listeners[evtName] && this.listeners[evtName].has(callback) ? this.listeners[evtName].delete(callback) : false;
}
removeEventListeners(){
this.listeners = {};
}
dispatchEvent(evtName, data){
this.listeners[evtName] && this.listeners[evtName].forEach(( clbk ) => {
clbk(data)
})
}
}
PresenceProvider.EVT_UPDATE_PRESENCE = "@@presenceProvider/update";
/* device sync failover: sync everything every 5 minute
setInterval(() => {
if(Object.keys(providers).length < 1){
utils.log("Cancel device sync: no provders registered.")
return;
}
Object.keys(subjects).forEach((subject) => {
if(subjects[subject].present !== null){
utils.log(`sync device for ${subject}: ${subjects[subject].present}`)
callDevice(subject, subjects[subject].present);
}
});
}, 300000)
*/
srv.addListener("request", (req, res) => {
const path = req.url.split("?");
let prm = null;
switch(path[0]){
case "/register":
prm = handler.register(req, res);
break;
case "/update":
prm = handler.update(req);
break;
case "/status":
prm = handler.status(req, res);
break;
default:
prm = Promise.reject(404);
}
prm.then((code)=>{
if(!res.headersSent){
res.writeHead(code ? code : 200);
}
res.end();
}).catch((code) => {
utils.log(code);
res.writeHead(typeof code === "number" ? code : 500);
res.end();
});
})
srv.listen(3300, () => {
utils.log("Listening on 3300.")
})