@iobroker/adapter-react-v5 3.5.2 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Connection.js CHANGED
@@ -1,3208 +1,16 @@
1
1
  "use strict";
2
2
 
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
3
  Object.defineProperty(exports, "__esModule", {
5
4
  value: true
6
5
  });
7
- exports["default"] = exports.PROGRESS = exports.ERRORS = void 0;
8
- exports.pattern2RegEx = pattern2RegEx;
9
- var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
10
- var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
11
- var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
12
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
13
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
14
- var _propTypes = _interopRequireDefault(require("prop-types"));
15
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
16
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
17
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
18
- /** Possible progress states. */
19
- var PROGRESS = {
20
- /** The socket is connecting. */
21
- CONNECTING: 0,
22
- /** The socket is successfully connected. */
23
- CONNECTED: 1,
24
- /** All objects are loaded. */
25
- OBJECTS_LOADED: 2,
26
- /** The socket is ready for use. */
27
- READY: 3
28
- };
29
- exports.PROGRESS = PROGRESS;
30
- var PERMISSION_ERROR = 'permissionError';
31
- var NOT_CONNECTED = 'notConnectedError';
32
- var TIMEOUT_FOR_ADMIN4 = 1300;
33
- var ERRORS = {
34
- PERMISSION_ERROR: PERMISSION_ERROR,
35
- NOT_CONNECTED: NOT_CONNECTED
36
- };
37
- exports.ERRORS = ERRORS;
38
- function fixAdminUI(obj) {
39
- if (obj && obj.common && !obj.common.adminUI) {
40
- if (obj.common.noConfig) {
41
- obj.common.adminUI = obj.common.adminUI || {};
42
- obj.common.adminUI.config = 'none';
43
- } else if (obj.common.jsonConfig) {
44
- obj.common.adminUI = obj.common.adminUI || {};
45
- obj.common.adminUI.config = 'json';
46
- } else if (obj.common.materialize) {
47
- obj.common.adminUI = obj.common.adminUI || {};
48
- obj.common.adminUI.config = 'materialize';
49
- } else {
50
- obj.common.adminUI = obj.common.adminUI || {};
51
- obj.common.adminUI.config = 'html';
52
- }
53
- if (obj.common.jsonCustom) {
54
- obj.common.adminUI = obj.common.adminUI || {};
55
- obj.common.adminUI.custom = 'json';
56
- } else if (obj.common.supportCustoms) {
57
- obj.common.adminUI = obj.common.adminUI || {};
58
- obj.common.adminUI.custom = 'json';
59
- }
60
- if (obj.common.materializeTab && obj.common.adminTab) {
61
- obj.common.adminUI = obj.common.adminUI || {};
62
- obj.common.adminUI.tab = 'materialize';
63
- } else if (obj.common.adminTab) {
64
- obj.common.adminUI = obj.common.adminUI || {};
65
- obj.common.adminUI.tab = 'html';
66
- }
67
- obj.common.adminUI && console.debug("Please add to \"".concat(obj._id.replace(/\.\d+$/, ''), "\" common.adminUI=").concat(JSON.stringify(obj.common.adminUI)));
6
+ Object.defineProperty(exports, "PROGRESS", {
7
+ enumerable: true,
8
+ get: function get() {
9
+ return _socketClient.PROGRESS;
68
10
  }
69
- return obj;
70
- }
71
-
72
- /** Converts ioB pattern into regex
73
- * @param {string} pattern
74
- * @returns {string}
75
- */
76
-
77
- function pattern2RegEx(pattern) {
78
- pattern = (pattern || '').toString();
79
- var startsWithWildcard = pattern[0] === '*';
80
- var endsWithWildcard = pattern[pattern.length - 1] === '*';
81
- pattern = pattern.replace(/[-/\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*');
82
- return (startsWithWildcard ? '' : '^') + pattern + (endsWithWildcard ? '' : '$');
83
- }
84
- var Connection = /*#__PURE__*/function () {
85
- /**
86
- * @param {import('./types').ConnectionProps} props
87
- */
88
- function Connection(props) {
89
- var _this = this;
90
- (0, _classCallCheck2["default"])(this, Connection);
91
- props = props || {
92
- protocol: window.location.protocol,
93
- host: window.location.hostname
94
- };
95
- this.props = props;
96
- this.autoSubscribes = this.props.autoSubscribes || [];
97
- this.autoSubscribeLog = this.props.autoSubscribeLog;
98
- this.props.protocol = this.props.protocol || window.location.protocol;
99
- this.props.host = this.props.host || window.location.hostname;
100
- this.props.port = this.props.port || (window.location.port === '3000' ? Connection.isWeb() ? 8082 : 8081 : window.location.port);
101
- this.props.ioTimeout = Math.max(this.props.ioTimeout || 20000, 20000);
102
- this.props.cmdTimeout = Math.max(this.props.cmdTimeout || 5000, 5000);
103
-
104
- // breaking change. Do not load all objects by default is true
105
- this.doNotLoadAllObjects = this.props.doNotLoadAllObjects === undefined ? true : this.props.doNotLoadAllObjects;
106
- this.doNotLoadACL = this.props.doNotLoadACL === undefined ? true : this.props.doNotLoadACL;
107
-
108
- /** @type {Record<string, ioBroker.State>} */
109
- this.states = {};
110
- this.objects = null;
111
- this.acl = null;
112
- this.firstConnect = true;
113
- this.waitForRestart = false;
114
- /** @type {ioBroker.Languages} */
115
- this.systemLang = 'en';
116
- this.connected = false;
117
- this._waitForFirstConnection = new Promise(function (resolve) {
118
- _this._waitForFirstConnectionResolve = resolve;
119
- });
120
-
121
- /** @type {Record<string, { reg: RegExp; cbs: ioBroker.StateChangeHandler[]}>} */
122
- this.statesSubscribes = {}; // subscribe for states
123
-
124
- /** @type {Record<string, { reg: RegExp; cbs: import('./types').ObjectChangeHandler[]}>} */
125
- this.objectsSubscribes = {}; // subscribe for objects
126
- this.filesSubscribes = {}; // subscribe for files
127
- this.onProgress = this.props.onProgress || function () {};
128
- this.onError = this.props.onError || function (err) {
129
- console.error(err);
130
- };
131
- this.loaded = false;
132
- this.loadTimer = null;
133
- this.loadCounter = 0;
134
- this.admin5only = this.props.admin5only || false;
135
-
136
- /** @type {((connected: boolean) => void)[]} */
137
- this.onConnectionHandlers = [];
138
- /** @type {((message: string) => void)[]} */
139
- this.onLogHandlers = [];
140
-
141
- /** @type {Record<string, Promise<any>>} */
142
- this._promises = {};
143
- this.log.error = function (text) {
144
- return _this.log(text, 'error');
145
- };
146
- this.log.warn = function (text) {
147
- return _this.log(text, 'warn');
148
- };
149
- this.log.info = function (text) {
150
- return _this.log(text, 'info');
151
- };
152
- this.log.debug = function (text) {
153
- return _this.log(text, 'debug');
154
- };
155
- this.log.silly = function (text) {
156
- return _this.log(text, 'silly');
157
- };
158
- this.startSocket();
159
- }
160
-
161
- /**
162
- * Checks if this connection is running in a web adapter and not in an admin.
163
- * @returns {boolean} True if running in a web adapter or in a socketio adapter.
164
- */
165
- (0, _createClass2["default"])(Connection, [{
166
- key: "startSocket",
167
- value:
168
- /**
169
- * Starts the socket.io connection.
170
- * @returns {void}
171
- */
172
- function startSocket() {
173
- var _this2 = this;
174
- // if socket io is not yet loaded
175
- if (typeof window.io === 'undefined') {
176
- // if in index.html the onLoad function not defined
177
- if (typeof window.registerSocketOnLoad !== 'function') {
178
- // poll if loaded
179
- this.scriptLoadCounter = this.scriptLoadCounter || 0;
180
- this.scriptLoadCounter++;
181
- if (this.scriptLoadCounter < 30) {
182
- // wait till the script loaded
183
- setTimeout(function () {
184
- return _this2.startSocket();
185
- }, 100);
186
- return;
187
- } else {
188
- window.alert('Cannot load socket.io.js!');
189
- }
190
- } else {
191
- // register on load
192
- window.registerSocketOnLoad(function () {
193
- return _this2.startSocket();
194
- });
195
- }
196
- return;
197
- } else {
198
- // socket was initialized, do not repeat
199
- if (this._socket) {
200
- return;
201
- }
202
- }
203
- var host = this.props.host;
204
- var port = this.props.port;
205
- var protocol = this.props.protocol.replace(':', '');
206
- var path = window.location.pathname;
207
- if (window.location.hostname === 'iobroker.net' || window.location.hostname === 'iobroker.pro') {
208
- path = '';
209
- } else {
210
- // if web adapter, socket io could be on other port or even host
211
- if (window.socketUrl) {
212
- var parts = window.socketUrl.split(':');
213
- host = parts[0] || host;
214
- port = parts[1] || port;
215
- if (host.includes('://')) {
216
- parts = host.split('://');
217
- protocol = parts[0];
218
- host = parts[1];
219
- }
220
- }
221
- // get current path
222
- var pos = path.lastIndexOf('/');
223
- if (pos !== -1) {
224
- path = path.substring(0, pos + 1);
225
- }
226
- if (Connection.isWeb()) {
227
- // remove one level, like echarts, vis, .... We have here: '/echarts/'
228
- var _parts = path.split('/');
229
- if (_parts.length > 2) {
230
- _parts.pop();
231
- // if it is version, like in material, so remove it too
232
- if (_parts[_parts.length - 1].match(/\d+\.\d+\.\d+/)) {
233
- _parts.pop();
234
- }
235
- _parts.pop();
236
- path = _parts.join('/');
237
- if (!path.endsWith('/')) {
238
- path += '/';
239
- }
240
- }
241
- }
242
- }
243
- var url = port ? "".concat(protocol, "://").concat(host, ":").concat(port).concat(path) : "".concat(protocol, "://").concat(host).concat(path);
244
- this._socket = window.io.connect(url, {
245
- path: path.endsWith('/') ? path + 'socket.io' : path + '/socket.io',
246
- query: 'ws=true',
247
- name: this.props.name,
248
- timeout: this.props.ioTimeout
249
- });
250
- this._socket.on('connect', function (noTimeout) {
251
- // If the user is not admin it takes some time to install the handlers, because all rights must be checked
252
- if (noTimeout !== true) {
253
- setTimeout(function () {
254
- return _this2.getVersion().then(function (info) {
255
- var _info$version$split = info.version.split('.'),
256
- _info$version$split2 = (0, _slicedToArray2["default"])(_info$version$split, 3),
257
- major = _info$version$split2[0],
258
- minor = _info$version$split2[1],
259
- patch = _info$version$split2[2];
260
- var v = parseInt(major, 10) * 10000 + parseInt(minor, 10) * 100 + parseInt(patch, 10);
261
- if (v < 40102) {
262
- _this2._authTimer = null;
263
- // possible this is old version of admin
264
- _this2.onPreConnect(false, false);
265
- } else {
266
- _this2._socket.emit('authenticate', function (isOk, isSecure) {
267
- return _this2.onPreConnect(isOk, isSecure);
268
- });
269
- }
270
- });
271
- }, 500);
272
- } else {
273
- // iobroker websocket waits, till all handlers are installed
274
- _this2._socket.emit('authenticate', function (isOk, isSecure) {
275
- return _this2.onPreConnect(isOk, isSecure);
276
- });
277
- }
278
- });
279
- this._socket.on('reconnect', function () {
280
- _this2.onProgress(PROGRESS.READY);
281
- _this2.connected = true;
282
- if (_this2.waitForRestart) {
283
- window.location.reload(false);
284
- } else {
285
- _this2._subscribe(true);
286
- _this2.onConnectionHandlers.forEach(function (cb) {
287
- return cb(true);
288
- });
289
- }
290
- });
291
- this._socket.on('disconnect', function () {
292
- _this2.connected = false;
293
- _this2.subscribed = false;
294
- _this2.onProgress(PROGRESS.CONNECTING);
295
- _this2.onConnectionHandlers.forEach(function (cb) {
296
- return cb(false);
297
- });
298
- });
299
- this._socket.on('reauthenticate', function () {
300
- return _this2.authenticate();
301
- });
302
- this._socket.on('log', function (message) {
303
- _this2.props.onLog && _this2.props.onLog(message);
304
- _this2.onLogHandlers.forEach(function (cb) {
305
- return cb(message);
306
- });
307
- });
308
- this._socket.on('error', function (err) {
309
- var _err = err || '';
310
- if (typeof _err.toString !== 'function') {
311
- _err = JSON.stringify(_err);
312
- console.error("Received strange error: ".concat(_err));
313
- }
314
- _err = _err.toString();
315
- if (_err.includes('User not authorized')) {
316
- _this2.authenticate();
317
- } else {
318
- window.alert("Socket Error: ".concat(err));
319
- }
320
- });
321
- this._socket.on('connect_error', function (err) {
322
- return console.error("Connect error: ".concat(err));
323
- });
324
- this._socket.on('permissionError', function (err) {
325
- return _this2.onError({
326
- message: 'no permission',
327
- operation: err.operation,
328
- type: err.type,
329
- id: err.id || ''
330
- });
331
- });
332
- this._socket.on('objectChange', function (id, obj) {
333
- return setTimeout(function () {
334
- return _this2.objectChange(id, obj);
335
- }, 0);
336
- });
337
- this._socket.on('stateChange', function (id, state) {
338
- return setTimeout(function () {
339
- return _this2.stateChange(id, state);
340
- }, 0);
341
- });
342
- this._socket.on('fileChange', function (id, fileName, size) {
343
- return setTimeout(function () {
344
- return _this2.fileChange(id, fileName, size);
345
- }, 0);
346
- });
347
- this._socket.on('cmdStdout', function (id, text) {
348
- return _this2.onCmdStdoutHandler && _this2.onCmdStdoutHandler(id, text);
349
- });
350
- this._socket.on('cmdStderr', function (id, text) {
351
- return _this2.onCmdStderrHandler && _this2.onCmdStderrHandler(id, text);
352
- });
353
- this._socket.on('cmdExit', function (id, exitCode) {
354
- return _this2.onCmdExitHandler && _this2.onCmdExitHandler(id, exitCode);
355
- });
356
- }
357
-
358
- /**
359
- * Called internally.
360
- * @private
361
- * @param {boolean} isOk
362
- * @param {boolean} isSecure
363
- */
364
- }, {
365
- key: "onPreConnect",
366
- value: function onPreConnect(isOk, isSecure) {
367
- var _this3 = this;
368
- if (this._authTimer) {
369
- clearTimeout(this._authTimer);
370
- this._authTimer = null;
371
- }
372
- this.connected = true;
373
- this.isSecure = isSecure;
374
- if (this.waitForRestart) {
375
- window.location.reload(false);
376
- } else {
377
- if (this.firstConnect) {
378
- // retry strategy
379
- this.loadTimer = setTimeout(function () {
380
- _this3.loadTimer = null;
381
- _this3.loadCounter++;
382
- if (_this3.loadCounter < 10) {
383
- _this3.onConnect();
384
- }
385
- }, 1000);
386
- if (!this.loaded) {
387
- this.onConnect();
388
- }
389
- } else {
390
- this.onProgress(PROGRESS.READY);
391
- }
392
- this._subscribe(true);
393
- this.onConnectionHandlers.forEach(function (cb) {
394
- return cb(true);
395
- });
396
- }
397
- if (this._waitForFirstConnectionResolve) {
398
- this._waitForFirstConnectionResolve();
399
- this._waitForFirstConnectionResolve = null;
400
- }
401
- }
402
-
403
- /**
404
- * Checks if the socket is connected.
405
- * @returns {boolean} true if connected.
406
- */
407
- }, {
408
- key: "isConnected",
409
- value: function isConnected() {
410
- return this.connected;
411
- }
412
-
413
- /**
414
- * Checks if the socket is connected.
415
- * @returns {Promise<void>} Promise resolves if once connected.
416
- */
417
- }, {
418
- key: "waitForFirstConnection",
419
- value: function waitForFirstConnection() {
420
- return this._waitForFirstConnection;
421
- }
422
-
423
- /**
424
- * Called internally.
425
- * @private
426
- */
427
- }, {
428
- key: "_getUserPermissions",
429
- value: function _getUserPermissions(cb) {
430
- if (this.doNotLoadACL) {
431
- return cb && cb();
432
- } else {
433
- this._socket.emit('getUserPermissions', cb);
434
- }
435
- }
436
-
437
- /**
438
- * Called internally.
439
- * @private
440
- */
441
- }, {
442
- key: "onConnect",
443
- value: function onConnect() {
444
- var _this4 = this;
445
- this._getUserPermissions(function (err, acl) {
446
- if (err) {
447
- return _this4.onError('Cannot read user permissions: ' + err);
448
- } else if (!_this4.doNotLoadACL) {
449
- if (_this4.loaded) {
450
- return;
451
- }
452
- _this4.loaded = true;
453
- clearTimeout(_this4.loadTimer);
454
- _this4.loadTimer = null;
455
- _this4.onProgress(PROGRESS.CONNECTED);
456
- _this4.firstConnect = false;
457
- _this4.acl = acl;
458
- }
459
-
460
- // Read system configuration
461
- return (_this4.admin5only && !window.vendorPrefix ? _this4.getCompactSystemConfig() : _this4.getSystemConfig()).then(function (data) {
462
- if (_this4.doNotLoadACL) {
463
- if (_this4.loaded) {
464
- return undefined;
465
- }
466
- _this4.loaded = true;
467
- clearTimeout(_this4.loadTimer);
468
- _this4.loadTimer = null;
469
- _this4.onProgress(PROGRESS.CONNECTED);
470
- _this4.firstConnect = false;
471
- }
472
- _this4.systemConfig = data;
473
- if (_this4.systemConfig && _this4.systemConfig.common) {
474
- _this4.systemLang = _this4.systemConfig.common.language;
475
- } else {
476
- _this4.systemLang = window.navigator.userLanguage || window.navigator.language;
477
- if (_this4.systemLang !== 'en' && _this4.systemLang !== 'de' && _this4.systemLang !== 'ru') {
478
- _this4.systemConfig.common.language = 'en';
479
- _this4.systemLang = 'en';
480
- }
481
- }
482
- _this4.props.onLanguage && _this4.props.onLanguage(_this4.systemLang);
483
- if (!_this4.doNotLoadAllObjects) {
484
- return _this4.getObjects().then(function () {
485
- _this4.onProgress(PROGRESS.READY);
486
- _this4.props.onReady && _this4.props.onReady(_this4.objects);
487
- });
488
- } else {
489
- _this4.objects = _this4.admin5only ? {} : {
490
- 'system.config': data
491
- };
492
- _this4.onProgress(PROGRESS.READY);
493
- _this4.props.onReady && _this4.props.onReady(_this4.objects);
494
- }
495
- return undefined;
496
- })["catch"](function (e) {
497
- return _this4.onError('Cannot read system config: ' + e);
498
- });
499
- });
500
- }
501
-
502
- /**
503
- * Called internally.
504
- * @private
505
- */
506
- }, {
507
- key: "authenticate",
508
- value: function authenticate() {
509
- if (window.location.search.includes('&href=')) {
510
- window.location = "".concat(window.location.protocol, "//").concat(window.location.host).concat(window.location.pathname).concat(window.location.search).concat(window.location.hash);
511
- } else {
512
- window.location = "".concat(window.location.protocol, "//").concat(window.location.host).concat(window.location.pathname, "?login&href=").concat(window.location.search).concat(window.location.hash);
513
- }
514
- }
515
-
516
- /**
517
- * Subscribe to changes of the given state.
518
- * @param {string} id The ioBroker state ID.
519
- * @param {ioBroker.StateChangeHandler} cb The callback.
520
- */
521
- /**
522
- * Subscribe to changes of the given state.
523
- * @param {string} id The ioBroker state ID.
524
- * @param {boolean} binary Set to true if the given state is binary and requires Base64 decoding.
525
- * @param {ioBroker.StateChangeHandler} cb The callback.
526
- */
527
- }, {
528
- key: "subscribeState",
529
- value: function subscribeState(id, binary, cb) {
530
- if (typeof binary === 'function') {
531
- cb = binary;
532
- binary = false;
533
- }
534
- if (!this.statesSubscribes[id]) {
535
- var reg = id.replace(/\./g, '\\.').replace(/\*/g, '.*').replace(/\(/g, '\\(').replace(/\)/g, '\\)').replace(/\+/g, '\\+').replace(/\[/g, '\\[');
536
- if (reg.indexOf('*') === -1) {
537
- reg += '$';
538
- }
539
- this.statesSubscribes[id] = {
540
- reg: new RegExp(reg),
541
- cbs: []
542
- };
543
- this.statesSubscribes[id].cbs.push(cb);
544
- if (this.connected) {
545
- this._socket.emit('subscribe', id);
546
- }
547
- } else {
548
- !this.statesSubscribes[id].cbs.includes(cb) && this.statesSubscribes[id].cbs.push(cb);
549
- }
550
- if (typeof cb === 'function' && this.connected) {
551
- if (binary) {
552
- this.getBinaryState(id).then(function (base64) {
553
- return cb(id, base64);
554
- })["catch"](function (e) {
555
- return console.error("Cannot getForeignStates \"".concat(id, "\": ").concat(JSON.stringify(e)));
556
- });
557
- } else {
558
- if (Connection.isWeb()) {
559
- this._socket.emit('getStates', id, function (err, states) {
560
- err && console.error("Cannot getForeignStates \"".concat(id, "\": ").concat(JSON.stringify(err)));
561
- states && Object.keys(states).forEach(function (id) {
562
- return cb(id, states[id]);
563
- });
564
- });
565
- } else {
566
- this._socket.emit('getForeignStates', id, function (err, states) {
567
- err && console.error("Cannot getForeignStates \"".concat(id, "\": ").concat(JSON.stringify(err)));
568
- states && Object.keys(states).forEach(function (id) {
569
- return cb(id, states[id]);
570
- });
571
- });
572
- }
573
- }
574
- }
575
- }
576
-
577
- /**
578
- * Unsubscribes all callbacks from changes of the given state.
579
- * @param {string} id The ioBroker state ID.
580
- */
581
- /**
582
- * Unsubscribes the given callback from changes of the given state.
583
- * @param {string} id The ioBroker state ID.
584
- * @param {ioBroker.StateChangeHandler} cb The callback.
585
- */
586
- }, {
587
- key: "unsubscribeState",
588
- value: function unsubscribeState(id, cb) {
589
- if (this.statesSubscribes[id]) {
590
- if (cb) {
591
- var pos = this.statesSubscribes[id].cbs.indexOf(cb);
592
- pos !== -1 && this.statesSubscribes[id].cbs.splice(pos, 1);
593
- } else {
594
- this.statesSubscribes[id].cbs = [];
595
- }
596
- if (!this.statesSubscribes[id].cbs || !this.statesSubscribes[id].cbs.length) {
597
- delete this.statesSubscribes[id];
598
- this.connected && this._socket.emit('unsubscribe', id);
599
- }
600
- }
601
- }
602
-
603
- /**
604
- * Subscribe to changes of the given object.
605
- * @param {string} id The ioBroker object ID.
606
- * @param {import('./types').ObjectChangeHandler} cb The callback.
607
- * @returns {Promise<void>}
608
- */
609
- }, {
610
- key: "subscribeObject",
611
- value: function subscribeObject(id, cb) {
612
- if (!this.objectsSubscribes[id]) {
613
- var reg = id.replace(/\./g, '\\.').replace(/\*/g, '.*');
614
- if (!reg.includes('*')) {
615
- reg += '$';
616
- }
617
- this.objectsSubscribes[id] = {
618
- reg: new RegExp(reg),
619
- cbs: []
620
- };
621
- this.objectsSubscribes[id].cbs.push(cb);
622
- this.connected && this._socket.emit('subscribeObjects', id);
623
- } else {
624
- !this.objectsSubscribes[id].cbs.includes(cb) && this.objectsSubscribes[id].cbs.push(cb);
625
- }
626
- return Promise.resolve();
627
- }
628
-
629
- /**
630
- * Unsubscribes all callbacks from changes of the given object.
631
- * @param {string} id The ioBroker object ID.
632
- * @returns {Promise<void>}
633
- */
634
- /**
635
- * Unsubscribes the given callback from changes of the given object.
636
- * @param {string} id The ioBroker object ID.
637
- * @param {import('./types').ObjectChangeHandler} cb The callback.
638
- * @returns {Promise<void>}
639
- */
640
- }, {
641
- key: "unsubscribeObject",
642
- value: function unsubscribeObject(id, cb) {
643
- if (this.objectsSubscribes[id]) {
644
- if (cb) {
645
- var pos = this.objectsSubscribes[id].cbs.indexOf(cb);
646
- pos !== -1 && this.objectsSubscribes[id].cbs.splice(pos, 1);
647
- } else {
648
- this.objectsSubscribes[id].cbs = [];
649
- }
650
- if (this.connected && (!this.objectsSubscribes[id].cbs || !this.objectsSubscribes[id].cbs.length)) {
651
- delete this.objectsSubscribes[id];
652
- this.connected && this._socket.emit('unsubscribeObjects', id);
653
- }
654
- }
655
- return Promise.resolve();
656
- }
657
-
658
- /**
659
- * Called internally.
660
- * @param id
661
- * @param fileName
662
- * @param size
663
- */
664
- }, {
665
- key: "fileChange",
666
- value: function fileChange(id, fileName, size) {
667
- for (var _i = 0, _Object$values = Object.values(this.filesSubscribes); _i < _Object$values.length; _i++) {
668
- var sub = _Object$values[_i];
669
- if (sub.regId.test(id) && sub.regFilePattern.test(fileName)) {
670
- var _iterator = _createForOfIteratorHelper(sub.cbs),
671
- _step;
672
- try {
673
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
674
- var cb = _step.value;
675
- cb(id, fileName, size);
676
- }
677
- } catch (err) {
678
- _iterator.e(err);
679
- } finally {
680
- _iterator.f();
681
- }
682
- }
683
- }
684
- }
685
-
686
- /**
687
- * Subscribe to changes of the files.
688
- * @param {string} id The ioBroker state ID for meat object. Could be a pattern
689
- * @param {string} filePattern Pattern or file name, like 'main/*' or 'main/visViews.json`
690
- * @param {function} cb The callback.
691
- */
692
- }, {
693
- key: "subscribeFiles",
694
- value: function () {
695
- var _subscribeFiles = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(id, filePattern, cb) {
696
- var key;
697
- return _regenerator["default"].wrap(function _callee$(_context) {
698
- while (1) {
699
- switch (_context.prev = _context.next) {
700
- case 0:
701
- if (!(typeof cb !== 'function')) {
702
- _context.next = 2;
703
- break;
704
- }
705
- throw new Error('The state change handler must be a function!');
706
- case 2:
707
- key = "".concat(id, "$%$").concat(filePattern);
708
- if (!this.filesSubscribes[key]) {
709
- this.filesSubscribes[key] = {
710
- regId: new RegExp(pattern2RegEx(id)),
711
- regFilePattern: new RegExp(pattern2RegEx(filePattern)),
712
- cbs: [cb]
713
- };
714
- this.connected && this._socket.emit('subscribeFiles', id, filePattern);
715
- } else {
716
- !this.filesSubscribes[key].cbs.includes(cb) && this.filesSubscribes[key].cbs.push(cb);
717
- }
718
- case 4:
719
- case "end":
720
- return _context.stop();
721
- }
722
- }
723
- }, _callee, this);
724
- }));
725
- function subscribeFiles(_x, _x2, _x3) {
726
- return _subscribeFiles.apply(this, arguments);
727
- }
728
- return subscribeFiles;
729
- }()
730
- /**
731
- * Unsubscribes the given callback from changes of files.
732
- * @param {string} id The ioBroker state ID.
733
- * @param {string} filePattern Pattern or file name, like 'main/*' or 'main/visViews.json`
734
- * @param {function} cb The callback.
735
- */
736
- }, {
737
- key: "unsubscribeFiles",
738
- value: function unsubscribeFiles(id, filePattern, cb) {
739
- var key = "".concat(id, "$%$").concat(filePattern);
740
- if (this.filesSubscribes[key]) {
741
- var sub = this.filesSubscribes[key];
742
- if (cb) {
743
- var pos = sub.cbs.indexOf(cb);
744
- pos !== -1 && sub.cbs.splice(pos, 1);
745
- } else {
746
- sub.cbs = [];
747
- }
748
- if (!sub.cbs || !sub.cbs.length) {
749
- delete this.filesSubscribes[key];
750
- this.connected && this._socket.emit('unsubscribeFiles', id, filePattern);
751
- }
752
- }
753
- }
754
-
755
- /**
756
- * Called internally.
757
- * @private
758
- * @param {string} id
759
- * @param {ioBroker.Object | null | undefined} obj
760
- */
761
- }, {
762
- key: "objectChange",
763
- value: function objectChange(id, obj) {
764
- var _this5 = this;
765
- // update main.objects cache
766
- if (!this.objects) {
767
- return;
768
- }
769
-
770
- /** @type {import("./types").OldObject} */
771
- var oldObj;
772
- var changed = false;
773
- if (obj) {
774
- if (obj._rev && this.objects[id]) {
775
- this.objects[id]._rev = obj._rev;
776
- }
777
- if (this.objects[id]) {
778
- oldObj = {
779
- _id: id,
780
- type: this.objects[id].type
781
- };
782
- }
783
- if (!this.objects[id] || JSON.stringify(this.objects[id]) !== JSON.stringify(obj)) {
784
- this.objects[id] = obj;
785
- changed = true;
786
- }
787
- } else if (this.objects[id]) {
788
- oldObj = {
789
- _id: id,
790
- type: this.objects[id].type
791
- };
792
- delete this.objects[id];
793
- changed = true;
794
- }
795
- Object.keys(this.objectsSubscribes).forEach(function (_id) {
796
- if (_id === id || _this5.objectsSubscribes[_id].reg.test(id)) {
797
- //@ts-ignore
798
- _this5.objectsSubscribes[_id].cbs.forEach(function (cb) {
799
- return cb(id, obj, oldObj);
800
- });
801
- }
802
- });
803
- if (changed && this.props.onObjectChange) {
804
- this.props.onObjectChange(id, obj);
805
- }
806
- }
807
-
808
- /**
809
- * Called internally.
810
- * @private
811
- * @param {string} id
812
- * @param {ioBroker.State | null | undefined} state
813
- */
814
- }, {
815
- key: "stateChange",
816
- value: function stateChange(id, state) {
817
- for (var task in this.statesSubscribes) {
818
- if (this.statesSubscribes.hasOwnProperty(task) && this.statesSubscribes[task].reg.test(id)) {
819
- this.statesSubscribes[task].cbs.forEach(function (cb) {
820
- return cb(id, state);
821
- });
822
- }
823
- }
824
- }
825
-
826
- /**
827
- * Gets all states.
828
- * @param {boolean} disableProgressUpdate don't call onProgress() when done
829
- * @returns {Promise<Record<string, ioBroker.State>>}
830
- */
831
- }, {
832
- key: "getStates",
833
- value: function getStates(disableProgressUpdate) {
834
- var _this6 = this;
835
- if (!this.connected) {
836
- return Promise.reject(NOT_CONNECTED);
837
- }
838
- return new Promise(function (resolve, reject) {
839
- return _this6._socket.emit('getStates', function (err, res) {
840
- _this6.states = res;
841
- //@ts-ignore
842
- !disableProgressUpdate && _this6.onProgress(PROGRESS.STATES_LOADED);
843
- return err ? reject(err) : resolve(_this6.states);
844
- });
845
- });
846
- }
847
-
848
- /**
849
- * Gets the given state.
850
- * @param {string} id The state ID.
851
- * @returns {Promise<ioBroker.State | null | undefined>}
852
- */
853
- }, {
854
- key: "getState",
855
- value: function getState(id) {
856
- var _this7 = this;
857
- if (!this.connected) {
858
- return Promise.reject(NOT_CONNECTED);
859
- }
860
- return new Promise(function (resolve, reject) {
861
- return _this7._socket.emit('getState', id, function (err, state) {
862
- return err ? reject(err) : resolve(state);
863
- });
864
- });
865
- }
866
-
867
- /**
868
- * Gets the given binary state.
869
- * @param {string} id The state ID.
870
- * @returns {Promise<Buffer | undefined>}
871
- */
872
- }, {
873
- key: "getBinaryState",
874
- value: function getBinaryState(id) {
875
- var _this8 = this;
876
- if (!this.connected) {
877
- return Promise.reject(NOT_CONNECTED);
878
- }
879
-
880
- // the data will come in base64
881
- return new Promise(function (resolve, reject) {
882
- return _this8._socket.emit('getBinaryState', id, function (err, state) {
883
- return err ? reject(err) : resolve(state);
884
- });
885
- });
886
- }
887
-
888
- /**
889
- * Sets the given binary state.
890
- * @param {string} id The state ID.
891
- * @param {string} base64 The Base64 encoded binary data.
892
- * @returns {Promise<void>}
893
- */
894
- }, {
895
- key: "setBinaryState",
896
- value: function setBinaryState(id, base64) {
897
- var _this9 = this;
898
- if (!this.connected) {
899
- return Promise.reject(NOT_CONNECTED);
900
- }
901
-
902
- // the data will come in base64
903
- return new Promise(function (resolve, reject) {
904
- return _this9._socket.emit('setBinaryState', id, base64, function (err) {
905
- return err ? reject(err) : resolve();
906
- });
907
- });
908
- }
909
-
910
- /**
911
- * Sets the given state value.
912
- * @param {string} id The state ID.
913
- * @param {string | number | boolean | ioBroker.State | ioBroker.SettableState | null} val The state value.
914
- * @param {boolean | null} ack Acknowledge flag
915
- * @returns {Promise<void>}
916
- */
917
- }, {
918
- key: "setState",
919
- value: function setState(id, val, ack) {
920
- var _this10 = this;
921
- if (!this.connected) {
922
- return Promise.reject(NOT_CONNECTED);
923
- }
924
- if (typeof ack === 'boolean') {
925
- val = {
926
- val: val,
927
- ack: ack
928
- };
929
- }
930
- return new Promise(function (resolve, reject) {
931
- return _this10._socket.emit('setState', id, val, function (err) {
932
- return err ? reject(err) : resolve();
933
- });
934
- });
935
- }
936
-
937
- /**
938
- * Gets all objects.
939
- * @param {(objects?: Record<string, ioBroker.Object>) => void} update Callback that is executed when all objects are retrieved.
940
- * @returns {void}
941
- */
942
- /**
943
- * Gets all objects.
944
- * @param {boolean} update Set to true to retrieve all objects from the server (instead of using the local cache).
945
- * @param {boolean} disableProgressUpdate don't call onProgress() when done
946
- * @returns {Promise<Record<string, ioBroker.Object>> | undefined}
947
- */
948
- }, {
949
- key: "getObjects",
950
- value: function getObjects(update, disableProgressUpdate) {
951
- var _this11 = this;
952
- if (!this.connected) {
953
- return Promise.reject(NOT_CONNECTED);
954
- } else {
955
- return new Promise(function (resolve, reject) {
956
- if (!update && _this11.objects) {
957
- return resolve(_this11.objects);
958
- }
959
- _this11._socket.emit(Connection.isWeb() ? 'getObjects' : 'getAllObjects', function (err, res) {
960
- _this11.objects = res;
961
- disableProgressUpdate && _this11.onProgress(PROGRESS.OBJECTS_LOADED);
962
- err ? reject(err) : resolve(_this11.objects);
963
- });
964
- });
965
- }
966
- }
967
-
968
- /**
969
- * Called internally.
970
- * @private
971
- * @param {boolean} isEnable
972
- */
973
- }, {
974
- key: "_subscribe",
975
- value: function _subscribe(isEnable) {
976
- var _this12 = this;
977
- if (isEnable && !this.subscribed) {
978
- this.subscribed = true;
979
- this.autoSubscribes.forEach(function (id) {
980
- return _this12._socket.emit('subscribeObjects', id);
981
- });
982
- // re subscribe objects
983
- Object.keys(this.objectsSubscribes).forEach(function (id) {
984
- return _this12._socket.emit('subscribeObjects', id);
985
- });
986
- // re-subscribe logs
987
- this.autoSubscribeLog && this._socket.emit('requireLog', true);
988
- // re subscribe states
989
- Object.keys(this.statesSubscribes).forEach(function (id) {
990
- return _this12._socket.emit('subscribe', id);
991
- });
992
- } else if (!isEnable && this.subscribed) {
993
- this.subscribed = false;
994
- // un-subscribe objects
995
- this.autoSubscribes.forEach(function (id) {
996
- return _this12._socket.emit('unsubscribeObjects', id);
997
- });
998
- Object.keys(this.objectsSubscribes).forEach(function (id) {
999
- return _this12._socket.emit('unsubscribeObjects', id);
1000
- });
1001
- // un-subscribe logs
1002
- this.autoSubscribeLog && this._socket.emit('requireLog', false);
1003
-
1004
- // un-subscribe states
1005
- Object.keys(this.statesSubscribes).forEach(function (id) {
1006
- return _this12._socket.emit('unsubscribe', id);
1007
- });
1008
- }
1009
- }
1010
-
1011
- /**
1012
- * Requests log updates.
1013
- * @param {boolean} isEnabled Set to true to get logs.
1014
- * @returns {Promise<void>}
1015
- */
1016
- }, {
1017
- key: "requireLog",
1018
- value: function requireLog(isEnabled) {
1019
- var _this13 = this;
1020
- if (!this.connected) {
1021
- return Promise.reject(NOT_CONNECTED);
1022
- }
1023
- return new Promise(function (resolve, reject) {
1024
- return _this13._socket.emit('requireLog', isEnabled, function (err) {
1025
- return err ? reject(err) : resolve();
1026
- });
1027
- });
1028
- }
1029
-
1030
- /**
1031
- * Deletes the given object.
1032
- * @param {string} id The object ID.
1033
- * @param {boolean} maintenance Force deletion of non conform IDs.
1034
- * @returns {Promise<void>}
1035
- */
1036
- }, {
1037
- key: "delObject",
1038
- value: function delObject(id, maintenance) {
1039
- var _this14 = this;
1040
- if (!this.connected) {
1041
- return Promise.reject(NOT_CONNECTED);
1042
- }
1043
- return new Promise(function (resolve, reject) {
1044
- return _this14._socket.emit('delObject', id, {
1045
- maintenance: !!maintenance
1046
- }, function (err) {
1047
- return err ? reject(err) : resolve();
1048
- });
1049
- });
1050
- }
1051
-
1052
- /**
1053
- * Deletes the given object and all its children.
1054
- * @param {string} id The object ID.
1055
- * @param {boolean} maintenance Force deletion of non conform IDs.
1056
- * @returns {Promise<void>}
1057
- */
1058
- }, {
1059
- key: "delObjects",
1060
- value: function delObjects(id, maintenance) {
1061
- var _this15 = this;
1062
- if (!this.connected) {
1063
- return Promise.reject(NOT_CONNECTED);
1064
- }
1065
- return new Promise(function (resolve, reject) {
1066
- return _this15._socket.emit('delObjects', id, {
1067
- maintenance: !!maintenance
1068
- }, function (err) {
1069
- return err ? reject(err) : resolve();
1070
- });
1071
- });
1072
- }
1073
-
1074
- /**
1075
- * Sets the object.
1076
- * @param {string} id The object ID.
1077
- * @param {ioBroker.SettableObject} obj The object.
1078
- * @returns {Promise<void>}
1079
- */
1080
- }, {
1081
- key: "setObject",
1082
- value: function setObject(id, obj) {
1083
- var _this16 = this;
1084
- if (!this.connected) {
1085
- return Promise.reject(NOT_CONNECTED);
1086
- }
1087
- if (!obj) {
1088
- return Promise.reject('Null object is not allowed');
1089
- }
1090
- obj = JSON.parse(JSON.stringify(obj));
1091
- if (obj.hasOwnProperty('from')) {
1092
- delete obj.from;
1093
- }
1094
- if (obj.hasOwnProperty('user')) {
1095
- delete obj.user;
1096
- }
1097
- if (obj.hasOwnProperty('ts')) {
1098
- delete obj.ts;
1099
- }
1100
- return new Promise(function (resolve, reject) {
1101
- return _this16._socket.emit('setObject', id, obj, function (err) {
1102
- return err ? reject(err) : resolve();
1103
- });
1104
- });
1105
- }
1106
-
1107
- /**
1108
- * Gets the object with the given id from the server.
1109
- * @param {string} id The object ID.
1110
- * @returns {ioBroker.GetObjectPromise} The object.
1111
- */
1112
- }, {
1113
- key: "getObject",
1114
- value: function getObject(id) {
1115
- var _this17 = this;
1116
- if (!this.connected) {
1117
- return Promise.reject(NOT_CONNECTED);
1118
- }
1119
- return new Promise(function (resolve, reject) {
1120
- return _this17._socket.emit('getObject', id, function (err, obj) {
1121
- return err ? reject(err) : resolve(obj);
1122
- });
1123
- });
1124
- }
1125
-
1126
- /**
1127
- * Get all adapter instances.
1128
- * @param {boolean} [update] Force update.
1129
- * @returns {Promise<ioBroker.Object[]>}
1130
- */
1131
- /**
1132
- * Get all instances of the given adapter.
1133
- * @param {string} adapter The name of the adapter.
1134
- * @param {boolean} [update] Force update.
1135
- * @returns {Promise<ioBroker.Object[]>}
1136
- */
1137
- }, {
1138
- key: "getAdapterInstances",
1139
- value: function getAdapterInstances(adapter, update) {
1140
- var _this18 = this;
1141
- if (typeof adapter === 'boolean') {
1142
- update = adapter;
1143
- adapter = '';
1144
- }
1145
- adapter = adapter || '';
1146
- if (!update && this._promises['instances_' + adapter]) {
1147
- return this._promises['instances_' + adapter];
1148
- }
1149
- if (!this.connected) {
1150
- return Promise.reject(NOT_CONNECTED);
1151
- }
1152
- this._promises['instances_' + adapter] = new Promise(function (resolve, reject) {
1153
- var timeout = setTimeout(function () {
1154
- timeout = null;
1155
- _this18.getObjectView("system.adapter.".concat(adapter ? adapter + '.' : ''), "system.adapter.".concat(adapter ? adapter + '.' : '', "\u9999"), 'instance').then(function (items) {
1156
- return resolve(Object.keys(items).map(function (id) {
1157
- return fixAdminUI(items[id]);
1158
- }));
1159
- })["catch"](function (e) {
1160
- return reject(e);
1161
- });
1162
- }, TIMEOUT_FOR_ADMIN4);
1163
- _this18._socket.emit('getAdapterInstances', adapter, function (err, instances) {
1164
- if (timeout) {
1165
- clearTimeout(timeout);
1166
- timeout = null;
1167
- return err ? reject(err) : resolve(instances);
1168
- }
1169
- });
1170
- });
1171
- return this._promises['instances_' + adapter];
1172
- }
1173
-
1174
- /**
1175
- * Get all adapters.
1176
- * @param {boolean} [update] Force update.
1177
- * @returns {Promise<ioBroker.Object[]>}
1178
- */
1179
- /**
1180
- * Get adapters with the given name.
1181
- * @param {string} adapter The name of the adapter.
1182
- * @param {boolean} [update] Force update.
1183
- * @returns {Promise<ioBroker.Object[]>}
1184
- */
1185
- }, {
1186
- key: "getAdapters",
1187
- value: function getAdapters(adapter, update) {
1188
- var _this19 = this;
1189
- if (Connection.isWeb()) {
1190
- return Promise.reject('Allowed only in admin');
1191
- }
1192
- if (typeof adapter === 'boolean') {
1193
- update = adapter;
1194
- adapter = '';
1195
- }
1196
- adapter = adapter || '';
1197
- if (!update && this._promises['adapter_' + adapter]) {
1198
- return this._promises['adapter_' + adapter];
1199
- }
1200
- if (!this.connected) {
1201
- return Promise.reject(NOT_CONNECTED);
1202
- }
1203
- this._promises['adapter_' + adapter] = new Promise(function (resolve, reject) {
1204
- var timeout = setTimeout(function () {
1205
- timeout = null;
1206
- _this19.getObjectView("system.adapter.".concat(adapter, "."), "system.adapter.".concat(adapter, ".\u9999"), 'adapter').then(function (items) {
1207
- return resolve(Object.keys(items).map(function (id) {
1208
- return fixAdminUI(items[id]);
1209
- }));
1210
- })["catch"](function (e) {
1211
- return reject(e);
1212
- });
1213
- }, TIMEOUT_FOR_ADMIN4);
1214
- _this19._socket.emit('getAdapters', adapter, function (err, adapters) {
1215
- if (timeout) {
1216
- clearTimeout(timeout);
1217
- timeout = null;
1218
- return err ? reject(err) : resolve(adapters);
1219
- }
1220
- });
1221
- });
1222
- return this._promises['adapter_' + adapter];
1223
- }
1224
-
1225
- /**
1226
- * Called internally.
1227
- * @private
1228
- * @param {any[]} objs
1229
- * @param {(err?: any) => void} cb
1230
- */
1231
- }, {
1232
- key: "_renameGroups",
1233
- value: function _renameGroups(objs, cb) {
1234
- var _this20 = this;
1235
- if (!objs || !objs.length) {
1236
- cb && cb();
1237
- } else {
1238
- var obj = objs.pop();
1239
- var oldId = obj._id;
1240
- obj._id = obj.newId;
1241
- delete obj.newId;
1242
- this.setObject(obj._id, obj).then(function () {
1243
- return _this20.delObject(oldId);
1244
- }).then(function () {
1245
- return setTimeout(function () {
1246
- return _this20._renameGroups(objs, cb);
1247
- }, 0);
1248
- })["catch"](function (err) {
1249
- return cb && cb(err);
1250
- });
1251
- }
1252
- }
1253
-
1254
- /**
1255
- * Rename a group.
1256
- * @param {string} id The id.
1257
- * @param {string} newId The new id.
1258
- * @param {string | { [lang in ioBroker.Languages]?: string; }} newName The new name.
1259
- */
1260
- }, {
1261
- key: "renameGroup",
1262
- value: function renameGroup(id, newId, newName) {
1263
- var _this21 = this;
1264
- if (Connection.isWeb()) {
1265
- return Promise.reject('Allowed only in admin');
1266
- }
1267
- return this.getGroups(true).then(function (groups) {
1268
- if (groups.length) {
1269
- // find all elements
1270
- var groupsToRename = groups.filter(function (group) {
1271
- return group._id.startsWith(id + '.');
1272
- });
1273
- groupsToRename.forEach(function (group) {
1274
- return group.newId = newId + group._id.substring(id.length);
1275
- });
1276
- return new Promise(function (resolve, reject) {
1277
- return _this21._renameGroups(groupsToRename, function (err) {
1278
- return err ? reject(err) : resolve();
1279
- });
1280
- }).then(function () {
1281
- var obj = groups.find(function (group) {
1282
- return group._id === id;
1283
- });
1284
- if (obj) {
1285
- obj._id = newId;
1286
- if (newName !== undefined) {
1287
- obj.common = obj.common || {};
1288
- obj.common.name = newName;
1289
- }
1290
- return _this21.setObject(obj._id, obj).then(function () {
1291
- return _this21.delObject(id);
1292
- });
1293
- }
1294
- });
1295
- }
1296
- });
1297
- }
1298
-
1299
- /**
1300
- * Sends a message to a specific instance or all instances of some specific adapter.
1301
- * @param {string} instance The instance to send this message to.
1302
- * @param {string} [command] Command name of the target instance.
1303
- * @param {ioBroker.MessagePayload} [data] The message data to send.
1304
- * @returns {Promise<ioBroker.Message | undefined>}
1305
- */
1306
- }, {
1307
- key: "sendTo",
1308
- value: function sendTo(instance, command, data) {
1309
- var _this22 = this;
1310
- if (!this.connected) {
1311
- return Promise.reject(NOT_CONNECTED);
1312
- }
1313
- return new Promise(function (resolve) {
1314
- return _this22._socket.emit('sendTo', instance, command, data, function (result) {
1315
- return resolve(result);
1316
- });
1317
- });
1318
- }
1319
-
1320
- /**
1321
- * Extend an object and create it if it might not exist.
1322
- * @param {string} id The id.
1323
- * @param {ioBroker.PartialObject} obj The object.
1324
- */
1325
- }, {
1326
- key: "extendObject",
1327
- value: function extendObject(id, obj) {
1328
- var _this23 = this;
1329
- if (!this.connected) {
1330
- return Promise.reject(NOT_CONNECTED);
1331
- }
1332
- obj = JSON.parse(JSON.stringify(obj));
1333
- if (obj.hasOwnProperty('from')) {
1334
- delete obj.from;
1335
- }
1336
- if (obj.hasOwnProperty('user')) {
1337
- delete obj.user;
1338
- }
1339
- if (obj.hasOwnProperty('ts')) {
1340
- delete obj.ts;
1341
- }
1342
- return new Promise(function (resolve, reject) {
1343
- return _this23._socket.emit('extendObject', id, obj, function (err) {
1344
- return err ? reject(err) : resolve();
1345
- });
1346
- });
1347
- }
1348
-
1349
- /**
1350
- * Register a handler for log messages.
1351
- * @param {(message: string) => void} handler The handler.
1352
- */
1353
- }, {
1354
- key: "registerLogHandler",
1355
- value: function registerLogHandler(handler) {
1356
- !this.onLogHandlers.includes(handler) && this.onLogHandlers.push(handler);
1357
- }
1358
-
1359
- /**
1360
- * Unregister a handler for log messages.
1361
- * @param {(message: string) => void} handler The handler.
1362
- */
1363
- }, {
1364
- key: "unregisterLogHandler",
1365
- value: function unregisterLogHandler(handler) {
1366
- var pos = this.onLogHandlers.indexOf(handler);
1367
- pos !== -1 && this.onLogHandlers.splice(pos, 1);
1368
- }
1369
-
1370
- /**
1371
- * Register a handler for the connection state.
1372
- * @param {(connected: boolean) => void} handler The handler.
1373
- */
1374
- }, {
1375
- key: "registerConnectionHandler",
1376
- value: function registerConnectionHandler(handler) {
1377
- !this.onConnectionHandlers.includes(handler) && this.onConnectionHandlers.push(handler);
1378
- }
1379
-
1380
- /**
1381
- * Unregister a handler for the connection state.
1382
- * @param {(connected: boolean) => void} handler The handler.
1383
- */
1384
- }, {
1385
- key: "unregisterConnectionHandler",
1386
- value: function unregisterConnectionHandler(handler) {
1387
- var pos = this.onConnectionHandlers.indexOf(handler);
1388
- pos !== -1 && this.onConnectionHandlers.splice(pos, 1);
1389
- }
1390
-
1391
- /**
1392
- * Set the handler for standard output of a command.
1393
- * @param {(id: string, text: string) => void} handler The handler.
1394
- */
1395
- }, {
1396
- key: "registerCmdStdoutHandler",
1397
- value: function registerCmdStdoutHandler(handler) {
1398
- this.onCmdStdoutHandler = handler;
1399
- }
1400
-
1401
- /**
1402
- * Unset the handler for standard output of a command.
1403
- * @param {(id: string, text: string) => void} handler The handler.
1404
- */
1405
- }, {
1406
- key: "unregisterCmdStdoutHandler",
1407
- value: function unregisterCmdStdoutHandler(handler) {
1408
- this.onCmdStdoutHandler = null;
1409
- }
1410
-
1411
- /**
1412
- * Set the handler for standard error of a command.
1413
- * @param {(id: string, text: string) => void} handler The handler.
1414
- */
1415
- }, {
1416
- key: "registerCmdStderrHandler",
1417
- value: function registerCmdStderrHandler(handler) {
1418
- this.onCmdStderrHandler = handler;
1419
- }
1420
-
1421
- /**
1422
- * Unset the handler for standard error of a command.
1423
- * @param {(id: string, text: string) => void} handler The handler.
1424
- */
1425
- }, {
1426
- key: "unregisterCmdStderrHandler",
1427
- value: function unregisterCmdStderrHandler(handler) {
1428
- this.onCmdStderrHandler = null;
1429
- }
1430
-
1431
- /**
1432
- * Set the handler for exit of a command.
1433
- * @param {(id: string, exitCode: number) => void} handler The handler.
1434
- */
1435
- }, {
1436
- key: "registerCmdExitHandler",
1437
- value: function registerCmdExitHandler(handler) {
1438
- this.onCmdExitHandler = handler;
1439
- }
1440
-
1441
- /**
1442
- * Unset the handler for exit of a command.
1443
- * @param {(id: string, exitCode: number) => void} handler The handler.
1444
- */
1445
- }, {
1446
- key: "unregisterCmdExitHandler",
1447
- value: function unregisterCmdExitHandler(handler) {
1448
- this.onCmdExitHandler = null;
1449
- }
1450
-
1451
- /**
1452
- * Get all enums with the given name.
1453
- * @param {string} [_enum] The name of the enum
1454
- * @param {boolean} [update] Force update.
1455
- * @returns {Promise<Record<string, ioBroker.Object>>}
1456
- */
1457
- }, {
1458
- key: "getEnums",
1459
- value: function getEnums(_enum, update) {
1460
- var _this24 = this;
1461
- if (!update && this._promises['enums_' + (_enum || 'all')]) {
1462
- return this._promises['enums_' + (_enum || 'all')];
1463
- }
1464
- if (!this.connected) {
1465
- return Promise.reject(NOT_CONNECTED);
1466
- }
1467
- this._promises['enums_' + (_enum || 'all')] = new Promise(function (resolve, reject) {
1468
- _this24._socket.emit('getObjectView', 'system', 'enum', {
1469
- startkey: 'enum.' + (_enum || ''),
1470
- endkey: 'enum.' + (_enum ? _enum + '.' : '') + "\u9999"
1471
- }, function (err, res) {
1472
- if (!err && res) {
1473
- var _res = {};
1474
- for (var i = 0; i < res.rows.length; i++) {
1475
- if (_enum && res.rows[i].id === 'enum.' + _enum) {
1476
- continue;
1477
- }
1478
- _res[res.rows[i].id] = res.rows[i].value;
1479
- }
1480
- resolve(_res);
1481
- } else {
1482
- reject(err);
1483
- }
1484
- });
1485
- });
1486
- return this._promises['enums_' + (_enum || 'all')];
1487
- }
1488
-
1489
- /**
1490
- * Query a predefined object view.
1491
- * @param {string} start The start ID.
1492
- * @param {string} end The end ID.
1493
- * @param {string} type The type of object.
1494
- * @returns {Promise<Record<string, ioBroker.Object>>}
1495
- */
1496
- }, {
1497
- key: "getObjectView",
1498
- value: function getObjectView(start, end, type) {
1499
- var _this25 = this;
1500
- if (!this.connected) {
1501
- return Promise.reject(NOT_CONNECTED);
1502
- }
1503
- start = start || '';
1504
- end = end || "\u9999";
1505
- return new Promise(function (resolve, reject) {
1506
- _this25._socket.emit('getObjectView', 'system', type, {
1507
- startkey: start,
1508
- endkey: end
1509
- }, function (err, res) {
1510
- if (!err) {
1511
- var _res = {};
1512
- if (res && res.rows) {
1513
- for (var i = 0; i < res.rows.length; i++) {
1514
- _res[res.rows[i].id] = res.rows[i].value;
1515
- }
1516
- }
1517
- resolve(_res);
1518
- } else {
1519
- reject(err);
1520
- }
1521
- });
1522
- });
1523
- }
1524
-
1525
- /**
1526
- * Get the stored certificates.
1527
- * @param {boolean} [update] Force update.
1528
- * @returns {Promise<{name: string; type: 'public' | 'private' | 'chained'}[]>}
1529
- */
1530
- }, {
1531
- key: "getCertificates",
1532
- value: function getCertificates(update) {
1533
- if (Connection.isWeb()) {
1534
- return Promise.reject('Allowed only in admin');
1535
- }
1536
- if (this._promises.cert && !update) {
1537
- return this._promises.cert;
1538
- }
1539
- if (!this.connected) {
1540
- return Promise.reject(NOT_CONNECTED);
1541
- }
1542
- this._promises.cert = this.getObject('system.certificates').then(function (res) {
1543
- var certs = [];
1544
- if (res && res["native"] && res["native"].certificates) {
1545
- Object.keys(res["native"].certificates).forEach(function (c) {
1546
- var cert = res["native"].certificates[c];
1547
- if (!cert) {
1548
- return;
1549
- }
1550
- var _cert = {
1551
- name: c,
1552
- type: ''
1553
- };
1554
- // If it is filename, it could be everything
1555
- if (cert.length < 700 && (cert.indexOf('/') !== -1 || cert.indexOf('\\') !== -1)) {
1556
- if (c.toLowerCase().includes('private')) {
1557
- _cert.type = 'private';
1558
- } else if (cert.toLowerCase().includes('private')) {
1559
- _cert.type = 'private';
1560
- } else if (c.toLowerCase().includes('public')) {
1561
- _cert.type = 'public';
1562
- } else if (cert.toLowerCase().includes('public')) {
1563
- _cert.type = 'public';
1564
- }
1565
- certs.push(_cert);
1566
- } else {
1567
- _cert.type = cert.substring(0, '-----BEGIN RSA PRIVATE KEY'.length) === '-----BEGIN RSA PRIVATE KEY' || cert.substring(0, '-----BEGIN PRIVATE KEY'.length) === '-----BEGIN PRIVATE KEY' ? 'private' : 'public';
1568
- if (_cert.type === 'public') {
1569
- var m = cert.split('-----END CERTIFICATE-----');
1570
- if (m.filter(function (t) {
1571
- return t.replace(/\r\n|\r|\n/, '').trim();
1572
- }).length > 1) {
1573
- _cert.type = 'chained';
1574
- }
1575
- }
1576
- certs.push(_cert);
1577
- }
1578
- });
1579
- }
1580
- return certs;
1581
- });
1582
- return this._promises.cert;
1583
- }
1584
-
1585
- /**
1586
- * Get the logs from a host (only for admin connection).
1587
- * @param {string} host
1588
- * @param {number} [linesNumber]
1589
- * @returns {Promise<string[]>}
1590
- */
1591
- }, {
1592
- key: "getLogs",
1593
- value: function getLogs(host, linesNumber) {
1594
- var _this26 = this;
1595
- if (Connection.isWeb()) {
1596
- return Promise.reject('Allowed only in admin');
1597
- }
1598
- if (!this.connected) {
1599
- return Promise.reject(NOT_CONNECTED);
1600
- }
1601
- return new Promise(function (resolve) {
1602
- return _this26._socket.emit('sendToHost', host, 'getLogs', linesNumber || 200, function (lines) {
1603
- return resolve(lines);
1604
- });
1605
- });
1606
- }
1607
-
1608
- /**
1609
- * Get the log files (only for admin connection).
1610
- * @returns {Promise<string[]>}
1611
- */
1612
- }, {
1613
- key: "getLogsFiles",
1614
- value: function getLogsFiles(host) {
1615
- var _this27 = this;
1616
- if (Connection.isWeb()) {
1617
- return Promise.reject('Allowed only in admin');
1618
- }
1619
- if (!this.connected) {
1620
- return Promise.reject(NOT_CONNECTED);
1621
- }
1622
- return new Promise(function (resolve, reject) {
1623
- return _this27._socket.emit('readLogs', host, function (err, files) {
1624
- return err ? reject(err) : resolve(files);
1625
- });
1626
- });
1627
- }
1628
-
1629
- /**
1630
- * Delete the logs from a host (only for admin connection).
1631
- * @param {string} host
1632
- * @returns {Promise<void>}
1633
- */
1634
- }, {
1635
- key: "delLogs",
1636
- value: function delLogs(host) {
1637
- var _this28 = this;
1638
- if (Connection.isWeb()) {
1639
- return Promise.reject('Allowed only in admin');
1640
- }
1641
- if (!this.connected) {
1642
- return Promise.reject(NOT_CONNECTED);
1643
- }
1644
- return new Promise(function (resolve, reject) {
1645
- return _this28._socket.emit('sendToHost', host, 'delLogs', null, function (error) {
1646
- return error ? reject(error) : resolve();
1647
- });
1648
- });
1649
- }
1650
-
1651
- /**
1652
- * Read the meta items.
1653
- * @returns {Promise<ioBroker.Object[]>}
1654
- */
1655
- }, {
1656
- key: "readMetaItems",
1657
- value: function readMetaItems() {
1658
- var _this29 = this;
1659
- if (!this.connected) {
1660
- return Promise.reject(NOT_CONNECTED);
1661
- }
1662
- return new Promise(function (resolve, reject) {
1663
- return _this29._socket.emit('getObjectView', 'system', 'meta', {
1664
- startkey: '',
1665
- endkey: "\u9999"
1666
- }, function (err, objs) {
1667
- return err ? reject(err) : resolve(objs.rows && objs.rows.map(function (obj) {
1668
- return obj.value;
1669
- }));
1670
- });
1671
- });
1672
- }
1673
-
1674
- /**
1675
- * Read the directory of an adapter.
1676
- * @param {string} adapter The adapter name.
1677
- * @param {string} fileName The directory name.
1678
- * @returns {Promise<ioBroker.ReadDirResult[]>}
1679
- */
1680
- }, {
1681
- key: "readDir",
1682
- value: function readDir(adapter, fileName) {
1683
- var _this30 = this;
1684
- if (!this.connected) {
1685
- return Promise.reject(NOT_CONNECTED);
1686
- }
1687
- return new Promise(function (resolve, reject) {
1688
- return _this30._socket.emit('readDir', adapter, fileName, function (err, files) {
1689
- return err ? reject(err) : resolve(files);
1690
- });
1691
- });
1692
- }
1693
-
1694
- /**
1695
- * Read a file of an adapter.
1696
- * @param {string} adapter The adapter name.
1697
- * @param {string} fileName The file name.
1698
- * @param {boolean} base64 If it must be a base64 format
1699
- * @returns {Promise<string>}
1700
- */
1701
- }, {
1702
- key: "readFile",
1703
- value: function readFile(adapter, fileName, base64) {
1704
- var _this31 = this;
1705
- if (!this.connected) {
1706
- return Promise.reject(NOT_CONNECTED);
1707
- }
1708
- return new Promise(function (resolve, reject) {
1709
- if (!base64) {
1710
- _this31._socket.emit('readFile', adapter, fileName, function (err, data, type) {
1711
- //@ts-ignore
1712
- err ? reject(err) : resolve({
1713
- data: data,
1714
- type: type
1715
- });
1716
- });
1717
- } else {
1718
- _this31._socket.emit('readFile64', adapter, fileName, base64, function (err, data) {
1719
- return err ? reject(err) : resolve(data);
1720
- });
1721
- }
1722
- });
1723
- }
1724
-
1725
- /**
1726
- * Write a file of an adapter.
1727
- * @param {string} adapter The adapter name.
1728
- * @param {string} fileName The file name.
1729
- * @param {Buffer | string} data The data (if it's a Buffer, it will be converted to Base64).
1730
- * @returns {Promise<void>}
1731
- */
1732
- }, {
1733
- key: "writeFile64",
1734
- value: function writeFile64(adapter, fileName, data) {
1735
- var _this32 = this;
1736
- if (!this.connected) {
1737
- return Promise.reject(NOT_CONNECTED);
1738
- }
1739
- return new Promise(function (resolve, reject) {
1740
- if (typeof data === 'string') {
1741
- _this32._socket.emit('writeFile', adapter, fileName, data, function (err) {
1742
- return err ? reject(err) : resolve();
1743
- });
1744
- } else {
1745
- var base64 = btoa(new Uint8Array(data).reduce(function (data, _byte) {
1746
- return data + String.fromCharCode(_byte);
1747
- }, ''));
1748
- _this32._socket.emit('writeFile64', adapter, fileName, base64, function (err) {
1749
- return err ? reject(err) : resolve();
1750
- });
1751
- }
1752
- });
1753
- }
1754
-
1755
- /**
1756
- * Rename a file or folder of an adapter.
1757
- *
1758
- * All files in folder will be renamed too.
1759
- * @param {string} adapter The adapter name.
1760
- * @param {string} oldName The file name of the file to be renamed.
1761
- * @param {string} newName The new file name.
1762
- * @returns {Promise<void>}
1763
- */
1764
- }, {
1765
- key: "rename",
1766
- value: function rename(adapter, oldName, newName) {
1767
- var _this33 = this;
1768
- if (!this.connected) {
1769
- return Promise.reject(NOT_CONNECTED);
1770
- }
1771
- return new Promise(function (resolve, reject) {
1772
- return _this33._socket.emit('rename', adapter, oldName, newName, function (err) {
1773
- return err ? reject(err) : resolve();
1774
- });
1775
- });
1776
- }
1777
-
1778
- /**
1779
- * Delete a file of an adapter.
1780
- * @param {string} adapter The adapter name.
1781
- * @param {string} fileName The file name.
1782
- * @returns {Promise<void>}
1783
- */
1784
- }, {
1785
- key: "deleteFile",
1786
- value: function deleteFile(adapter, fileName) {
1787
- var _this34 = this;
1788
- if (!this.connected) {
1789
- return Promise.reject(NOT_CONNECTED);
1790
- }
1791
- return new Promise(function (resolve, reject) {
1792
- return _this34._socket.emit('unlink', adapter, fileName, function (err) {
1793
- return err ? reject(err) : resolve();
1794
- });
1795
- });
1796
- }
1797
-
1798
- /**
1799
- * Delete a folder of an adapter.
1800
- * All files in folder will be deleted.
1801
- * @param {string} adapter The adapter name.
1802
- * @param {string} folderName The folder name.
1803
- * @returns {Promise<void>}
1804
- */
1805
- }, {
1806
- key: "deleteFolder",
1807
- value: function deleteFolder(adapter, folderName) {
1808
- var _this35 = this;
1809
- if (!this.connected) {
1810
- return Promise.reject(NOT_CONNECTED);
1811
- }
1812
- return new Promise(function (resolve, reject) {
1813
- return _this35._socket.emit('deleteFolder', adapter, folderName, function (err) {
1814
- return err ? reject(err) : resolve();
1815
- });
1816
- });
1817
- }
1818
-
1819
- /**
1820
- * Get the list of all hosts.
1821
- * @param {boolean} [update] Force update.
1822
- * @returns {Promise<ioBroker.Object[]>}
1823
- */
1824
- }, {
1825
- key: "getHosts",
1826
- value: function getHosts(update) {
1827
- var _this36 = this;
1828
- if (Connection.isWeb()) {
1829
- return Promise.reject('Allowed only in admin');
1830
- }
1831
- if (!update && this._promises.hosts) {
1832
- return this._promises.hosts;
1833
- }
1834
- if (!this.connected) {
1835
- return Promise.reject(NOT_CONNECTED);
1836
- }
1837
- this._promises.hosts = new Promise(function (resolve, reject) {
1838
- return _this36._socket.emit('getObjectView', 'system', 'host', {
1839
- startkey: 'system.host.',
1840
- endkey: "system.host.\u9999"
1841
- }, function (err, doc) {
1842
- if (err) {
1843
- reject(err);
1844
- } else {
1845
- resolve(doc.rows.map(function (item) {
1846
- return item.value;
1847
- }));
1848
- }
1849
- });
1850
- });
1851
- return this._promises.hosts;
1852
- }
1853
-
1854
- /**
1855
- * Get the list of all users.
1856
- * @param {boolean} [update] Force update.
1857
- * @returns {Promise<ioBroker.Object[]>}
1858
- */
1859
- }, {
1860
- key: "getUsers",
1861
- value: function getUsers(update) {
1862
- var _this37 = this;
1863
- if (Connection.isWeb()) {
1864
- return Promise.reject('Allowed only in admin');
1865
- }
1866
- if (!update && this._promises.users) {
1867
- return this._promises.users;
1868
- }
1869
- if (!this.connected) {
1870
- return Promise.reject(NOT_CONNECTED);
1871
- }
1872
- this._promises.users = new Promise(function (resolve, reject) {
1873
- return _this37._socket.emit('getObjectView', 'system', 'user', {
1874
- startkey: 'system.user.',
1875
- endkey: "system.user.\u9999"
1876
- }, function (err, doc) {
1877
- if (err) {
1878
- reject(err);
1879
- } else {
1880
- resolve(doc.rows.map(function (item) {
1881
- return item.value;
1882
- }));
1883
- }
1884
- });
1885
- });
1886
- return this._promises.users;
1887
- }
1888
-
1889
- /**
1890
- * Get the list of all groups.
1891
- * @param {boolean} [update] Force update.
1892
- * @returns {Promise<ioBroker.Object[]>}
1893
- */
1894
- }, {
1895
- key: "getGroups",
1896
- value: function getGroups(update) {
1897
- var _this38 = this;
1898
- if (!update && this._promises.groups) {
1899
- return this._promises.groups;
1900
- }
1901
- if (!this.connected) {
1902
- return Promise.reject(NOT_CONNECTED);
1903
- }
1904
- this._promises.groups = new Promise(function (resolve, reject) {
1905
- return _this38._socket.emit('getObjectView', 'system', 'group', {
1906
- startkey: 'system.group.',
1907
- endkey: "system.group.\u9999"
1908
- }, function (err, doc) {
1909
- if (err) {
1910
- reject(err);
1911
- } else {
1912
- resolve(doc.rows.map(function (item) {
1913
- return item.value;
1914
- }));
1915
- }
1916
- });
1917
- });
1918
- return this._promises.groups;
1919
- }
1920
-
1921
- /**
1922
- * Get the host information.
1923
- * @param {string} host
1924
- * @param {boolean} [update] Force update.
1925
- * @param {number} [timeoutMs] optional read timeout.
1926
- * @returns {Promise<any>}
1927
- */
1928
- }, {
1929
- key: "getHostInfo",
1930
- value: function getHostInfo(host, update, timeoutMs) {
1931
- var _this39 = this;
1932
- if (Connection.isWeb()) {
1933
- return Promise.reject('Allowed only in admin');
1934
- }
1935
- if (!host.startsWith('system.host.')) {
1936
- host += 'system.host.' + host;
1937
- }
1938
- if (!update && this._promises['hostInfo' + host]) {
1939
- return this._promises['hostInfo' + host];
1940
- }
1941
- if (!this.connected) {
1942
- return Promise.reject(NOT_CONNECTED);
1943
- }
1944
- this._promises['hostInfo' + host] = new Promise(function (resolve, reject) {
1945
- var timeout = setTimeout(function () {
1946
- if (timeout) {
1947
- timeout = null;
1948
- reject('getHostInfo timeout');
1949
- }
1950
- }, timeoutMs || _this39.props.cmdTimeout);
1951
- _this39._socket.emit('sendToHost', host, 'getHostInfo', null, function (data) {
1952
- if (timeout) {
1953
- clearTimeout(timeout);
1954
- timeout = null;
1955
- if (data === PERMISSION_ERROR) {
1956
- reject('May not read "getHostInfo"');
1957
- } else if (!data) {
1958
- reject('Cannot read "getHostInfo"');
1959
- } else {
1960
- resolve(data);
1961
- }
1962
- }
1963
- });
1964
- });
1965
- return this._promises['hostInfo' + host];
1966
- }
1967
-
1968
- /**
1969
- * Get the host information (short version).
1970
- * @param {string} host
1971
- * @param {boolean} [update] Force update.
1972
- * @param {number} [timeoutMs] optional read timeout.
1973
- * @returns {Promise<any>}
1974
- */
1975
- }, {
1976
- key: "getHostInfoShort",
1977
- value: function getHostInfoShort(host, update, timeoutMs) {
1978
- var _this40 = this;
1979
- if (Connection.isWeb()) {
1980
- return Promise.reject('Allowed only in admin');
1981
- }
1982
- if (!host.startsWith('system.host.')) {
1983
- host += 'system.host.' + host;
1984
- }
1985
- if (!update && this._promises['hostInfoShort' + host]) {
1986
- return this._promises['hostInfoShort' + host];
1987
- }
1988
- if (!this.connected) {
1989
- return Promise.reject(NOT_CONNECTED);
1990
- }
1991
- this._promises['hostInfoShort' + host] = new Promise(function (resolve, reject) {
1992
- var timeout = setTimeout(function () {
1993
- if (timeout) {
1994
- timeout = null;
1995
- reject('hostInfoShort timeout');
1996
- }
1997
- }, timeoutMs || _this40.props.cmdTimeout);
1998
- _this40._socket.emit('sendToHost', host, 'getHostInfoShort', null, function (data) {
1999
- if (timeout) {
2000
- clearTimeout(timeout);
2001
- timeout = null;
2002
- if (data === PERMISSION_ERROR) {
2003
- reject('May not read "getHostInfoShort"');
2004
- } else if (!data) {
2005
- reject('Cannot read "getHostInfoShort"');
2006
- } else {
2007
- resolve(data);
2008
- }
2009
- }
2010
- });
2011
- });
2012
- return this._promises['hostInfoShort' + host];
2013
- }
2014
-
2015
- /**
2016
- * Get the repository.
2017
- * @param {string} host
2018
- * @param {any} [args]
2019
- * @param {boolean} [update] Force update.
2020
- * @param {number} [timeoutMs] timeout in ms.
2021
- * @returns {Promise<any>}
2022
- */
2023
- }, {
2024
- key: "getRepository",
2025
- value: function getRepository(host, args, update, timeoutMs) {
2026
- var _this41 = this;
2027
- if (Connection.isWeb()) {
2028
- return Promise.reject('Allowed only in admin');
2029
- }
2030
- if (!update && this._promises.repo) {
2031
- return this._promises.repo;
2032
- }
2033
- if (!this.connected) {
2034
- return Promise.reject(NOT_CONNECTED);
2035
- }
2036
- if (!host.startsWith('system.host.')) {
2037
- host += 'system.host.' + host;
2038
- }
2039
- this._promises.repo = new Promise(function (resolve, reject) {
2040
- var timeout = setTimeout(function () {
2041
- if (timeout) {
2042
- timeout = null;
2043
- reject('getRepository timeout');
2044
- }
2045
- }, timeoutMs || _this41.props.cmdTimeout);
2046
- _this41._socket.emit('sendToHost', host, 'getRepository', args, function (data) {
2047
- if (timeout) {
2048
- clearTimeout(timeout);
2049
- timeout = null;
2050
- if (data === PERMISSION_ERROR) {
2051
- reject('May not read "getRepository"');
2052
- } else if (!data) {
2053
- reject('Cannot read "getRepository"');
2054
- } else {
2055
- resolve(data);
2056
- }
2057
- }
2058
- });
2059
- });
2060
- return this._promises.repo;
2061
- }
2062
-
2063
- /**
2064
- * Get the installed.
2065
- * @param {string} host
2066
- * @param {boolean} [update] Force update.
2067
- * @param {number} [cmdTimeout] timeout in ms (optional)
2068
- * @returns {Promise<any>}
2069
- */
2070
- }, {
2071
- key: "getInstalled",
2072
- value: function getInstalled(host, update, cmdTimeout) {
2073
- var _this42 = this;
2074
- if (Connection.isWeb()) {
2075
- return Promise.reject('Allowed only in admin');
2076
- }
2077
- this._promises.installed = this._promises.installed || {};
2078
- if (!update && this._promises.installed[host]) {
2079
- return this._promises.installed[host];
2080
- }
2081
- if (!this.connected) {
2082
- return Promise.reject(NOT_CONNECTED);
2083
- }
2084
- if (!host.startsWith('system.host.')) {
2085
- host += 'system.host.' + host;
2086
- }
2087
- this._promises.installed[host] = new Promise(function (resolve, reject) {
2088
- var timeout = setTimeout(function () {
2089
- if (timeout) {
2090
- timeout = null;
2091
- reject('getInstalled timeout');
2092
- }
2093
- }, cmdTimeout || _this42.props.cmdTimeout);
2094
- _this42._socket.emit('sendToHost', host, 'getInstalled', null, function (data) {
2095
- if (timeout) {
2096
- clearTimeout(timeout);
2097
- timeout = null;
2098
- if (data === PERMISSION_ERROR) {
2099
- reject('May not read "getInstalled"');
2100
- } else if (!data) {
2101
- reject('Cannot read "getInstalled"');
2102
- } else {
2103
- resolve(data);
2104
- }
2105
- }
2106
- });
2107
- });
2108
- return this._promises.installed[host];
2109
- }
2110
-
2111
- /**
2112
- * Execute a command on a host.
2113
- * @param {string} host The host name.
2114
- * @param {string} cmd The command.
2115
- * @param {string} cmdId The command ID.
2116
- * @param {number} cmdTimeout Timeout of command in ms
2117
- * @returns {Promise<void>}
2118
- */
2119
- }, {
2120
- key: "cmdExec",
2121
- value: function cmdExec(host, cmd, cmdId, cmdTimeout) {
2122
- var _this43 = this;
2123
- if (Connection.isWeb()) {
2124
- return Promise.reject('Allowed only in admin');
2125
- }
2126
- if (!this.connected) {
2127
- return Promise.reject(NOT_CONNECTED);
2128
- }
2129
- if (!host.startsWith(host)) {
2130
- host += 'system.host.' + host;
2131
- }
2132
- return new Promise(function (resolve, reject) {
2133
- var timeout = cmdTimeout && setTimeout(function () {
2134
- if (timeout) {
2135
- timeout = null;
2136
- reject('cmdExec timeout');
2137
- }
2138
- }, cmdTimeout);
2139
- _this43._socket.emit('cmdExec', host, cmdId, cmd, null, function (err) {
2140
- if (!cmdTimeout || timeout) {
2141
- timeout && clearTimeout(timeout);
2142
- timeout = null;
2143
- if (err) {
2144
- reject(err);
2145
- } else {
2146
- resolve();
2147
- }
2148
- }
2149
- });
2150
- });
2151
- }
2152
-
2153
- /**
2154
- * Checks if a given feature is supported.
2155
- * @param {string} feature The feature to check.
2156
- * @param {boolean} [update] Force update.
2157
- * @returns {Promise<any>}
2158
- */
2159
- }, {
2160
- key: "checkFeatureSupported",
2161
- value: function checkFeatureSupported(feature, update) {
2162
- var _this44 = this;
2163
- if (!update && this._promises['supportedFeatures_' + feature]) {
2164
- return this._promises['supportedFeatures_' + feature];
2165
- }
2166
- if (!this.connected) {
2167
- return Promise.reject(NOT_CONNECTED);
2168
- }
2169
- this._promises['supportedFeatures_' + feature] = new Promise(function (resolve, reject) {
2170
- return _this44._socket.emit('checkFeatureSupported', feature, function (err, features) {
2171
- err ? reject(err) : resolve(features);
2172
- });
2173
- });
2174
- return this._promises['supportedFeatures_' + feature];
2175
- }
2176
-
2177
- /**
2178
- * Read the base settings of a given host.
2179
- * @param {string} host
2180
- * @returns {Promise<any>}
2181
- */
2182
- }, {
2183
- key: "readBaseSettings",
2184
- value: function readBaseSettings(host) {
2185
- var _this45 = this;
2186
- if (Connection.isWeb()) {
2187
- return Promise.reject('Allowed only in admin');
2188
- }
2189
- return this.checkFeatureSupported('CONTROLLER_READWRITE_BASE_SETTINGS').then(function (result) {
2190
- if (result) {
2191
- if (!_this45.connected) {
2192
- return Promise.reject(NOT_CONNECTED);
2193
- }
2194
- return new Promise(function (resolve, reject) {
2195
- var timeout = setTimeout(function () {
2196
- if (timeout) {
2197
- timeout = null;
2198
- reject('readBaseSettings timeout');
2199
- }
2200
- }, _this45.props.cmdTimeout);
2201
- if (host.startsWith('system.host.')) {
2202
- host = host.replace(/^system\.host\./, '');
2203
- }
2204
- _this45._socket.emit('sendToHost', host, 'readBaseSettings', null, function (data) {
2205
- if (timeout) {
2206
- clearTimeout(timeout);
2207
- timeout = null;
2208
- if (data === PERMISSION_ERROR) {
2209
- reject('May not read "BaseSettings"');
2210
- } else if (!data) {
2211
- reject('Cannot read "BaseSettings"');
2212
- } else {
2213
- resolve(data);
2214
- }
2215
- }
2216
- });
2217
- });
2218
- } else {
2219
- return Promise.reject('Not supported');
2220
- }
2221
- });
2222
- }
2223
-
2224
- /**
2225
- * Write the base settings of a given host.
2226
- * @param {string} host
2227
- * @param {any} config
2228
- * @returns {Promise<any>}
2229
- */
2230
- }, {
2231
- key: "writeBaseSettings",
2232
- value: function writeBaseSettings(host, config) {
2233
- var _this46 = this;
2234
- if (Connection.isWeb()) {
2235
- return Promise.reject('Allowed only in admin');
2236
- }
2237
- return this.checkFeatureSupported('CONTROLLER_READWRITE_BASE_SETTINGS').then(function (result) {
2238
- if (result) {
2239
- if (!_this46.connected) {
2240
- return Promise.reject(NOT_CONNECTED);
2241
- }
2242
- return new Promise(function (resolve, reject) {
2243
- var timeout = setTimeout(function () {
2244
- if (timeout) {
2245
- timeout = null;
2246
- reject('writeBaseSettings timeout');
2247
- }
2248
- }, _this46.props.cmdTimeout);
2249
- _this46._socket.emit('sendToHost', host, 'writeBaseSettings', config, function (data) {
2250
- if (timeout) {
2251
- clearTimeout(timeout);
2252
- timeout = null;
2253
- if (data === PERMISSION_ERROR) {
2254
- reject('May not write "BaseSettings"');
2255
- } else if (!data) {
2256
- reject('Cannot write "BaseSettings"');
2257
- } else {
2258
- resolve(data);
2259
- }
2260
- }
2261
- });
2262
- });
2263
- } else {
2264
- return Promise.reject('Not supported');
2265
- }
2266
- });
2267
- }
2268
-
2269
- /**
2270
- * Send command to restart the iobroker on host
2271
- * @param {string} host
2272
- * @returns {Promise<any>}
2273
- */
2274
- }, {
2275
- key: "restartController",
2276
- value: function restartController(host) {
2277
- var _this47 = this;
2278
- if (Connection.isWeb()) {
2279
- return Promise.reject('Allowed only in admin');
2280
- }
2281
- return new Promise(function (resolve, reject) {
2282
- _this47._socket.emit('sendToHost', host, 'restartController', null, function (error) {
2283
- error ? reject(error) : resolve(true);
2284
- });
2285
- });
2286
- }
2287
-
2288
- /**
2289
- * Read statistics information from host
2290
- * @param {string} host
2291
- * @param {string} typeOfDiag one of none, normal, no-city, extended
2292
- * @returns {Promise<any>}
2293
- */
2294
- }, {
2295
- key: "getDiagData",
2296
- value: function getDiagData(host, typeOfDiag) {
2297
- var _this48 = this;
2298
- if (Connection.isWeb()) {
2299
- return Promise.reject('Allowed only in admin');
2300
- }
2301
- return new Promise(function (resolve) {
2302
- _this48._socket.emit('sendToHost', host, 'getDiagData', typeOfDiag, function (result) {
2303
- return resolve(result);
2304
- });
2305
- });
2306
- }
2307
-
2308
- /**
2309
- * Read all states (which might not belong to this adapter) which match the given pattern.
2310
- * @param {string} pattern
2311
- * @returns {ioBroker.GetStatesPromise}
2312
- */
2313
- }, {
2314
- key: "getForeignStates",
2315
- value: function getForeignStates(pattern) {
2316
- var _this49 = this;
2317
- if (!this.connected) {
2318
- return Promise.reject(NOT_CONNECTED);
2319
- }
2320
- if (Connection.isWeb()) {
2321
- return new Promise(function (resolve, reject) {
2322
- return _this49._socket.emit('getStates', pattern || '*', function (err, states) {
2323
- return err ? reject(err) : resolve(states);
2324
- });
2325
- });
2326
- } else {
2327
- return new Promise(function (resolve, reject) {
2328
- return _this49._socket.emit('getForeignStates', pattern || '*', function (err, states) {
2329
- return err ? reject(err) : resolve(states);
2330
- });
2331
- });
2332
- }
2333
- }
2334
-
2335
- /**
2336
- * Get foreign objects by pattern, by specific type and resolve their enums.
2337
- * @param {string} pattern
2338
- * @param {string} [type]
2339
- * @returns {ioBroker.GetObjectsPromise}
2340
- */
2341
- }, {
2342
- key: "getForeignObjects",
2343
- value: function getForeignObjects(pattern, type) {
2344
- var _this50 = this;
2345
- if (!this.connected) {
2346
- return Promise.reject(NOT_CONNECTED);
2347
- }
2348
- return new Promise(function (resolve, reject) {
2349
- return _this50._socket.emit('getForeignObjects', pattern || '*', type, function (err, states) {
2350
- return err ? reject(err) : resolve(states);
2351
- });
2352
- });
2353
- }
2354
-
2355
- /**
2356
- * Gets the system configuration.
2357
- * @param {boolean} [update] Force update.
2358
- * @returns {Promise<ioBroker.OtherObject>}
2359
- */
2360
- }, {
2361
- key: "getSystemConfig",
2362
- value: function getSystemConfig(update) {
2363
- if (!update && this._promises.systemConfig) {
2364
- return this._promises.systemConfig;
2365
- }
2366
- if (!this.connected) {
2367
- return Promise.reject(NOT_CONNECTED);
2368
- }
2369
- this._promises.systemConfig = this.getObject('system.config').then(function (systemConfig) {
2370
- //@ts-ignore
2371
- systemConfig = systemConfig || {};
2372
- //@ts-ignore
2373
- systemConfig.common = systemConfig.common || {};
2374
- //@ts-ignore
2375
- systemConfig["native"] = systemConfig["native"] || {};
2376
- return systemConfig;
2377
- });
2378
- return this._promises.systemConfig;
2379
- }
2380
-
2381
- /**
2382
- * Sets the system configuration.
2383
- * @param {ioBroker.SettableObjectWorker<ioBroker.OtherObject>} obj
2384
- * @returns {Promise<ioBroker.SettableObjectWorker<ioBroker.OtherObject>>}
2385
- */
2386
- }, {
2387
- key: "setSystemConfig",
2388
- value: function setSystemConfig(obj) {
2389
- var _this51 = this;
2390
- return this.setObject('system.config', obj).then(function () {
2391
- return _this51._promises.systemConfig = Promise.resolve(obj);
2392
- });
2393
- }
2394
-
2395
- /**
2396
- * Get the raw socket.io socket.
2397
- * @returns {any}
2398
- */
2399
- }, {
2400
- key: "getRawSocket",
2401
- value: function getRawSocket() {
2402
- return this._socket;
2403
- }
2404
-
2405
- /**
2406
- * Get the history of a given state.
2407
- * @param {string} id
2408
- * @param {ioBroker.GetHistoryOptions} options
2409
- * @returns {Promise<ioBroker.GetHistoryResult>}
2410
- */
2411
- }, {
2412
- key: "getHistory",
2413
- value: function getHistory(id, options) {
2414
- var _this52 = this;
2415
- if (!this.connected) {
2416
- return Promise.reject(NOT_CONNECTED);
2417
- }
2418
- return new Promise(function (resolve, reject) {
2419
- return _this52._socket.emit('getHistory', id, options, function (err, values) {
2420
- return err ? reject(err) : resolve(values);
2421
- });
2422
- });
2423
- }
2424
-
2425
- /**
2426
- * Get the history of a given state.
2427
- * @param {string} id
2428
- * @param {ioBroker.GetHistoryOptions} options
2429
- * @returns {Promise<{values: ioBroker.GetHistoryResult; sesionId: string; stepIgnore: number}>}
2430
- */
2431
- }, {
2432
- key: "getHistoryEx",
2433
- value: function getHistoryEx(id, options) {
2434
- var _this53 = this;
2435
- if (!this.connected) {
2436
- return Promise.reject(NOT_CONNECTED);
2437
- }
2438
- return new Promise(function (resolve, reject) {
2439
- return _this53._socket.emit('getHistory', id, options, function (err, values, stepIgnore, sessionId) {
2440
- return err ? reject(err) : resolve({
2441
- values: values,
2442
- sessionId: sessionId,
2443
- stepIgnore: stepIgnore
2444
- });
2445
- });
2446
- });
2447
- }
2448
-
2449
- /**
2450
- * Change the password of the given user.
2451
- * @param {string} user
2452
- * @param {string} password
2453
- * @returns {Promise<void>}
2454
- */
2455
- }, {
2456
- key: "changePassword",
2457
- value: function changePassword(user, password) {
2458
- var _this54 = this;
2459
- if (Connection.isWeb()) {
2460
- return Promise.reject('Allowed only in admin');
2461
- }
2462
- return new Promise(function (resolve, reject) {
2463
- return _this54._socket.emit('changePassword', user, password, function (err) {
2464
- return err ? reject(err) : resolve();
2465
- });
2466
- });
2467
- }
2468
-
2469
- /**
2470
- * Get the IP addresses of the given host.
2471
- * @param {string} host
2472
- * @param {boolean} [update] Force update.
2473
- * @returns {Promise<string[]>}
2474
- */
2475
- }, {
2476
- key: "getIpAddresses",
2477
- value: function getIpAddresses(host, update) {
2478
- if (Connection.isWeb()) {
2479
- return Promise.reject('Allowed only in admin');
2480
- }
2481
- if (!host.startsWith('system.host.')) {
2482
- host = 'system.host.' + host;
2483
- }
2484
- if (!update && this._promises['IPs_' + host]) {
2485
- return this._promises['IPs_' + host];
2486
- }
2487
- this._promises['IPs_' + host] = this.getObject(host).then(function (obj) {
2488
- return obj && obj.common ? obj.common.address || [] : [];
2489
- });
2490
- return this._promises['IPs_' + host];
2491
- }
2492
-
2493
- /**
2494
- * Get the IP addresses with interface names of the given host or find host by IP.
2495
- * @param {string} ipOrHostName
2496
- * @param {boolean} [update] Force update.
2497
- * @returns {Promise<any[<name, address, family>]>}
2498
- */
2499
- }, {
2500
- key: "getHostByIp",
2501
- value: function getHostByIp(ipOrHostName, update) {
2502
- var _this55 = this;
2503
- if (Connection.isWeb()) {
2504
- return Promise.reject('Allowed only in admin');
2505
- }
2506
- if (ipOrHostName.startsWith('system.host.')) {
2507
- ipOrHostName = ipOrHostName.replace(/^system\.host\./, '');
2508
- }
2509
- if (!update && this._promises['rIPs_' + ipOrHostName]) {
2510
- return this._promises['rIPs_' + ipOrHostName];
2511
- }
2512
- this._promises['rIPs_' + ipOrHostName] = new Promise(function (resolve) {
2513
- return _this55._socket.emit('getHostByIp', ipOrHostName, function (ip, host) {
2514
- var _host$native, _host$native$hardware;
2515
- var IPs4 = [{
2516
- name: '[IPv4] 0.0.0.0 - Listen on all IPs',
2517
- address: '0.0.0.0',
2518
- family: 'ipv4'
2519
- }];
2520
- var IPs6 = [{
2521
- name: '[IPv6] :: - Listen on all IPs',
2522
- address: '::',
2523
- family: 'ipv6'
2524
- }];
2525
- if (host !== null && host !== void 0 && (_host$native = host["native"]) !== null && _host$native !== void 0 && (_host$native$hardware = _host$native.hardware) !== null && _host$native$hardware !== void 0 && _host$native$hardware.networkInterfaces) {
2526
- for (var eth in host["native"].hardware.networkInterfaces) {
2527
- if (!host["native"].hardware.networkInterfaces.hasOwnProperty(eth)) {
2528
- continue;
2529
- }
2530
- for (var num = 0; num < host["native"].hardware.networkInterfaces[eth].length; num++) {
2531
- if (host["native"].hardware.networkInterfaces[eth][num].family !== 'IPv6') {
2532
- IPs4.push({
2533
- name: "[".concat(host["native"].hardware.networkInterfaces[eth][num].family, "] ").concat(host["native"].hardware.networkInterfaces[eth][num].address, " - ").concat(eth),
2534
- address: host["native"].hardware.networkInterfaces[eth][num].address,
2535
- family: 'ipv4'
2536
- });
2537
- } else {
2538
- IPs6.push({
2539
- name: "[".concat(host["native"].hardware.networkInterfaces[eth][num].family, "] ").concat(host["native"].hardware.networkInterfaces[eth][num].address, " - ").concat(eth),
2540
- address: host["native"].hardware.networkInterfaces[eth][num].address,
2541
- family: 'ipv6'
2542
- });
2543
- }
2544
- }
2545
- }
2546
- }
2547
- for (var i = 0; i < IPs6.length; i++) {
2548
- IPs4.push(IPs6[i]);
2549
- }
2550
- resolve(IPs4);
2551
- });
2552
- });
2553
- return this._promises['rIPs_' + ipOrHostName];
2554
- }
2555
-
2556
- /**
2557
- * Encrypt a text
2558
- * @param {string} text
2559
- * @returns {Promise<string>}
2560
- */
2561
- }, {
2562
- key: "encrypt",
2563
- value: function encrypt(text) {
2564
- var _this56 = this;
2565
- if (Connection.isWeb()) {
2566
- return Promise.reject('Allowed only in admin');
2567
- }
2568
- return new Promise(function (resolve, reject) {
2569
- return _this56._socket.emit('encrypt', text, function (err, text) {
2570
- return err ? reject(err) : resolve(text);
2571
- });
2572
- });
2573
- }
2574
-
2575
- /**
2576
- * Decrypt a text
2577
- * @param {string} encryptedText
2578
- * @returns {Promise<string>}
2579
- */
2580
- }, {
2581
- key: "decrypt",
2582
- value: function decrypt(encryptedText) {
2583
- var _this57 = this;
2584
- if (Connection.isWeb()) {
2585
- return Promise.reject('Allowed only in admin');
2586
- }
2587
- return new Promise(function (resolve, reject) {
2588
- return _this57._socket.emit('decrypt', encryptedText, function (err, text) {
2589
- return err ? reject(err) : resolve(text);
2590
- });
2591
- });
2592
- }
2593
-
2594
- /**
2595
- * Gets the version.
2596
- * @returns {Promise<{version: string; serverName: string}>}
2597
- */
2598
- }, {
2599
- key: "getVersion",
2600
- value: function getVersion(update) {
2601
- var _this58 = this;
2602
- if (update && this._promises.version) {
2603
- this._promises.version = null;
2604
- }
2605
- this._promises.version = this._promises.version || new Promise(function (resolve, reject) {
2606
- return _this58._socket.emit('getVersion', function (err, version, serverName) {
2607
- // support of old socket.io
2608
- if (err && !version && typeof err === 'string' && err.match(/\d+\.\d+\.\d+/)) {
2609
- resolve({
2610
- version: err,
2611
- serverName: 'socketio'
2612
- });
2613
- } else {
2614
- return err ? reject(err) : resolve({
2615
- version: version,
2616
- serverName: serverName
2617
- });
2618
- }
2619
- });
2620
- });
2621
- return this._promises.version;
2622
- }
2623
-
2624
- /**
2625
- * Gets the web server name.
2626
- * @returns {Promise<string>}
2627
- */
2628
- }, {
2629
- key: "getWebServerName",
2630
- value: function getWebServerName() {
2631
- var _this59 = this;
2632
- this._promises.webName = this._promises.webName || new Promise(function (resolve, reject) {
2633
- return _this59._socket.emit('getAdapterName', function (err, name) {
2634
- return err ? reject(err) : resolve(name);
2635
- });
2636
- });
2637
- return this._promises.webName;
2638
- }
2639
-
2640
- /**
2641
- * Gets the admin version.
2642
- * @deprecated use getVersion()
2643
- * @returns {Promise<{version: string; serverName: string}>}
2644
- */
2645
- }, {
2646
- key: "getAdminVersion",
2647
- value: function getAdminVersion() {
2648
- console.log('Deprecated: use getVersion');
2649
- return this.getVersion();
2650
- }
2651
-
2652
- /**
2653
- * Change access rights for file
2654
- * @param {string} [adapter] adapter name
2655
- * @param {string} [filename] file name with full path. it could be like vis.0/*
2656
- * @param {object} [options] like {mode: 0x644}
2657
- * @returns {Promise<{entries: array}>}
2658
- */
2659
- }, {
2660
- key: "chmodFile",
2661
- value: function chmodFile(adapter, filename, options) {
2662
- var _this60 = this;
2663
- if (Connection.isWeb()) {
2664
- return Promise.reject('Allowed only in admin');
2665
- }
2666
- if (!this.connected) {
2667
- return Promise.reject(NOT_CONNECTED);
2668
- }
2669
- return new Promise(function (resolve, reject) {
2670
- return _this60._socket.emit('chmodFile', adapter, filename, options, function (err, entries, id) {
2671
- return err ? reject(err) : resolve({
2672
- entries: entries,
2673
- id: id
2674
- });
2675
- });
2676
- });
2677
- }
2678
-
2679
- /**
2680
- * Change owner or/and owner group for file
2681
- * @param {string} [adapter] adapter name
2682
- * @param {string} [filename] file name with full path. it could be like vis.0/*
2683
- * @param {object} [options] like {owner: 'newOwner', ownerGroup: 'newGroup'}
2684
- * @returns {Promise<{entries: array}>}
2685
- */
2686
- }, {
2687
- key: "chownFile",
2688
- value: function chownFile(adapter, filename, options) {
2689
- var _this61 = this;
2690
- if (Connection.isWeb()) {
2691
- return Promise.reject('Allowed only in admin');
2692
- }
2693
- if (!this.connected) {
2694
- return Promise.reject(NOT_CONNECTED);
2695
- }
2696
- return new Promise(function (resolve, reject) {
2697
- return _this61._socket.emit('chownFile', adapter, filename, options, function (err, entries, id) {
2698
- return err ? reject(err) : resolve({
2699
- entries: entries,
2700
- id: id
2701
- });
2702
- });
2703
- });
2704
- }
2705
-
2706
- /**
2707
- * Check if the file exists
2708
- * @param {string} [adapter] adapter name
2709
- * @param {string} [filename] file name with full path. it could be like vis.0/*
2710
- * @returns {Promise<boolean>}
2711
- */
2712
- }, {
2713
- key: "fileExists",
2714
- value: function fileExists(adapter, filename) {
2715
- var _this62 = this;
2716
- if (!this.connected) {
2717
- return Promise.reject(NOT_CONNECTED);
2718
- }
2719
- return new Promise(function (resolve, reject) {
2720
- return _this62._socket.emit('fileExists', adapter, filename, function (err, exists) {
2721
- return err ? reject(err) : resolve(exists);
2722
- });
2723
- });
2724
- }
2725
-
2726
- /**
2727
- * Get the alarm notifications from a host (only for admin connection).
2728
- * @param {string} host
2729
- * @param {string} [category] - optional
2730
- * @returns {Promise<any>}
2731
- */
2732
- }, {
2733
- key: "getNotifications",
2734
- value: function getNotifications(host, category) {
2735
- var _this63 = this;
2736
- if (Connection.isWeb()) {
2737
- return Promise.reject('Allowed only in admin');
2738
- }
2739
- if (!this.connected) {
2740
- return Promise.reject(NOT_CONNECTED);
2741
- }
2742
- return new Promise(function (resolve) {
2743
- return _this63._socket.emit('sendToHost', host, 'getNotifications', {
2744
- category: category
2745
- }, function (notifications) {
2746
- return resolve(notifications);
2747
- });
2748
- });
2749
- }
2750
-
2751
- /**
2752
- * Clear the alarm notifications on a host (only for admin connection).
2753
- * @param {string} host
2754
- * @param {string} [category] - optional
2755
- * @returns {Promise<any>}
2756
- */
2757
- }, {
2758
- key: "clearNotifications",
2759
- value: function clearNotifications(host, category) {
2760
- var _this64 = this;
2761
- if (Connection.isWeb()) {
2762
- return Promise.reject('Allowed only in admin');
2763
- }
2764
- if (!this.connected) {
2765
- return Promise.reject(NOT_CONNECTED);
2766
- }
2767
- return new Promise(function (resolve) {
2768
- return _this64._socket.emit('sendToHost', host, 'clearNotifications', {
2769
- category: category
2770
- }, function (notifications) {
2771
- return resolve(notifications);
2772
- });
2773
- });
2774
- }
2775
-
2776
- /**
2777
- * Read if only easy mode is allowed (only for admin connection).
2778
- * @returns {Promise<boolean>}
2779
- */
2780
- }, {
2781
- key: "getIsEasyModeStrict",
2782
- value: function getIsEasyModeStrict() {
2783
- var _this65 = this;
2784
- if (Connection.isWeb()) {
2785
- return Promise.reject('Allowed only in admin');
2786
- }
2787
- if (!this.connected) {
2788
- return Promise.reject(NOT_CONNECTED);
2789
- }
2790
- return new Promise(function (resolve, reject) {
2791
- return _this65._socket.emit('getIsEasyModeStrict', function (error, isStrict) {
2792
- return error ? reject(error) : resolve(isStrict);
2793
- });
2794
- });
2795
- }
2796
-
2797
- /**
2798
- * Read easy mode configuration (only for admin connection).
2799
- * @returns {Promise<any>}
2800
- */
2801
- }, {
2802
- key: "getEasyMode",
2803
- value: function getEasyMode() {
2804
- var _this66 = this;
2805
- if (Connection.isWeb()) {
2806
- return Promise.reject('Allowed only in admin');
2807
- }
2808
- if (!this.connected) {
2809
- return Promise.reject(NOT_CONNECTED);
2810
- }
2811
- return new Promise(function (resolve, reject) {
2812
- return _this66._socket.emit('getEasyMode', function (error, config) {
2813
- return error ? reject(error) : resolve(config);
2814
- });
2815
- });
2816
- }
2817
-
2818
- /**
2819
- * Read current user
2820
- * @returns {Promise<string>}
2821
- */
2822
- }, {
2823
- key: "getCurrentUser",
2824
- value: function getCurrentUser() {
2825
- var _this67 = this;
2826
- if (!this.connected) {
2827
- return Promise.reject(NOT_CONNECTED);
2828
- }
2829
- return new Promise(function (resolve) {
2830
- return _this67._socket.emit('authEnabled', function (isSecure, user) {
2831
- return resolve(user);
2832
- });
2833
- });
2834
- }
2835
- }, {
2836
- key: "getCurrentSession",
2837
- value: function getCurrentSession(cmdTimeout) {
2838
- if (!this.connected) {
2839
- return Promise.reject(NOT_CONNECTED);
2840
- }
2841
- return new Promise(function (resolve, reject) {
2842
- var controller = new AbortController();
2843
- var timeout = setTimeout(function () {
2844
- if (timeout) {
2845
- timeout = null;
2846
- controller.abort();
2847
- reject('getCurrentSession timeout');
2848
- }
2849
- }, cmdTimeout || 5000);
2850
- return fetch('./session', {
2851
- signal: controller.signal
2852
- }).then(function (res) {
2853
- return res.json();
2854
- }).then(function (json) {
2855
- if (timeout) {
2856
- clearTimeout(timeout);
2857
- timeout = null;
2858
- resolve(json);
2859
- }
2860
- })["catch"](function (e) {
2861
- return reject('getCurrentSession: ' + e);
2862
- });
2863
- });
2864
- }
2865
-
2866
- /**
2867
- * Read adapter ratings
2868
- * @returns {Promise<any>}
2869
- */
2870
- }, {
2871
- key: "getRatings",
2872
- value: function getRatings(update) {
2873
- var _this68 = this;
2874
- if (Connection.isWeb()) {
2875
- return Promise.reject('Allowed only in admin');
2876
- }
2877
- if (!this.connected) {
2878
- return Promise.reject(NOT_CONNECTED);
2879
- }
2880
- return new Promise(function (resolve, reject) {
2881
- return _this68._socket.emit('getRatings', update, function (err, ratings) {
2882
- return err ? reject(err) : resolve(ratings);
2883
- });
2884
- });
2885
- }
2886
-
2887
- /**
2888
- * Read current web, socketio or admin namespace, like admin.0
2889
- * @returns {Promise<string>}
2890
- */
2891
- }, {
2892
- key: "getCurrentInstance",
2893
- value: function getCurrentInstance() {
2894
- var _this69 = this;
2895
- if (!this.connected) {
2896
- return Promise.reject(NOT_CONNECTED);
2897
- }
2898
- this._promises.currentInstance = this._promises.currentInstance || new Promise(function (resolve, reject) {
2899
- return _this69._socket.emit('getCurrentInstance', function (err, namespace) {
2900
- return err ? reject(err) : resolve(namespace);
2901
- });
2902
- });
2903
- return this._promises.currentInstance;
2904
- }
2905
-
2906
- // returns very optimized information for adapters to minimize connection load
2907
- }, {
2908
- key: "getCompactAdapters",
2909
- value: function getCompactAdapters(update) {
2910
- var _this70 = this;
2911
- if (Connection.isWeb()) {
2912
- return Promise.reject('Allowed only in admin');
2913
- }
2914
- if (!update && this._promises.compactAdapters) {
2915
- return this._promises.compactAdapters;
2916
- }
2917
- if (!this.connected) {
2918
- return Promise.reject(NOT_CONNECTED);
2919
- }
2920
- this._promises.compactAdapters = new Promise(function (resolve, reject) {
2921
- return _this70._socket.emit('getCompactAdapters', function (err, adapters) {
2922
- return err ? reject(err) : resolve(adapters);
2923
- });
2924
- });
2925
- return this._promises.compactAdapters;
2926
- }
2927
- }, {
2928
- key: "getAdaptersResetCache",
2929
- value: function getAdaptersResetCache(adapter) {
2930
- adapter = adapter || '';
2931
- this._promises.compactAdapters = null;
2932
- this._promises['adapter_' + adapter] = null;
2933
- }
2934
-
2935
- // returns very optimized information for adapters to minimize connection load
2936
- }, {
2937
- key: "getCompactInstances",
2938
- value: function getCompactInstances(update) {
2939
- var _this71 = this;
2940
- if (Connection.isWeb()) {
2941
- return Promise.reject('Allowed only in admin');
2942
- }
2943
- if (!update && this._promises.compactInstances) {
2944
- return this._promises.compactInstances;
2945
- }
2946
- if (!this.connected) {
2947
- return Promise.reject(NOT_CONNECTED);
2948
- }
2949
- this._promises.compactInstances = new Promise(function (resolve, reject) {
2950
- return _this71._socket.emit('getCompactInstances', function (err, instances) {
2951
- return err ? reject(err) : resolve(instances);
2952
- });
2953
- });
2954
- return this._promises.compactInstances;
2955
- }
2956
- }, {
2957
- key: "getAdapternInstancesResetCache",
2958
- value: function getAdapternInstancesResetCache(adapter) {
2959
- adapter = adapter || '';
2960
- this._promises.compactInstances = null;
2961
- this._promises['instances_' + adapter] = null;
2962
- }
2963
-
2964
- // returns very optimized information for adapters to minimize connection load
2965
- // reads only version of installed adapter
2966
- }, {
2967
- key: "getCompactInstalled",
2968
- value: function getCompactInstalled(host, update, cmdTimeout) {
2969
- var _this72 = this;
2970
- if (Connection.isWeb()) {
2971
- return Promise.reject('Allowed only in admin');
2972
- }
2973
- this._promises.installedCompact = this._promises.installedCompact || {};
2974
- if (!update && this._promises.installedCompact[host]) {
2975
- return this._promises.installedCompact[host];
2976
- }
2977
- if (!this.connected) {
2978
- return Promise.reject(NOT_CONNECTED);
2979
- }
2980
- if (!host.startsWith('system.host.')) {
2981
- host += 'system.host.' + host;
2982
- }
2983
- this._promises.installedCompact[host] = new Promise(function (resolve, reject) {
2984
- var timeout = setTimeout(function () {
2985
- if (timeout) {
2986
- timeout = null;
2987
- reject('getCompactInstalled timeout');
2988
- }
2989
- }, cmdTimeout || _this72.props.cmdTimeout);
2990
- _this72._socket.emit('getCompactInstalled', host, function (data) {
2991
- if (timeout) {
2992
- clearTimeout(timeout);
2993
- timeout = null;
2994
- if (data === PERMISSION_ERROR) {
2995
- reject('May not read "getCompactInstalled"');
2996
- } else if (!data) {
2997
- reject('Cannot read "getCompactInstalled"');
2998
- } else {
2999
- resolve(data);
3000
- }
3001
- }
3002
- });
3003
- });
3004
- return this._promises.installedCompact[host];
3005
- }
3006
-
3007
- // returns very optimized information for adapters to minimize connection load
3008
- // reads only version of installed adapter
3009
- }, {
3010
- key: "getCompactSystemRepositories",
3011
- value: function getCompactSystemRepositories(update, cmdTimeout) {
3012
- var _this73 = this;
3013
- if (Connection.isWeb()) {
3014
- return Promise.reject('Allowed only in admin');
3015
- }
3016
- this._promises.installedCompact = this._promises.installedCompact || {};
3017
- if (!this.connected) {
3018
- return Promise.reject(NOT_CONNECTED);
3019
- }
3020
- this._promises.getCompactSystemRepositories = new Promise(function (resolve, reject) {
3021
- var timeout = setTimeout(function () {
3022
- if (timeout) {
3023
- timeout = null;
3024
- reject('getCompactSystemRepositories timeout');
3025
- }
3026
- }, cmdTimeout || _this73.props.cmdTimeout);
3027
- _this73._socket.emit('getCompactSystemRepositories', function (data) {
3028
- if (timeout) {
3029
- clearTimeout(timeout);
3030
- timeout = null;
3031
- if (data === PERMISSION_ERROR) {
3032
- reject('May not read "getCompactSystemRepositories"');
3033
- } else if (!data) {
3034
- reject('Cannot read "getCompactSystemRepositories"');
3035
- } else {
3036
- resolve(data);
3037
- }
3038
- }
3039
- });
3040
- });
3041
- return this._promises.getCompactSystemRepositories;
3042
- }
3043
- }, {
3044
- key: "getInstalledResetCache",
3045
- value: function getInstalledResetCache(host) {
3046
- this._promises.repoCompact = null;
3047
- this._promises.repo = null;
3048
- }
3049
-
3050
- /**
3051
- * Get the list of all hosts in compact form (only _id, common.name, common.icon, common.color, native.hardware.networkInterfaces)
3052
- * @param {boolean} [update] Force update.
3053
- * @returns {Promise<ioBroker.Object[]>}
3054
- */
3055
- }, {
3056
- key: "getCompactSystemConfig",
3057
- value:
3058
- // returns very optimized information for adapters to minimize connection load
3059
- function getCompactSystemConfig(update) {
3060
- var _this74 = this;
3061
- if (!update && this._promises.systemConfigCommon) {
3062
- return this._promises.systemConfigCommon;
3063
- }
3064
- if (!this.connected) {
3065
- return Promise.reject(NOT_CONNECTED);
3066
- }
3067
- this._promises.systemConfigCommon = new Promise(function (resolve, reject) {
3068
- return _this74._socket.emit('getCompactSystemConfig', function (err, systemConfig) {
3069
- return err ? reject(err) : resolve(systemConfig);
3070
- });
3071
- });
3072
- return this._promises.systemConfigCommon;
3073
- }
3074
-
3075
- /**
3076
- * Get the repository in compact form (only version and icon).
3077
- * @param {string} host
3078
- * @param {boolean} [update] Force update.
3079
- * @param {number} [timeoutMs] timeout in ms.
3080
- * @returns {Promise<any>}
3081
- */
3082
- }, {
3083
- key: "getCompactRepository",
3084
- value: function getCompactRepository(host, update, timeoutMs) {
3085
- var _this75 = this;
3086
- if (Connection.isWeb()) {
3087
- return Promise.reject('Allowed only in admin');
3088
- }
3089
- if (!update && this._promises.repoCompact) {
3090
- return this._promises.repoCompact;
3091
- }
3092
- if (!this.connected) {
3093
- return Promise.reject(NOT_CONNECTED);
3094
- }
3095
- if (!host.startsWith('system.host.')) {
3096
- host += 'system.host.' + host;
3097
- }
3098
- this._promises.repoCompact = new Promise(function (resolve, reject) {
3099
- var timeout = setTimeout(function () {
3100
- if (timeout) {
3101
- timeout = null;
3102
- reject('getCompactRepository timeout');
3103
- }
3104
- }, timeoutMs || _this75.props.cmdTimeout);
3105
- _this75._socket.emit('getCompactRepository', host, function (data) {
3106
- if (timeout) {
3107
- clearTimeout(timeout);
3108
- timeout = null;
3109
- if (data === PERMISSION_ERROR) {
3110
- reject('May not read "getCompactRepository"');
3111
- } else if (!data) {
3112
- reject('Cannot read "getCompactRepository"');
3113
- } else {
3114
- resolve(data);
3115
- }
3116
- }
3117
- });
3118
- });
3119
- return this._promises.repoCompact;
3120
- }
3121
- }, {
3122
- key: "getCompactHosts",
3123
- value: function getCompactHosts(update) {
3124
- var _this76 = this;
3125
- if (Connection.isWeb()) {
3126
- return Promise.reject('Allowed only in admin');
3127
- }
3128
- if (!update && this._promises.hostsCompact) {
3129
- return this._promises.hostsCompact;
3130
- }
3131
- if (!this.connected) {
3132
- return Promise.reject(NOT_CONNECTED);
3133
- }
3134
- this._promises.hostsCompact = new Promise(function (resolve, reject) {
3135
- return _this76._socket.emit('getCompactHosts', function (err, hosts) {
3136
- return err ? reject(err) : resolve(hosts);
3137
- });
3138
- });
3139
- return this._promises.hostsCompact;
3140
- }
3141
-
3142
- /**
3143
- * Get uuid
3144
- * @returns {Promise<ioBroker.Object[]>}
3145
- */
3146
- }, {
3147
- key: "getUuid",
3148
- value: function getUuid() {
3149
- if (this._promises.uuid) {
3150
- return this._promises.uuid;
3151
- }
3152
- if (!this.connected) {
3153
- return Promise.reject(NOT_CONNECTED);
3154
- }
3155
- this._promises.uuid = this.getObject('system.meta.uuid')
3156
- //@ts-ignore
3157
- .then(function (obj) {
3158
- var _obj$native;
3159
- return obj === null || obj === void 0 ? void 0 : (_obj$native = obj["native"]) === null || _obj$native === void 0 ? void 0 : _obj$native.uuid;
3160
- });
3161
- return this._promises.uuid;
3162
- }
3163
-
3164
- /**
3165
- * Send log to ioBroker log
3166
- * @param {string} [text] Log text
3167
- * @param {string} [level] `info`, `debug`, `warn`, `error` or `silly`
3168
- * @returns {void}
3169
- */
3170
- }, {
3171
- key: "log",
3172
- value: function log(text, level) {
3173
- text && this._socket.emit('log', text, level || 'debug');
3174
- }
3175
-
3176
- /**
3177
- * Logout current user
3178
- * @returns {Promise<null>}
3179
- */
3180
- }, {
3181
- key: "logout",
3182
- value: function logout() {
3183
- var _this77 = this;
3184
- if (!this.connected) {
3185
- return Promise.reject(NOT_CONNECTED);
3186
- }
3187
- return new Promise(function (resolve, reject) {
3188
- return _this77._socket.emit('logout', function (err) {
3189
- return err ? reject(err) : resolve(null);
3190
- });
3191
- });
3192
- }
3193
- }], [{
3194
- key: "isWeb",
3195
- value: function isWeb() {
3196
- return window.adapterName === 'material' || window.adapterName === 'vis' || window.adapterName === 'echarts-show' || window.socketUrl !== undefined;
3197
- }
3198
- }]);
3199
- return Connection;
3200
- }();
3201
- Connection.Connection = {
3202
- onLog: _propTypes["default"].func,
3203
- onReady: _propTypes["default"].func,
3204
- onProgress: _propTypes["default"].func
3205
- };
3206
- var _default = Connection;
11
+ });
12
+ exports["default"] = void 0;
13
+ var _socketClient = require("@iobroker/socket-client");
14
+ var _default = _socketClient.Connection;
3207
15
  exports["default"] = _default;
3208
16
  //# sourceMappingURL=Connection.js.map