-
Notifications
You must be signed in to change notification settings - Fork 3
/
node_helper.js
1637 lines (1545 loc) · 55.5 KB
/
node_helper.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
var NodeHelper = require("node_helper");
const { spawn, exec } = require("child_process");
const express = require("express");
const path = require("path");
const os = require("os");
const stream = require("stream");
const _ = require("lodash");
const remote = new stream.Writable();
let debug = false;
const diff = require("deep-object-diff").diff;
const detailedDiff = require("deep-object-diff").detailedDiff;
const updatedDiff = require("deep-object-diff").updatedDiff;
const fs = require("fs");
const default_config_name=path.sep+"config"+path.sep+"config.js"
let oc =
__dirname.split(path.sep).slice(0, -2).join(path.sep) + default_config_name ;
// get the default module positions old way
let module_positions = JSON.parse(
fs.readFileSync(__dirname + "/templates/module_positions.json", "utf8")
);
// set the modules folder to the environment variable if set
let modules_folder=process.env.MM_MODULES_DIR?process.env.MM_MODULES_DIR:"modules"
if(debug){
console.log("modules folder set at init to ="+modules_folder)
}
try {
let mp =
fs.readFileSync(
path.join(__dirname, "/../../js/positions.js"),
"utf8"
)
module_positions= JSON.parse(mp.split('=')[1])
module_positions.push("none")
} catch(error){
}
// get the default modules list from the MM core
const defaultModules = require("../../modules/default/defaultmodules.js");
const module_jsonform_converter = "_converter.js"
const our_name = __dirname.split(path.sep).slice(-2,-1)
const QRCode = require("qrcode");
const checking_diff = false;
var socket_io_port = 8200;
var pm2_id = -1;
const getPort = require("get-port");
const closeString =
';\n\
\n\
/*************** DO NOT EDIT THE LINE BELOW ***************/\n\
if (typeof module !== "undefined") {module.exports = config;}';
String.prototype.hashCode = function(port) {
var hash = 0,
i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash.toString().replace('-','')+port.toString();
}
// add require of other javascripot components here
// var xxx = require('yyy') here
// disable savinging while testing = false
let doSave = true;
module.exports = NodeHelper.create({
config: {debug:false},
module_scripts: {},
imageurl:null,
buildQR_URI(){
//console.log("in buildQR_URI");
this.hostname = //os.hostname();
this.getIPAddress()
this.config.url =
"http://" +
(this.config.address == "0.0.0.0"
? this.hostname
: this.config.address) +
":" +
this.config.port;
if (this.config.showQR) {
let url = this.config.url + "/"+modules_folder+"/" + this.name + "/review";
this.imageurl =
//this.config.url +
"/"+modules_folder+"/" + this.name + "/qrfile.png";
QRCode.toFile(this.path + "/qrfile.png", url, (err) => {
if (!err) {
if (debug) console.log("QRCode build done");
} else {
console.log("QR image create failed =" + JSON.stringif(err));
}
});
}
},
setconfigpath(){
//console.log("in setconfigpath");
// get the environment var for config files
let cf = process.env.MM_CONFIG_FILE
// if set and it does not contain path separator, its only the filename, not the folder
if(cf && !cf.includes(path.sep)){
// add the default config folder to the name
cf = "/config/"+cf;
}
if(cf && !cf.startsWith(path.sep)){
cf=path.sep+cf
}
// set the output config file name
oc=__dirname.split(path.sep).slice(0, -2).join(path.sep) + (cf?cf:default_config_name);
if(debug){
console.log("config folder set at form start ="+cf);
console.log("modules folder set at form start="+modules_folder)
}
},
setConfig(){
//console.log("in setConfig");
this.setconfigpath()
// watch out for env variable setting port
let mm_port = process.env.MM_PORT
//console.log("config port=", config.port, " env port=", mm_port)
this.config.address = config.address;
this.config.port = mm_port || config.port;
this.config.whiteList = config.ipWhitelist
for(let m of config.modules){
if(m.module === this.name){
debug=this.config.debug = m.config.debug || false
this.config.force_update = m.config.force_update || true
this.config.restart = m.config.restart || ""
if(m.config.showQR){
this.config.showQR=m.config.showQR || false
this.buildQR_URI()
}
break;
}
}
this.startit()
},
// MM calls start
start() {
if(this.config.debug) console.log('Starting module helper:' +this.name+ JSON.stringify(this.data));
//console.log("full config=",config)
this.setConfig()
},
// collect the data in background
launchit() {
if (debug) console.log("execing " + this.command);
exec(this.command, { env: {...process.env, MM_identifier: oc.hashCode(this.config.port)} }, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
if (debug) console.log(`stdout: ${stdout}`);
if (stderr) console.error(`stderr 2: ${stderr}`);
});
},
// add express routes to allow invoking the form
extraRoutes: function () {
this.expressApp.get("/modules/MMM-Config/review", (req, res) => {
// redirect to config form
res.redirect(
//this.config.url +
"/modules/" + this.name + "/config.html?port=" + socket_io_port
);
});
},
getIPAddress(){
const nets = os.networkInterfaces();
const results = Object.create(null); // Or just '{}', an empty object
for (const name of Object.keys(nets)) {
for (const net of nets[name]) {
// Skip over non-IPv4 and internal (i.e. 127.0.0.1) addresses
if (net.family === 'IPv4' && !net.internal) {
if (!results[name]) {
results[name] = [];
}
results[name].push(net.address);
}
}
}
//console.log(JSON.stringify(results,null,2))
return results[Object.keys(results)[0]]
},
// module startup after receiving MM ready
startit() {
//console.log("in startit")
// if restart is the old pm2: value, fix it
if (this.config.restart.toLowerCase().startsWith("pm2:")){
const parts=this.config.restart.split(':')
this.config.restart = parts[0]
pm2_id=parts[1]
if(debug){
console.info(this.name+" pm2 id specified for restart="+pm2_id)
}
}
console.info(this.name+" restart parm ='"+this.config.restart+"'")
// handle how we restart, if any
switch (this.config.restart) {
case "static":
// setup the handler
let ep =
__dirname.split(path.sep).slice(0, -2).join(path.sep) +
"/node_modules/.bin/electron" +
(os.platform() == "win32" ? ".cmd" : "");
if(debug) console.log("electron path=" + ep);
require("electron-reload")(oc, {
electron: ep,
argv: [
__dirname.split(path.sep).slice(0, -2).join(path.sep) +
"/js/electron.js"
],
forceHardReset: true,
hardResetMethod: "exit"
});
break;
case "pm2":
// if the id was not set from config
if(pm2_id == -1){
// if the pm2 process_env is set
if(process.env.unique_id !== undefined){
// running under pm2
if (debug) console.log("getting pm2 process list");
exec("pm2 jlist", (error, stdout, stderr) => {
if (!error) {
let o=stdout.toString()
// maybe there is a pm2 error message in front of the json
if(!o.startsWith('[')){
// remove everything before process list
o=o.slice(o.indexOf('['))
}
if(debug){
console.log("json="+o)
}
let output = JSON.parse(o);
if (debug)
console.log(
"processing pm2 jlist output, " + output.length + " entries"
);
output.forEach((managed_process) => {
if(managed_process.pm2_env.status === 'online' ){
if(process.env.unique_id === managed_process.pm2_env.env.unique_id){
if (debug)
console.info(
"found our pm2 entry, id=" + managed_process.pm_id
);
pm2_id = managed_process.pm_id;
}
}
});
}
});
} else {
if(debug)
console.info(this.name+" MagicMirror not running under pm2")
}
}
else {
if(debug){
console.info(this.name+" pm2 restart app id is ", pm2_id)
}
}
break;
default:
}
this.command =
__dirname +
(os.platform() == "win32" ? "\\test_convert.cmd" : "/test_convert.sh");
this.command += this.config.force_update ? " override" : "";
if(debug){
console.log("command =" + this.command);
console.log("Starting module helper:" + this.name);
}
//console.log("environment vars="+JSON.stringify(process.env,null,2))
this.launchit();
this.extraRoutes();
this.remote_start(this);
},
// handle messages from our module// each notification indicates a different messages
// payload is a data structure that is different per message.. up to you to design this
socketNotificationReceived(notification, payload) {
// if config message from module
if (notification === "CONFIG") {
// save payload config info
//this.config = payload;
if(this.imageurl){
this.sendSocketNotification(
"qr_url",
this.imageurl
);
}
}
},
// get the module properties from the config.js entry
getConfigModule: function (m, source, index) {
// module name is not a direct key
let i = -1;
for (let x of source) {
if (x.module === m) {
if(debug)
console.log("found module "+m+" in "+oc.split('/').slice(-1)+" search for index="+index+" has index="+x.index-1)
// if we didn't care which module instance
// return first
// else return instance of matching index (if any)
i++;
if (
index === -2 ||
(x.index !== undefined && x.index-1 === index)
//|| i === index
) {
/*if(m.index && index != m.index )
{
continue
}*/
//console.log(" getconf="+ x.module)
return x;
}
}
}
return null;
},
reformat_array: function (data, self, key) {
if (Array.isArray(data[key])) {
if (debug)
console.log(
"reformat_array data present =" +
JSON.stringify(data[key], self.tohandler, 2)
);
if (debug) console.log("reformat_array to object from array");
let d = [];
if (debug) console.log("reformatting array of strings back to object");
data[key].forEach((element) => {
if (typeof element === "string") {
let tt;
if (element.startsWith("{") && element.endsWith("}")) {
if (debug)
console.log(
"reformat_array, about to parse=" +
element.replace(/\r?\n|\r/gm, "")
);
tt = JSON.parse(
element.replace(/\r?\n|\r/gm, ""),
self.fromhandler
);
if (debug) console.log("reformat_array, after parse=" + tt);
} else {
tt = element;
if (debug) console.log("reformat_array, just copy string=" + tt);
}
d.push(tt);
if (debug)
console.log(
" item added to object=" + JSON.stringify(d, self.tohandler, 2)
);
} else {
if (!Array.isArray(element)) {
if (debug)
console.log(
"reformat_array, just copy object=" +
JSON.stringify(element, self.tohandler, 2)
);
d.push(element);
}
}
});
if (debug)
console.log(
" new data contents=" + JSON.stringify(d, self.tohandler, 2)
);
data[key] = d;
if (debug)
console.log(
" new data contents=" + JSON.stringify(d, self.tohandler, 2)
);
} else if (!Array.isArray(data)) {
if (debug)
console.log(
"reformat_array data present =" +
JSON.stringify(data, self.tohandler, 2)
);
if (debug) console.log("reformat_array to array from object");
let d = [];
Object.keys(data).forEach((a) => {
if (debug) console.log("saving item=" + JSON.stringify(data[a]));
d.push(data[a]);
});
data = d;
}
},
object_from_key: function (object, key, type) {
if (debug) console.log("key = " + key);
if (key && key.includes(".")) {
let r = key.split(".");
if (debug)
console.log(
"object from key after split(.)=" + JSON.stringify(r, null, 2)
);
let left = r.shift().replace(/' '/g, ".");
let index = -1;
let li = left.split("[");
if (debug)
console.log(
"object from key after left split([)=" + JSON.stringify(li, null, 2)
);
left = li[0];
let obj = object[left];
if (debug)
console.log(
"object from key after indexing=" + JSON.stringify(obj, null, 2)
);
if (li.length > 1) {
index = parseInt(li[1]);
obj = obj[index];
}
if (debug) console.log("object[" + left + "]=" + JSON.stringify(obj));
if (type === "array" || r.length > 1 || obj !== undefined) {
if (obj != undefined) {
return this.object_from_key(obj, r.join("."), type);
} else key = left;
} else key = left;
}
if (debug)
console.log(type + " object from key=" + JSON.stringify(object[key]));
//console.log("checking item "+key+" in "+JSON.stringify(object, ' ',2))
if (object[key] === undefined)
//----------mykle
object[key] = JSON.parse(
type === "array"
? JSON.stringify(["fribble"])
: JSON.stringify({ fribble: null })
);
return { object: object, key: key };
},
clean_diff: function (diff) {
let object = diff; // JSON.parse(JSON.stringify(diff))
let a = Object.keys(object.added).length;
if (a > 0)
if (debug)
console.log(
"a=" + a + " " + JSON.stringify(Object.keys(object.added), " ", 2)
);
let d = Object.keys(object.deleted).length;
if (d > 0) {
if (debug)
console.log(
"d=" + d + " " + JSON.stringify(Object.keys(object.deleted), " ", 2)
);
Object.keys(object.deleted).forEach((k) => {
console.log("d=" + k + " " + JSON.stringify(object.deleted[k], " ", 2));
});
}
let u = Object.keys(object.updated).length;
if (u > 0)
if (debug)
console.log(
"u=" + u + " " + JSON.stringify(Object.keys(object.updated), " ", 2)
);
if (debug) console.log("a=" + a + " d=" + d + " u=" + u);
return a + d + u === 0;
},
isNumeric: function (n) {
return !isNaN(parseFloat(n)) && isFinite(parseInt(n));
},
// check to see if objects are the same, including sub objects..
// return a list of flat variables
// and subobject/variable name
objectsAreSame: function (x, y) {
if (debug)
console.log(
"objectsAreSame x=" + JSON.stringify(x,this.tohandler, 2) + " y=" + JSON.stringify(y, this.tohandler, 2)
);
var proplist = [];
for (var propertyName in y) {
if (
typeof x[propertyName] === "object" &&
typeof y[propertyName] === "object"
) {
if (debug) console.log("comparing objects=" + propertyName);
if(Array.isArray(x[propertyName]) && Array.isArray(y[propertyName])){
if(JSON.stringify(x[propertyName])!==JSON.stringify(y[propertyName])){
proplist.push(propertyName)
}
}
else // is object, not array
{
let t = {};
let r = this.objectsAreSame(x[propertyName], y[propertyName]);
if (r.length) {
t[propertyName] = r;
if (debug) console.log("object list=" + JSON.stringify(t, null, 2));
proplist = proplist.concat(t);
if (debug)
console.log(
"concat object list=" + JSON.stringify(proplist, null, 2)
);
}
}
} else if (x[propertyName] !== y[propertyName]) {
if (debug) console.log("comparing prop=" + propertyName);
proplist.push(propertyName);
}
}
if (debug)
console.log("returning list=" + JSON.stringify(proplist, null, 2));
return proplist;
},
merge_nested: function (output, input, changed_vars) {
changed_vars.forEach((sub_object) => {
// loop thru array of objects
if (debug)
console.log("changed object=" + JSON.stringify(sub_object, null, 2));
Object.keys(sub_object).forEach((entry) => {
// e = OS
if (debug)
console.log(
"changed object name=" +
entry +
" array=" +
Array.isArray(sub_object[entry])
);
if (output[entry] === undefined) output[entry] = {};
_.assign(output[entry], _.pick(input[entry], sub_object[entry]));
if (debug) console.log(" merged =" + JSON.stringify(output, null, 2));
let r = sub_object[entry].filter((x) => {
if (debug) console.log("testing item in array=" + typeof x + " " + x);
if (typeof x === "object") return true;
});
if (r.length) {
if (debug) console.log("have more to merge for sub_object");
this.merge_nested(output[entry], input[entry], r);
}
});
});
},
// we need to figure out what changed in the data
// analogSize in config, but no config object in config.js
// so picking the keys for the config doesn't help, not present
// and then merge those in.. ( clock, defaults, )
mergeModule: function (module_entry, data, defaults) {
if (debug) console.log("merge data=" + JSON.stringify(data, this.tohandler, 2));
let keys = _.keys(module_entry);
if (!keys.includes("disabled")) keys.push("disabled");
if (!keys.includes("label")) keys.push("label");
keys = _.without(keys, "config");
if(debug){
console.log("merge keys for fields="+JSON.stringify(keys))
}
_.assign(module_entry, _.pick(data, keys));
if (debug)
console.log(
"config after assign=" +
JSON.stringify(module_entry, null, 2) +
" keys=" +
JSON.stringify(keys, null, 2)
);
// if the module_entry config section exists
if (module_entry["config"] !== undefined) {
// loop thru all the items in the existing config
if (debug) console.log("checking for items in old config data, same as defaults");
// loop thru the config.js version of the module config
Object.keys(data.config).forEach((key) => {
// if that key isn't in the new data
if(debug){
console.log("comparing module data with defaults for key="+key+ " new="+JSON.stringify(module_entry.config[key])+" default="+JSON.stringify(defaults[key]))
}
if (JSON.stringify(module_entry.config[key],this.tohandler) === JSON.stringify(defaults[key],this.tohandler)) {
if (debug)
console.log("deleting item=" + key + " from old config data");
delete module_entry.config[key];
} else{
if(debug)
console.log("data not equal for key="+key)
}
});
}
// compare the form data with the info from the defaults..
let keydiff = this.objectsAreSame(defaults, data.config); // this is deep compare
if(debug)
console.log("keys different data vs defaults="+JSON.stringify(keydiff))
if(module_entry.config !== undefined){
let keydiff2=this.objectsAreSame(data.config,module_entry.config)
if(debug)
console.log("keys different data vs prior config="+JSON.stringify(keydiff2))
keydiff2.forEach(k=>{
if(!keydiff.includes(k))
keydiff.push(k);
})
}
if (debug)
console.log("keydiff after assign=" + JSON.stringify(keydiff, null, 2));
if (keydiff.length) {
if (debug)
console.log("keydiff in merge=" + JSON.stringify(keydiff, null, 2));
if (module_entry.config === undefined) module_entry.config = {};
// assign only does flat variables, not subobjects (aka shallow assign)
_.assign(module_entry.config, _.pick(data.config, keydiff));
// filter out the flat variables
// leaving only sub objects
let nested = keydiff.filter((x) => {
if (typeof x === "object") return true;
});
// of ther were any subobjects
if (nested.length) {
// handle nested objects
this.merge_nested(module_entry.config, data.config, nested);
}
}
return module_entry;
},
fixobject_name: function (object, key, newname) {
if (debug) console.log("splitting key=" + key);
let x = key.split(".");
if (debug)
console.log("processing mangled_names, part=" + JSON.stringify(x));
if (x.length == 1) {
object[newname] = object[x[0]];
delete object[x[0]];
} else {
let l = x.shift();
this.fixobject_name(object[l], x.join("."), newname);
}
},
tohandler: function (key, value) {
if (typeof value === "function") {
return value + ""; // implicitly `toString` it
}
return value;
},
fromhandler: function (key, value) {
if (
value &&
typeof value == "string" &&
(value.startsWith("(") || value.startsWith("function(")) &&
value.endsWith("}")
) {
return eval("(" + value + ")");
}
return value;
},
clone: function (input, self) {
return JSON.parse(JSON.stringify(input, self.tohandler), self.fromhandler);
},
getpair: function (datasource, key, self) {
if (debug) console.log("getpair key=" + key);
let left = key;
if (key.includes(".")) {
let v = key.split(".");
// check for any array notation
let li=v[0].split('[')
// if there WAS an arry index, then rest is in the next element
if(li.length >1){
// make it numeric
let index= parseInt(li[1])
// get the left edge
datasource= datasource[li[0]]
// look only at this instance
left = index
v.shift()
} else
left = v.shift();
if (v.length) {
if (datasource[left] === undefined)
datasource[left] = self.clone({}, self);
if (debug) console.log("getpair remaining key=" + v.join("."));
return self.getpair(datasource[left], v.join("."), self);
}
}
if(debug)
console.log("left="+left+" datasource="+JSON.stringify(datasource,null,2))
if (datasource[left] == undefined) datasource[left] = self.clone({}, self);
return datasource[left];
},
setpair: function (datasource, key, self, value) {
if (debug) console.log("setpair key=" + key);
let left = key;
if (key.includes(".")) {
let v = key.split(".");
// check for any array notation
let li=v[0].split('[')
// if there WAS an arry index, then rest is in the next element
if(li.length >1){
// make it numeric
let index= parseInt(li[1])
// get the left edge
datasource= datasource[li[0]]
// look only at this instance
left = index
// discard the 1st array element
v.shift()
} else
// use and discard the 1st element
left = v.shift();
if (v.length) {
if (datasource[left] === undefined)
datasource[left] = self.clone({}, self);
if (debug) console.log("getpair remaining key=" + v.join("."));
return self.setpair(datasource[left], v.join("."), self, value);
}
}
if (debug)
console.log(
"setpair setting value=" + JSON.stringify(value, self.tohandler, 2)
);
datasource[left] = self.clone(value, self);
return datasource[left];
},
check_for_module_file: function(module_name,type) {
// get the name of the module schema file
// check in the module folder
let fn
let isDefault = defaultModules.includes(module_name);
if(type === 'schema'){
fn = isDefault
? path.join(
__dirname,
"..",
"default",
our_name +
"."+
module_jsonform_info_name.slice(1)
)
: path.join(__dirname, "..", module_name+"."+module_jsonform_info_name.slice(1));
if(debug)
console.log("1 checking for module ="+module_name+" in "+fn);
// if the module doesn't supply a schema file
if (!fs.existsSync(fn)) {
fn = path.join(
__dirname,
"schemas",
//"../../MagicMirror/modules",
module_name + "." + module_jsonform_info_name.slice(1)
);
// check to see if we have one
if (!fs.existsSync(fn)) {
fn = null;
}
}
} else if(type=='converter'){
fn = isDefault
? path.join(
__dirname,
"..",
"default",
module_name,
"MMM-Config"+"."+module_jsonform_converter.slice(1)
)
: path.join(__dirname, "..", module_name,our_name+"."+module_jsonform_converter.slice(1));
if(debug)
console.log("1 checking for module ="+module_name+" in "+fn);
// if the module doesn't supply a schema file
if (!fs.existsSync(fn)) {
fn = path.join(
__dirname,
"schemas",
//"../../MagicMirror/modules",
module_name+module_jsonform_converter
);
if(debug)
console.log("2 checking for module ="+module_name+" in "+fn);
//console.log("filename 2="+fn);
// check to see if we have one
if (!fs.existsSync(fn)) {
fn = null;
}
}
}
return fn;
},
//
// handle form submission from web browser
//
process_submit: async function (data, self, socket) {
let cfg = require(__dirname + "/defaults_"+oc.hashCode(this.config.port)+".js");
//if(debug) console.log(" loaded module info="+JSON.stringify(cfg,self.tohandler,2))
// cleanup the arrays
if (debug) console.log("\nstart processing form submit\n");
if (debug)
console.log("posted data=" + JSON.stringify(data, self.tohandler, 2));
if (1) {
if (debug)
console.log(
"potential empty objects=" +
JSON.stringify(data.objects, self.tohandler, 2)
);
data.objects.forEach((p) => {
let t = p;
while (t.includes("..")) t = t.replace("..", ".");
if (debug) console.log("processing for " + p + " cleanup=" + t);
let v = t.split(".");
if (debug)
console.log("processing for " + p + " parts=" + JSON.stringify(v));
// "MMM-AlexaControl.config.devices.devices",
let o = self.object_from_key(data, t, "object");
if (debug) console.log("object=" + JSON.stringify(o, " ", 2));
if (o && _.isEqual(o.object[o.key], { fribble: null })) {
if (debug) console.log("reset missing object");
o.object[o.key] = {};
}
if (debug) {
let rr = data[v[0]];
console.log(
"done 3 setting object=" +
JSON.stringify(rr, self.tohandler, 2) +
"\n"
);
}
});
delete data.objects;
if (debug) console.log("restoring converted (obj->array) objects\n");
data.convertedObjects.forEach((key) => {
if (debug) console.log("converted object found item for key=" + key);
let obj = self.object_from_key(data, key, "object");
// if we have data in the form
// its in the wrong format, array instead of object
// so make each array element a new object for this module object
if (obj) {
// could have been restored by the missing object function above
//
if (typeof obj.object === "array") {
if (debug) console.log("found item as array");
let result = {};
// loop thru the elements of the array
for (let i in obj.object) {
// save in has
// supposedly these are going to be 'objects' themselves
// but the editor was a textarea.. so no validation
result[i] = obj.object[i];
}
// overlay the object with the new results
obj.object = self.clone(result, self);
}
// didn't find any form data
else {
// wasn't an array, so...
if (debug)
console.log(
" found converted object for key=" + key + " but not an array\n"
);
if (_.isEqual(obj.object[obj.key], { fribble: null })) {
// it was the lookup inserted dummy
if (debug)
console.log(
"converted object reset missing object key=" + key + "\n"
);
obj.object[obj.key] = {};
} else {
if (debug) console.log("converted object already restored");
}
}
}
});
if (debug)
console.log(
"\npotential arrays=" + JSON.stringify(data.arrays, self.tohandler, 2)
);
// loop thru the list of potential arrays in the form that might not be returned cause they are empty
for (const p of data.arrays) {
let t = p;
while (t.includes("..")) t = t.replace("..", ".");
if (debug) console.log("processing for " + p + " cleanup=" + t);
let nested = false;
if (p.endsWith("[]")) {
nested = true;
t = p.slice(0, -2);
}
let v = t.split(".");
if (debug)
console.log("processing for " + p + " parts=" + JSON.stringify(v));
// MMM-GooglePhotos.config.albums"
let rr = data[v[0]];
let o = self.object_from_key(data, t, "array");
if (debug) console.log("array=" + JSON.stringify(o, self.tohandler, 2));
// if these was no object found (the function inserted dummy data for us to find )
// if we find it, the array was not returned from the form handler
// this is standard web form technology that we have to recover from
if (_.isEqual(o.object[o.key], ["fribble"])) {
if (debug) console.log("items equal key=" + o.key);
// check to see if the returned key is the end of the total key
// if not, a middle part of the key (array embedding array) was also not returned
if (!t.endsWith(o.key)) {
// if the key is config
if (o.key === "config") {
if (debug)
console.log(
"setting array=" + JSON.stringify(o.object) + " key=" + o.key
);
o.object[o.key] = {};
if (debug)
console.log(
"done setting array=" +
JSON.stringify(o.object) +
" key=" +
o.key
);
o.object = o.object[o.key];
if (debug)
console.log(
"done 1 setting array=" +
JSON.stringify(o.object) +
" key=" +
o.key
);
// get last entry
o.key = v.slice(-1);
if (debug)
console.log(
"done 2 setting array=" +
JSON.stringify(o.object) +
" key=" +
o.key
);
}
}
if (nested) {
o.object[o.key] = [[]];
//console.log("set nested")
} else {
o.object[o.key] = [];
//console.log("set NOT nested")
}
} else {
// was this a converted object?
if(debug) console.log("is this item="+p+" a converted to array? "+data.convertedObjects.includes(p))
if(data.convertedObjects.includes(p)){
// present but NOT an empty array
if (debug) console.log("reformat_array key=" + o.key);
self.reformat_array(o.object, self, o.key);
}
}
if (debug)
console.log(
"done 3 setting array=" +
JSON.stringify(rr, self.tohandler, 2) +
"\n"
);
}
delete data.arrays;
delete data.convertedObjects;
}
// cleanup the pairs
if (1) {
if (debug)
console.log(
"potential pairs=\n" + JSON.stringify(data.pairs, self.tohandler, 2)
);
// loop thru the variables we treateed as pairs (key/value)
// and put them back in their expected form { key:value }
for (const p of Object.keys(data["pairs"])) {
let modified_value = {};
let j = self.getpair(data, p, self);
// if(debug)
// console.log("found data for key="+p+"="+JSON.stringify(data['calendar'],null,2))