-
Notifications
You must be signed in to change notification settings - Fork 149
/
node_helper.js
1176 lines (1073 loc) · 48.8 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
/* MagicMirror²
* Module: Remote Control
*
* By Joseph Bethge
* MIT Licensed.
*/
/* jshint node: true, esversion: 6 */
const NodeHelper = require("node_helper");
const path = require("path");
const url = require("url");
const fs = require("fs");
const util = require("util");
const exec = require("child_process").exec;
const Log = require("logger");
const os = require("os");
const simpleGit = require("simple-git");
const bodyParser = require("body-parser");
const express = require("express");
const _ = require("lodash");
var defaultModules = require(path.resolve(__dirname + "/../../modules/default/defaultmodules.js"));
Module = {
configDefaults: {},
notificationHandler: {},
register(name, moduleDefinition) {
Module.configDefaults[name] = moduleDefinition.defaults;
/* API EXTENSION - Added v2.0.0 */
Module.notificationHandler[name] = ("notificationReceived" in moduleDefinition) ?
moduleDefinition.notificationReceived.toString() : "";
}
};
module.exports = NodeHelper.create(Object.assign({
// Subclass start method.
start: function() {
var self = this;
this.initialized = false;
Log.log("Starting node helper for: " + self.name);
// load fall back translation
self.loadTranslation("en");
this.configOnHd = {};
this.configData = {};
this.waiting = [];
this.template = "";
this.modulesAvailable = [];
this.modulesInstalled = [];
this.delayedQueryTimers = {};
fs.readFile(path.resolve(__dirname + "/remote.html"), function(err, data) {
self.template = data.toString();
});
this.combineConfig();
this.updateModuleList();
this.createRoutes();
/* API EXTENSION - Added v2.0.0 */
this.externalApiRoutes = {};
this.moduleApiMenu = {};
},
stop() {
// Clear all timeouts for clean shutdown
Object.keys(this.delayedQueryTimers).forEach(t => {
clearTimeout(this.delayedQueryTimers[t]);
});
},
onModulesLoaded() {
/* CALLED AFTER MODULES AND CONFIG DATA ARE LOADED */
/* API EXTENSION - Added v2.0.0 */
this.createApiRoutes();
this.loadTimers();
},
loadTimers() {
var delay = 24*3600;
var self = this;
clearTimeout(this.delayedQueryTimers['update'])
this.delayedQueryTimers['update'] = setTimeout(function () {
self.updateModuleList();
self.loadTimers();
}, delay*1000);
},
combineConfig() {
// function copied from MagicMirrorOrg (MIT)
var defaults = require(__dirname + "/../../js/defaults.js");
var configFilename = path.resolve(__dirname + "/../../config/config.js");
if (typeof(global.configuration_file) !== "undefined") {
configFilename = global.configuration_file;
}
this.thisConfig = {};
try {
fs.accessSync(configFilename, fs.F_OK);
var c = require(configFilename);
var config = Object.assign({}, defaults, c);
this.configOnHd = config;
// Get the configuration for this module.
if ("modules" in this.configOnHd) {
let thisModule = this.configOnHd.modules.find(m => m.module === 'MMM-Remote-Control');
if (thisModule && "config" in thisModule) {
this.thisConfig = thisModule.config;
}
}
} catch (e) {
if (e.code == "ENOENT") {
console.error("MMM-Remote-Control WARNING! Could not find config file. Please create one. Starting with default configuration.");
this.configOnHd = defaults;
} else if (e instanceof ReferenceError || e instanceof SyntaxError) {
console.error("MMM-Remote-Control WARNING! Could not validate config file. Please correct syntax errors. Starting with default configuration.");
this.configOnHd = defaults;
} else {
console.error("MMM-Remote-Control WARNING! Could not load config file. Starting with default configuration. Error found: " + e);
this.configOnHd = defaults;
}
}
this.loadTranslation(this.configOnHd.language);
},
createRoutes() {
var self = this;
this.expressApp.get("/remote.html", function(req, res) {
if (self.template === "") {
res.send(503);
} else {
res.contentType("text/html");
res.set('Content-Security-Policy', "frame-ancestors http://*:*")
var transformedData = self.fillTemplates(self.template);
res.send(transformedData);
}
});
this.expressApp.get("/get", function(req, res) {
var query = url.parse(req.url, true).query;
self.answerGet(query, res);
});
this.expressApp.post("/post", function(req, res) {
var query = url.parse(req.url, true).query;
self.answerPost(query, req, res);
});
this.expressApp.get("/config-help.html", function(req, res) {
var query = url.parse(req.url, true).query;
self.answerConfigHelp(query, res);
});
this.expressApp.get("/remote", function(req, res) {
var query = url.parse(req.url, true).query;
if (query.action && ["COMMAND"].indexOf(query.action)===-1) {
var result = self.executeQuery(query, res);
if (result === true) {
return;
}
}
res.send({ "status": "error", "reason": "unknown_command", "info": "original input: " + JSON.stringify(query) });
});
},
capitalizeFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
},
formatName(string) {
string = string.replace(/MMM-/g, '').replace(/([a-z])([A-Z])/g, "$1 $2").replace(/(^|[-_])(\w)/g, function($0, $1, $2) {
return ($1 && ' ') + $2.toUpperCase();
});
return string;
},
updateModuleList(force) {
var self = this;
var downloadModules = require('./scripts/download_modules');
downloadModules({
force: force,
callback: (result) => {
if (result && result.startsWith("ERROR")) { console.error(result); }
this.readModuleData();
}
});
},
readModuleData() {
var self = this;
fs.readFile(path.resolve(__dirname + "/modules.json"), (err, data) => {
self.modulesAvailable = JSON.parse(data.toString());
for (let i = 0; i < self.modulesAvailable.length; i++) {
self.modulesAvailable[i].name = self.formatName(self.modulesAvailable[i].longname);
self.modulesAvailable[i].isDefaultModule = false;
}
for (let i = 0; i < defaultModules.length; i++) {
self.modulesAvailable.push({
longname: defaultModules[i],
name: self.capitalizeFirst(defaultModules[i]),
isDefaultModule: true,
installed: true,
author: "MagicMirrorOrg",
desc: "",
id: "MagicMirrorOrg/MagicMirror",
url: "https://docs.magicmirror.builders/modules/introduction.html"
});
var module = self.modulesAvailable[self.modulesAvailable.length - 1];
var modulePath = "modules/default/" + defaultModules[i];
self.loadModuleDefaultConfig(module, modulePath, i === defaultModules.length-1);
}
// now check for installed modules
fs.readdir(path.resolve(__dirname + "/.."), function(err, files) {
let installedModules = files.filter(f => ['node_modules', 'default', 'README.md'].indexOf(f) === -1);
installedModules.forEach((dir, i, a) => {
self.addModule(dir, (i === installedModules.length - 1));
});
});
});
},
getModuleDir() {
return this.configOnHd.foreignModulesDir ? this.configOnHd.foreignModulesDir : (this.configOnHd.paths ? this.configOnHd.paths.modules : "modules");
},
addModule(folderName, lastOne) {
var self = this;
var modulePath = this.getModuleDir() + "/" + folderName;
fs.stat(modulePath, (err, stats) => {
if (stats.isDirectory()) {
var isInList = false;
var currentModule;
self.modulesInstalled.push(folderName);
for (var i = 0; i < self.modulesAvailable.length; i++) {
if (self.modulesAvailable[i].longname === folderName) {
isInList = true;
self.modulesAvailable[i].installed = true;
currentModule = self.modulesAvailable[i];
}
}
if (!isInList) {
var newModule = {
longname: folderName,
name: self.formatName(folderName),
isDefaultModule: false,
installed: true,
author: "unknown",
desc: "",
id: "local/" + folderName,
url: ""
};
self.modulesAvailable.push(newModule);
currentModule = newModule;
}
self.loadModuleDefaultConfig(currentModule, modulePath, lastOne);
// check for available updates
var stat;
try {
stat = fs.statSync(path.join(modulePath, '.git'));
} catch (err) {
// Error when directory .git doesn't exist
// This module is not managed with git, skip
return;
}
var sg = simpleGit(modulePath);
sg.fetch().status(function(err, data) {
if (!err) {
if (data.behind > 0) {
currentModule.updateAvailable = true;
}
}
});
if (!isInList) {
sg.getRemotes(true, function(error, result) {
if (error) {
Log.error(error);
}
try {
var baseUrl = result[0].refs.fetch;
// replacements
baseUrl = baseUrl.replace(".git", "").replace("github.com:", "github.com/");
// if cloned with ssh
currentModule.url = baseUrl.replace("git@", "https://");
} catch (e) {
// Something happened. Skip it.
return;
}
});
}
}
});
},
loadModuleDefaultConfig(module, modulePath, lastOne) {
// function copied from MagicMirrorOrg (MIT)
var filename = path.resolve(modulePath + "/" + module.longname + ".js");
try {
fs.accessSync(filename, fs.F_OK);
var jsfile = require(filename);
/* Defaults are stored when Module.register is called during require(filename); */
} catch (e) {
if (e.code == "ENOENT") {
console.error("ERROR! Could not find main module js file for " + module.longname);
} else if (e instanceof ReferenceError || e instanceof SyntaxError) {
console.error("ERROR! Could not validate main module js file.");
console.error(e);
} else {
console.error("ERROR! Could not load main module js file. Error found: " + e);
}
}
if (lastOne) { this.onModulesLoaded(); }
},
answerConfigHelp(query, res) {
if (defaultModules.indexOf(query.module) !== -1) {
// default module
var dir = path.resolve(__dirname + "/..");
let git = simpleGit(dir);
git.revparse(["HEAD"], function(error, result) {
if (error) {
Log.error(error);
}
res.writeHead(302, { 'Location': "https://github.com/MagicMirrorOrg/MagicMirror/tree/" + result.trim() + "/modules/default/" + query.module });
res.end();
});
return;
}
var modulePath = this.getModuleDir() + "/" + query.module;
let git = simpleGit(modulePath);
git.getRemotes(true, function(error, result) {
if (error) {
Log.error(error);
}
var baseUrl = result[0].refs.fetch;
// replacements
baseUrl = baseUrl.replace(".git", "").replace("github.com:", "github.com/");
// if cloned with ssh
baseUrl = baseUrl.replace("git@", "https://");
git.revparse(["HEAD"], function(error, result) {
if (error) {
Log.error(error);
}
res.writeHead(302, { 'Location': baseUrl + "/tree/" + result.trim() });
res.end();
});
});
},
getConfig() {
var config = this.configOnHd;
for (let i = 0; i < config.modules.length; i++) {
var current = config.modules[i];
var def = Module.configDefaults[current.module];
if (!("config" in current)) {
current.config = {};
}
if (!def) {
def = {};
}
for (var key in def) {
if (!(key in current.config)) {
current.config[key] = def[key];
}
}
}
return config;
},
removeDefaultValues(config) {
// remove cached version
delete require.cache[require.resolve(__dirname + "/../../js/defaults.js")];
// then reload default config
var defaultConfig = require(__dirname + "/../../js/defaults.js");
for (let key in defaultConfig) {
if (defaultConfig.hasOwnProperty(key) && config && config.hasOwnProperty(key) && _.isEqual(defaultConfig[key], config[key])) {
delete config[key];
}
}
for (let i = 0; i < config.modules.length; i++) {
var current = config.modules[i];
var def = Module.configDefaults[current.module];
if (!def) {
def = {};
}
for (let key in def) {
if (def.hasOwnProperty(key) && current.config.hasOwnProperty(key) && _.isEqual(def[key], current.config[key])) {
delete current.config[key];
}
}
// Log.log(current.config);
if (current.config === {}) {
delete current[config];
continue;
}
// Log.log(current);
}
return config;
},
answerPost(query, req, res) {
var self = this;
if (query.data === "config") {
var backupHistorySize = 5;
var configPath = path.resolve("config/config.js");
var best = -1;
var bestTime = null;
for (var i = backupHistorySize - 1; i > 0; i--) {
let backupPath = path.resolve("config/config.js.backup" + i);
try {
var stats = fs.statSync(backupPath);
if (best === -1 || stats.mtime < bestTime) {
best = i;
bestTime = stats.mtime;
}
} catch (e) {
if (e.code === "ENOENT") {
// does not exist yet
best = i;
bestTime = "0000-00-00T00:00:00Z";
}
}
}
if (best === -1) {
// can not backup, panic!
console.error("MMM-Remote-Control Error! Backing up config failed, not saving!");
self.sendResponse(res, new Error("Backing up config failed, not saving!"), { query: query });
return;
}
let backupPath = path.resolve("config/config.js.backup" + best);
var source = fs.createReadStream(configPath);
var destination = fs.createWriteStream(backupPath);
// back up last config
source.pipe(destination, { end: false });
source.on("end", () => {
self.configOnHd = self.removeDefaultValues(req.body);
var header = "/*************** AUTO GENERATED BY REMOTE CONTROL MODULE ***************/\n\nvar config = \n";
var footer = "\n\n/*************** DO NOT EDIT THE LINE BELOW ***************/\nif (typeof module !== 'undefined') {module.exports = config;}\n";
fs.writeFile(configPath, header + util.inspect(self.configOnHd, {
showHidden: false,
depth: null,
maxArrayLength: null,
compact: false
}) + footer,
(error) => {
query.data = "config_update";
if (error) {
self.sendResponse(res, error, { query: query, backup: backupPath, data: self.configOnHd });
}
console.info("MMM-Remote-Control saved new config!");
console.info("Used backup: " + backupPath);
self.sendResponse(res, undefined, { query: query, backup: backupPath, data: self.configOnHd });
}
);
});
}
},
answerGet(query, res) {
var self = this;
if (query.data === "moduleAvailable") {
this.modulesAvailable.sort(function(a, b) { return a.name.localeCompare(b.name); });
this.sendResponse(res, undefined, { query: query, data: this.modulesAvailable });
return;
}
if (query.data === "moduleInstalled") {
var filterInstalled = function(value) {
return value.installed && !value.isDefaultModule;
};
var installed = self.modulesAvailable.filter(filterInstalled);
installed.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
this.sendResponse(res, undefined, { query: query, data: installed });
return;
}
if (query.data === "translations") {
this.sendResponse(res, undefined, { query: query, data: this.translation });
return;
}
if (query.data === "mmUpdateAvailable") {
var sg = simpleGit(__dirname + "/..");
sg.fetch().status((err, data) => {
if (!err) {
if (data.behind > 0) {
this.sendResponse(res, undefined, { query: query, result: true });
return;
}
}
this.sendResponse(res, undefined, { query: query, result: false });
});
return;
}
if (query.data === "config") {
this.sendResponse(res, undefined, { query: query, data: this.getConfig() });
return;
}
if (query.data === "classes") {
var thisconfig = this.getConfig().modules.find(m => m.module === "MMM-Remote-Control").config || {};
this.sendResponse(res, undefined, { query: query, data: thisconfig.classes ? thisconfig.classes : {} });
return;
}
if (query.data === "saves") {
var backupHistorySize = 5;
let times = [];
for (var i = backupHistorySize - 1; i > 0; i--) {
let backupPath = path.resolve("config/config.js.backup" + i);
try {
var stats = fs.statSync(backupPath);
times.push(stats.mtime)
} catch (e) {
continue;
}
}
this.sendResponse(res, undefined, { query: query, data: times.sort((a,b) => b - a) });
return
}
if (query.data === "defaultConfig") {
if (!(query.module in Module.configDefaults)) {
this.sendResponse(res, undefined, { query: query, data: {} });
} else {
this.sendResponse(res, undefined, { query: query, data: Module.configDefaults[query.module] });
}
return;
}
if (query.data === "modules") {
if (!this.checkInititialized(res)) { return; }
this.callAfterUpdate(() => {
this.sendResponse(res, undefined, { query: query, data: self.configData.moduleData });
});
return;
}
if (query.data === "brightness") {
if (!this.checkInititialized(res)) { return; }
this.callAfterUpdate(() => {
this.sendResponse(res, undefined, { query: query, result: self.configData.brightness });
});
return;
}
if (query.data === "userPresence") {
this.sendResponse(res, undefined, { query: query, result: this.userPresence });
return;
}
// Unknown Command, Return Error
this.sendResponse(res, "Unknown or Bad Command.", query);
},
callAfterUpdate(callback, timeout) {
if (timeout === undefined) {
timeout = 3000;
}
var waitObject = {
finished: false,
run: function() {
if (this.finished) {
return;
}
this.finished = true;
this.callback();
},
callback: callback
};
this.waiting.push(waitObject);
this.sendSocketNotification("UPDATE");
setTimeout(function() {
waitObject.run();
}, timeout);
},
delayedQuery(query, res) {
if (query.did in this.delayedQueryTimers) {
clearTimeout(this.delayedQueryTimers[query.did]);
delete this.delayedQueryTimers[query.did];
}
if (!query.abort) {
this.delayedQueryTimers[query.did] = setTimeout(() => {
this.executeQuery(query.query);
delete this.delayedQueryTimers[query.did];
}, (("timeout" in query) ? query.timeout : 10) * 1000);
}
this.sendResponse(res, undefined, query);
},
sendResponse(res, error, data) {
let response = { success: true };
let status = 200;
let result = true;
if (error) {
Log.error(error);
response = { success: false, status: "error", reason: "unknown", info: error };
status = 400;
result = false;
}
if (data) {
response = Object.assign({}, response, data);
}
if (res) {
if ("isSocket" in res && res.isSocket) {
this.sendSocketNotification("REMOTE_ACTION_RESULT", response);
} else {
res.status(status).json(response);
}
}
return result;
},
monitorControl(action, opts, res) {
let status = "unknown";
let offArr = ["false","TV is off","standby","display_power=0"];
let monitorOnCommand = (this.initialized && "monitorOnCommand" in this.thisConfig.customCommand) ?
this.thisConfig.customCommand.monitorOnCommand :
"vcgencmd display_power 1";
let monitorOffCommand = (this.initialized && "monitorOffCommand" in this.thisConfig.customCommand) ?
this.thisConfig.customCommand.monitorOffCommand :
"vcgencmd display_power 0";
let monitorStatusCommand = (this.initialized && "monitorStatusCommand" in this.thisConfig.customCommand) ?
this.thisConfig.customCommand.monitorStatusCommand :
"vcgencmd display_power -1";
switch (action) {
case "MONITORSTATUS": exec(monitorStatusCommand, opts, (error, stdout, stderr) => {
status = offArr.indexOf(stdout.trim()) !== -1 ? "off" : "on";
this.checkForExecError(error, stdout, stderr, res, { monitor: status });
return;
});
break;
case "MONITORTOGGLE": exec(monitorStatusCommand, opts, (error, stdout, stderr) => {
status = offArr.indexOf(stdout.trim()) !== -1 ? "off" : "on";
if(status === "on") this.monitorControl("MONITOROFF", opts, res);
else this.monitorControl("MONITORON", opts, res);
return;
});
break;
case "MONITORON": exec(monitorOnCommand, opts, (error, stdout, stderr) => {
this.checkForExecError(error, stdout, stderr, res, { monitor: "on" });
});
this.sendSocketNotification("USER_PRESENCE", true);
break;
case "MONITOROFF": exec(monitorOffCommand, opts, (error, stdout, stderr) => {
this.checkForExecError(error, stdout, stderr, res, { monitor: "off" });
});
this.sendSocketNotification("USER_PRESENCE", false);
break;
}
},
shutdownControl(action, opts, res) {
let shutdownCommand = (this.initialized && "shutdownCommand" in this.thisConfig.customCommand) ?
this.thisConfig.customCommand.shutdownCommand :
"sudo shutdown -h now";
let rebootCommand = (this.initialized && "rebootCommand" in this.thisConfig.customCommand) ?
this.thisConfig.customCommand.rebootCommand :
"sudo shutdown -r now";
if (action === "SHUTDOWN") {
exec(shutdownCommand, opts, (error, stdout, stderr, res) => { this.checkForExecError(error, stdout, stderr, res); });
}
if (action === "REBOOT") {
exec(rebootCommand, opts, (error, stdout, stderr, res) => { this.checkForExecError(error, stdout, stderr, res); });
}
},
executeQuery(query, res) {
var self = this;
var opts = { timeout: 15000 };
if (["SHUTDOWN", "REBOOT"].indexOf(query.action) !== -1) {
this.shutdownControl(query.action, opts, res);
return true;
}
if (query.action === "RESTART" || query.action === "STOP") {
this.controlPm2(res, query);
return true;
}
if (query.action === "COMMAND") {
if (this.thisConfig.customCommand && this.thisConfig.customCommand[query.command]) {
exec(this.thisConfig.customCommand[query.command], opts, (error, stdout, stderr) => {
self.checkForExecError(error, stdout, stderr, res, { stdout: stdout });
});
} else {
self.sendResponse(res, new Error("Command not found"), query);
}
return true;
}
if (query.action === "USER_PRESENCE") {
this.sendSocketNotification("USER_PRESENCE", query.value);
this.userPresence = query.value;
this.sendResponse(res, undefined, query);
return true;
}
if (["MONITORON", "MONITOROFF", "MONITORTOGGLE", "MONITORSTATUS"].indexOf(query.action) !== -1) {
this.monitorControl(query.action, opts, res);
return true;
}
if (query.action === "HIDE" || query.action === "SHOW" || query.action === "TOGGLE") {
self.sendSocketNotification(query.action, query);
self.sendResponse(res);
return true;
}
if (query.action === "BRIGHTNESS") {
self.sendResponse(res);
self.sendSocketNotification(query.action, query.value);
return true;
}
if (query.action === "SAVE") {
self.sendResponse(res);
self.callAfterUpdate(function() { self.saveDefaultSettings(); });
return true;
}
if (query.action === "MODULE_DATA") {
self.callAfterUpdate(function() {
self.sendResponse(res, undefined, self.configData);
});
return true;
}
if (query.action === "INSTALL") {
self.installModule(query.url, res, query);
return true;
}
if (query.action === "REFRESH") {
self.sendResponse(res);
self.sendSocketNotification(query.action);
return true;
}
if (query.action === "HIDE_ALERT") {
self.sendResponse(res);
self.sendSocketNotification(query.action);
return true;
}
if (query.action === "SHOW_ALERT") {
self.sendResponse(res);
var type = query.type ? query.type : "alert";
var title = query.title ? query.title : "Note";
var message = query.message ? query.message : "Attention!";
var timer = query.timer ? query.timer : 4;
self.sendSocketNotification(query.action, {
type: type,
title: title,
message: message,
timer: timer * 1000
});
return true;
}
if (query.action === "UPDATE") {
self.updateModule(decodeURI(query.module), res);
return true;
}
if (query.action === 'NOTIFICATION') {
try {
var payload = {}; // Assume empty JSON-object if no payload is provided
if (typeof query.payload === 'undefined') {
payload = query.payload;
} else if (typeof query.payload === 'object') {
payload = query.payload;
} else if (typeof query.payload === 'string') {
if (query.payload.startsWith("{")) {
payload = JSON.parse(query.payload);
} else {
payload = query.payload;
}
}
this.sendSocketNotification(query.action, { 'notification': query.notification, 'payload': payload });
this.sendResponse(res);
return true;
} catch (err) {
Log.error("ERROR: ", err);
this.sendResponse(res, err, { reason: err.message });
return true;
}
}
if (query.action === "MANAGE_CLASSES") {
if (!query.payload || !query.payload.classes || !this.thisConfig || !this.thisConfig.classes) return;
let classes = [];
switch (typeof query.payload.classes) {
case 'string': classes.push(this.thisConfig.classes[query.payload.classes]); break;
case 'object': query.payload.classes.forEach((t)=>classes.push(this.thisConfig.classes[t]))
}
classes.forEach((cl)=>{
for(const act in cl) {
if (["SHOW","HIDE","TOGGLE"].includes(act.toUpperCase())) {
if(typeof cl[act] == 'string') this.sendSocketNotification(act.toUpperCase(),{ module: cl[act]});
else {
cl[act].forEach((t)=>{
this.sendSocketNotification(act.toUpperCase(),{ module: t});
})
}
}
}
})
this.sendResponse(res);
return;
}
if (["MINIMIZE", "TOGGLEFULLSCREEN", "DEVTOOLS"].indexOf(query.action) !== -1) {
try {
let electron = require("electron").BrowserWindow;
if (!electron) { throw "Could not get Electron window instance."; }
let win = electron.getAllWindows()[0]
switch (query.action) {
case "MINIMIZE":
win.minimize();
break;
case "TOGGLEFULLSCREEN":
win.setFullScreen(!win.isFullScreen());
break;
case "DEVTOOLS":
if (win.webContents.isDevToolsOpened()) win.webContents.closeDevTools();
else win.webContents.openDevTools();
break;
default:
}
this.sendResponse(res);
} catch (err) {
this.sendResponse(res, err);
}
return;
}
if (query.action === "DELAYED") {
/* Expects a nested query object
* {
* action: "DELAYED",
* did: "SOME_UNIQUE_ID",
* timeout: 10000, // Optional; Default 10000ms
* abort: false, // Optional; send to cancel
* query: {
* action: "SHOW_ALERT",
* title: "Delayed Alert!",
* message: "This is a delayed alert test."
* }
* }
* Resending with same ID resets delay, unless abort:true
*/
this.delayedQuery(query, res);
return;
}
self.sendResponse(res, new Error(`Invalid Option: ${ query.action }`));
return false;
},
installModule(url, res, data) {
var self = this;
simpleGit(path.resolve(__dirname + "/..")).clone(url, path.basename(url), function(error, result) {
if (error) {
Log.error(error);
self.sendResponse(res, error);
} else {
var workDir = path.resolve(__dirname + "/../" + path.basename(url));
exec("npm install", { cwd: workDir, timeout: 120000 }, (error, stdout, stderr) => {
if (error) {
Log.error(error);
self.sendResponse(res, error, Object.assign({ stdout: stdout, stderr: stderr }, data));
} else {
// success part
self.readModuleData();
self.sendResponse(res, undefined, Object.assign({ stdout: stdout }, data));
}
});
}
});
},
updateModule(module, res) {
Log.log("UPDATE " + (module || "MagicMirror"));
var self = this;
var path = __dirname + "/../../";
var name = "MM";
if (typeof module !== 'undefined' && module !== 'undefined') {
if (self.modulesAvailable) {
var modData = self.modulesAvailable.find(m => m.longname === module);
if (modData === undefined) {
this.sendResponse(res, new Error("Unknown Module"), { info: modules });
return;
}
path = __dirname + "/../" + modData.longname;
name = modData.name;
}
}
Log.log("path: " + path + " name: " + name);
var git = simpleGit(path);
git.reset('hard').then(() => {
git.pull((error, result) => {
if (error) {
Log.error(error);
self.sendResponse(res, error);
return;
}
if (result.summary.changes) {
exec("npm install", { cwd: path, timeout: 120000 }, (error, stdout, stderr) => {
if (error) {
Log.error(error);
self.sendResponse(res, error, { stdout: stdout, stderr: stderr });
} else {
// success part
self.readModuleData();
fs.readdir(path, function(err, files) {
if (files.includes("CHANGELOG.md")) {
var chlog = fs.readFileSync(path+"/CHANGELOG.md", 'utf-8')
self.sendResponse(res, undefined, { code: "restart", info: name + " updated.", chlog: chlog });
} else {
self.sendResponse(res, undefined, { code: "restart", info: name + " updated."});
}
})
//var chlog = fs.readFileSync(path+"/CHANGELOG.md")
//self.sendResponse(res, undefined, { code: "restart", info: name + " updated.", chlog: "" });
}
});
} else {
self.sendResponse(res, undefined, { code: "up-to-date", info: name + " already up to date." });
}
});
});
},
checkForExecError(error, stdout, stderr, res, data) {
if(error) Log.error(stderr);
this.sendResponse(res, error, data);
},
controlPm2(res, query) {
try {require('pm2')} catch (err) {
this.sendResponse(res, err, { reason: "PM2 not installed or unlinked" });
return;
}
var pm2 = require('pm2');
let processName = query.processName || this.thisConfig.pm2ProcessName || "mm";
pm2.connect((err) => {
if (err) {
this.sendResponse(res, err);
return;
}
var actionName = query.action.toLowerCase();
Log.log(`PM2 process: ${actionName} ${processName}`);
switch (actionName) {
case 'restart':
pm2.restart(processName, (err, apps) => {
this.sendResponse(res, undefined, { action: actionName, processName: processName});
if (err) { this.sendResponse(res, err); }
});
break;
case 'stop':
pm2.stop(processName, (err, apps) => {
this.sendResponse(res, undefined, { action: actionName, processName: processName });
pm2.disconnect();
if (err) { this.sendResponse(res, err); }
});
break;
}
});
},
translate(data) {
Object.keys(this.translation).forEach(t => {
let pattern = "%%TRANSLATE:" + t + "%%";
let re = new RegExp(pattern, "g");
data = data.replace(re, this.translation[t]);
});
return data;
},