-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
adapter-settings.js
2423 lines (2240 loc) · 101 KB
/
adapter-settings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var path = location.pathname;
var parts = path.split('/');
parts.splice(-3);
if (location.pathname.match(/^\/admin\//)) {
parts = [];
}
var systemConfig;
var socket = io.connect('/', {path: parts.join('/') + '/socket.io'});
var instance = window.location.search.slice(1);
var common = null; // common information of adapter
var host = null; // host object on which the adapter runs
var changed = false;
var certs = [];
var adapter = '';
var onChangeSupported = false;
var isMaterialize = false;
var ___onChange = null;
var systemSecret = 'Zgfr56gFe87jJOM';
var supportedFeatures = [
'ADAPTER_AUTO_DECRYPT_NATIVE', // all native attributes, that are listed in an array `encryptedNative` in io-pack will be automatically decrypted and encrypted. Since js-controller 3.0
];
function preInit () {
'use strict';
var tmp = window.location.pathname.split('/');
adapter = tmp[tmp.length - 2];
var id = 'system.adapter.' + adapter + '.' + instance;
// Extend dictionary with standard words for adapter
if (typeof systemDictionary === 'undefined') {
systemDictionary = {};
}
systemDictionary.save = {"en": "Save", "fr": "Sauvegarder", "nl": "Opslaan", "es": "Salvar", "pt": "Salve", "it": "Salvare", "de": "Speichern", "pl": "Zapisać", "ru": "Сохранить", "zh-cn": "保存"};
systemDictionary.saveclose = {"en": "Save and close", "fr": "Sauver et fermer", "nl": "Opslaan en afsluiten","es": "Guardar y cerrar", "pt": "Salvar e fechar", "it": "Salva e chiudi", "de": "Speichern und schließen", "pl": "Zapisz i zamknij", "ru": "Сохранить и выйти", "zh-cn": "保存并关闭"};
systemDictionary.none = {"en": "none", "fr": "aucun", "nl": "geen", "es": "ninguna", "pt": "Nenhum", "it": "nessuna", "de": "keins", "pl": "Żaden", "ru": "ничего", "zh-cn": "无"};
systemDictionary.nonerooms = {"en": "", "fr": "", "nl": "", "es": "", "pt": "", "it": "", "de": "", "pl": "", "ru": "", "zh-cn": ""};
systemDictionary.nonefunctions = {"en": "", "fr": "", "nl": "", "es": "", "pt": "", "it": "", "de": "", "pl": "", "ru": "", "zh-cn": ""};
systemDictionary.all = {"en": "all", "fr": "tout", "nl": "alle", "es": "todas", "pt": "todos", "it": "tutti", "de": "alle", "pl": "wszystko", "ru": "все", "zh-cn": "所有"};
systemDictionary['Device list'] = {"en": "Device list", "fr": "Liste des périphériques", "nl": "Lijst met apparaten", "es": "Lista de dispositivos", "pt": "Lista de dispositivos", "it": "Elenco dispositivi", "de": "Geräteliste", "pl": "Lista urządzeń", "ru": "Список устройств", "zh-cn": "设备清单"};
systemDictionary['new device'] = {"en": "new device", "fr": "nouvel appareil", "nl": "nieuw apparaat", "es": "Nuevo dispositivo", "pt": "Novo dispositivo", "it": "nuovo dispositivo", "de": "Neues Gerät", "pl": "nowe urządzenie", "ru": "Новое устройство", "zh-cn": "新设备"};
systemDictionary.edit = {"en": "edit", "fr": "modifier", "nl": "Bewerk", "es": "editar", "pt": "editar", "it": "modificare", "de": "Ändern", "pl": "edytować", "ru": "Изменить", "zh-cn": "编辑"};
systemDictionary.delete = {"en": "delete", "fr": "effacer", "nl": "Delete", "es": "borrar", "pt": "excluir", "it": "Elimina", "de": "Löschen", "pl": "kasować", "ru": "Удалить", "zh-cn": "删除"};
systemDictionary.pair = {"en": "pair", "fr": "paire", "nl": "paar", "es": "par", "pt": "par", "it": "paio", "de": "Verbinden", "pl": "para", "ru": "Связать", "zh-cn": "配对"};
systemDictionary.unpair = {"en": "unpair", "fr": "unpair", "nl": "Unpair", "es": "desvincular", "pt": "unpair", "it": "Disaccoppia", "de": "Trennen", "pl": "unpair", "ru": "Разорвать связь", "zh-cn": "取消配对"};
systemDictionary.ok = {"en": "Ok", "fr": "D'accord", "nl": "OK", "es": "De acuerdo", "pt": "Está bem", "it": "Ok", "de": "Ok", "pl": "Ok", "ru": "Ok", "zh-cn": "确认"};
systemDictionary.cancel = {"en": "Cancel", "fr": "Annuler", "nl": "Annuleer", "es": "Cancelar", "pt": "Cancelar", "it": "Annulla", "de": "Abbrechen", "pl": "Anuluj", "ru": "Отмена", "zh-cn": "取消"};
systemDictionary.Message = {"en": "Message", "fr": "Message", "nl": "Bericht", "es": "Mensaje", "pt": "Mensagem", "it": "Messaggio", "de": "Mitteilung", "pl": "Wiadomość", "ru": "Сообщение", "zh-cn": "信息"};
systemDictionary.close = {"en": "Close", "fr": "Fermer", "nl": "Dichtbij", "es": "Cerca", "pt": "Fechar", "it": "Vicino", "de": "Schließen", "pl": "Blisko", "ru": "Закрыть", "zh-cn": "关闭"};
systemDictionary.htooltip = {"en": "Click for help", "fr": "Cliquez pour obtenir de l'aide", "nl": "Klik voor hulp", "es": "Haz clic para obtener ayuda", "pt": "Clique para ajuda", "it": "Fai clic per chiedere aiuto", "de": "Anklicken", "pl": "Kliknij, aby uzyskać pomoc", "ru": "Перейти по ссылке", "zh-cn": "单击获取帮助"};
systemDictionary.saveConfig = {
"en": "Save configuration to file",
"de": "Speichern Sie die Konfiguration in der Datei",
"ru": "Сохранить конфигурацию в файл",
"pt": "Salvar configuração no arquivo",
"nl": "Sla configuratie op naar bestand",
"fr": "Enregistrer la configuration dans un fichier",
"it": "Salva la configurazione nel file",
"es": "Guardar configuración en archivo",
"pl": "Zapisz konfigurację do pliku",
"zh-cn": "将配置保存到文件"
};
systemDictionary.loadConfig = {
"en": "Load configuration from file",
"de": "Laden Sie die Konfiguration aus der Datei",
"ru": "Загрузить конфигурацию из файла",
"pt": "Carregar configuração do arquivo",
"nl": "Laad de configuratie uit het bestand",
"fr": "Charger la configuration à partir du fichier",
"it": "Carica la configurazione dal file",
"es": "Cargar configuración desde archivo",
"pl": "Załaduj konfigurację z pliku",
"zh-cn": "从文件加载配置"
};
systemDictionary.otherConfig = {
"en": "Configuration from other adapter %s",
"de": "Konfiguration von anderem Adapter %s",
"ru": "Конфигурация из другого адаптера %s",
"pt": "Configuração de outro adaptador %s",
"nl": "Configuratie vanaf andere adapter %s",
"fr": "Configuration à partir d'un autre adaptateur %s",
"it": "Configurazione da altro adattatore %s",
"es": "Configuración desde otro adaptador %s",
"pl": "Konfiguracja z innego adaptera %s",
"zh-cn": "从其他适配器%s配置"
};
systemDictionary.invalidConfig = {
"en": "Invalid JSON file",
"de": "Ungültige JSON-Datei",
"ru": "Недопустимый файл JSON",
"pt": "Arquivo JSON inválido",
"nl": "Ongeldig JSON-bestand",
"fr": "Fichier JSON non valide",
"it": "File JSON non valido",
"es": "Archivo JSON no válido",
"pl": "Nieprawidłowy plik JSON",
"zh-cn": "无效的JSON文件"
};
systemDictionary.configLoaded = {
"en": "Configuration was successfully loaded",
"de": "Die Konfiguration wurde erfolgreich geladen",
"ru": "Конфигурация успешно загружена",
"pt": "Configuração foi carregada com sucesso",
"nl": "Configuratie is succesvol geladen",
"fr": "La configuration a été chargée avec succès",
"it": "La configurazione è stata caricata correttamente",
"es": "La configuración se cargó correctamente",
"pl": "Konfiguracja została pomyślnie załadowana",
"zh-cn": "配置已成功加载"
};
systemDictionary.maxTableRaw = {
"en": "Maximum number of allowed raws",
"de": "Maximale Anzahl von erlaubten Tabellenzeilen",
"ru": "Достигнуто максимальное число строк",
"it": "Numero massimo di raw consentiti",
"fr": "Nombre maximum de raw autorisés",
"nl": "Maximumaantal toegestane raws",
"pt": "Número máximo de raias permitidas",
"es": "Número máximo de raws permitidos",
"pl": "Maksymalna liczba dozwolonych surowców",
"zh-cn": "允许的最大原始数量"
};
systemDictionary.maxTableRawInfo = {"en": "Warning", "de": "Warnung", "ru": "Внимание", "pt": "Atenção", "nl": "Waarschuwing", "fr": "Attention", "it": "avvertimento", "es": "Advertencia", "pl": "Ostrzeżenie", "zh-cn": "警告"};
systemDictionary["Main settings"] = {
"en": "Main settings",
"de": "Haupteinstellungen",
"ru": "Основные настройки",
"pt": "Configurações principais",
"nl": "Belangrijkste instellingen",
"fr": "Réglages principaux",
"it": "Impostazioni principali",
"es": "Ajustes principales",
"pl": "Ustawienia główne",
"zh-cn": "主要设置"
};
systemDictionary["Let's Encrypt SSL"] = {
"en": "Let's Encrypt Certificates",
"de": "Let's Encrypt Zertifikate",
"ru": "Let's Encrypt Сертификаты",
"pt": "Let's Encrypt Certificados",
"nl": "Let's Encrypt certificaten",
"fr": "Let's Encrypt Certificats",
"it": "Let's Encrypt certificati",
"es": "Let's Encrypt Certificados",
"pl": "Let's Encrypt certyfikaty",
"zh-cn": "Let's Encrypt证书"
};
systemDictionary["Please activate secure communication"] = {
"en": "Please activate secure communication",
"de": "Bitte sichere Kommunikation aktivieren",
"ru": "Включите безопасную связь",
"pt": "Active a comunicação segura",
"nl": "Activeer alstublieft beveiligde communicatie",
"fr": "Veuillez activer la communication sécurisée",
"it": "Si prega di attivare la comunicazione sicura",
"es": "Por favor active la comunicación segura",
"pl": "Aktywuj bezpieczną komunikację",
"zh-cn": "请激活安全通信"
};
if (socket.connected) {
loadSystemConfig(function () {
typeof translateAll === 'function' && translateAll();
loadSettings(prepareTooltips);
});
} else {
socket.on('connect', function () {
loadSystemConfig(function () {
typeof translateAll === 'function' && translateAll();
loadSettings(prepareTooltips);
});
});
}
var $body = $('body');
$body.wrapInner('<div class="adapter-body"></div>');
/*$body.prepend('<div class="header ui-tabs-nav ui-widget ui-widget-header ui-corner-all" style="padding: 2px" >' +
'<button id="save" class="translateB">save</button> ' +
'<button id="saveclose" class="translateB">saveclose</button> ' +
'<button id="close" class="translateB" style="float: right;">cancel</button> ' +
'</div>');
*/
$body.append(
'<div class="m"><nav class="dialog-config-buttons nav-wrapper footer">' +
' <a class="btn btn-active btn-save"><i class="material-icons left">save</i><span class="translate">save</span></a> ' +
' <a class="btn btn-save-close"><i class="material-icons left">save</i><i class="material-icons left">close</i><span class="translate">saveclose</span></a> ' +
' <a class="btn btn-cancel"><i class="material-icons left">close</i><span class="translate">close</span></a>' +
'</nav></div>');
var $navButtons = $('.dialog-config-buttons');
$navButtons.find('.btn-save').on('click', function () {
if (typeof save === 'undefined') {
alert('Please implement save function in your admin/index.html');
return;
}
save(function (obj, common, redirect) {
if (redirect && parent && parent.adapterRedirect) {
parent.adapterRedirect(redirect);
}
saveSettings(obj, common);
});
});
function close() {
if (typeof parent !== 'undefined' && parent) {
try {
if (parent.$iframeDialog && typeof parent.$iframeDialog.close === 'function') {
parent.$iframeDialog.close();
} else {
parent.postMessage('close', '*');
}
} catch (e) {
parent.postMessage('close', '*');
}
}
}
$navButtons.find('.btn-save-close').on('click', function () {
if (typeof save === 'undefined') {
alert('Please implement save function in your admin/index.html');
return;
}
save(function (obj, common, redirect) {
if (redirect && parent && parent.adapterRedirect) {
parent.adapterRedirect(redirect);
}
saveSettings(obj, common, function () {
// window.close();
close();
});
});
});
$navButtons.find('.btn-cancel').on('click', function () {
close();
});
// detect, that we are now in react container
if (window.location.search.indexOf('react=true') !== -1) {
$('.adapter-container').addClass('react');
}
function saveSettings(native, common, callback) {
if (typeof common === 'function') {
callback = common;
common = null;
}
socket.emit('getObject', id, function (err, oldObj) {
oldObj = oldObj || {};
for (var a in native) {
if (native.hasOwnProperty(a)) {
oldObj.native[a] = native[a];
// encode all native attributes listed in oldObj.encryptedNative
if (oldObj.encryptedNative &&
typeof oldObj.encryptedNative === 'object' &&
oldObj.encryptedNative instanceof Array &&
oldObj.encryptedNative.indexOf(a) !== -1) {
oldObj.native[a] = encrypt(oldObj.native[a]);
}
}
}
if (common) {
for (var b in common) {
if (common.hasOwnProperty(b)) {
oldObj.common[b] = common[b];
}
}
}
if (onChangeSupported) {
$navButtons.find('.btn-save').addClass('disabled');
$navButtons.find('.btn-save-close').addClass('disabled');
$navButtons.find('.btn-cancel').find('span').html(_('close'));
}
socket.emit('setObject', id, oldObj, function (err) {
if (err) {
showMessage(err, _('Error'), 'alert');
return;
}
parent.postMessage('nochange', '*');
changed = false;
callback && callback();
});
});
}
var loadCount = 0;
var loaded = false;
// Read language settings
function loadSystemConfig(callback) {
if (loaded) {
return;
}
// retry strategy
var _timeout = setTimeout(function () {
_timeout = null;
loadCount++;
if (loadCount < 10) {
loadSystemConfig(callback);
}
}, 1000);
socket.emit('getObject', 'system.config', function (err, res) {
if (loaded) {
return;
}
loaded = true;
clearTimeout(_timeout);
_timeout = null;
if (!err && res && res.common) {
systemLang = res.common.language || systemLang;
systemConfig = res;
systemSecret = (systemConfig && systemConfig.native && systemConfig.native.secret) || 'Zgfr56gFe87jJOM';
}
socket.emit('getObject', 'system.certificates', function (err, res) {
if (!err && res) {
if (res.native && res.native.certificates) {
certs = [];
for (var c in res.native.certificates) {
if (!res.native.certificates.hasOwnProperty(c) || !res.native.certificates[c]) {
continue;
}
// If it is filename, it could be everything
if (res.native.certificates[c].length < 700 && (res.native.certificates[c].indexOf('/') !== -1 || res.native.certificates[c].indexOf('\\') !== -1)) {
var __cert = {
name: c,
type: ''
};
if (c.toLowerCase().indexOf('private') !== -1) {
__cert.type = 'private';
} else if (res.native.certificates[c].toLowerCase().indexOf('private') !== -1) {
__cert.type = 'private';
} else if (c.toLowerCase().indexOf('public') !== -1) {
__cert.type = 'public';
} else if (res.native.certificates[c].toLowerCase().indexOf('public') !== -1) {
__cert.type = 'public';
}
certs.push(__cert);
continue;
}
var _cert = {
name: c,
type: (res.native.certificates[c].substring(0, '-----BEGIN RSA PRIVATE KEY'.length) === '-----BEGIN RSA PRIVATE KEY' || res.native.certificates[c].substring(0, '-----BEGIN PRIVATE KEY'.length) === '-----BEGIN PRIVATE KEY') ? 'private' : 'public'
};
if (_cert.type === 'public') {
var m = res.native.certificates[c].split('-----END CERTIFICATE-----');
var count = 0;
for (var _m = 0; _m < m.length; _m++) {
if (m[_m].replace(/\r\n|\r|\n/, '').trim()) count++;
}
if (count > 1) _cert.type = 'chained';
}
certs.push(_cert);
}
}
}
callback && callback();
});
});
}
// callback if something changed
function onChange(isChanged) {
onChangeSupported = true;
if (typeof isChanged === 'boolean' && isChanged === false) {
parent.postMessage('nochange', '*');
changed = false;
$navButtons.find('.btn-save').addClass('disabled');
$navButtons.find('.btn-save-close').addClass('disabled');
$navButtons.find('.btn-cancel').find('span').html(_('close'));
} else {
parent.postMessage('change', '*');
changed = true;
$navButtons.find('.btn-save').removeClass('disabled');
$navButtons.find('.btn-save-close').removeClass('disabled');
$navButtons.find('.btn-cancel').find('span').html(_('cancel'));
}
}
function loadSettings(callback) {
socket.emit('getObject', id, function (err, res) {
if (!err && res && res.native) {
$('.adapter-instance').html(adapter + '.' + instance);
$('.adapter-config').html('system.adapter.' + adapter + '.' + instance);
common = res.common;
res.common && res.common.name && $('.adapter-name').html(res.common.name);
if (typeof load === 'undefined') {
alert('Please implement save function in your admin/index.html');
} else {
// decode all native attributes listed in res.encryptedNative
if (res.encryptedNative && typeof res.encryptedNative === 'object' && res.encryptedNative instanceof Array) {
for (var i = 0; i < res.encryptedNative.length; i++) {
if (res.native[res.encryptedNative[i]]) {
res.native[res.encryptedNative[i]] = decrypt(res.native[res.encryptedNative[i]]);
}
}
} else {
var idx = supportedFeatures.indexOf('ADAPTER_AUTO_DECRYPT_NATIVE');
if (idx !== -1) {
// if no encryptedNative exists the feature is irrelevant, remove for compatibility reasons
supportedFeatures.splice(idx, 1);
}
}
load(res.native, onChange);
// init selects
if (isMaterialize) {
$('select').select();
M.updateTextFields();
// workaround for materialize checkbox problem
$('input[type="checkbox"]+span').off('click').on('click', function (event) {
var $input = $(this).prev();
if (!$input.prop('disabled')) {
$input.prop('checked', !$input.prop('checked')).trigger('change');
// prevent propagation to prevent original handling from reverting our value change
event.preventDefault();
event.stopImmediatePropagation();
}
});
}
}
if (typeof callback === 'function') {
callback();
}
} else {
if (typeof callback === 'function') {
callback();
}
alert('error loading settings for ' + id + '\n\n' + err);
}
});
}
___onChange = onChange;
}
$(document).ready(function () {
'use strict';
if (window.location.pathname.indexOf('/index_m.html') === -1) {
// load materialize
var cssLink = document.createElement('link');
cssLink.href = '../../lib/css/materialize.css';
cssLink.type = 'text/css';
cssLink.rel = 'stylesheet';
cssLink.media = 'screen,print';
document.getElementsByTagName('head')[0].appendChild(cssLink);
// load materialize.js
var jsLink = document.createElement('script');
jsLink.onload = preInit;
jsLink.src = '../../lib/js/materialize.js';
document.head.appendChild(jsLink);
} else {
isMaterialize = true;
preInit();
}
});
function handleFileSelect(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
try {
var json = JSON.parse(contents);
if (json.native && json.common) {
if (json.common.name !== common.name) {
showError(_('otherConfig', json.common.name));
} else {
load(json.native, ___onChange);
// init selects
if (isMaterialize) {
$('select').select();
M.updateTextFields();
// workaround for materialize checkbox problem
$('input[type="checkbox"]+span').off('click').on('click', function (event) {
var $input = $(this).prev();
if (!$input.prop('disabled')) {
$input.prop('checked', !$input.prop('checked')).trigger('change');
// prevent propagation to prevent original handling from reverting our value change
event.preventDefault();
event.stopImmediatePropagation();
}
});
}
___onChange();
showToast(null, _('configLoaded'));
}
} else {
showError(_('invalidConfig'));
}
} catch (e) {
showError(e.toString());
}
};
r.readAsText(f);
} else {
alert('Failed to open JSON File');
}
}
function generateFile(filename, obj) {
var el = document.createElement('a');
el.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(obj, null, 2)));
el.setAttribute('download', filename);
el.style.display = 'none';
document.body.appendChild(el);
el.click();
document.body.removeChild(el);
}
function prepareTooltips() {
if (isMaterialize) {
// init tabs
$('.tabs').mtabs();
var buttonsText = '';
if (common && common.readme) {
buttonsText += ' <a class="btn-floating btn-small waves-effect waves-light" href="' + common.readme +'" target="_blank">' +
' <i class="material-icons">live_help</i>' +
' </a>';
}
buttonsText += ' <a class="btn-floating btn-small waves-effect waves-light adapter-config-load" title="' + _('loadConfig') + '">' +
' <i class="material-icons">file_upload</i>' +
' </a>';
buttonsText += ' <a class="btn-floating btn-small waves-effect waves-light adapter-config-save" title="' + _('saveConfig') + '">' +
' <i class="material-icons">file_download</i>' +
' </a>';
if (buttonsText) {
// add help link after logo
var $logo = $('.logo').first().parent();
if ($logo.length) {
$('<div class="col s6 help-link">' + buttonsText + '</div>').insertAfter($logo);
}
$('.adapter-config-load').click(function () {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('id', 'files');
input.setAttribute('opacity', 0);
input.addEventListener('change', function (e) {
handleFileSelect(e, function () {});
}, false);
(input.click)();
});
$('.adapter-config-save').click(function () {
save(function (native, cmn) {
var result = {
_id: 'system.adapter.' + common.name + '.' + instance,
common: JSON.parse(JSON.stringify(common)),
native: native
};
// remove unimportant information
if (result.common.news) {
delete result.common.news;
}
if (result.common.titleLang) {
delete result.common.titleLang;
}
if (result.common.desc) {
delete result.common.desc;
}
if (cmn) {
for (var b in cmn) {
if (cmn.hasOwnProperty(b)) {
result.common[b] = cmn[b];
}
}
}
//window.open('data:application/iobroker; content-disposition=attachment; filename=' + result._id + '.json,' + JSON.stringify(result, null, 2));
generateFile(result._id + '.json', result);
});
})
}
$('.value').each(function () {
var $this = $(this);
// replace all labels after checkboxes to span (bug in materialize)
if ($this.attr('type') === 'checkbox') {
$this.addClass('filled-in');
var $label = $this.next();
if ($label.prop('tagName') === 'LABEL') {
$label.replaceWith('<span style="' + ($label.attr('style') || '') + '" class="' + ($label.attr('class') || '') + '">' + $label.html() +'</span>');
$label = $this.next();
}
$label.off('click').on('click', function () {
var $input = $(this).prev();
if (!$input.prop('disabled')) {
$input.prop('checked', !$input.prop('checked')).trigger('change');
}
});
}
var id = $this.data('id');
var tooltip = '';
if (systemDictionary['tooltip_' + id]) {
tooltip = systemDictionary['tooltip_' + id][systemLang] || systemDictionary['tooltip_' + id].en;
}
var link = $this.data('link');
if (link && common) {
if (link === true) {
if (common.readme) {
link = common.readme + '#' + id;
} else {
link = 'https://github.com/ioBroker/ioBroker.' + common.name + '#' + id;
}
}
if (!link.match('^https?:\/\/')) {
if (common.readme) {
link = common.readme + '#' + link;
} else {
link = 'https://github.com/ioBroker/ioBroker.' + common.name + '#' + link;
}
}
}
if (link) {
$('<a class="tooltip" href="' + link + '" title="' + (tooltip || systemDictionary.htooltip[systemLang]) + '" target="_blank"><i class="material-icons tooltip">live_help</i></a>').insertBefore($this);
} else if (tooltip) {
$('<i class="material-icons tooltip" title="' + tooltip + '">help_outline</i>').insertBefore($this);
}
});
} else {
$('.admin-icon').each(function () {
var id = $(this).data('id');
if (!id) {
var $prev = $(this).prev();
var $input = $prev.find('input');
if (!$input.length) $input = $prev.find('select');
if (!$input.length) $input = $prev.find('textarea');
if (!$input.length) {
$prev = $prev.parent();
$input = $prev.find('input');
if (!$input.length) $input = $prev.find('select');
if (!$input.length) $input = $prev.find('textarea');
}
if ($input.length) id = $input.attr('id');
}
if (!id) {
return;
}
var tooltip = '';
if (systemDictionary['tooltip_' + id]) {
tooltip = systemDictionary['tooltip_' + id][systemLang] || systemDictionary['tooltip_' + id].en;
}
var icon = '';
var link = $(this).data('link');
if (link && common) {
if (link === true) {
if (common.readme) {
link = common.readme + '#' + id;
} else {
link = 'https://github.com/ioBroker/ioBroker.' + common.name + '#' + id;
}
}
if (!link.match('^https?:\/\/')) {
if (common.readme) {
link = common.readme + '#' + link;
} else {
link = 'https://github.com/ioBroker/ioBroker.' + common.name + '#' + link;
}
}
icon += '<a class="admin-tooltip-link" target="config_help" href="' + link + '" title="' + (tooltip || systemDictionary.htooltip[systemLang]) + '"><img class="admin-tooltip-icon" src="../../img/info.png" /></a>';
} else if (tooltip) {
icon += '<img class="admin-tooltip-icon" title="' + tooltip + '" src="../../img/info.png"/>';
}
if (icon) {
$(this).html(icon);
}
});
$('.admin-text').each(function () {
var id = $(this).data('id');
if (!id) {
var $prev = $(this).prev();
var $input = $prev.find('input');
if (!$input.length) {
$input = $prev.find('select');
}
if (!$input.length) {
$input = $prev.find('textarea');
}
if (!$input.length) {
$prev = $prev.parent();
$input = $prev.find('input');
if (!$input.length) {
$input = $prev.find('select');
}
if (!$input.length) {
$input = $prev.find('textarea');
}
}
if ($input.length) {
id = $input.attr('id');
}
}
if (!id) {
return;
}
// check if translation for this exist
if (systemDictionary['info_' + id]) {
$(this).html('<span class="admin-tooltip-text">' + (systemDictionary['info_' + id][systemLang] || systemDictionary['info_' + id].en) + '</span>');
}
});
}
}
function supportsFeature(feature) {
return supportedFeatures.indexOf(feature) !== -1;
}
function showMessageJQ(message, title, icon, width) {
var $dialogMessage = $('#dialog-message-settings');
if (!$dialogMessage.length) {
$('body').append('<div id="dialog-message-settings" title="Message" style="display: none">\n' +
'<p>' +
'<span id="dialog-message-icon-settings" class="ui-icon ui-icon-circle-check" style="float :left; margin: 0 7px 50px 0;"></span>\n' +
'<span id="dialog-message-text-settings"></span>\n' +
'</p>\n' +
'</div>');
$dialogMessage = $('#dialog-message-settings');
$dialogMessage.dialog({
autoOpen: false,
modal: true,
buttons: [
{
text: _('Ok'),
click: function () {
$(this).dialog('close');
}
}
]
});
}
$dialogMessage.dialog('option', 'width', width + 500);
if (typeof _ !== 'undefined') {
$dialogMessage.dialog('option', 'title', title || _('Message'));
} else {
$dialogMessage.dialog('option', 'title', title || 'Message');
}
$('#dialog-message-text-settings').html(message);
if (icon) {
$('#dialog-message-icon-settings')
.show()
.attr('class', '')
.addClass('ui-icon ui-icon-' + icon);
} else {
$('#dialog-message-icon-settings').hide();
}
$dialogMessage.dialog('open');
}
function showMessage(message, title, icon) {
if (!isMaterialize) {
return showMessageJQ(message, title, icon);
}
var $dialogMessage;
// noinspection JSJQueryEfficiency
$dialogMessage = $('#dialog-message');
if (!$dialogMessage.length) {
$('body').append(
'<div class="m"><div id="dialog-message" class="modal modal-fixed-footer">' +
' <div class="modal-content">' +
' <h6 class="dialog-title title"></h6>' +
' <p><i class="large material-icons dialog-icon"></i><span class="dialog-text"></span></p>' +
' </div>' +
' <div class="modal-footer">' +
' <a class="modal-action modal-close waves-effect waves-green btn-flat translate">Ok</a>' +
' </div>' +
'</div></div>');
$dialogMessage = $('#dialog-message');
}
if (icon) {
$dialogMessage.find('.dialog-icon')
.show()
.html(icon);
} else {
$dialogMessage.find('.dialog-icon').hide();
}
if (title) {
$dialogMessage.find('.dialog-title').html(title).show();
} else {
$dialogMessage.find('.dialog-title').hide();
}
$dialogMessage.find('.dialog-text').html(message);
$dialogMessage.modal().modal('open');
}
function confirmMessageJQ(message, title, icon, buttons, callback) {
var $dialogConfirm = $('#dialog-confirm-settings');
if (!$dialogConfirm.length) {
$('body').append('<div id="dialog-confirm-settings" title="Message" style="display: none">\n' +
'<p>' +
'<span id="dialog-confirm-icon-settings" class="ui-icon ui-icon-circle-check" style="float :left; margin: 0 7px 50px 0;"></span>\n' +
'<span id="dialog-confirm-text-settings"></span>\n' +
'</p>\n' +
'</div>');
$dialogConfirm = $('#dialog-confirm-settings');
$dialogConfirm.dialog({
autoOpen: false,
modal: true
});
}
if (typeof buttons === 'function') {
callback = buttons;
$dialogConfirm.dialog('option', 'buttons', [
{
text: _('Ok'),
click: function () {
var cb = $(this).data('callback');
$(this).data('callback', null);
$(this).dialog('close');
cb && cb(true);
}
},
{
text: _('Cancel'),
click: function () {
var cb = $(this).data('callback');
$(this).data('callback', null);
$(this).dialog('close');
cb && cb(false);
}
}
]);
} else if (typeof buttons === 'object') {
for (var b = 0; b < buttons.length; b++) {
buttons[b] = {
text: buttons[b],
id: 'dialog-confirm-button-' + b,
click: function (e) {
var id = parseInt(e.currentTarget.id.substring('dialog-confirm-button-'.length), 10);
var cb = $(this).data('callback');
$(this).data('callback', null);
$(this).dialog('close');
cb && cb(id);
}
}
}
$dialogConfirm.dialog('option', 'buttons', buttons);
}
$dialogConfirm.dialog('option', 'title', title || _('Message'));
$('#dialog-confirm-text-settings').html(message);
if (icon) {
$('#dialog-confirm-icon-settings')
.show()
.attr('class', '')
.addClass('ui-icon ui-icon-' + icon);
} else {
$('#dialog-confirm-icon-settings').hide();
}
$dialogConfirm.data('callback', callback);
$dialogConfirm.dialog('open');
}
function confirmMessage(message, title, icon, buttons, callback) {
if (!isMaterialize) {
return confirmMessageJQ(message, title, icon, buttons, callback);
}
var $dialogConfirm;
// noinspection JSJQueryEfficiency
$dialogConfirm = $('#dialog-confirm');
if (!$dialogConfirm.length) {
$('body').append(
'<div class="m"><div id="dialog-confirm" class="modal modal-fixed-footer">' +
' <div class="modal-content">' +
' <h6 class="dialog-title title"></h6>' +
' <p><i class="large material-icons dialog-icon"></i><span class="dialog-text"></span></p>' +
' </div>' +
' <div class="modal-footer">' +
' </div>' +
'</div></div>'
);
$dialogConfirm = $('#dialog-confirm');
}
if (typeof buttons === 'function') {
callback = buttons;
$dialogConfirm.find('.modal-footer').html(
'<a class="modal-action modal-close waves-effect waves-green btn-flat translate" data-result="true">' + _('Ok') + '</a>' +
'<a class="modal-action modal-close waves-effect waves-green btn-flat translate">' + _('Cancel') + '</a>');
$dialogConfirm.find('.modal-footer .modal-action').on('click', function () {
var cb = $dialogConfirm.data('callback');
cb && cb($(this).data('result'));
});
} else if (typeof buttons === 'object') {
var tButtons = '';
for (var b = buttons.length - 1; b >= 0; b--) {
tButtons += '<a class="modal-action modal-close waves-effect waves-green btn-flat translate" data-id="' + b + '">' + buttons[b] + '</a>';
}
$dialogConfirm.find('.modal-footer').html(tButtons);
$dialogConfirm.find('.modal-footer .modal-action').on('click', function () {
var cb = $dialogConfirm.data('callback');
cb && cb($(this).data('id'));
});
}
$dialogConfirm.find('.dialog-title').text(title || _('Please confirm'));
if (icon) {
$dialogConfirm.find('.dialog-icon')
.show()
.html(icon);
} else {
$dialogConfirm.find('.dialog-icon').hide();
}
if (title) {
$dialogConfirm.find('.dialog-title').html(title).show();
} else {
$dialogConfirm.find('.dialog-title').hide();
}
$dialogConfirm.find('.dialog-text').html(message);
$dialogConfirm.data('callback', callback);
$dialogConfirm.modal({
dismissible: false
}).modal('open');
}
function showError(error) {
showMessage(_(error), _('Error'), 'error_outline');
}
function showToast(parent, message, icon, duration, isError, classes) {
if (typeof parent === 'string') {
classes = isError;
isError = duration;
icon = message;
message = parent;
parent = null;
}
if (parent && parent instanceof jQuery) {
parent = parent[0];
}
classes = classes || [];
if (typeof classes === 'string') {
classes = [classes];
}
isError && classes.push('dropZone-error');
M.toast({
parentSelector: parent || $('body')[0],
html: message + (icon ? '<i class="material-icons">' + icon + '</i>' : ''),
displayLength: duration || 3000,
classes: classes
});
}
function getObject(id, callback) {
socket.emit('getObject', id, function (err, res) {
if (!err && res) {
callback && callback(err, res);
} else {
callback && callback(null);
}
});
}
function getState(id, callback) {
socket.emit('getState', id, function (err, res) {
if (!err && res) {
callback && callback(err, res);
} else {
callback && callback(null);
}
});