-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmain.js
1216 lines (1114 loc) · 50.1 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
/* jshint -W097 */
/* jshint strict: false */
/* jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const SocketCloud = require('./lib/socketCloud.js');
const axios = require('axios');
const pack = require('./io-package.json');
const adapterName = require('./package.json').name.split('.').pop();
let socket = null;
let ioSocket = null;
let pingTimer = null;
let connected = false;
let connectTimer = null;
let uuid = null;
let waiting = false;
let apikey = '';
let server = 'http://localhost:8082';
let adminServer = 'http://localhost:8081';
let lovelaceServer = 'http://localhost:8091';
let TEXT_PING_TIMEOUT = 'Ping timeout';
let redirectRunning = false; // is redirect in progress
let timeouts = {
terminate: null,
onCloudWait: null,
detectDisconnect: null,
redirect: null,
onCloudStop: null,
createAppKey: null,
readAppKey: null,
};
let adapter;
function startAdapter(options) {
options = options || {};
Object.assign(options,{
name: adapterName,
objectChange: (id, obj) => {
if (id === adapter.config.instance) {
const _server = getConnectionString(obj);
if (_server !== server) {
server = _server;
adapter.log.info(`Reconnect because web instance ${obj && obj.common && obj.common.enabled ? 'started' : 'stopped'}`);
startConnect(true);
}
} else
if (id === adapter.config.allowAdmin) {
const _adminServer = getConnectionString(obj);
if (_adminServer !== adminServer) {
adminServer = _adminServer;
adapter.log.info(`Reconnect because admin instance ${obj && obj.common && obj.common.enabled ? 'started' : 'stopped'}`);
startConnect(true);
}
} else
if (id === adapter.config.lovelace) {
const _lovelaceServer = getConnectionString(obj);
if (_lovelaceServer !== lovelaceServer) {
lovelaceServer = _lovelaceServer;
adapter.log.info(`Reconnect because lovelace instance ${obj && obj.common && obj.common.enabled ? 'started' : 'stopped'}`);
startConnect(true);
}
}
ioSocket && ioSocket.send(socket, 'objectChange', id, obj);
},
stateChange: (id, state) => {
if (socket) {
if (id === `${adapter.namespace}.services.ifttt` && state && !state.ack) {
sendDataToIFTTT({
id: id,
val: state.val,
ack: false
});
} else {
ioSocket && ioSocket.send(socket, 'stateChange', id, state);
}
}
},
unload: callback => {
if (connectTimer) {
clearInterval(connectTimer);
connectTimer = null;
}
if (pingTimer) {
clearInterval(pingTimer);
pingTimer = null;
}
Object.keys(timeouts).forEach(tm => {
if (timeouts[tm]) {
clearTimeout(timeouts[tm]);
timeouts[tm] = null;
}
});
try {
if (socket) {
socket.close();
}
ioSocket = null;
callback();
} catch (e) {
callback();
}
},
message: obj => {
if (obj) {
switch (obj.command) {
case 'ifttt':
sendDataToIFTTT(obj.message);
break;
case 'getIFTTTLink':
if (typeof obj.message === 'string') {
return obj.callback && adapter.sendTo(obj.from, obj.command, 'invalid config', obj.callback);
}
if (obj.message.useCredentials) {
_readAppKeyFromCloud(obj.message.server, obj.message.login, obj.message.pass, (err, key) => {
const text = `https://${obj.message.server}/ifttt/${key}`;
obj.callback && adapter.sendTo(obj.from, obj.command, text, obj.callback);
})
} else {
const text = `https://${obj.message.apikey.startsWith('@pro_') ? 'iobroker.pro' : 'iobroker.net'}/ifttt/${obj.message.apikey}`;
obj.callback && adapter.sendTo(obj.from, obj.command, text, obj.callback);
}
break;
case 'getServiceLink':
if (typeof obj.message === 'string') {
return obj.callback && adapter.sendTo(obj.from, obj.command, 'invalid config', obj.callback);
}
if (obj.message.useCredentials) {
_readAppKeyFromCloud(obj.message.server, obj.message.login, obj.message.pass, (err, key) => {
const text = `https://${obj.message.server}/service/custom_<NAME>/${key}/<data>`;
obj.callback && adapter.sendTo(obj.from, obj.command, text, obj.callback);
})
} else {
const text = `https://${obj.message.apikey.startsWith('@pro_') ? 'iobroker.pro' : 'iobroker.net'}/service/custom_<NAME>/${obj.message.apikey}/<data>`;
obj.callback && adapter.sendTo(obj.from, obj.command, text, obj.callback);
}
break;
case 'cmdStdout':
case 'cmdStderr':
case 'cmdExit':
case 'getHostInfo':
// send to cloud
ioSocket && ioSocket.send(socket, obj.command, obj.message.id, obj.message.data);
break;
case 'tts': {
if (obj.callback) {
const params = {
text: typeof obj.message === 'object' ? obj.message.text : obj.message,
apiKey: apikey,
textType: obj.message.textType || 'text',
voiceId: obj.message.voiceId || 'Marlene',
engine: obj.message.engine,
};
axios.post(`${adapter.config.cloudUrl.replace(/:(\d+)$/, ':3001')}/api/v1/polly`, params, {
headers: {
'Content-Type': 'application/json',
},
responseType: 'arraybuffer',
})
.then(response => {
if (response.data) {
const base64 = Buffer.from(response.data, 'binary').toString('base64');
obj.callback && adapter.sendTo(obj.from, obj.command, {base64}, obj.callback);
} else {
obj.callback && adapter.sendTo(obj.from, obj.command, {error: 'no data'}, obj.callback);
}
})
.catch(e => adapter.sendTo(obj.from, obj.command, {error: (e.response && e.response.data) || e.toString()}, obj.callback));
}
break;
}
default:
adapter.log.warn(`Unknown command_: ${obj.command}`);
break;
}
}
},
ready: () => createInstancesStates(main),
});
adapter = new utils.Adapter(options);
adapter.on('log', obj => {
if (apikey && apikey.startsWith('@pro_')) {
ioSocket && ioSocket.send(socket, 'log', obj);
}
});
return adapter;
}
function getConnectionString(obj) {
let conn = null;
if (obj && obj.common && obj.native) {
if (obj.native.auth) {
adapter.log.error(`Cannot activate ${obj._id.replace('system.adapter.', '')} for cloud, because authentication is enabled. Please create extra instance for cloud`);
return conn;
} else
if (obj.native.secure) {
adapter.log.error(`Cannot activate ${obj._id.replace('system.adapter.', '')} for cloud, because HTTPs is enabled. Please create extra instance for cloud`);
return conn;
} else
if (!obj.common.enabled) {
adapter.log.error(`Instance ${obj._id.replace('system.adapter.', '')} not enabled. Please enable this instance for cloud`);
return conn;
} else {
conn = `http${obj.native.secure ? 's' : ''}://`;
// todo if run on other host
conn += (!obj.native.bind || obj.native.bind === '0.0.0.0') ? '127.0.0.1' : obj.native.bind;
conn += `:${obj.native.port}`;
}
} else {
conn = null;
adapter.log.error(`Unknown instance ${obj ? obj._id : 'undefined'}`);
}
return conn;
}
function sendDataToIFTTT(obj) {
if (!obj) {
adapter.log.warn('No data to send to IFTTT');
return;
}
if (!adapter.config.iftttKey && (typeof obj !== 'object' || !obj.key)) {
adapter.log.warn('No IFTTT key is defined');
return;
}
if (typeof obj !== 'object') {
ioSocket && ioSocket.send(socket, 'ifttt', {
id: `${adapter.namespace}.services.ifttt`,
key: adapter.config.iftttKey,
val: obj
});
} else if (obj.event) {
ioSocket && ioSocket.send(socket, 'ifttt', {
event: obj.event,
key: obj.key || adapter.config.iftttKey,
value1: obj.value1,
value2: obj.value2,
value3: obj.value3
});
} else {
if (obj.val === undefined) {
adapter.log.warn('No value is defined');
return;
}
obj.id = obj.id || (`${adapter.namespace}.services.ifttt`);
ioSocket && ioSocket.send(socket, 'ifttt', {
id: obj.id,
key: obj.key || adapter.config.iftttKey,
val: obj.val,
ack: obj.ack
});
}
}
function pingConnection() {
if (!timeouts.detectDisconnect) {
if (connected && ioSocket) {
// cannot use "ping" because reserved by socket.io
ioSocket.send(socket, 'pingg');
timeouts.detectDisconnect = setTimeout(() => {
timeouts.detectDisconnect = null;
adapter.log.error(TEXT_PING_TIMEOUT);
onDisconnect(TEXT_PING_TIMEOUT);
}, adapter.config.pingTimeout);
}
}
}
function checkPing() {
if (connected) {
pingTimer = pingTimer || setInterval(pingConnection, 30000);
} else {
if (pingTimer) {
clearInterval(pingTimer);
pingTimer = null;
}
if (timeouts.detectDisconnect) {
clearTimeout(timeouts.detectDisconnect);
timeouts.detectDisconnect = null;
}
}
}
function controlState(id, data, callback) {
id = id || 'services.ifttt';
if (typeof data === 'object') {
if (data.id) {
if (data.id === `${adapter.namespace}.services.ifttt`) {
data.ack = true;
}
if (data.val === undefined) {
return callback && callback('No value set');
}
adapter.getForeignObject(data.id, (err, obj) => {
if (!obj || !obj.common) {
callback && callback(`Unknown ID: ${data.id}`);
} else {
if (typeof data.val === 'string') {
data.val = data.val.replace(/^@ifttt\s?/, '');
}
if (obj.common.type === 'boolean') {
data.val = data.val === true || data.val === 'true' || data.val === 'on' || data.val === 'ON' || data.val === 1 || data.val === '1';
} else if (obj.common.type === 'number') {
data.val = parseFloat(data.val);
}
adapter.setForeignState(data.id, data.val, data.ack, callback);
}
});
} else if (data.val !== undefined) {
if (typeof data.val === 'string') {
data.val = data.val.replace(/^@ifttt\s?/, '');
}
adapter.setState(id, data.val, data.ack !== undefined ? data.ack : true, callback);
} else {
if (typeof data === 'string') {
data = data.replace(/^@ifttt\s?/, '');
}
adapter.setState(id, JSON.stringify(data), true, callback);
}
} else {
if (typeof data === 'string') {
data = data.replace(/^@ifttt\s?/, '');
}
adapter.setState(id, data, true, callback);
}
}
function processIfttt(data, callback) {
adapter.log.debug(`Received IFTTT object: ${data}`);
let id;
if (typeof data === 'object' && data.id && data.data !== undefined) {
id = data.id;
if (typeof data.data === 'string' && data.data[0] === '{') {
try {
data = JSON.parse(data.data);
} catch (e) {
adapter.log.debug(`Cannot parse: ${data.data}`);
}
} else {
data = data.data;
}
} else {
if (typeof data === 'string' && data[0] === '{') {
try {
data = JSON.parse(data);
if (typeof data.id === 'string') {
id = data.id;
if (data.data) {
data = data.data;
}
}
} catch (e) {
adapter.log.debug(`Cannot parse: ${data}`);
}
}
}
if (id) {
adapter.getForeignObject(id, (err, obj) => {
if (obj) {
controlState(id, data, callback);
} else {
adapter.getForeignObject(`${adapter.namespace}.services.${id}`, (err, obj) => {
if (!obj) {
// create state
adapter.setObject(`services.${id}`, {
type: 'state',
common: {
name: 'IFTTT value',
write: false,
role: 'state',
read: true,
type: 'mixed',
desc: 'Custom state'
},
native: {}
},
() => controlState(`${adapter.namespace}.services.${id}`, data, callback));
} else {
controlState(obj._id, data, callback);
}
});
}
});
} else {
controlState(null, data, callback);
}
}
function onDisconnect(event) {
if (typeof event === 'string') {
!redirectRunning && adapter.log.info(`Connection changed: ${event}`);
} else {
adapter.log.info('Connection changed: disconnect');
}
if (connected) {
!redirectRunning && adapter.log.info('Connection lost');
connected = false;
adapter.setState('info.connection', false, true);
// clear ping timers
checkPing();
if (adapter.config.restartOnDisconnect && !redirectRunning) {
adapter.log.info('Restart adapter by disconnect');
// simulate scheduled restart
timeouts.terminate = setTimeout(() => {
timeouts.terminate = null;
adapter.terminate ? adapter.terminate(-100) : process.exit(-100);
}, 10000);
} else {
redirectRunning = false;
startConnect();
}
}
}
function onConnect() {
if (!connected) {
adapter.log.info('Connection changed: connect');
connected = true;
adapter.setState('info.connection', connected, true);
checkPing();
} else {
adapter.log.debug('Connection not changed: was connected');
}
if (connectTimer) {
clearInterval(connectTimer);
connectTimer = null;
}
}
function onCloudConnect(clientId) {
adapter.log.info(`User accessed from cloud: ${clientId || ''}`);
adapter.setState('info.userOnCloud', true, true);
}
function onCloudDisconnect(clientId, name) {
adapter.log.info(`User disconnected from cloud: ${clientId || ''} ${name || ''}`);
adapter.setState('info.userOnCloud', false, true);
}
function onCloudWait(seconds) {
waiting = true;
adapter.log.info(`Server asked to wait for ${seconds || 60} seconds`);
if (socket) {
socket.disconnect();
socket.off();
socket = null;
}
if (connectTimer) {
clearInterval(connectTimer);
connectTimer = null;
}
timeouts.onCloudWait = setTimeout(() => {
timeouts.onCloudWait = null;
waiting = false;
startConnect(true);
}, (seconds * 1000) || 60000);
}
function onCloudRedirect(data) {
if (!data) {
adapter.log.info('Received invalid redirect command from server');
return;
}
if (!data.url) {
adapter.log.error('Received redirect, but no URL.');
} else
if (data.notSave) {
redirectRunning = true;
adapter.log.info(`Adapter redirected temporally to "${data.url}" ${adapter.config.cloudUrl.includes('https://iobroker.pro:') ? 'in 30 seconds' : 'in one minute'}. Reason: ${data && data.reason ? data.reason : 'command from server'}`);
adapter.config.cloudUrl = data.url;
if (socket) {
socket.disconnect();
socket.off();
}
startConnect();
} else {
adapter.log.info(`Adapter redirected continuously to "${data.url}". Reason: ${data && data.reason ? data.reason : 'command from server'}`);
adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
err && adapter.log.error(`redirectAdapter [getForeignObject]: ${err}`);
if (obj) {
obj.native.cloudUrl = data.url;
timeouts.redirect = setTimeout(() => {
timeouts.redirect = null;
adapter.setForeignObject(obj._id, obj, err => {
err && adapter.log.error(`redirectAdapter [setForeignObject]: ${err}`);
adapter.config.cloudUrl = data.url;
if (socket) {
socket.disconnect();
socket.off();
}
startConnect();
});
}, 3000);
}
});
}
}
function onCloudError(error) {
adapter.log.error(`Cloud says: ${error}`);
}
function onCloudStop() {
adapter.getForeignObject(`system.adapter.${adapter.namespace}`, (err, obj) => {
err && adapter.log.error(`[onCloudStop]: ${err}`);
if (obj) {
obj.common.enabled = false;
timeouts.onCloudStop = setTimeout(() => {
timeouts.onCloudStop = null;
adapter.setForeignObject(obj._id, obj, err => {
err && adapter.log.error(`[setForeignObject]: ${err}`);
adapter.terminate ? adapter.terminate(): process.exit();
});
}, 5000);
} else {
adapter.terminate ? adapter.terminate(): process.exit();
}
});
}
// this is bug of socket.io
// sometimes auto-reconnect does not work.
function startConnect(immediately) {
if (waiting) {
return;
}
if (connectTimer) {
clearInterval(connectTimer);
connectTimer = null;
}
connectTimer = setInterval(connect, adapter.config.cloudUrl.includes('https://iobroker.pro:') ? 30000 : 60000); // on pro there are not so many users as on net.
if (immediately) {
connect();
}
}
function initConnect(socket, options) {
ioSocket = new SocketCloud(socket, options, adapter, lovelaceServer);
ioSocket.on('connect', onConnect);
ioSocket.on('disconnect', onDisconnect);
ioSocket.on('cloudError', onCloudError);
ioSocket.on('cloudConnect', onCloudConnect);
ioSocket.on('cloudDisconnect', onCloudDisconnect);
ioSocket.on('connectWait', onCloudWait);
ioSocket.on('cloudRedirect', onCloudRedirect);
ioSocket.on('cloudStop', onCloudStop);
}
function answerWithReason(instance, name, cb) {
if (!instance) {
adapter.log.error(`${name} instance not defined. Please specify the lovelace instance in settings`);
} else {
adapter.getForeignObjectAsync(instance)
.catch(() => null)
.then(obj => {
const conn = getConnectionString(obj);
if (conn) {
if (!obj.common.enabled) {
adapter.log.error(`${name} instance "${instance}" not activated.`);
} else {
adapter.log.error(`${name} instance "${instance}" not available.`);
}
}
});
}
cb && cb(`${name} is inactive`, 404, [], `${name} is inactive`);
}
function connect() {
if (waiting) {
return;
}
adapter.log.debug(`Connection attempt to ${adapter.config.cloudUrl} ...`);
if (socket) {
socket.off();
socket.disconnect();
}
socket = require('socket.io-client')(adapter.config.cloudUrl, {
transports: ['websocket'],
autoConnect: true,
reconnection: !adapter.config.restartOnDisconnect,
rejectUnauthorized: !adapter.config.allowSelfSignedCertificate,
randomizationFactor: 0.9,
reconnectionDelay: 60000,
timeout: parseInt(adapter.config.connectionTimeout, 10) || 10000,
reconnectionDelayMax: 120000
});
socket.on('connect_error', error => adapter.log.error(`Error while connecting to cloud: ${error}`));
// cannot use "pong" because reserved by socket.io
socket.on('pongg', (/*error*/) => {
clearTimeout(timeouts.detectDisconnect);
timeouts.detectDisconnect = null;
});
socket.on('method', (url, options, cb) => {
if (url.startsWith('/lovelace/')) {
url = url.replace(/^\/lovelace\//, '/');
if (!lovelaceServer) {
answerWithReason(adapter.config.lovelace, 'Lovelace', cb);
} else {
axios({
url: lovelaceServer + url,
method: options.method,
data: options.body,
// responseType: 'arraybuffer',
validateStatus: status => status < 400
})
.then(response => cb(null, response.status, response.headers, JSON.stringify(response.data)))
.catch(error => {
if (error.response) {
adapter.log.error(`Cannot request lovelace pages "${url}": ${error.response.data || error.response.status}`);
cb(error.response.data || error.response.status, error.response.status || 501, error.response.headers, JSON.stringify(error.response.data));
} else {
adapter.log.error(`Cannot request lovelace pages "${url}": ${error.code}`);
cb(error.code, 501, {}, JSON.stringify({error: 'unexpected error'}));
}
});
}
} else {
adapter.log.error(`Unexpected request: ${url}`);
if (!server) {
answerWithReason(adapter.config.instance, 'Web', cb);
} else {
axios({
url: server + url,
method: options.method,
data: options.body,
// responseType: 'arraybuffer',
validateStatus: status => status < 400
})
.then(response => cb(null, response.status, response.headers, JSON.stringify(response.data)))
.catch(error => {
if (error.response) {
adapter.log.error(`Cannot request web pages "${server}${url}": ${error.response.data || error.response.status}`);
cb(error.response.data || error.response.status, error.response.status || 501, error.response.headers, JSON.stringify(error.response.data));
} else {
adapter.log.error(`Cannot request web pages "${server}${url}": ${error.code}`);
cb(error.code, 501, {}, JSON.stringify({error: 'unexpected error'}));
}
});
}
}
});
socket.on('html', (url, cb) => {
try {
if (url.match(/^\/admin\//)) {
if (adminServer && adapter.config.allowAdmin) {
url = url.substring(6);
if (url.includes('loginBackgroundImage')) {
console.log('AAA')
}
if (url === '/@@loginBackgroundImage@@') {
url = '/files/admin.0/login-bg.png';
}
axios.get(adminServer + url, {responseType: 'arraybuffer', validateStatus: status => status < 400})
.then(response => cb(null, response.status, response.headers, response.data))
.catch(error => {
if (error.response) {
adapter.log.error('Cannot request admin pages: ' + (error.response.data || error.response.status));
cb(error.code, error.response.status || 501, error.response.headers, error.response.data);
} else {
adapter.log.error('Cannot request admin pages: no response');
cb('no response', 501, {}, 'no response from admin');
}
});
} else {
answerWithReason(adapter.config.allowAdmin, 'Admin');
cb('Enable admin in cloud settings. And only pro.', 404, [], 'Enable admin in cloud settings. And only pro.');
}
} else
// if admin
if (url.startsWith('/adapter/') || url.startsWith('/lib/js/ace-') || url.startsWith('/lib/js/cron') || url.startsWith('/lib/js/jqGrid')) {
if (adminServer && adapter.config.allowAdmin) {
axios.get(adminServer + url, {responseType: 'arraybuffer', validateStatus: status => status < 400})
.then(response => cb(null, response.status, response.headers, response.data))
.catch(error => {
if (error.response) {
adapter.log.error(`Cannot request admin pages: ${error.response.data || error.response.status}`);
cb(error.code, error.response.status || 501, error.response.headers, error.response.data);
} else {
adapter.log.error('Cannot request admin pages: no response');
cb('no response', 501, {}, 'no response from admin');
}
});
} else {
answerWithReason(adapter.config.allowAdmin, 'Admin');
cb('Enable admin in cloud settings. And only pro.', 404, [], 'Enable admin in cloud settings. And only pro.');
}
} else
// if lovelace
if (url.startsWith('/lovelace/')) {
if (lovelaceServer && adapter.config.lovelace) {
url = url.replace(/^\/lovelace\//, '/');
axios.get(lovelaceServer + url, {responseType: 'arraybuffer', validateStatus: status => status < 400})
.then(response => cb(null, response.status, response.headers, response.data))
.catch(error => {
if (error.response) {
adapter.log.error(`Cannot request lovelace pages "${lovelaceServer + url}": ${error.response.data || error.response.status}`);
cb(error.code, error.response.status || 501, error.response.headers, error.response.data);
} else {
adapter.log.error(`Cannot request lovelace pages "${lovelaceServer + url}": no response`);
cb('no response', 501, {}, 'no response from lovelace');
}
});
} else {
answerWithReason(adapter.config.lovelace, 'Lovelace', cb);
}
} else
// web
if (server) {
axios.get(server + url, {responseType: 'arraybuffer', validateStatus: status => status < 400})
.then(response => cb(null, response.status, response.headers, response.data))
.catch(error => {
if (error.response) {
adapter.log.error(`Cannot request web pages "${server + url}": ${error.response.data || error.response.status}`);
cb(error.code, error.response.status || 501, error.response.headers, error.response.data);
} else {
adapter.log.error(`Cannot request web pages"${server + url}": no response`);
cb('no response', 501, {}, 'no response from web');
}
});
} else {
// analyse answer
return answerWithReason(adapter.config.instance, 'Web', cb);
}
} catch (e) {
adapter.log.error(`Cannot request: ${e}`);
cb('Admin or Web are inactive.', 404, {}, 'Admin or Web are inactive.');
}
});
socket.on('ifttt', processIfttt);
socket.on('iftttError', error => adapter.log.error(`Error from IFTTT: ${JSON.stringify(error)}`));
socket.on('cloudError', error => adapter.log.error(`Cloud says: ${error}`));
socket.on('service', (data, callback) => {
adapter.log.debug('service: ' + JSON.stringify(data));
// supported services:
// - text2command
// - simpleApi
// - custom, e.g. torque
if (!data || !data.name) {
callback && callback({error: 'no name'});
} else
if (data.name === 'ifttt' && adapter.config.iftttKey) {
processIfttt(data.data, callback);
} else {
let isCustom = false;
if (data.name.match(/^custom_/)) {
data.name = data.name.substring(7);
isCustom = true;
}
if (adapter.config.allowedServices[0] === '*' || adapter.config.allowedServices.includes(data.name)) {
if (!isCustom && data.name === 'text2command') {
if (adapter.config.text2command !== undefined && adapter.config.text2command !== '') {
adapter.setForeignState(`text2command.${adapter.config.text2command}.text`, decodeURIComponent(data.data), err =>
callback && callback({result: err || 'Ok'}));
} else {
adapter.log.warn('Received service text2command, but instance is not defined');
callback && callback({error: 'instance is not defined'});
}
} else if (!isCustom && (data.name === 'simpleApi' || data.name === 'simpleapi')) {
// GET https://iobroker.net/service/simpleApi/<user-app-key>/get/system.adapter.admin.0.cputime
const parts = (data.data || '').split('/');
if (parts[0] === 'get') {
adapter.getForeignState(parts[1], (error, state) => {
if (error) {
callback && callback({error});
} else if (state) {
state.result = 'Ok';
callback && callback(state);
} else {
callback && callback({result: 'Not found'});
}
});
} else if (parts[0] === 'getPlainValue') {
adapter.getForeignState(parts[1], (error, state) => {
if (error) {
callback && callback({error});
} else if (state) {
callback && callback({result: 'Ok', val: state.val, plain: true});
} else {
callback && callback({result: 'Not found', val: null, plain: true});
}
});
} else if (parts[0] === 'set') {
// https://iobroker.pro/service/simpleapi/<user-app-key>/set/stateID?value=1
let [id, val] = parts[1].split('?');
if (id === undefined || val === undefined) {
return callback && callback({error: 'invalid call'});
}
val = val.replace(/^value=/, '');
adapter.getForeignObject(id, (error, obj) => {
if (error || !obj) {
callback && callback({error: error || 'not found'});
} else if (obj.type !== 'state') {
callback && callback({error: 'only states can be controlled'});
} else {
if (obj.common && obj.common.type === 'boolean') {
val = val === 'true' || val === '1' || val === 'ON' || val === 'on';
} else if (obj.common && obj.common.type === 'number') {
val = parseFloat(val);
}
adapter.setForeignState(id, val, error => {
if (error) {
callback && callback({error});
} else {
callback && callback({result: 'Ok'});
}
});
}
});
} else {
callback && callback({error: 'not implemented'});
}
} else if (isCustom) {
adapter.getObject(`services.custom_${data.name}`, (err, obj) => {
if (!obj) {
adapter.setObject(`services.custom_${data.name}`, {
_id: `${adapter.namespace}.services.custom_${data.name}`,
type: 'state',
common: {
name: `Service for ${data.name}`,
write: false,
read: true,
type: 'mixed',
role: 'value'
},
native: {}
}, err => {
if (!err) {
adapter.setState(`services.custom_${data.name}`, data.data, false, err => callback && callback({result: err || 'Ok'}));
} else {
callback && callback({result: err});
}
});
} else {
adapter.setState(`services.custom_${data.name}`, data.data, false, err => callback && callback({result: err || 'Ok'}));
}
});
} else {
callback && callback({error: 'not allowed'});
}
} else {
adapter.log.warn(`Received service "${data.name}", but it is not found in whitelist`);
callback && callback({error: 'blocked'});
}
}
});
socket.on('error', error => {
console.error(`Some error: ${error}`);
startConnect()
});
return new Promise(resolve => {
if (adapter.config.instance) {
adapter.getForeignObjectAsync(adapter.config.instance)
.then(obj => {
server = getConnectionString(obj);
resolve();
})
.catch(() => null);
} else {
resolve();
}
})
.then(() => {
if (adapter.config.allowAdmin) {
return adapter.getForeignObjectAsync(adapter.config.allowAdmin)
.then(obj => adminServer = getConnectionString(obj))
.catch(() => null);
} else {
return Promise.resolve();
}
})
.then(() => {
if (adapter.config.lovelace) {
return adapter.getForeignObjectAsync(adapter.config.lovelace)
.then(obj => lovelaceServer = getConnectionString(obj))
.catch(() => null);
} else {
return Promise.resolve();
}
})
.then(() => {
if (socket && (server || lovelaceServer || adminServer)) {
initConnect(socket, {
apikey,
uuid,
version: pack.common.version,
allowAdmin: adapter.config.allowAdmin,
lovelace: adapter.config.lovelace
});
}
});
}
function createInstancesStates(callback, objs) {
if (!objs) {
const pack = require('./io-package.json');
objs = pack.instanceObjects;
}
if (!objs || !objs.length) {
callback();
} else {
const obj = objs.shift();
adapter.getObject(obj._id, (err, _obj) => {
if (!_obj) {
adapter.setObject(obj._id, obj, err => {
err && adapter.log.error(`Cannot setObject: ${err}`);
setImmediate(createInstancesStates, callback, objs);
});
} else {
setImmediate(createInstancesStates, callback, objs);
}
});
}
}
function _createAppKey(cb) {
adapter.log.info('Create new APP-KEY...')
const url = `https://${adapter.config.server}:3001/api/v1/appkeys`;
axios.post(url, null, {
headers: {Authorization: `Basic ${Buffer.from(`${adapter.config.login}:${adapter.config.pass}`).toString('base64')}`},
validateStatus: status => status < 400
})
.then(response => {
let body = response.data;
if (body && body.key && body.key[0]) {
adapter.log.info(`New APP-KEY is ${body.key[0]}`);
cb(null, body.key[0]);
} else {
cb(`Cannot create app-key on server "${url}": ${JSON.stringify(body)}`);
}
})
.catch(error => {
if (error.code === 'ECONNREFUSED') {
adapter.log.warn('Server is offline or no connection. Retry in 10 seconds');
timeouts.createAppKey = setTimeout(() => {
timeouts.createAppKey = null;
_createAppKey(cb);
}, 10000);
} else
if (error.response && error.response.status === 401) {
return cb(`Invalid user name or password or server (may be it is ${adapter.config.server === 'iobroker.pro' ? 'iobroker.net' : 'iobroker.pro'})`);
} else if (error.response && error.response.data) {
let body = error.response.data;
if (body && body.key && body.key[0]) {
adapter.log.info(`New APP-KEY is ${body.key[0]}`);
cb(null, body.key[0]);
} else {
cb(`Cannot create app-key on server "${url}": ${
(error.response && error.response.status) ||