-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
t6websockets.js
633 lines (618 loc) · 28.9 KB
/
t6websockets.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
"use strict";
var t6websockets = module.exports = {};
let audioExtension;
switch (tts.audioEncoding) {
case "LINEAR16": audioExtension = "wav"; break;
case "MP3":
default: audioExtension = "mp3"; break;
}
const defaultChunkSize = 12 * 1024; // set the size of each chunk to send
const defaultChunkDelay = 300; // send the next chunk after a delay
t6websockets.init = async function() {
t6console.log("");
t6console.log("===========================================================");
t6console.log("==================== Init Web Sockets... ==================");
t6console.log("===========================================================");
global.wsClients = new Map();
global.wss = new WebSocketServer({
port: socketsPort,
perMessageDeflate: {
zlibDeflateOptions: {
// See zlib defaults.
chunkSize: 1024,
memLevel: 7,
level: 3
},
zlibInflateOptions: {
chunkSize: 10 * 1024
},
// Other options settable:
clientNoContextTakeover: true, // Defaults to negotiated value.
serverNoContextTakeover: true, // Defaults to negotiated value.
serverMaxWindowBits: 10, // Defaults to negotiated value.
// Below options specified as default values.
concurrencyLimit: 10, // Limits zlib concurrency for perf.
threshold: 1024 // Size (in bytes) below which messages
// should not be compressed if context takeover is disabled.
},
verifyClient: (info, callback) => {
t6console.debug("verifyClient headers", info.req.headers);
t6console.debug("verifyClient url", info.req.url);
let authHeader;
let basic_token;
let credentials;
try {
authHeader = info.req.headers.authorization;
basic_token = url.parse(info.req.url, true).query.BASIC_TOKEN;
t6console.debug(`authHeader: ${authHeader}`);
t6console.debug(`basic_token: ${basic_token}`);
} catch (error) {
info.req.user_id = null;
t6console.debug("verifyClient error", error);
callback(false, 203 ,"Non-Authoritative Information");
return;
}
if (typeof authHeader!=="undefined" && authHeader?.split(" ")) {
credentials = atob(authHeader.split(" ")[1])?.split(":");
} else if(typeof basic_token!=="undefined") {
credentials = basic_token?.split(":");
} else {
callback(false, 401 ,"Non-Authoritative Information");
}
if ( typeof credentials!=="undefined" ) {
let key = credentials[0];
let secret = credentials[1];
let queryT = {
"$and": [
{ "key": key },
{ "secret": secret },
]
};
let u = access_tokens.findOne(queryT);
if ( u && typeof u.user_id !== "undefined" ) {
let user = users.findOne({id: u.user_id});
if (user.id) {
t6console.debug("verifyClient headers OK", u.user_id);
info.req.user_id = u.user_id;
callback(true, 200, "OK");
t6events.addAudit("t6App", "Socket_authenticate key:secret", u.user_id, info.req.headers["sec-websocket-key"], {"status": 200});
} else {
info.req.user_id = null;
callback(false, 401, "Not Authorized");
t6events.addAudit("t6App", "Socket_authenticate key:secret", "anonymous", info.req.headers["sec-websocket-key"], {"status": 401, "error_id": 444403});
}
} else {
t6console.debug("verifyClient headers NOK1");
info.req.user_id = null;
callback(false, 401, "Not Authorized");
t6events.addAudit("t6App", "Socket_authenticate key:secret", "anonymous", info.req.headers["sec-websocket-key"], {"status": 401, "error_id": 444402});
}
}
}
});
wss.on("connection", (ws, req) => {
let id = uuid.v4();
wsClients.set(ws, { id: id, user_id: req.user_id, "channels": [], webSocket: {"ua": req.headers["user-agent"], key: req.headers["sec-websocket-key"]} });
t6console.debug(`Welcoming socket_id: ${id}`);
ws.send(JSON.stringify({"arduinoCommand": "info", "message": `Welcome socket_id: ${id}`}));
ws.send(JSON.stringify({"arduinoCommand": "claimRequest", "socket_id": id}));
t6events.addStat("t6App", "Socket welcoming", req.user_id, id, {"status": 200});
t6mqtt.publish(null, `${mqttSockets}/${id}`, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": "Socket welcome", "environment": process.env.NODE_ENV}), false);
//wss.on("pong", t6websockets.heartbeat);
ws.on("close", () => {
let metadata = wsClients.get(ws);
t6console.debug("Closing Closing Closing Closing Closing", metadata.id);
let i = t6ConnectedObjects.indexOf(metadata.object_id);
if (i > -1) {
t6ConnectedObjects.splice(i, 1);
t6console.debug(`Object Status Changed: ${metadata.object_id} is hidden`);
}
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.id === metadata.id) {
wss.clients.delete(client);
t6console.debug("ws", "clients deleted", current);
}
});
t6console.debug(`Closing ${metadata.id}`);
wsClients.delete(ws);
t6events.addStat("t6App", "Socket closing", req.user_id, metadata.id, {"status": 200});
t6mqtt.publish(null, `${mqttSockets}/${metadata.id}`, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": "Socket close", "environment": process.env.NODE_ENV}), false);
});
ws.on("publish", (message) => {
t6console.debug("Received publish event", message);
});
ws.on("message", (message) => {
let metadata = wsClients.get(ws);
t6events.addStat("t6App", "Socket messaging", req.user_id, metadata.id, {"status": 200});
t6mqtt.publish(null, `${mqttSockets}/${metadata.id}`, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": "Socket message", "environment": process.env.NODE_ENV}), false);
message = getJson( message.toString("utf-8") );
if (typeof message === "object") {
t6console.debug(`Received command "${message.command}" from socket_id: ${metadata.id}`);
switch(message.command) {
case "subscribe":
metadata = wsClients.get(ws);
((message.channel).toLowerCase().split(/[\s,^!]+/)).map((chan) => {
if(chan !== "") {
t6console.debug(`-> Subscribing to ${chan}`);
(metadata.channels).indexOf(chan) === -1?(metadata.channels).push(chan.toLowerCase()):t6console.log(`Already subscribed to ${chan}`);
t6events.addStat("t6App", "Socket subscribe", req.user_id, metadata.id, {"status": 200, "channel": chan});
}
});
wsClients.set(ws, metadata);
t6console.debug(`-> metadata.channels: ${metadata.channels}`);
ws.send(JSON.stringify({"arduinoCommand": "info", "channels": metadata.channels}));
break;
case "unsubscribe":
metadata = wsClients.get(ws);
(message.channel).toLowerCase().split(/[\s,^!]+/).map((chan) => {
t6console.debug(`-> Unsubscribing from ${chan}`);
let i = (metadata.channels).indexOf(chan);
if (i>-1) {
(metadata.channels).splice(i, 1);
t6events.addStat("t6App", "Socket unsubscribe", req.user_id, metadata.id, {"status": 200, "channel": chan});
}
});
wsClients.set(ws, metadata);
ws.send(JSON.stringify({"arduinoCommand": "info", "channels": metadata.channels}));
break;
case "getSubscription":
metadata = wsClients.get(ws);
if(typeof metadata.channels!=="undefined") {
ws.send(JSON.stringify({"arduinoCommand": "info", "channels": metadata.channels}));
t6events.addStat("t6App", "Socket getSubscription", req.user_id, metadata.id, {"status": 200});
} else {
ws.send(JSON.stringify({"arduinoCommand": "info", "channels": undefined}));
}
break;
case "unicast":
if(typeof message.object_id!=="undefined" && message.object_id!==null) {
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.object_id === message.object_id) {
if (message.payload.arduinoCommand === "tts") {
let outputFile = process.env.NODE_ENV==="development"?`${tts.audioFolder}/unicast.${audioExtension}`:`${tts.outputFolder}/${uuid.v4()}.${audioExtension}`;
if (process.env.NODE_ENV==="production" || tts.activateInDevelopment) {
if(process.env.NODE_ENV==="development") {
outputFile = `${tts.outputFolder}/${uuid.v4()}.${audioExtension}`; // force uuid filename
}
const ttsClient = new textToSpeech.TextToSpeechClient();
const request = {
input: { text: message.payload.value },
voice: { languageCode: typeof message.payload.languageCode!=="undefined"?message.payload.languageCode:"en-US", ssmlGender: tts.ssmlVoiceGender },
audioConfig: { audioEncoding: tts.audioEncoding },
};
ttsClient.synthesizeSpeech(request, (err, response) => {
if (err) {
t6console.error(`TTS error: ${err}`);
return;
}
fs.writeFile(outputFile, response.audioContent, (err) => {
if (err) {
t6console.error(`File write error: ${err}`);
return;
}
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket unicast", req.user_id, metadata.id, {"status": 200});
});
});
} else {
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket unicast", req.user_id, metadata.id, {"status": 200});
}
} else {
client.send(JSON.stringify(message.payload));
}
ws.send(`Unicasted to object_id: ${current.object_id}`);
}
});
} else {
ws.send("NOK");
}
break;
case "broadcast":
// Broadcast only to the same user as the claimed object
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.user_id === req.user_id) {
if (message.payload.arduinoCommand === "tts") {
let outputFile = process.env.NODE_ENV==="development"?`${tts.audioFolder}/broadcast.${audioExtension}`:`${tts.outputFolder}/${uuid.v4()}.${audioExtension}`;
if (process.env.NODE_ENV==="production" || tts.activateInDevelopment) {
if(process.env.NODE_ENV==="development") {
outputFile = `${tts.outputFolder}/${uuid.v4()}.${audioExtension}`; // force uuid filename
}
const ttsClient = new textToSpeech.TextToSpeechClient();
const request = {
input: { text: message.payload.value },
voice: { languageCode: typeof message.payload.languageCode!=="undefined"?message.payload.languageCode:"en-US", ssmlGender: tts.ssmlVoiceGender },
audioConfig: { audioEncoding: tts.audioEncoding },
};
ttsClient.synthesizeSpeech(request, (err, response) => {
if (err) {
t6console.error(`TTS error: ${err}`);
return;
}
fs.writeFile(outputFile, response.audioContent, (err) => {
if (err) {
t6console.error(`File write error: ${err}`);
return;
}
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket broadcast", req.user_id, metadata.id, {"status": 200});
});
});
} else {
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket broadcast", req.user_id, metadata.id, {"status": 200});
}
} else {
client.send(JSON.stringify(message.payload));
}
ws.send(`Broadcasted (filtered on user_id ${req.user_id}) to object_id: ${current.object_id}`);
}
});
ws.send("OK");
break;
case "multicast":
// Multicasted only to the same user as the claimed object and to the Objects that subscribed to the specified channel
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.user_id === req.user_id && (current.channels).indexOf(message.channel) > -1 ) {
if (message.payload.arduinoCommand === "tts") {
let outputFile = process.env.NODE_ENV==="development"?`${tts.audioFolder}/multicast.${audioExtension}`:`${tts.outputFolder}/${uuid.v4()}.${audioExtension}`;
if (process.env.NODE_ENV==="production" || tts.activateInDevelopment) {
if(process.env.NODE_ENV==="development") {
outputFile = `${tts.outputFolder}/${uuid.v4()}.${audioExtension}`; // force uuid filename
}
const ttsClient = new textToSpeech.TextToSpeechClient();
const request = {
input: { text: message.payload.value },
voice: { languageCode: typeof message.payload.languageCode!=="undefined"?message.payload.languageCode:"en-US", ssmlGender: tts.ssmlVoiceGender },
audioConfig: { audioEncoding: tts.audioEncoding },
};
ttsClient.synthesizeSpeech(request, (err, response) => {
if (err) {
t6console.error(`TTS error: ${err}`);
return;
}
fs.writeFile(outputFile, response.audioContent, (err) => {
if (err) {
t6console.error(`File write error: ${err}`);
return;
}
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket multicast", req.user_id, metadata.id, {"status": 200});
});
});
} else {
const readTtsStream = fs.readFileSync(outputFile);
let offset = 0;
const sendData = () => {
const chunk = readTtsStream.slice(offset, offset + defaultChunkSize);
client.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readTtsStream.length) {
t6console.debug("ws/tts", "send ttsStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
t6console.debug("ws/tts", "File sent");
if (process.env.NODE_ENV==="production") {
fs.unlink(outputFile, (err) => {
if (err) {
t6console.error(`File delete error: ${err}`);
}
});
}
}
};
sendData();
t6events.addStat("t6App", "Socket multicast", req.user_id, metadata.id, {"status": 200});
}
} else {
client.send(JSON.stringify(message.payload));
}
ws.send(`Multicasted (filtered on user_id ${req.user_id}) and channel "${message.channel}" to object_id: ${current.object_id}`);
}
});
ws.send("OK");
break;
case "claimUI":
if( message.ui_id ) {
t6console.debug("No signature check - Claim auto-accepted");
metadata = wsClients.get(ws);
metadata.ui_id = message.ui_id;
wsClients.set(ws, metadata);
ws.send(JSON.stringify({"arduinoCommand": "claimed", "status": "OK Accepted", "ui_id": metadata.ui_id, "socket_id": metadata.id}));
t6events.addStat("t6App", "Socket claimUI", req.user_id, metadata.id, {"status": 200});
t6mqtt.publish(null, mqttSockets+"/"+metadata.id, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": `Socket Claim accepted ui_id ${metadata.ui_id}`, "environment": process.env.NODE_ENV}), false);
t6ConnectedObjects.push(metadata.ui_id);
t6console.debug(`Object/UI Status Changed: ${metadata.ui_id} is visible`);
}
break;
case "claimObject":
let query = { "$and": [ { "user_id" : req.user_id }, { "id" : message.object_id }, ] };
let object = objects.findOne(query);
if( message.object_id && object && typeof object.secret_key!=="undefined" && object.secret_key!==null && object.secret_key!=="" ) {
t6console.debug("Found key from Object (for Claim)", object.id);
//t6console.debug("secret_key", object.secret_key);
t6console.debug("Verifying signature", message.signature);
jsonwebtoken.verify(String(message.signature), object.secret_key, (error, unsignedObject_id) => {
if(!error && unsignedObject_id && unsignedObject_id.object_id===message.object_id) {
//t6console.debug(object);
t6console.debug("Signature is valid - Cleaning previous Object");
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.object_id === message.object_id) {
wss.clients.delete(client);
t6console.debug("ws", "clients deleted", current);
}
});
t6console.debug("Signature is valid - Claim accepted");
metadata = wsClients.get(ws);
metadata.object_id = message.object_id;
metadata.t6_feat_audio = message.t6_feat_audio;
wsClients.set(ws, metadata);
t6ConnectedObjects.push(metadata.object_id);
t6mqtt.publish(null, mqttSockets+"/"+metadata.id, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": `Socket Claim accepted object_id ${metadata.object_id}`, "environment": process.env.NODE_ENV}), false);
t6events.addStat("t6App", "Socket claimObject", req.user_id, metadata.id, {"status": 200});
t6console.debug(`Object Status Changed: ${metadata.object_id} is visible`);
//wss.binaryType = "arraybuffer";
// Play Audio welcome sound to Object
if (message.t6_feat_audio === true) {
const readWelcomeStream = fs.readFileSync(`${tts.audioFolder}/socketopened.${audioExtension}`);
let offset = 0;
const sendData = () => {
const chunk = readWelcomeStream.slice(offset, offset + defaultChunkSize);
ws.send(chunk, {binary: true});
offset += defaultChunkSize;
if (offset < readWelcomeStream.length) {
t6console.debug("ws/tts", "send welcomeStream chunk offset", offset);
setTimeout(sendData, defaultChunkDelay);
} else {
ws.send(JSON.stringify({"arduinoCommand": "claimed", "status": "OK Accepted", "object_id": metadata.object_id, "socket_id": metadata.id, "t6_feat_audio": message.t6_feat_audio}));
t6console.debug("ws/tts", "Welcome audio sent to", message.object_id);
}
};
sendData();
t6console.debug("Sound-compatible Object: Welcome sound sent.", message.t6_feat_audio);
} else {
ws.send(JSON.stringify({"arduinoCommand": "claimed", "status": "OK Accepted", "object_id": metadata.object_id, "socket_id": metadata.id, "t6_feat_audio": message.t6_feat_audio}));
t6console.debug("Not sound-compatible Object.", message.t6_feat_audio);
}
} else {
t6console.debug("Error", error);
t6console.debug("unsignedObject_id", object.id);
t6console.debug("message.object_id", message.object_id);
t6console.debug("Signature is invalid - Claim rejected");
ws.send(JSON.stringify({"arduinoCommand": "claimed", "status": "Not Authorized, invalid signature", "object_id": null, "socket_id": metadata.id}));
t6mqtt.publish(null, mqttSockets+"/"+metadata.id, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": `Socket Claim rejected object_id ${metadata.object_id}`, "environment": process.env.NODE_ENV}), false);
}
});
} else {
t6console.debug("No Secret Key available on Object or Object is not yours or Object does not have a valid signature key.");
ws.send(JSON.stringify({"arduinoCommand": "claimed", "status": "Not Authorized, invalid signature", "object_id": null, "socket_id": metadata.id}));
t6mqtt.publish(null, mqttSockets+"/"+metadata.id, JSON.stringify({date: moment().format("LLL"), "dtepoch": parseInt(moment().format("x"), 10), "message": `Socket Claim rejected object_id ${metadata.object_id}`, "environment": process.env.NODE_ENV}), false);
}
break;
case "getUA":
metadata = wsClients.get(ws);
if(typeof metadata.webSocket.ua!=="undefined") {
ws.send(JSON.stringify({ua: metadata.webSocket.ua}));
t6events.addStat("t6App", "Socket getUA", req.user_id, metadata.id, {"status": 200});
} else {
ws.send(JSON.stringify({ua: undefined}));
}
break;
case "getKey":
metadata = wsClients.get(ws);
ws.send(JSON.stringify({key: metadata.webSocket.key}));
t6events.addStat("t6App", "Socket getKey", req.user_id, metadata.id, {"status": 200});
break;
case "getObject":
metadata = wsClients.get(ws);
if(typeof metadata.object_id!=="undefined") {
ws.send(JSON.stringify({object_id: metadata.object_id, socket_id: metadata.id, channels: metadata.channels, self: true, t6_feat_audio: metadata.t6_feat_audio}));
t6events.addStat("t6App", "Socket getObject", req.user_id, metadata.id, {"status": 200});
} else {
ws.send(JSON.stringify({object_id: undefined}));
}
break;
case "getObjects":
let listObjects = [];
metadata = wsClients.get(ws);
if(typeof metadata.user_id!=="undefined") {
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
// list only opened connection for the current user
t6console.debug("ws", current.id, ":", client.readyState);
if(current.user_id === req.user_id && client.readyState === 1) {
listObjects.push({object_id: current.object_id, socket_id: current.id, channels: current.channels, self: current.id===metadata.id?true:false, t6_feat_audio: current.t6_feat_audio});
}
});
ws.send(JSON.stringify(listObjects));
t6events.addStat("t6App", "Socket getObjects", req.user_id, metadata.id, {"status": 200});
} else {
ws.send(JSON.stringify([]));
}
break;
case "getUser":
metadata = wsClients.get(ws);
if(typeof metadata.user_id!=="undefined") {
ws.send(JSON.stringify({user_id: metadata.user_id}));
t6events.addStat("t6App", "Socket getUser", req.user_id, metadata.id, {"status": 200});
} else {
ws.send(JSON.stringify({user_id: undefined}));
}
break;
case "remindMeToMeasure":
metadata = wsClients.get(ws);
if(typeof message.object_id!=="undefined" && message.object_id!==null) {
wss.clients.forEach(function each(client) {
let current = wsClients.get(client);
if(current.object_id === message.object_id) {
message.payload ={
"arduinoCommand": "measureRequest",
"measurement": message.measurement
};
setTimeout(function(payload, current) {
client.send(JSON.stringify(payload));
ws.send(`Sent scheduled measureRequest command to object_id: ${current.object_id}`);
t6console.debug(`Sent scheduled measureRequest command to object_id: ${current.object_id}`);
}, message.delay, message.payload, current);
t6events.addStat("t6App", "Socket remindMeToMeasure", req.user_id, metadata.id, {"status": 200});
t6console.debug(`setTimeout for measureRequest at ${moment().add(message.delay, "milliseconds").format(logDateFormat)}`);
}
});
} else {
ws.send("NOK");
}
break;
case "help":
ws.send(`Hello ${metadata.id}, welcome to t6 IoT sockets command interface.`);
ws.send("Here are the commands :");
ws.send("- broadcast: to cast a message to any connected Object from your user account.");
ws.send("- multicast: to cast a message to both connected Object to the same user as the claimed object, and to the Objects that subscribed to the specified channel.");
ws.send("- unicast: to cast a message to a specif Object you own.");
ws.send("- claimObject: to Claim the id of a specific Object.");
ws.send("- claimUi: to Claim the id of current UI.");
ws.send("- getObject: to get the id of an Object claimed to server.");
ws.send("- getUser: to get the user_id of an Object claimed to server.");
ws.send("- getObjects: to get the Objects claimed to server.");
ws.send("- getUA: to get the user-agent of an Object.");
ws.send("- remindMeToMeasure: set a delayed task to call back the object for a measurement.");
break;
default:
break;
}
} else {
t6console.debug(`Received message ${message} from socket_id ${metadata.id}`);
}
});
});
wss.on("upgrade", (request, socket, head) => {
authenticate(request, function next(err, client) {
t6console.debug(err);
t6console.debug(client);
if (err || !client) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit("connection", ws, request, client);
});
});
});
wss.on("close", function close() {
t6console.warning(`${appName} wsClose.`);
});
wss.onerror = () => {
t6console.error(`${appName} wsError.`);
};
t6console.log("-audioEncoding", `${tts.audioEncoding}.`);
t6console.log("-ssmlVoiceGender", `${tts.ssmlVoiceGender}.`);
t6console.log("-audioFolder", smartTrim(tts.audioFolder, 40));
t6console.log("-outputFolder", smartTrim(tts.outputFolder, 40));
t6console.log(`${appName} ws(s) listening to ${socketsScheme}${socketsHost}:${socketsPort}.`);
};
module.exports = t6websockets;