-
Notifications
You must be signed in to change notification settings - Fork 0
/
skreen.js
executable file
·1372 lines (1238 loc) · 47.8 KB
/
skreen.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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/*
* skreen.js by Aaron Becker
* Skreen Node.JS Server
*
* Dedicated to Marc Perkel
*/
/*
* Copyright (c) 2018 Aaron Becker <[email protected]>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
/*
---- CODE LAYOUT ----
This descriptor describes the layout of the code in this file.
2 main phases: Initialization (I1-I16) and Runtime Code (R1)
Initialization (16 steps):
1) Module Initialization: initalizes modules that are required later on, root check, very early stuff
2) Runtime Info/Settings: Reads and parses runtime information and settings from external JSON file, essential for later on
3) State Machine Init: Initializes state machine that keeps track of the state of each module
4) Console Colors: overrides prototypes for console to provide colors in console
5) File Logging Setup: Initializes file logging handlers for functions that output to console
6) Serial Device Logic: Reads command line arguments and determines valid serial devices to connect to. Also opens a serial port if a valid device is found
7) Arduino Command Handling: defines handling of arduino commands
8) Data File Parsers: parses files that contain information like data for commands and responses for speech matching
9) Neural Network Setup: sets up and trains neural network for processing of speech commands
10) Reading From Stdin: initializes handlers for reading from stdin (arduino commands from stdin)
11) Error and Exit Handling: initializes error & exit (Ctrl+C) handlers
12) Soundcloud Init Code: Initializes soundcloud (from ext file soundManager) and starts caching of soundcloud files to server
13) OpenCV Init Code: Initializes and trains OpenCV model for facial recognition
14) Mapping Init Code: Initializes and loads offline map data for display in Leaflet maps
15) Oled Driver Init: Initializes OLED driver for external oled display. (update set in misc init code)
16) Misc. Init Code: Initializes loops for tracking runtimeInformation and sending to clients, as well as listener for terminal resize. Also sends information to oled
Runtime Code (1 step):
1) HTTP Server Setup/Handling: sets up server
-Initializes all dependencies for secure server, including
- Passport.js
- Express.js
- and a bunch of other stuff
-Initializes all HTTP paths and exposes API
-Initializes Passport.JS and sets up routing to user database
*/
/**********************************
--I1-- MODULE INITIALIZATION --I1--
**********************************/
const fs = require('fs');
const os = require('os');
const path = require('path');
const singleLineLog = require('single-line-log').stdout; //single line logging
var cwd = __dirname;
process.title = "Skreen V1";
/**********************************
--I2-- RUNTIME INFO/SETTINGS --I2--
**********************************/
var runtimeSettings = {}; //holds settings like maximum passcode tries
var runtimeInformation = {}; //holds information like version, arduino. Updated while running
var soundcloudSettings = {};
var neuralSettings = {};
var airplaySettings = {};
var lutronSettings = {};
try {
var settingsData = JSON.parse(fs.readFileSync(path.join(cwd,"/data/settings.json")));
} catch(e) {
console.error("[FATAL] Error reading info/settings file");
throw "[FATAL] Error reading info/settings file";
}
function shallowCopy(from, to) {
let keys = Object.keys(from); //only override keys from settingsData
for (var i=0; i<keys.length; i++) {
to[keys[i]] = from[keys[i]];
}
}
shallowCopy(settingsData.information, runtimeInformation);
shallowCopy(settingsData.soundcloudSettings, soundcloudSettings);
shallowCopy(settingsData.settings, runtimeSettings);
shallowCopy(settingsData.neuralSettings, neuralSettings);
shallowCopy(settingsData.airplaySettings, airplaySettings);
shallowCopy(settingsData.lutronSettings, lutronSettings);
runtimeSettings.loginMessage = settingsData.loginMessage;
//console.clear();
console.log("~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\nSkreen V0.2\nBy AAron Becker\nPORT: "+runtimeSettings.serverPort+"\nCWD: "+cwd+"\nPID: "+process.pid+"\n~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n");
/***************************
--I4-- CONSOLE COLORS --I4--
****************************/
var colors = require('colors');
const originalWarn = console.warn;
const originalErr = console.error;
const originalInfo = console.info;
const originalLog = console.log;
if (runtimeSettings.loginMessage && runtimeSettings.loginMessage[0] && runtimeSettings.loginMessage[1]) {
originalLog(colors.italic.bold.green(runtimeSettings.loginMessage[0]));
for (var i=1; i<runtimeSettings.loginMessage.length-1; i++) {
originalLog(runtimeSettings.loginMessage[i]);
}
originalLog(colors.italic.bold.green(runtimeSettings.loginMessage[runtimeSettings.loginMessage.length-1]));
} else {
originalErr(colors.red("No runtimeMessage provided in json config when it is required"));
}
if (runtimeSettings.logLevel < 4) {
originalLog(colors.cyan("Overriding console.log because logLevel="+runtimeSettings.logLevel+" is too low"));
console.log = function(){};
}
if (runtimeSettings.logLevel >= 3) {
console.info = function(){
if (arguments.length > 1) {
var firstArg = arguments[0];
var restArgs = [];
for (var i=1; i<arguments.length; i++) {
restArgs.push(arguments[i]);
}
originalInfo(colors.blue.underline(firstArg),restArgs);
} else {
originalInfo(colors.blue.underline(arguments[0]));
}
}
} else {
originalLog(colors.cyan("Overriding console.info because logLevel="+runtimeSettings.logLevel+" is too low"));
console.info = function(){};
}
if (runtimeSettings.logLevel >= 2) {
console.warn = function(){
if (arguments.length > 1) {
var firstArg = arguments[0];
var restArgs = [];
for (var i=1; i<arguments.length; i++) {
restArgs.push(arguments[i]);
}
originalWarn(colors.yellow.underline(firstArg),restArgs);
} else {
originalWarn(colors.yellow.underline(arguments[0]));
}
}
} else {
originalLog(colors.cyan("Overriding console.warn because logLevel="+runtimeSettings.logLevel+" is too low"));
console.warn = function(){}; //redir to empty function
}
if (runtimeSettings.logLevel >= 1) {
console.error = function(){
if (arguments.length > 1) {
var firstArg = arguments[0];
var restArgs = [];
for (var i=1; i<arguments.length; i++) {
restArgs.push(arguments[i]);
}
originalErr(colors.red.underline(firstArg),restArgs);
} else {
originalErr(colors.red.underline(arguments[0]));
}
}
} else {
originalLog(colors.cyan("Overriding console.error because logLevel="+runtimeSettings.logLevel+" is too low"));
originalWarn(colors.yellow.underline("[WARNING] No logging enabled, will not show any more messages. You might want to disable this to logLevel=1 because you won't see any errors"));
console.error = function(){}; //redir to empty function
}
console.importantInfo = function(){
if (arguments.length > 1) {
var firstArg = arguments[0];
var restArgs = [];
for (var i=1; i<arguments.length; i++) {
restArgs.push(arguments[i]);
}
originalInfo("\n"+colors.cyan.bold.underline(firstArg),restArgs);
} else {
originalInfo("\n"+colors.cyan.bold.underline(arguments[0]));
}
}
console.importantLog = function(){
if (arguments.length > 1) {
var firstArg = arguments[0];
var restArgs = [];
for (var i=1; i<arguments.length; i++) {
restArgs.push(arguments[i]);
}
originalLog("\n"+colors.white.bold(firstArg),restArgs);
} else {
originalLog("\n"+colors.white.bold(arguments[0]));
}
}
/********************************
--I5-- FILE LOGGING SETUP --I5--
********************************/
const loggingUtils = require("./drivers/logging.js");
const semiOriginalLog = console.log;
const semiOriginalWarn = console.warn;
const semiOriginalInfo = console.info;
const semiOriginalError = console.error;
const semiOriginalIInfo = console.importantInfo;
const semiOriginalILog = console.importantLog;
loggingUtils.init(cwd, runtimeSettings).then( () => {
console.importantLog("Logging master init ok (1/4)");
try {
console.log = function() {
loggingUtils.log(arguments,"log");
semiOriginalLog.apply(null, arguments);
}
console.warn = function() {
loggingUtils.warn(arguments,"warn");
semiOriginalWarn.apply(null, arguments);
}
console.error = function() {
loggingUtils.error(arguments,"error");
semiOriginalError.apply(null, arguments);
}
console.importantLog = function() {
loggingUtils.ilog(arguments,"ilog");
semiOriginalILog.apply(null, arguments);
}
console.importantInfo = function() {
loggingUtils.iinfo(arguments,"iinfo");
semiOriginalIInfo.apply(null, arguments);
}
console.importantLog("Logging commands init ok (2/4)");
loggingUtils.registerValidationInterval();
console.importantLog("Logging validationListener init ok (3/4)");
console.importantInfo("LOGGING INIT OK");
} catch(e) {
console.error("Logging init error: "+e);
}
}).catch( err => {
console.error("Error initializing logger: "+err);
});
/*************************************
--I7-- ARDUINO COMMAND HANDLING --I7--
*************************************/
var arduinoUtils = require('./drivers/arduino.js'); //require the driver;
runtimeInformation.arduinoConnected = false;
arduinoUtils.init(runtimeSettings, runtimeInformation).then(() => {
console.importantLog("Arduino driver initialized successfully (1/5)");
arduinoUtils.findArduino().then(arduinoAddr => {
console.importantLog("Arduino located on serial port '"+arduinoAddr+"' successfully (2/5)");
arduinoUtils.connectArduino(arduinoAddr).then( () => {
console.importantLog("Arduino connected successfully (3/5)");
runtimeInformation.arduinoConnected = true;
arduinoUtils.setupExistenceCheck(runtimeInformation).then(() => {
console.importantLog("Arduino existence check enabled (4/5)");
arduinoUtils.setupQueueCommandSending().then(() => {
console.importantLog("Arduino queue command sending setup OK (5/5)");
console.importantInfo("ARDU INIT OK");
}).catch(err => {
console.error("Ardu init error (enabling queue command sending): "+err);
})
}).catch( err => {
console.error("Ardu init error (enabling existence check): "+err);
});
}).catch( err => {
console.error("Failed to connect to arduino for the following reason: '"+err+"'");
});
}).catch(err => {
console.warn("[WARNING] Server running without arduino. Errors may occur. Once you have connected an arduino, you have to relaunch the start script.");
console.importantInfo("ARDU INIT ERR: NO ARDU CONNECTED (reason: "+err+")");
arduinoUtils.setArduinoFakeClass();
});
}).catch( err => {
console.error("Arduino driver failed to initialize for the following reason: '"+err+"'");
}) //setup arduino object and libs
/*********************************
--I9-- NEURAL NETWORK SETUP --I9--
*********************************/
const NeuralMatcher = require('./drivers/neuralMatcherCommandWrapper.js');
NeuralMatcher.init(neuralSettings)
.then( () => {
console.importantInfo("NEURAL_MATCHER INIT OK");
})
.catch( err => {
console.error("Error initializing NeuralCommandMatcher: "+err);
});
/*******************************
--I10-- READING FROM STDIN --I10--
*******************************/
const advancedEventListener = require("./drivers/advancedEventListener.js");
var stdinputListener = new advancedEventListener(process.openStdin(),"data"); //register stdin to listener
var sendArduinoMode = false;
stdinputListener.addPersistentListener("*",function(d) { //All events, set to persist
var uI = d.toString().trim();
console.log("you entered: [" + uI + "]");
if (uI == "help") {
console.importantLog("Right now, sA or sendArduinoMode toggles sending raw to arduino.")
} else if (uI == "sA" || uI == "sendArduinoMode") {
sendArduinoMode = !sendArduinoMode;
console.importantLog("Send arduino mode toggled ("+sendArduinoMode+")");
} else {
if (sendArduinoMode) {
arduinoUtils.sendCommand(uI);
} else {
console.importantLog("Command not recognized");
}
}
});
/************************************
--I11-- ERROR AND EXIT HANDLING --I11--
************************************/
process.on('SIGINT', function (code) { //on ctrl+c or exit
console.importantLog("\nSIGINT signal recieved, graceful exit (garbage collection) w/code "+code);
process.exit(); //exit completely
});
/*
process.on('uncaughtException', function (err) { //on error
console.importantLog("\nCRASH REPORT\n-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\nError:\n"+err+"\n-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~\n");
console.importantLog("\nError signal recieved, graceful exiting (garbage collection)");
process.exit();
});*/
process.on('unhandledRejection', (reason, p) => {
console.error("Unhandled Promise Rejection at: Promise '"+p.name+"'");
console.error(p);
console.error("Because reason: ", reason.stack || reason);
//process.exit();
});
/***********************************
--I12-- MUSIC INIT CODE --I12--
***********************************/
var soundManager = require('./drivers/soundManager.js');
console.info("Starting SC MASTER");
soundManager.init(soundcloudSettings, airplaySettings, cwd).then( () => { //no username param so that username is not passed
console.importantInfo("SM INIT OK");
}).catch( err => {
console.error("Error initializing SC: "+err);
});
/***********************************
--I13-- LIGHTS INIT CODE --I13--
***********************************/
const telnetHandler = require("./drivers/telnetM.js");
const timingHandler = require("./drivers/timingM.js");
console.log("Required all packages successfully");
//JSON file parsing
const rdContents = fs.readFileSync(lutronSettings.roomDataPath, 'utf8');
var roomData = JSON.parse(rdContents);
//Hub connection via telnet server
const hub = new telnetHandler(lutronSettings.baseHubIP, lutronSettings.baseHubUser, lutronSettings.baseHubPass, roomData);
var hubConnected = false;
hub.begin().then(() => {
hubConnected = true;
console.importantInfo("LUTRON/LIGHTS INIT OK");
/**** EXAMPLE USAGE
Single light (by device identifier):
SET VALUE
hub.setLightOutput(2,0).then(() => {
console.log("Success");
}).catch(e => {
console.error("Light output value fail: "+e);
});
GET VALUE
hub.getLightOutput(2).then(value => {
console.log("Light output value: "+value);
}).catch(e => {
console.error("Light output value fail: "+e);
});
Location (room, by room name):
hub.setLocationLight("AaronsRoom",100).then(() => {
console.log("AaronsRoom success");
}).catch(e => {
console.error(e);
})
*/
}).catch(e => {
console.error("Hub connection failure: "+e);
process.exit(1);
});
//Timer setup for autodimming of lights, etc
const timing = new timingHandler(roomData.timeShift, hub); //pass in hub reference to allow control
timing.enableTimers(); //by default, enable the timers
/**************************************
--I14-- REALTIME DATA INIT CODE --I14--
***************************************/
const {RPIgetCPUInfo, RPIgetMemoryInfo, RPIgetTempInfo, RPIgetUptimeInfo} = require("./drivers/rpiStats.js"); //require it in oneliner
/***************************************
--R1-- HTTP SERVER SETUP/HANDLING --R1--
***************************************/
//Much love to Evan Gow for his great tutorial at https://medium.com/@evangow/server-authentication-basics-express-sessions-passport-and-curl-359b7456003d
/****
DEPS
*****/
//express deps
const express = require("express");
//init the routers
var APIrouter = express.Router();
var SCrouter = express.Router();
var AUTHrouter = express.Router();
var ARDUrouter = express.Router();
var LIGHTSrouter = express.Router();
var STATrouter = express.Router();
const session = require('express-session');
const FileStore = require('session-file-store')(session);
//create app instance
const app = express();
const server = require('http').Server(app);
//express modules
const serveFavicon = require('serve-favicon');
const bodyParser = require('body-parser');
const cors = require('cors');
//authentication deps
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const CustomStrategy = require('passport-custom').Strategy;
const passportDebug = false;
const bcrypt = require('bcrypt');
const jsonDB = require('node-json-db').JsonDB;
const db = new jsonDB(runtimeSettings.jsonDBPath, true, false); //connect to json-database
/****
CONSTANTS
****/
const RequestHandler = {
SUCCESS: function(message) {
if (typeof message == "undefined") {
message = "";
}
return JSON.stringify({"error": false, "wait": false, "message": message});
},
FAILURE: function(message) {
if (typeof message == "undefined") {
message = "";
}
return JSON.stringify({"error": true, "wait": false, "message": message});
},
WAIT: function(message) {
if (typeof message == "undefined") {
message = "";
}
return JSON.stringify({"error": false, "wait": true, "message": message});
}
}
/****
INIT MODS
*****/
console.log("[AUTH] Init modules begun");
app.use(serveFavicon(path.join(cwd,runtimeSettings.faviconDirectory))); //serve favicon
app.use(cors()); //enable cors
app.use(express.static(path.join(cwd,runtimeSettings.assetsDirectory))); //define a static directory
app.use(bodyParser.urlencoded({ extended: true })); //, limit: '50mb' })); //bodyparser for getting json data, big limit for images
app.use(bodyParser.json());
const sessionFileStore = new FileStore(); //create the session file store
//Simple UUID generation
function generateUUID(){
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
}
app.use(session({
genid: (req) => {
//console.log('Inside UUID-generation');
return generateUUID(); // use UUIDs for session IDs
},
store: sessionFileStore, //filestore for sessions
secret: "k3yB0ARdC@3t5s!", //set secret to new ID
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize()); //passport.js init
app.use(passport.session());
/****
INIT STRATS
*****/
console.log("[AUTH] Init strategies begun");
// configure passport.js to use the local strategy
passport.use(new LocalStrategy(
{ usernameField: 'name' },
(name, password, done) => {
if (passportDebug) {
console.log('[PASSPORT] localStrategy found, looking up user w/name: '+name+", passwd: "+password);
}
try {
let allUserData = db.getData("/users/");
for (var i=0; i<allUserData.length; i++) {
if (allUserData[i].name == name) { //Is the name the same? Okay we located the user
if (!bcrypt.compareSync(password, allUserData[i].password)) {
return done(null, false, { message: 'Invalid credentials: password invalid.\n' });
} else {
return done(null, allUserData[i]);
}
}
}
return done(null, false, { message: 'Invalid credentials: user not found (und in db).\n' });
} catch (e) {
return done(null, false, { message: 'Invalid credentials: user not found (err in db lookup).\n' });
}
}
));
//Use https://www.browserling.com/tools/bcrypt to add passcodes
passport.use('passcode', new CustomStrategy( function(req, done) {
if (typeof req.body.passcode !== "undefined") {
if (passportDebug) {
console.log("[PASSPORT] psc entered="+req.body.passcode+", now checking");
}
let passcodes = db.getData("/passcodes/");
let pscUser = db.getData("/passcodeUser/");
req.body.passcode = String(req.body.passcode).trim(); //jank fix but it worko
for (var i=0; i<passcodes.length; i++) {
if (bcrypt.compareSync(String(req.body.passcode), passcodes[i])) {
return done(null, pscUser);
}
}
return done(null, false, { message: 'Passcode invalid.\n' });
} else {
if (passportDebug) {
console.log("[PASSPORT] no psc entered?");
}
return done(null, false, { message: 'No passcode entered\n' });
}
}));
//User serialization and deserialization
passport.serializeUser((user, done) => {
if (passportDebug) {
console.log("[PASSPORT] Serializing user with id: "+user.id);
}
done(null, user.id);
});
passport.deserializeUser((id, done) => {
if (passportDebug) {
console.log("[PASSPORT] Deserializing user with id: "+id);
}
try {
let pscUser = db.getData("/passcodeUser/");
if (id == pscUser.id) {
return done(null, pscUser);
} else {
let allUserData = db.getData("/users/");
for (var i=0; i<allUserData.length; i++) {
if (allUserData[i].id == id) {
return done(null, allUserData[i]);
}
}
console.warn("Couldn't find user w/id "+id+" in db when deserializing");
return done("Couldn't find user in db when deserializing", false);
}
} catch (e) {
return done(e, false);
}
});
/****
INIT ROUTES
*****/
//MAIN ROUTES
app.get("/client", function(req, res, next) { //Skreen main route
if (req.isAuthenticated() || runtimeSettings.disableLogin) {
fs.readFile(path.join(cwd,runtimeSettings.defaultFileDirectory,runtimeSettings.defaultClientFile), function (err, buf) {
if (err) {
res.end("Error reading client file (this shouldn't happen?)");
} else {
//res.setHeader('Content-Type', 'text/html')
res.end(buf);
}
})
} else {
res.redirect('/login');
}
});
app.get('/login', (req, res) => {
if (req.isAuthenticated() || runtimeSettings.disableLogin) {
res.redirect("/client");
} else {
fs.readFile(path.join(cwd,runtimeSettings.defaultFileDirectory,runtimeSettings.defaultLoginFile), function (err, buf) {
if (err) {
next(err); //pass err to express
} else {
//res.setHeader('Content-Type', 'text/html')
res.end(buf);
}
});
}
})
//AUTH ROUTES
AUTHrouter.post('/regular', (req, res, next) => {
if (!req.session.regularAttemptNumber) {
req.session.regularAttemptNumber = 0;
}
if (req.session.regularAttemptNumber >= runtimeSettings.maxRegularAttempts) { //-1 to fix off by one
if (passportDebug) {
console.log("[PASSPORT] regular attempt maxOut@ att#="+req.session.regularAttemptNumber);
}
return res.end(RequestHandler.FAILURE("Too many login attempts w/mode=Regular"))
} else { //Ok we don't have too many attempts so actually check now
passport.authenticate('local', (err, user, info) => {
//Check for error or info conditions
if (info) {
req.session.regularAttemptNumber++;
return res.send(RequestHandler.FAILURE(info.message))
}
if (err) {
req.session.regularAttemptNumber++;
return next(err);
}
if (!user) {
return res.redirect('/login');
}
//Basic validity checks passed, pass login
req.login(user, (err) => {
if (err) {
return next(err);
}
if (passportDebug) {
console.log("[PASSPORT] You were authenticated :)");
}
//Reset attempts
req.session.regularAttemptNumber = 0;
req.session.passcodeAttemptNumber = 0;
return res.end(RequestHandler.SUCCESS());
});
})(req, res, next);
}
});
AUTHrouter.post('/passcode', bodyParser.json(), (req, res, next) => {
if (!req.session.passcodeAttemptNumber) {
req.session.passcodeAttemptNumber = 0;
}
if (req.session.passcodeAttemptNumber >= runtimeSettings.maxPasscodeAttempts) { //-1 to fix off by one
if (passportDebug) {
console.log("[PASSPORT] passcode attempt maxOut@ att#="+req.session.passcodeAttemptNumber);
}
return res.end(RequestHandler.FAILURE("Too many login attempts w/mode=Passcode"))
} else { //Ok we don't have too many attempts so actually check now
passport.authenticate('passcode', (err, user, info) => {
if (info) {
req.session.passcodeAttemptNumber++;
return res.send(RequestHandler.FAILURE(info.message))
}
if (err) {
req.session.passcodeAttemptNumber++;
return next(err);
}
if (!user) {
return res.redirect('/login');
}
req.login(user, (err) => {
if (err) {
return next(err);
}
if (passportDebug) {
console.log("[PASSPORT] You were authenticated :)");
}
//Reset attempts
req.session.regularAttemptNumber = 0;
req.session.passcodeAttemptNumber = 0;
return res.end(RequestHandler.SUCCESS());
})
})(req, res, next);
}
});
//API ROUTES
APIrouter.use(function(req, res, next) { //Middleware to check whether the user is authenticated
if (passportDebug) {
console.log("API endpoint targeted; checking authentication...");
}
if (req.isAuthenticated() || runtimeSettings.disableLogin) {
next();
} else {
return res.status(401).end(RequestHandler.FAILURE("Error: Not authenticated to make API request to APIRouter"));
}
});
APIrouter.get("/isup", function(req, res) {
res.status(200);
res.end(RequestHandler.SUCCESS());
});
APIrouter.get("/runtime", function(req, res) {
res.end(RequestHandler.SUCCESS(runtimeInformation));
});
APIrouter.get("/session", function(req, res) {
let authenticated = req.isAuthenticated();
let sessionAttemptsData = {
"passcode": req.session.passcodeAttemptNumber,
"regular": req.session.regularAttemptNumber
}
let id = req.sessionID;
return res.end(RequestHandler.SUCCESS({
authenticated: authenticated || false,
id: id || -1,
attempts: sessionAttemptsData
}));
});
APIrouter.get("/speech/:data", function(req, res) {
try {
var speechData = JSON.parse(req.params.data);
} catch(e) {
return res.end(RequestHandler.FAILURE("Error: Failed to parse speech data. Is it in the form of an array?"));
}
if (speechNetReady) {
console.log("processing speech: '"+JSON.stringify(speechData)+"'");
var classifiedSpeech = []; //array to hold speech that is classified
if (speechData.constructor === Array) { //array of possibilities?
var classifications = []; //array of potential classifications
for (var i=0; i<speechData.length; i++) { //part 1: get all possibilities
console.log("running speech possibility: "+speechData[i]);
var classification = neuralMatcher.algorithm.classify(speechClassifierNet, speechData[i]);
if (classification.length > 0) {
classifiedSpeech.push(speechData[i]);
}
console.log("Speech classification: "+JSON.stringify(classification));
for (var j=0; j<classification.length; j++) {
var category = classification[j][0];
var confidence = classification[j][1];
var contains = false;
var containIndex = -1;
for (var b=0; b<classifications.length; b++) {
if (classifications[b][0] == category) {
contains = true;
containIndex = b;
}
}
if (contains) {
console.log("contains, push _ cat="+category+", conf="+confidence);
classifications[containIndex][1].push(confidence);
} else {
console.log("no contain, not averaging _ cat="+category+", conf="+confidence);
classifications[classifications.length] = classification[j];
classifications[classifications.length-1][1] = [classifications[classifications.length-1][1]];
}
}
}
var max = 0;
for (var i=0; i<classifications.length; i++) { //part 2: total possibilities
if (classifications[i][1].length > 1) {
console.log("averaging "+JSON.stringify(classifications[i][1]));
var tot = 0;
var len = classifications[i][1].length;
for (var j=0; j<classifications[i][1].length; j++) {
tot += classifications[i][1][j];
}
var avg = tot/len;
if (tot > max) {
max = tot;
}
console.log("avg="+avg+", tot="+tot)
classifications[i][1] = avg*tot; //multiply by total to weight more answers (I know this results in just total)
}
}
for (var i=0; i<classifications.length; i++) { //part 3, scale by max
console.log("Scaling classification "+classifications[i][1]+" by max val "+max);
if (max == 0) {
console.warn("Dividing factor max is 0, did you pass only a single word in an array?");
} else {
classifications[i][1] /= max;
}
}
var finalClassifications = [];
for (var i=0; i<classifications.length; i++) {
if (classifications[i][1] > neuralMatcher.algorithm.cutoffOutput) {
finalClassifications.push(classifications[i]);
}
}
console.log("classifications: "+JSON.stringify(classifications)+", cutoff filtered classifications: "+JSON.stringify(finalClassifications));
//pick the more likely response from the ones provided
var likelyResponse = ["",[0]];
for (var i=0; i<finalClassifications.length; i++) {
if (finalClassifications[i][1] > likelyResponse[1]) {
likelyResponse = finalClassifications[i];
}
}
var response;
if (likelyResponse.constructor == Array && likelyResponse[0] !== "" && likelyResponse[1][1] !== 0) {
speechParser.algorithm.addRNGClass(likelyResponse[0]); //generate rng class from classification
response = speechParser.algorithm.dumpAndClearQueue();
} else {
console.warn("Likelyresponse is blank, what happened?")
response = "";
}
return res.end(RequestHandler.SUCCESS({classification: finalClassifications, likelyResponse: likelyResponse, transcript: speechData, classifiedTranscript: classifiedSpeech, response: response}));;
} else {
var classification = neuralMatcher.algorithm.classify(speechClassifierNet, speechData); //classify speech
console.log("Speech classification: "+JSON.stringify(classification));
var response;
if (classification.constructor == Array && classification.length > 0) {
speechParser.algorithm.addRNGClass(classification[0][0]); //generate rng class from classification
response = speechParser.algorithm.dumpAndClearQueue(); //dump queue to response (if backed up w/multiple calls)
} else {
console.warn("Classification length is 0, response is nothing");
response = "";
}
return res.end(RequestHandler.SUCCESS({classification: classification, transcript: speechData, classifiedTranscript: classifiedSpeech, response: response}));
}
} else {
res.end(RequestHandler.FAILURE("Error: Speechnet not ready"));
}
})
APIrouter.get("/time", function(req, res) {
timing.getCurrentTime().then(time => {
return res.end(RequestHandler.SUCCESS(time));
}).catch(e => {
return res.end(RequestHandler.FAILURE(e));
})
})
APIrouter.get("/action/kill", function(req, res) {
res.end(RequestHandler.SUCCESS("bai"));
console.log("Client requested exit; exiting");
setTimeout(() => {
process.exit()
},1500);
})
//Stat Routes
STATrouter.get("/temp", function(req, res) {
RPIgetTempInfo().then(tempInfo => {
return res.end(RequestHandler.SUCCESS(tempInfo));
}).catch(e => {
return res.end(RequestHandler.FAILURE(e));
})
});
STATrouter.get("/cpu", function(req, res) {
RPIgetCPUInfo().then(cpuInfo => {
return res.end(RequestHandler.SUCCESS(cpuInfo));
}).catch(e => {
return res.end(RequestHandler.FAILURE(e));
})
});
STATrouter.get("/mem", function(req, res) {
RPIgetMemoryInfo().then(memInfo => {
return res.end(RequestHandler.SUCCESS(memInfo));
}).catch(e => {
return res.end(RequestHandler.FAILURE(e));
})
});
STATrouter.get("/uptime", function(req, res) {
RPIgetUptimeInfo().then(uptimeInfo => {
return res.end(RequestHandler.SUCCESS(uptimeInfo));
}).catch(e => {
return res.end(RequestHandler.FAILURE(e));
})
});
STATrouter.get("/devicesStatus", function(req, res) {
return res.end(RequestHandler.SUCCESS({
arduinoConnected: arduinoUtils.arduinoConnected,
serverConnected: true,
lutronConnected: hub.connectionStatus.connected,
lutronLoginOK: hub.connectionStatus.login
}));
});
STATrouter.get("/all", function(req, res) {
//ooh let's use pAralLeLiZaTioN
var memCompleted = false;
var memInfo;
RPIgetMemoryInfo().then(memInfoInternal => {
memInfo = memInfoInternal;
memCompleted = true;
finishedCB();
}).catch(e => {
memCompleted = true;
finishedCB();
});
var cpuCompleted = false;
var cpuInfo;
RPIgetCPUInfo().then(cpuInfoInternal => {
cpuInfo = cpuInfoInternal;
cpuCompleted = true;
finishedCB();
}).catch(e => {
cpuCompleted = true;
finishedCB();
});
var tempCompleted = false;
var tempInfo;
RPIgetTempInfo().then(tempInfoInternal => {
tempInfo = tempInfoInternal;
tempCompleted = true;
finishedCB();
}).catch(e => {
tempCompleted = true;
finishedCB();
});
var uptimeCompleted = false;
var uptimeInfo;
RPIgetUptimeInfo().then(uptimeInfoInternal => {
uptimeInfo = uptimeInfoInternal;
uptimeCompleted = true;
finishedCB();
}).catch(e => {
uptimeCompleted = true;
finishedCB();
});
let finishedCB = () => {
if (memCompleted && cpuCompleted && tempCompleted && uptimeCompleted) {
res.end(RequestHandler.SUCCESS({ //values may be undefined if a check failed but that's ok because it's dealt with client side lol
"memInfo": memInfo,
"uptimeInfo": uptimeInfo,
"cpuInfo": cpuInfo,
"temp": tempInfo,
"devicesStatus": {
arduinoConnected: arduinoUtils.arduinoConnected,
serverConnected: true,