-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathsetupUpload.ts
878 lines (783 loc) · 32.8 KB
/
setupUpload.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
/**
* Upload adapter files into DB
*
* Copyright 2013-2023 bluefox <[email protected]>
*
* MIT License
*
*/
import * as fs from 'fs-extra';
import { tools } from '@iobroker/js-controller-common';
import deepClone from 'deep-clone';
import { isDeepStrictEqual } from 'util';
import axios from 'axios';
import mime from 'mime-types';
import { join } from 'path';
import type { Client as StatesRedisClient } from '@iobroker/db-states-redis';
import type { Client as ObjectsRedisClient } from '@iobroker/db-objects-redis';
import type { InternalLogger } from '@iobroker/js-controller-common/tools';
const hostname = tools.getHostName();
export interface CLIUploadOptions {
states: StatesRedisClient;
objects: ObjectsRedisClient;
}
interface File {
adapter: string;
path: string;
}
interface Logger extends InternalLogger {
log(message: string): void;
}
export class Upload {
private readonly states: StatesRedisClient;
private readonly objects: ObjectsRedisClient;
private readonly regApp: RegExp;
private callbackId: number;
private readonly sendToHostFromCliAsync: (...args: any[]) => Promise<any>;
private callbacks: Record<string, any> = {};
private lastProgressUpdate: number;
constructor(_options: CLIUploadOptions) {
const options = _options || {};
if (!options.states) {
throw new Error('Invalid arguments: states is missing');
}
if (!options.objects) {
throw new Error('Invalid arguments: objects is missing');
}
this.states = options.states;
this.objects = options.objects;
this.callbackId = 1;
this.regApp = new RegExp('/' + tools.appName.replace(/\./g, '\\.') + '\\.', 'i');
this.sendToHostFromCliAsync = tools.promisifyNoError(this.sendToHostFromCli);
this.lastProgressUpdate = Date.now();
}
async checkHostsIfAlive(hosts: string[]): Promise<string[]> {
const result = [];
if (hosts) {
for (const host of hosts) {
const state = await this.states.getStateAsync(`${host}.alive`);
if (state?.val) {
result.push(host);
}
}
}
return result;
}
async getHosts(onlyAlive: boolean): Promise<string[]> {
const hosts = [];
try {
const arr = await this.objects.getObjectListAsync({
startkey: 'system.host.',
endkey: 'system.host.\u9999'
});
if (arr?.rows) {
for (const row of arr.rows) {
if (row.value.type !== 'host') {
continue;
}
hosts.push(row.value._id);
}
}
} catch (e) {
// ignore
console.warn(`Cannot read hosts: ${e.message}`);
}
if (onlyAlive) {
return this.checkHostsIfAlive(hosts);
} else {
return hosts;
}
}
// Check if some adapters must be restarted and restart them
async checkRestartOther(adapter: string): Promise<void> {
const adapterDir = tools.getAdapterDir(adapter);
if (!adapterDir) {
console.error(`Adapter directory of adapter "${adapter}" not found`);
return;
}
try {
const adapterConf = await fs.readJSON(join(adapterDir, 'io-package.json'));
if (adapterConf.common.restartAdapters) {
if (!Array.isArray(adapterConf.common.restartAdapters)) {
// it's not an array, now it can only be a single adapter as string
if (typeof adapterConf.common.restartAdapters !== 'string') {
return;
}
adapterConf.common.restartAdapters = [adapterConf.common.restartAdapters];
}
if (adapterConf.common.restartAdapters.length && adapterConf.common.restartAdapters[0]) {
const instances = await tools.getAllInstances(adapterConf.common.restartAdapters, this.objects);
if (instances?.length) {
for (const instance of instances) {
try {
const obj = await this.objects.getObjectAsync(instance);
// if instance is enabled
if (obj?.common?.enabled) {
obj.common.enabled = false; // disable instance
obj.from = `system.host.${tools.getHostName()}.cli`;
obj.ts = Date.now();
await this.objects.setObjectAsync(obj._id, obj);
obj.common.enabled = true; // enable instance
obj.ts = Date.now();
await this.objects.setObjectAsync(obj._id, obj);
console.log(`Adapter "${obj._id}" restarted.`);
}
} catch (e) {
console.error(`Cannot restart adapter "${instance}": ${e.message}`);
}
}
}
}
}
} catch (e) {
console.error(`Cannot parse ${adapterDir}/io-package.json: ${e.message}`);
}
}
sendToHostFromCli(
host: string,
command: string,
message: ioBroker.MessagePayload,
callback: ioBroker.MessageCallback | null
): void {
const time = Date.now();
const from = `system.host.${hostname}_cli_${time}`;
const timeout = setTimeout(() => {
if (callback) {
callback();
}
callback = null;
this.states.unsubscribeMessage(from);
// @ts-expect-error todo: I don't think this works
this.states.onChange = null;
}, 60_000);
// @ts-expect-error todo: I don't think this works
this.states.onChange = (id, msg) => {
if (id.endsWith(from)) {
if (msg.command === 'log' || msg.command === 'error' || msg.command === 'warn') {
// @ts-expect-error
console[msg.command](`${host} -> ${msg.text}`);
} else if (callback) {
callback(msg && msg.message);
callback = null;
clearTimeout(timeout);
this.states.unsubscribeMessage(from);
// @ts-expect-error
this.states.onChange = null;
}
}
};
this.states.subscribeMessage(from, () => {
const obj = {
command,
message: message,
from: `system.host.${hostname}_cli_${time}`,
callback: {
message,
id: this.callbackId++,
ack: false,
time
}
} as const;
if (this.callbackId > 0xffffffff) {
this.callbackId = 1;
}
this.callbacks[`_${obj.callback.id}`] = { cb: callback };
// we cannot receive answers from hosts in CLI, so this command is "fire and forget"
this.states.pushMessage(host, obj);
});
}
async uploadAdapterFullAsync(adapters: string[]): Promise<void> {
if (adapters?.length) {
const liveHosts = await this.getHosts(true);
for (const adapter of adapters) {
// Find the host which has this adapter
const instances = await tools.getInstances(adapter, this.objects, true);
// try to find instance on this host
let instance = instances.find(obj => obj?.common?.host === hostname);
// try to find enabled instance on live host
instance =
instance || instances.find(obj => obj?.common?.enabled && liveHosts.includes(obj.common.host));
// try to find any instance
instance = instance || instances.find(obj => obj?.common && liveHosts.includes(obj.common.host));
if (instance && instance.common.host !== hostname) {
console.log(`Send upload command to host "${instance.common.host}"... `);
// send upload message to the host
const response = await this.sendToHostFromCliAsync(instance.common.host, 'upload', adapter);
if (response) {
console.log(`Upload result: ${response.result}`);
} else {
console.error(`No answer from ${instance.common.host}`);
}
} else {
if (!instance) {
// no one alive instance found
const adapterDir = tools.getAdapterDir(adapter);
if (!adapterDir || !fs.existsSync(adapterDir)) {
console.warn(
`No alive host found which has the adapter ${adapter} installed! No upload possible. Skipped.`
);
continue;
}
}
// try to upload on this host. It will print an error if the adapter directory not found
await this.uploadAdapter(adapter, true, true);
await this.upgradeAdapterObjects(adapter);
await this.uploadAdapter(adapter, false, true);
}
}
}
}
/**
* Uploads a file
*/
async uploadFile(source: string, target: string): Promise<string> {
target = target.replace(/\\/g, '/');
source = source.replace(/\\/g, '/');
if (target[0] === '/') {
target = target.substring(1);
}
if (target[target.length - 1] === '/') {
let name = source.split('/').pop()!;
name = name.split('?')[0];
if (!name.includes('.')) {
name = 'index.html';
}
target += name;
}
const parts = target.split('/');
const adapter = parts[0];
parts.splice(0, 1);
target = parts.join('/');
if (source.match(/^http:\/\/|^https:\/\//)) {
try {
const result = await axios(source, {
responseType: 'arraybuffer',
validateStatus: status => status === 200
});
if (result?.data) {
await this.objects.writeFileAsync(adapter, target, result.data);
} else {
console.error(`Empty response from URL "${source}"`);
throw new Error(`Empty response from URL "${source}"`);
}
} catch (err) {
let result;
if (err.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
result = err.response.data || err.response.status;
} else if (err.request) {
// The request was made but no response was received
// `err.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
result = err.request;
} else {
// Something happened in setting up the request that triggered an Error
result = err.message;
}
console.error(`Cannot get URL "${source}": ${result}`);
throw new Error(result);
}
} else {
try {
await this.objects.writeFileAsync(adapter, target, fs.readFileSync(source));
} catch (err) {
console.error(`Cannot read file "${source}": ${err.message}`);
throw err;
}
}
return `${adapter}/${target}`;
}
async eraseFiles(files: any[], logger: Logger | typeof console): Promise<void> {
if (files && files.length) {
for (const file of files) {
try {
await this.objects.unlinkAsync(file.adapter, file.path);
} catch (err) {
logger.error(`Cannot delete file "${file.path}": ${err}`);
}
}
}
}
/**
* Collect Files of an adapter specific directory from the ioBroker storage
*
* @param adapter Adapter name
* @param path path in the adapter specific storage space
* @param logger Logger instance
*/
async collectExistingFilesToDelete(
adapter: string,
path: string,
logger: Logger | typeof console
): Promise<{ filesToDelete: File[]; dirs: File[] }> {
let _files: File[] = [];
let _dirs: File[] = [];
let files: ioBroker.ReadDirResult[];
try {
files = await this.objects.readDirAsync(adapter, path);
} catch {
// ignore err
files = [];
}
if (files?.length) {
for (const file of files) {
if (file.file === '.' || file.file === '..') {
continue;
}
const newPath = path + file.file;
if (file.isDir) {
if (!_dirs.find(e => e.path === newPath)) {
_dirs.push({ adapter, path: newPath });
}
try {
const result = await this.collectExistingFilesToDelete(adapter, `${newPath}/`, logger);
if (result.filesToDelete) {
_files = _files.concat(result.filesToDelete);
}
_dirs = _dirs.concat(result.dirs);
} catch (err) {
logger.warn(`Cannot delete folder "${adapter}${newPath}/": ${err.message}`);
}
} else if (!_files.find(e => e.path === newPath)) {
_files.push({ adapter, path: newPath });
}
}
}
return { filesToDelete: _files, dirs: _dirs };
}
async upload(
adapter: string,
isAdmin: boolean,
files: string[],
id: string,
rev: any,
logger: Logger | typeof console
): Promise<string> {
const uploadID = `system.adapter.${adapter}.upload`;
await this.states.setStateAsync(uploadID, { val: 0, ack: true });
for (let f = 0; f < files.length; f++) {
const file = files[f];
// do not upload '.gitignore' files. Todo: add other exceptions
if (file === '.gitignore') {
continue;
}
const mimeType = mime.lookup(file);
let attNameArr = file.split(this.regApp);
// try to find anyway if adapter is not lower case
if (attNameArr.length === 1 && file.toLowerCase().includes(tools.appName.toLowerCase())) {
attNameArr = ['', file.substring(tools.appName.length + 2)];
}
let attName = attNameArr.pop()!;
attName = attName.split('/').slice(2).join('/');
const remainingFiles = files.length - f - 1;
if (remainingFiles >= 100) {
(!f || !(remainingFiles % 50)) &&
logger.log(`upload [${remainingFiles}] ${id} ${file} ${attName} ${mimeType}`);
} else if (remainingFiles > 20) {
if (!f || !(remainingFiles % 10)) {
logger.log(`upload [${remainingFiles}] ${id} ${file} ${attName} ${mimeType}`);
}
} else {
logger.log(`upload [${remainingFiles}] ${id} ${file} ${attName} ${mimeType}`);
}
// Update upload indicator
if (!isAdmin) {
const now = Date.now();
if (now - this.lastProgressUpdate > 1_000) {
this.lastProgressUpdate = now;
await this.states.setStateAsync(uploadID, {
val: Math.round((1_000 * (files.length - f)) / files.length) / 10,
ack: true
});
}
}
try {
await new Promise<void>((resolve, reject) => {
const stream = fs.createReadStream(file);
stream.on('error', e => reject(e));
stream.pipe(
this.objects.insert(id, attName, null, mimeType || {}, { rev }, err => {
if (err) {
console.log(err);
}
resolve();
})
);
});
} catch (e) {
console.error(`Error: Cannot upload ${file}: ${e.message}`);
}
}
// Set upload progress to 0;
if (!isAdmin && files.length) {
await this.states.setStateAsync(uploadID, { val: 0, ack: true });
}
return adapter;
}
// Read synchronous all files recursively from local directory
walk(dir: string, _results?: string[]): string[] {
const results = _results || [];
try {
if (fs.existsSync(dir)) {
const list = fs.readdirSync(dir);
list.map(file => {
const stat = fs.statSync(`${dir}/${file}`);
if (stat.isDirectory()) {
this.walk(`${dir}/${file}`, results);
} else {
if (!file.endsWith('.npmignore') && !file.endsWith('.gitignore')) {
results.push(`${dir}/${file}`);
}
}
});
}
} catch (err) {
console.error(err);
}
return results;
}
/**
* Upload given adapter
*/
async uploadAdapter(
adapter: string,
isAdmin: boolean,
forceUpload: boolean,
subTree?: string,
_logger?: Logger
): Promise<string> {
const id = adapter + (isAdmin ? '.admin' : '');
const adapterDir = tools.getAdapterDir(adapter);
let dir = adapterDir ? adapterDir + (isAdmin ? '/admin' : '/www') : '';
const logger = _logger || console;
if (subTree && dir) {
dir += `/${subTree}`;
}
if (adapterDir === null || !fs.existsSync(adapterDir)) {
console.log(
`INFO: Directory "${
adapterDir || `for ${adapter}${isAdmin ? '.admin' : ''}`
}" does not exist. Nothing was uploaded or deleted.`
);
return adapter;
}
let cfg;
try {
cfg = await fs.readJSON(`${adapterDir}/io-package.json`);
} catch (err) {
// file not parsable or does not exist
console.error(`Could not read io-package.json: ${err.message}`);
}
if (!fs.existsSync(dir)) {
// www folder have not all adapters. So show warning only for admin folder
// widgets do not have www folder, but they have onlyWWW flag
(isAdmin || (cfg?.common?.onlyWWW && !cfg.common.visWidgets)) &&
console.log(
`INFO: Directory "${
dir || `for ${adapter}${isAdmin ? '.admin' : ''}`
}" was not found! Nothing was uploaded or deleted.`
);
if (isAdmin) {
return adapter;
} else {
await this.checkRestartOther(adapter);
return adapter;
}
}
// check for common.wwwDontUpload (required for legacy adapters and admin)
if (!isAdmin && cfg?.common?.wwwDontUpload) {
return adapter;
}
// Create "upload progress" object if not exists
if (!isAdmin) {
let obj;
const uploadID = `system.adapter.${adapter}.upload`;
try {
obj = await this.objects.getObjectAsync(uploadID);
} catch {
// ignore
}
if (!obj) {
await this.objects.setObjectAsync(uploadID, {
_id: uploadID,
type: 'state',
common: {
name: `${adapter}.upload`,
type: 'number',
role: 'indicator.state',
unit: '%',
min: 0,
max: 100,
def: 0,
desc: 'Upload process indicator',
read: true,
write: false
},
from: `system.host.${tools.getHostName()}.cli`,
ts: Date.now(),
native: {}
});
}
// Set indicator to 0
// @ts-expect-error fixed with #1917
await this.states.setStateAsync(uploadID, 0, true);
}
let result;
try {
result = await this.objects.getObjectAsync(id);
} catch {
// ignore
}
// Read all names with subtrees from local directory
const files = this.walk(dir);
if (!result) {
// @ts-expect-error types needed admin is not allowed for meta, but it should be allowed
await this.objects.setObjectAsync(id, {
type: 'meta',
common: {
name: id.split('.').pop()!,
type: isAdmin ? 'admin' : 'www'
},
from: `system.host.${tools.getHostName()}.cli`,
ts: Date.now(),
native: {}
});
forceUpload = true;
}
if (forceUpload) {
// only skip if explicitly opted out
// The visualization check is needed as user of legacy systems often stored files inside adapter directories like `vis`
// in the long term, such adapters should explicitly opt out, so we can hopefully remove this line in 2-3 versions (current 5.0)
if (
cfg?.common?.eraseOnUpload !== false &&
!(cfg?.common?.eraseOnUpload === undefined && cfg?.common?.type === 'visualization')
) {
const { filesToDelete } = await this.collectExistingFilesToDelete(
isAdmin ? `${adapter}.admin` : adapter,
'/',
logger
);
// delete old files, before upload of new
await this.eraseFiles(filesToDelete, logger);
}
if (!isAdmin) {
await this.checkRestartOther(adapter);
await new Promise<void>(resolve => setTimeout(() => resolve(), 25));
// @ts-expect-error TODO rev is not required and should not exist on an object?
await this.upload(adapter, isAdmin, files, id, result?.rev, logger);
} else {
// @ts-expect-error TODO rev is not required and should not exist on an object?
await this.upload(adapter, isAdmin, files, id, result?.rev, logger);
}
}
return adapter;
}
extendNative(target: Record<string, any>, additional: Record<string, unknown>): Record<string, any> {
if (tools.isObject(additional)) {
for (const [attr, attrData] of Object.entries(additional)) {
if (target[attr] === undefined) {
target[attr] = attrData;
} else if (tools.isObject(attrData)) {
try {
target[attr] = target[attr] || {};
} catch {
console.warn(`Cannot update attribute ${attr} of native`);
}
if (typeof target[attr] === 'object' && target[attr] !== null) {
this.extendNative(target[attr], attrData);
}
}
}
}
return target;
}
extendCommon(
target: Record<string, any>,
additional: Record<string, any>,
instance: string
): ioBroker.InstanceCommon {
if (tools.isObject(additional)) {
const preserveAttributes = [
'title',
'schedule',
'restartSchedule',
'mode',
'loglevel',
'enabled',
'custom',
'tier'
];
for (const [attr, attrData] of Object.entries(additional)) {
// preserve these attributes, except, they were undefined before and preserve titleLang if current titleLang is of type string (changed by user)
if (preserveAttributes.includes(attr) || (attr === 'titleLang' && typeof attrData === 'string')) {
if (target[attr] === undefined) {
target[attr] = attrData;
}
} else if (typeof attrData !== 'object' || attrData instanceof Array) {
try {
target[attr] = attrData;
// dataFolder can have wildcards
if (attr === 'dataFolder' && target.dataFolder && target.dataFolder.includes('%INSTANCE%')) {
target.dataFolder = target.dataFolder.replace(/%INSTANCE%/g, instance);
}
} catch {
console.warn(`Cannot update attribute ${attr} of common`);
}
} else {
target[attr] = target[attr] || {};
if (typeof target[attr] !== 'object') {
target[attr] = {}; // here we clean the simple value with object
}
this.extendCommon(target[attr], attrData, instance);
}
}
}
return target as ioBroker.InstanceCommon;
}
/**
* Extends the `system.instance.adapter.<instanceNumber>` objects with the native properties from adapters io-package.json
*
* @param name name of the adapter
* @param ioPack parsed io-package content
* @param hostname name of the host where the adapter is installed on
* @param logger instance of logger
*/
async _upgradeAdapterObjectsHelper(
name: string,
ioPack: ioBroker.AdapterObject,
hostname: string,
logger: Logger | typeof console
): Promise<string> {
// Update all instances of this host
const res = await this.objects.getObjectViewAsync('system', 'instance', {
startkey: `system.adapter.${name}.`,
endkey: `system.adapter.${name}.\u9999`
});
if (res) {
for (const row of res.rows) {
if (row.value?.common.host === hostname) {
const _obj = await this.objects.getObjectAsync(row.id);
const newObject = deepClone(_obj) as ioBroker.InstanceObject;
// TODO: refactor the following assignments into a method, where we can define which attributes need a real override and their defaults
// all common settings should be taken from new one
newObject.common = this.extendCommon(
newObject.common,
ioPack.common,
newObject._id.split('.').pop()!
);
newObject.native = this.extendNative(newObject.native, ioPack.native);
// protected/encryptedNative and notifications also need to be updated
newObject.protectedNative = ioPack.protectedNative || [];
newObject.encryptedNative = ioPack.encryptedNative || [];
newObject.notifications = ioPack.notifications || [];
// update instanceObjects and objects
newObject.instanceObjects = ioPack.instanceObjects || [];
newObject.objects = ioPack.objects || [];
newObject.common.version = ioPack.common.version;
newObject.common.installedVersion = ioPack.common.version;
newObject.common.installedFrom = ioPack.common.installedFrom;
if (ioPack.common.visWidgets) {
newObject.common.visWidgets = ioPack.common.visWidgets;
} else {
delete newObject.common.visWidgets;
}
if (!ioPack.common.compact && newObject.common.compact) {
newObject.common.compact = ioPack.common.compact;
}
// Compare objects to reduce restarts of instances
if (!isDeepStrictEqual(newObject, _obj)) {
logger.log(`Update "${newObject._id}"`);
newObject.from = `system.host.${tools.getHostName()}.cli`;
newObject.ts = Date.now();
await this.objects.setObjectAsync(newObject._id, newObject);
}
}
}
}
// updates only "_design/system" and co "_design/*"
if (Array.isArray(ioPack.objects)) {
for (const obj of ioPack.objects) {
if (name === 'js-controller' && !obj._id.startsWith('_design/')) {
continue;
}
obj.from = `system.host.${hostname}.cli`;
obj.ts = Date.now();
try {
await this.objects.setObjectAsync(obj._id, obj);
} catch (err) {
logger.error(`Cannot update object: ${err}`);
}
}
}
return name;
}
/**
* Create object from io-package json
*/
async upgradeAdapterObjects(
name: string,
ioPack?: ioBroker.AdapterObject,
_logger?: Logger | typeof console
): Promise<string> {
const logger = _logger || console;
const adapterDir = tools.getAdapterDir(name);
let ioPackFile;
try {
ioPackFile = fs.readJSONSync(`${adapterDir}/io-package.json`);
} catch {
if (adapterDir) {
logger.error(`Cannot find io-package.json in ${adapterDir}`);
} else {
logger.error(`Cannot find io-package.json for "${name}"`);
}
ioPackFile = null;
}
ioPack = ioPack || ioPackFile;
if (ioPack) {
// Always update installedFrom from File on disk if exists and set
if (ioPackFile?.common?.installedFrom) {
ioPack.common = ioPack.common || {};
ioPack.common.installedFrom = ioPackFile.common.installedFrom;
}
// Not existing? Why ever ... we recreate
let _obj;
try {
_obj = await this.objects.getObject(`system.adapter.${name}`);
} catch {
// ignore err
}
const obj: Omit<ioBroker.AdapterObject, '_id'> = _obj || {
common: ioPack.common,
native: ioPack.native,
type: 'adapter',
instanceObjects: [],
objects: []
};
obj.common = ioPack.common || {};
obj.native = ioPack.native || {};
// protected/encryptedNative and notifications also need to be updated
obj.protectedNative = ioPack.protectedNative || [];
obj.encryptedNative = ioPack.encryptedNative || [];
obj.notifications = ioPack.notifications || [];
// update instanceObjects and objects
obj.instanceObjects = ioPack.instanceObjects || [];
obj.objects = ioPack.objects || [];
obj.type = 'adapter';
obj.common.installedVersion = ioPack.common.version;
if (obj.common.news) {
delete obj.common.news; // remove this information as it could be big, but it will be taken from repo
}
const hostname = tools.getHostName();
obj.from = `system.host.${hostname}.cli`;
obj.ts = Date.now();
try {
await this.objects.setObjectAsync(`system.adapter.${name}`, obj);
} catch (err) {
logger.error(`Cannot set system.adapter.${name}: ${err.message}`);
}
await this._upgradeAdapterObjectsHelper(name, ioPack, hostname, logger);
}
return name;
}
}