forked from ioBroker/ioBroker.javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1672 lines (1480 loc) · 64.7 KB
/
main.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
/*
* Javascript adapter
*
* The MIT License (MIT)
*
* Copyright (c) 2014-2020 bluefox <[email protected]>,
*
* Copyright (c) 2014 hobbyquaker
*/
/* jshint -W097 */
/* jshint -W083 */
/* jshint strict: false */
/* jslint node: true */
/* jshint shadow: true */
'use strict';
let NodeVM;
let VMScript;
let vm;
if (true || parseInt(process.versions.node.split('.')[0]) < 6) {
vm = require('vm');
} else {
try {
const VM2 = require('vm2');
NodeVM = VM2.NodeVM;
VMScript = VM2.VMScript;
} catch (e) {
vm = require('vm');
}
}
const nodeFS = require('fs');
const nodePath = require('path');
const coffeeCompiler = require('coffee-compiler');
const tsc = require('virtual-tsc');
const typescript = require('typescript');
const nodeSchedule = require('node-schedule');
const Mirror = require('./lib/mirror');
const mods = {
fs: {},
dgram: require('dgram'),
crypto: require('crypto'),
dns: require('dns'),
events: require('events'),
http: require('http'),
https: require('https'),
net: require('net'),
os: require('os'),
path: require('path'),
util: require('util'),
child_process: require('child_process'),
suncalc: require('suncalc2'),
request: require('./lib/request'),
wake_on_lan: require('wake_on_lan')
};
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const words = require('./lib/words');
const sandBox = require('./lib/sandbox');
const eventObj = require('./lib/eventObj');
const Scheduler = require('./lib/scheduler');
const {
resolveTypescriptLibs,
resolveTypings,
scriptIdToTSFilename
} = require('./lib/typescriptTools');
const adapterName = require('./package.json').name.split('.').pop();
const scriptCodeMarker = 'script.js.';
const stopCounters = {};
// for node version <= 0.12
if (''.startsWith === undefined) {
String.prototype.startsWith = function (s) {
return this.indexOf(s) === 0;
};
}
if (''.endsWith === undefined) {
String.prototype.endsWith = function (s) {
return this.slice(0 - s.length) === s;
};
}
///
let webstormDebug;
if (process.argv) {
for (let a = 1; a < process.argv.length; a++) {
if (process.argv[a].startsWith('--webstorm')) {
webstormDebug = process.argv[a].replace(/^(.*?=\s*)/, '');
break;
}
}
}
const isCI = !!process.env.CI;
// NodeJS 8+ supports the features of ES2017
// When upgrading the minimum supported version to NodeJS 10 or higher,
// consider changing this, so we get to support the newest features too
const targetTsLib = 'es2017';
/** @type {typescript.CompilerOptions} */
const tsCompilerOptions = {
// don't compile faulty scripts
noEmitOnError: true,
// emit declarations for global scripts
declaration: true,
// This enables TS users to `import * as ... from` and `import ... from`
esModuleInterop: true,
// In order to run scripts as a NodeJS vm.Script,
// we need to target ES5, otherwise the compiled
// scripts may include `import` keywords, which are not
// supported by vm.Script.
target: typescript.ScriptTarget.ES5,
lib: [`lib.${targetTsLib}.d.ts`],
};
const jsDeclarationCompilerOptions = Object.assign(
{}, tsCompilerOptions,
{
// we only care about the declarations
emitDeclarationOnly: true,
// allow errors
noEmitOnError: false,
noImplicitAny: false,
strict: false,
}
);
// ambient declarations for typescript
/** @type {Record<string, string>} */
let tsAmbient;
/** @type {tsc.Server} */
let tsServer;
/** @type {tsc.Server} */
let jsDeclarationServer;
let mirror;
/** @type {boolean} if logs are subscribed or not */
let logSubscribed;
/**
* @param {string} scriptID - The current script the declarations were generated from
* @param {string} declarations
*/
function provideDeclarationsForGlobalScript(scriptID, declarations) {
// Remember which declarations this global script had access to
// we need this so the editor doesn't show a duplicate identifier error
if (globalDeclarations != null && globalDeclarations !== '') {
knownGlobalDeclarationsByScript[scriptID] = globalDeclarations;
}
// and concatenate the global declarations for the next scripts
globalDeclarations += declarations + '\n';
// remember all previously generated global declarations,
// so global scripts can reference each other
const globalDeclarationPath = 'global.d.ts';
tsAmbient[globalDeclarationPath] = globalDeclarations;
// make sure the next script compilation has access to the updated declarations
tsServer.provideAmbientDeclarations({
[globalDeclarationPath]: globalDeclarations
});
jsDeclarationServer.provideAmbientDeclarations({
[globalDeclarationPath]: globalDeclarations
});
}
function loadTypeScriptDeclarations() {
// try to load the typings on disk for all 3rd party modules
const packages = [
'node', // this provides auto completion for most builtins
'request', // preloaded by the adapter
];
// Also include user-selected libraries (but only those that are also installed)
if (
adapter.config
&& typeof adapter.config.libraries === 'string'
&& typeof adapter.config.libraryTypings === 'string'
) {
const installedLibs = adapter.config.libraries.split(/[,;\s]+/).map(s => s.trim());
const wantsTypings = adapter.config.libraryTypings.split(/[,;\s]+/).map(s => s.trim());
// Add all installed libraries the user has requested typings for to the list of packages
for (const lib of installedLibs) {
if (
wantsTypings.indexOf(lib) > -1
&& packages.indexOf(lib) === -1
) {
packages.push(lib);
}
}
// Some packages have sub-modules (e.g. rxjs/operators) that are not exposed through the main entry point
// If typings are requested for them, also add them if the base module is installed
for (const lib of wantsTypings) {
// Extract the package name and check if we need to add it
if (lib.indexOf('/') === -1) continue;
const pkgName = lib.substr(0, lib.indexOf('/'));
if (
installedLibs.indexOf(pkgName) > -1
&& packages.indexOf(lib) === -1
) {
packages.push(lib);
}
}
}
for (const pkg of packages) {
const pkgTypings = resolveTypings(
pkg,
// node needs ambient typings, so we don't wrap it in declare module
pkg !== 'node'
);
if (pkgTypings) {
adapter.log.debug(`Loaded TypeScript definitions for ${pkg}: ${JSON.stringify(Object.keys(pkgTypings))}`);
// remember the declarations for the editor
Object.assign(tsAmbient, pkgTypings);
// and give the language servers access to them
tsServer.provideAmbientDeclarations(pkgTypings);
jsDeclarationServer.provideAmbientDeclarations(pkgTypings);
}
}
}
const context = {
mods,
objects: {},
states: {},
stateIds: [],
errorLogFunction: null,
subscriptions: [],
adapterSubs: {},
subscribedPatterns: {},
cacheObjectEnums: {},
isEnums: false, // If some subscription wants enum
channels: null,
devices: null,
logWithLineInfo: null,
scheduler: null,
timers: {},
enums: [],
timerId: 0,
names: {},
scripts: {},
messageBusHandlers: {},
logSubscriptions: {},
updateLogSubscriptions,
timeSettings: {
format12: false,
leadingZeros: true
}
};
const regExGlobalOld = /_global$/;
const regExGlobalNew = /script\.js\.global\./;
function checkIsGlobal(obj) {
return regExGlobalOld.test(obj.common.name) || regExGlobalNew.test(obj._id);
}
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options, {
name: adapterName,
useFormatDate: true, // load float formatting
objectChange: (id, obj) => {
if (id.startsWith('enum.')) {
// clear cache
context.cacheObjectEnums = {};
// update context.enums array
if (obj) {
// If new
if (context.enums.indexOf(id) === -1) {
context.enums.push(id);
context.enums.sort();
}
} else {
const pos = context.enums.indexOf(id);
// if deleted
if (pos !== -1) {
context.enums.splice(pos, 1);
}
}
}
// update stored time format for variables.dayTime
if (id === adapter.namespace + '.variables.dayTime' && obj && obj.native) {
context.timeSettings.format12 = obj.native.format12 || false;
context.timeSettings.leadingZeros = obj.native.leadingZeros === undefined ? true : obj.native.leadingZeros;
}
// send changes to disk mirror
mirror && mirror.onObjectChange(id, obj);
if (obj) {
// add state to state ID's list
if (obj.type === 'state' && !context.stateIds.includes(id)) {
context.stateIds.push(id);
context.stateIds.sort();
}
} else {
// delete object from state ID's list
const pos = context.stateIds.indexOf(id);
pos !== -1 && context.stateIds.splice(pos, 1);
}
if (!obj) {
// object deleted
if (!context.objects[id]) return;
// Script deleted => remove it
if (context.objects[id].type === 'script' && context.objects[id].common.engine === 'system.adapter.' + adapter.namespace) {
stop(id);
// delete scriptEnabled.blabla variable
const idActive = 'scriptEnabled.' + id.substring('script.js.'.length);
adapter.delObject(idActive);
adapter.delState(idActive);
// delete scriptProblem.blabla variable
const idProblem = 'scriptProblem.' + id.substring('script.js.'.length);
adapter.delObject(idProblem);
adapter.delState(idProblem);
}
removeFromNames(id);
delete context.objects[id];
} else if (!context.objects[id]) {
// New object
context.objects[id] = obj;
addToNames(obj);
if (obj.type === 'script' && obj.common.engine === 'system.adapter.' + adapter.namespace) {
// create states for scripts
createActiveObject(id, obj.common.enabled, () => createProblemObject(id));
if (obj.common.enabled) {
if (checkIsGlobal(obj)) {
// restart adapter
adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, _obj) =>
_obj && adapter.setForeignObject('system.adapter.' + adapter.namespace, _obj));
return;
}
// Start script
load(id);
}
}
// added new script to this engine
} else if (context.objects[id].common) {
const n = getName(id);
if (n !== context.objects[id].common.name) {
if (n) removeFromNames(id);
if (context.objects[id].common.name) addToNames(obj);
}
// Object just changed
if (obj.type !== 'script') {
context.objects[id] = obj;
if (id === 'system.config') {
// set language for debug messages
if (obj.common && obj.common.language) {
words.setLanguage(obj.common.language);
}
}
return;
}
// Analyse type = 'script'
if (checkIsGlobal(context.objects[id])) {
// restart adapter
adapter.getForeignObject('system.adapter.' + adapter.namespace, (err, obj) =>
obj && adapter.setForeignObject('system.adapter.' + adapter.namespace, obj));
return;
}
if (obj.common && obj.common.engine === 'system.adapter.' + adapter.namespace) {
// create states for scripts
createActiveObject(id, obj.common.enabled, () => createProblemObject(id));
}
if ((context.objects[id].common.enabled && !obj.common.enabled) ||
(context.objects[id].common.engine === 'system.adapter.' + adapter.namespace && obj.common.engine !== 'system.adapter.' + adapter.namespace)) {
// Script disabled
if (context.objects[id].common.enabled && context.objects[id].common.engine === 'system.adapter.' + adapter.namespace) {
// Remove it from executing
context.objects[id] = obj;
stop(id);
} else {
context.objects[id] = obj;
}
} else if ((!context.objects[id].common.enabled && obj.common.enabled) ||
(context.objects[id].common.engine !== 'system.adapter.' + adapter.namespace && obj.common.engine === 'system.adapter.' + adapter.namespace)) {
// Script enabled
context.objects[id] = obj;
if (context.objects[id].common.enabled && context.objects[id].common.engine === 'system.adapter.' + adapter.namespace) {
// Start script
load(id);
}
} else { //if (obj.common.source !== context.objects[id].common.source) {
context.objects[id] = obj;
// Source changed => restart it
stopCounters[id] = stopCounters[id] ? stopCounters[id] + 1 : 1;
stop(id, (res, _id) =>
// only start again after stop when "last" object change to prevent problems on
// multiple changes in fast frequency
!--stopCounters[id] && load(_id));
} /*else {
// Something changed or not for us
objects[id] = obj;
}*/
}
},
stateChange: (id, state) => {
if (!id || id.startsWith('messagebox.') || id.startsWith('log.')) {
return;
}
const oldState = context.states[id];
if (state) {
if (oldState) {
// enable or disable script
if (!state.ack && id.startsWith(activeStr) && context.objects[id] && context.objects[id].native && context.objects[id].native.script) {
adapter.extendForeignObject(context.objects[id].native.script, { common: { enabled: state.val } });
}
// monitor if adapter is alive and send all subscriptions once more, after adapter goes online
if (/*oldState && */oldState.val === false && state.val && id.endsWith('.alive')) {
if (context.adapterSubs[id]) {
const parts = id.split('.');
const a = parts[2] + '.' + parts[3];
for (let t = 0; t < context.adapterSubs[id].length; t++) {
adapter.log.info('Detected coming adapter "' + a + '". Send subscribe: ' + context.adapterSubs[id][t]);
adapter.sendTo(a, 'subscribe', context.adapterSubs[id][t]);
}
}
}
} else if (/*!oldState && */context.stateIds.indexOf(id) === -1) {
context.stateIds.push(id);
context.stateIds.sort();
}
context.states[id] = state;
} else {
if (oldState) delete context.states[id];
state = {};
const pos = context.stateIds.indexOf(id);
if (pos !== -1) {
context.stateIds.splice(pos, 1);
}
}
const _eventObj = eventObj.createEventObject(context, id, state, oldState);
// if this state matches any subscriptions
for (let i = 0, l = context.subscriptions.length; i < l; i++) {
const sub = context.subscriptions[i];
if (sub && patternMatching(_eventObj, sub.patternCompareFunctions)) {
sub.callback(_eventObj);
}
}
},
unload: callback => {
stopTimeSchedules();
stopAllScripts(callback);
},
ready: () => {
mods.request.setLogger(adapter.log);
if (adapter.supportsFeature && adapter.supportsFeature('PLUGINS')) {
const sentryInstance = adapter.getPluginInstance('sentry');
if (sentryInstance) {
const Sentry = sentryInstance.getSentryObject();
if (Sentry) {
Sentry.configureScope(scope => {
scope.addEventProcessor((event, _hint) => {
if (event.exception && event.exception.values && event.exception.values[0]) {
const eventData = event.exception.values[0];
if (eventData.stacktrace && eventData.stacktrace.frames && Array.isArray(eventData.stacktrace.frames) && eventData.stacktrace.frames.length) {
// Exclude event if script Marker is included
if (eventData.stacktrace.frames.find(frame => frame.filename && frame.filename.includes(scriptCodeMarker))) {
return null;
}
//Exclude event if own directory is included but not inside own node_modules
const ownNodeModulesDir = nodePath.join(__dirname, 'node_modules');
if (!eventData.stacktrace.frames.find(frame => frame.filename && frame.filename.includes(__dirname) && !frame.filename.includes(ownNodeModulesDir))) {
return null;
}
// We have exception data and do not sorted it out, so report it
return event;
}
}
// No exception in it ... do not report
return null;
});
main();
});
} else {
main();
}
} else {
main();
}
} else {
main();
}
},
message: obj => {
if (obj) {
switch (obj.command) {
// process messageTo commands
case 'jsMessageBus':
if (obj.message && (
obj.message.instance === null ||
obj.message.instance === undefined ||
('javascript.' + obj.instance === adapter.namespace) ||
(obj.instance === adapter.namespace)
)) {
Object.keys(context.messageBusHandlers).forEach(name => {
// script name could be script.js.xxx or only xxx
if ((!obj.message.script || obj.message.script === name) && context.messageBusHandlers[name][obj.message.message]) {
context.messageBusHandlers[name][obj.message.message].forEach(handler => {
try {
if (obj.callback) {
handler.cb.call(handler.sandbox, obj.message.data, result =>
adapter.sendTo(obj.from, obj.command, result, obj.callback));
} else {
handler.cb.call(handler.sandbox, obj.message.data, result => {/* nop */ });
}
} catch (e) {
adapter.setState('scriptProblem.' + name.substring('script.js.'.length), true, true);
context.logError('Error in callback', e);
}
});
}
});
}
break;
case 'loadTypings': { // Load typings for the editor
const typings = {};
// try to load TypeScript lib files from disk
try {
const typescriptLibs = resolveTypescriptLibs(targetTsLib);
Object.assign(typings, typescriptLibs);
} catch (e) { /* ok, no lib then */
}
// provide the already-loaded ioBroker typings and global script declarations
Object.assign(typings, tsAmbient);
// also provide the known global declarations for each global script
for (const globalScriptPaths of Object.keys(knownGlobalDeclarationsByScript)) {
typings[globalScriptPaths + '.d.ts'] = knownGlobalDeclarationsByScript[globalScriptPaths];
}
if (obj.callback) {
adapter.sendTo(obj.from, obj.command, {typings}, obj.callback);
}
break;
}
case 'calcAstro': {
if (obj.message) {
const sunriseOffset = parseInt(obj.message.sunriseOffset === undefined ? adapter.config.sunriseOffset : obj.message.sunriseOffset, 10) || 0;
const sunsetOffset = parseInt(obj.message.sunsetOffset === undefined ? adapter.config.sunsetOffset : obj.message.sunsetOffset, 10) || 0;
const longitude = parseFloat(obj.message.longitude === undefined ? adapter.config.longitude : obj.message.longitude) || 0;
const latitude = parseFloat(obj.message.latitude === undefined ? adapter.config.latitude : obj.message.latitude) || 0;
const now = new Date();
const nextSunrise = getAstroEvent(
now,
obj.message.sunriseEvent || adapter.config.sunriseEvent,
obj.message.sunriseLimitStart || adapter.config.sunriseLimitStart,
obj.message.sunriseLimitEnd || adapter.config.sunriseLimitEnd,
sunriseOffset,
false,
latitude,
longitude
);
const nextSunset = getAstroEvent(
now,
obj.message.sunsetEvent || adapter.config.sunsetEvent,
obj.message.sunsetLimitStart || adapter.config.sunsetLimitStart,
obj.message.sunsetLimitEnd || adapter.config.sunsetLimitEnd,
sunsetOffset,
true,
latitude,
longitude
);
obj.callback && adapter.sendTo(obj.from, obj.command, {
nextSunrise,
nextSunset
}, obj.callback);
}
break;
}
}
}
},
/**
* If the JS-Controller catches an unhandled error, this will be called
* so we have a chance to handle it ourself.
* @param {Error} err
*/
error: (err) => {
// Identify unhandled errors originating from callbacks in scripts
// These are not caught by wrapping the execution code in try-catch
if (err && typeof err.stack === 'string') {
const scriptCodeMarkerIndex = err.stack.indexOf(scriptCodeMarker);
if (scriptCodeMarkerIndex > -1) {
// This is a script error
let scriptName = err.stack.substr(scriptCodeMarkerIndex);
scriptName = scriptName.substr(0, scriptName.indexOf(':'));
context.logError(scriptName, err);
// Leave the script running for now
// signal to the JS-Controller that we handled the error ourselves
return true;
}
// check if a path contains adaptername but not own node_module
// this regex matched "iobroker.javascript/" if NOT followed by "node_modules"
if (!err.stack.match(/iobroker\.javascript[/\\](?!.*node_modules).*/g)) {
// This is an error without any info on origin (mostly async errors like connection errors)
// also consider it as being from a script
adapter.log.error('An error happened which is most likely from one of your scripts, but the originating script could not be detected.');
adapter.log.error('Error: ' + err.message);
adapter.log.error(err.stack);
// signal to the JS-Controller that we handled the error ourselves
return true;
}
}
}
});
adapter = new utils.Adapter(options);
// handler for logs
adapter.on('log', msg =>
Object.keys(context.logSubscriptions)
.forEach(name =>
context.logSubscriptions[name].forEach(handler => {
if (typeof handler.cb === 'function' && (handler.severity === '*' || handler.severity === msg.severity)) {
handler.sandbox.logHandler = handler.severity || '*';
handler.cb.call(handler.sandbox, msg);
handler.sandbox.logHandler = null;
}
})));
context.adapter = adapter;
return adapter;
}
function main() {
// todo
context.errorLogFunction = webstormDebug ? console : adapter.log;
activeStr = adapter.namespace + '.scriptEnabled.';
mods.fs = new require('./lib/protectFs')(adapter.log);
// try to read TS declarations
try {
tsAmbient = {
'javascript.d.ts': nodeFS.readFileSync(mods.path.join(__dirname, 'lib/javascript.d.ts'), 'utf8')
};
tsServer.provideAmbientDeclarations(tsAmbient);
jsDeclarationServer.provideAmbientDeclarations(tsAmbient);
} catch (e) {
adapter.log.warn('Could not read TypeScript ambient declarations: ' + e);
}
context.logWithLineInfo = function (level, msg) {
if (msg === undefined) {
return context.logWithLineInfo('info', msg);
}
context.errorLogFunction && context.errorLogFunction[level](msg);
const stack = (new Error().stack).split('\n');
for (let i = 3; i < stack.length; i++) {
if (!stack[i]) continue;
if (stack[i].match(/runInContext|runInNewContext|javascript\.js:/)) break;
context.errorLogFunction && context.errorLogFunction[level](fixLineNo(stack[i]));
}
};
context.logWithLineInfo.warn = context.logWithLineInfo.bind(1, 'warn');
context.logWithLineInfo.error = context.logWithLineInfo.bind(1, 'error');
context.logWithLineInfo.info = context.logWithLineInfo.bind(1, 'info');
context.scheduler = new Scheduler(adapter.log, Date, mods.suncalc, adapter.config.latitude, adapter.config.longitude);
installLibraries(() => {
// Load the TS declarations for Node.js and all 3rd party modules
loadTypeScriptDeclarations();
getData(() => {
dayTimeSchedules(adapter, context);
timeSchedule(adapter, context);
adapter.subscribeForeignObjects('*');
if (!adapter.config.subscribe) {
adapter.subscribeForeignStates('*');
}
// Warning. It could have a side-effect in compact mode, so all adapters will accept self signed certificates
if (adapter.config.allowSelfSignedCerts) {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
}
adapter.getObjectView('script', 'javascript', {}, (err, doc) => {
globalScript = '';
globalDeclarations = '';
knownGlobalDeclarationsByScript = {};
let count = 0;
if (doc && doc.rows && doc.rows.length) {
// assemble global script
for (let g = 0; g < doc.rows.length; g++) {
if (checkIsGlobal(doc.rows[g].value)) {
const obj = doc.rows[g].value;
if (obj && obj.common.enabled) {
const engineType = (obj.common.engineType || '').toLowerCase();
if (engineType.startsWith('coffee')) {
count++;
coffeeCompiler.fromSource(obj.common.source, {
sourceMap: false,
bare: true
}, (err, js) => {
if (err) {
adapter.log.error('coffee compile ' + err);
return;
}
globalScript += js + '\n';
if (!--count) {
globalScriptLines = globalScript.split(/\r\n|\n|\r/g).length;
// load all scripts
for (let i = 0; i < doc.rows.length; i++) {
if (!checkIsGlobal(doc.rows[i].value)) {
load(doc.rows[i].value._id);
}
}
}
});
} else if (engineType.startsWith('typescript')) {
// compile the current global script
const filename = scriptIdToTSFilename(obj._id);
const tsCompiled = tsServer.compile(filename, obj.common.source);
const errors = tsCompiled.diagnostics.map(diag => diag.annotatedSource + '\n').join('\n');
if (tsCompiled.success) {
if (errors.length > 0) {
adapter.log.warn('TypeScript compilation completed with errors: \n' + errors);
} else {
adapter.log.info('TypeScript compilation successful');
}
globalScript += tsCompiled.result + '\n';
// if declarations were generated, remember them
if (tsCompiled.declarations != null) {
provideDeclarationsForGlobalScript(obj._id, tsCompiled.declarations);
}
} else {
adapter.log.error('TypeScript compilation failed: \n' + errors);
}
} else { // javascript
const sourceCode = obj.common.source;
globalScript += sourceCode + '\n';
// try to compile the declarations so TypeScripts can use
// functions defined in global JavaScripts
const filename = scriptIdToTSFilename(obj._id);
const tsCompiled = jsDeclarationServer.compile(filename, sourceCode);
// if declarations were generated, remember them
if (tsCompiled.success && tsCompiled.declarations != null) {
provideDeclarationsForGlobalScript(obj._id, tsCompiled.declarations);
}
}
}
}
}
}
if (!count) {
globalScript = globalScript.replace(/\r\n/g, '\n');
globalScriptLines = globalScript.split(/\n/g).length - 1;
if (doc && doc.rows && doc.rows.length) {
// load all scripts
for (let i = 0; i < doc.rows.length; i++) {
if (!checkIsGlobal(doc.rows[i].value)) {
load(doc.rows[i].value);
}
}
}
}
if (adapter.config.mirrorPath) {
adapter.config.mirrorInstance = parseInt(adapter.config.mirrorInstance, 10) || 0;
if (adapter.instance === adapter.config.mirrorInstance) {
mirror = new Mirror({
adapter,
log: adapter.log,
diskRoot: adapter.config.mirrorPath
});
}
}
});
});
});
}
function stopAllScripts(cb) {
Object.keys(context.scripts).forEach(id => stop(id));
setTimeout(() => cb(), 0);
}
const attempts = {};
let globalScript = '';
/** Generated declarations for global TypeScripts */
let globalDeclarations = '';
// Remember which definitions the global scripts
// have access to, because it depends on the compile order
let knownGlobalDeclarationsByScript = {};
let globalScriptLines = 0;
// let activeRegEx = null;
let activeStr = ''; // enabled state prefix
let daySchedule = null; // schedule for astrological day
function getNextTimeEvent(time) {
const now = new Date();
let [timeHours, timeMinutes] = time.split(':');
timeHours = parseInt(timeHours, 10);
timeMinutes = parseInt(timeMinutes, 10);
if ((now.getHours() > timeHours) ||
(now.getHours() === timeHours && now.getMinutes() > timeMinutes)) {
now.setDate(now.getDate() + 1);
}
now.setHours(timeHours);
now.setMinutes(timeMinutes);
return now;
}
function getAstroEvent(now, astroEvent, start, end, offsetMinutes, isDayEnd, latitude, longitude) {
let ts = mods.suncalc.getTimes(now, latitude, longitude)[astroEvent];
if (!ts || ts.getTime().toString() === 'NaN') {
ts = isDayEnd ? getNextTimeEvent(end) : getNextTimeEvent(start);
}
ts.setSeconds(0);
ts.setMilliseconds(0);
let [timeHoursStart, timeMinutesStart] = start.split(':');
timeHoursStart = parseInt(timeHoursStart, 10);
timeMinutesStart = parseInt(timeMinutesStart, 10) || 0;
if (ts.getHours() < timeHoursStart || (ts.getHours() === timeHoursStart && ts.getMinutes() < timeMinutesStart)) {
ts = getNextTimeEvent(start);
}
let [timeHoursEnd, timeMinutesEnd] = end.split(':');
timeHoursEnd = parseInt(timeHoursEnd, 10);
timeMinutesEnd = parseInt(timeMinutesEnd, 10) || 0;
if (ts.getHours() > timeHoursEnd || (ts.getHours() === timeHoursEnd && ts.getMinutes() > timeMinutesEnd)) {
ts = getNextTimeEvent(end);
}
// if event in the past
if (now > ts) {
// take next day
ts.setDate(ts.getDate() + 1);
}
return ts;
}
function timeSchedule(adapter, context) {
const now = new Date();
let hours = now.getHours();
let minutes = now.getMinutes();
if (context.timeSettings.format12) {
if (hours > 12) {
hours -= 12;
}
}
if (context.timeSettings.leadingZeros && hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
adapter.setState('variables.dayTime', hours + ':' + minutes, true);
now.setMinutes(now.getMinutes() + 1);
now.setSeconds(0);
now.setMilliseconds(0);
const interval = now.getTime() - Date.now();
setTimeout(timeSchedule, interval, adapter, context);
}
function dayTimeSchedules(adapter, context) {
// get astrological event
if (adapter.config.latitude === undefined || adapter.config.longitude === undefined ||
adapter.config.latitude === '' || adapter.config.longitude === '' ||
adapter.config.latitude === null || adapter.config.longitude === null) {
adapter.log.error('Longitude or latitude does not set. Cannot use astro.');
return;
}
// Calculate next event;
const nowDate = new Date();
const nextSunrise = getAstroEvent(nowDate, adapter.config.sunriseEvent, adapter.config.sunriseLimitStart, adapter.config.sunriseLimitEnd, adapter.config.sunriseOffset, false, adapter.config.latitude, adapter.config.longitude);
const nextSunset = getAstroEvent(nowDate, adapter.config.sunsetEvent, adapter.config.sunsetLimitStart, adapter.config.sunsetLimitEnd, adapter.config.sunsetOffset, true, adapter.config.latitude, adapter.config.longitude);
// Sunrise
let sunriseTimeout = nextSunrise.getTime() - nowDate.getTime();
if (sunriseTimeout > 3600000) {
sunriseTimeout = 3600000;
}
// Sunset
let sunsetTimeout = nextSunset.getTime() - nowDate.getTime();
if (sunsetTimeout > 3600000) {
sunsetTimeout = 3600000;
}
let isDay;
if (sunriseTimeout < 5000) {
isDay = true;
} else if (sunsetTimeout < 5000) {
isDay = false;
} else {
// check if in between
// todo
const nowStartDate = new Date();
nowStartDate.setHours(0);
nowStartDate.setMinutes(0);
nowStartDate.setSeconds(0);
nowStartDate.setMilliseconds(0);
const todaySunrise = getAstroEvent(nowStartDate, adapter.config.sunriseEvent, adapter.config.sunriseLimitStart, adapter.config.sunriseLimitEnd, adapter.config.sunriseOffset, false);
const todaySunset = getAstroEvent(nowStartDate, adapter.config.sunsetEvent, adapter.config.sunsetLimitStart, adapter.config.sunsetLimitEnd, adapter.config.sunsetOffset, false);
isDay = nowDate > todaySunrise && nowDate <= todaySunset;
}
adapter.getState('variables.isDayTime', (err, state) => {
const val = state ? !!state.val : false;
if (val !== isDay) {
adapter.setState('variables.isDayTime', isDay, true);
}
});
let nextTimeout = sunriseTimeout;
if (sunriseTimeout > sunsetTimeout) {
nextTimeout = sunsetTimeout;
}
nextTimeout = nextTimeout - 3000;
if (nextTimeout < 3000) {
nextTimeout = 3000;
}
daySchedule = setTimeout(dayTimeSchedules, nextTimeout, adapter, context);
}
function stopTimeSchedules() {
daySchedule && clearTimeout(daySchedule);
}
/**
* Redirects the virtual-tsc log output to the ioBroker log
* @param {string} msg message
* @param {string} sev severity (info, silly, debug, warn, error)
*/
function tsLog(msg, sev) {
// shift the severities around, we don't care about the small details