@iobroker/legacy-testing 0.0.2 → 0.0.3

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.
Files changed (4) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +34 -34
  3. package/package.json +1 -1
  4. package/setup.js +949 -949
package/setup.js CHANGED
@@ -1,949 +1,949 @@
1
- /* jshint -W097 */
2
- /* jshint strict: false */
3
- /* jslint node: true */
4
-
5
- // check if tmp directory exists
6
- const fs = require('fs');
7
- const path = require('path');
8
- const child_process = require('child_process');
9
- const rootDir = path.normalize(`${__dirname}/../../`);
10
- const pkg = require(`${rootDir}package.json`);
11
- const debug = typeof v8debug === 'object';
12
- pkg.main = pkg.main || 'main.js';
13
-
14
- let JSONLDB;
15
-
16
- let adapterName = path.normalize(rootDir).replace(/\\/g, '/').split('/');
17
- adapterName = adapterName[adapterName.length - 2];
18
- let adapterStarted = false;
19
-
20
- function getAppName() {
21
- const parts = __dirname.replace(/\\/g, '/').split('/');
22
- return parts[parts.length - 3].split('.')[0];
23
- }
24
-
25
- function loadJSONLDB() {
26
- if (!JSONLDB) {
27
- const dbPath = require.resolve('@alcalzone/jsonl-db', {
28
- paths: [`${rootDir}tmp/node_modules`, rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
29
- });
30
- console.log(`JSONLDB path: ${dbPath}`);
31
- try {
32
- const { JsonlDB } = require(dbPath);
33
- JSONLDB = JsonlDB;
34
- } catch (err) {
35
- console.log(`Jsonl require error: ${err}`);
36
- }
37
- }
38
- }
39
-
40
- const appName = getAppName().toLowerCase();
41
-
42
- let objects;
43
- let states;
44
-
45
- let pid = null;
46
-
47
- let systemConfig = null;
48
-
49
- function copyFileSync(source, target) {
50
-
51
- let targetFile = target;
52
-
53
- //if target is a directory a new file with the same name will be created
54
- if (fs.existsSync(target) && fs.lstatSync( target ).isDirectory() ) {
55
- targetFile = path.join(target, path.basename(source));
56
- }
57
-
58
- try {
59
- fs.writeFileSync(targetFile, fs.readFileSync(source));
60
- } catch (err) {
61
- console.log(`file copy error: ${source} -> ${targetFile} (error ignored)`);
62
- }
63
- }
64
-
65
- function copyFolderRecursiveSync(source, target, ignore) {
66
- let files = [];
67
-
68
- let base = path.basename(source);
69
- if (base === adapterName) {
70
- base = pkg.name;
71
- }
72
- //check if folder needs to be created or integrated
73
- const targetFolder = path.join(target, base);
74
- if (!fs.existsSync(targetFolder)) {
75
- fs.mkdirSync(targetFolder);
76
- }
77
-
78
- //copy
79
- if (fs.lstatSync(source).isDirectory()) {
80
- files = fs.readdirSync(source);
81
- files.forEach(file => {
82
- if (ignore && ignore.includes(file)) {
83
- return;
84
- }
85
-
86
- const curSource = path.join(source, file);
87
- const curTarget = path.join(targetFolder, file);
88
- if (fs.lstatSync(curSource).isDirectory()) {
89
- // ignore grunt files
90
- if (file.includes('grunt') || file === 'chai' || file === 'mocha') {
91
- return;
92
- }
93
- copyFolderRecursiveSync(curSource, targetFolder, ignore);
94
- } else {
95
- copyFileSync(curSource, curTarget);
96
- }
97
- });
98
- }
99
- }
100
-
101
- if (!fs.existsSync(rootDir + 'tmp')) {
102
- fs.mkdirSync(rootDir + 'tmp');
103
- }
104
-
105
- async function storeOriginalFiles() {
106
- console.log('Store original files...');
107
- const dataDir = `${rootDir}tmp/${appName}-data/`;
108
-
109
- if (fs.existsSync(dataDir + 'objects.json')) {
110
- const f = fs.readFileSync(`${dataDir}objects.json`);
111
- const objects = JSON.parse(f.toString());
112
- if (objects['system.adapter.admin.0'] && objects['system.adapter.admin.0'].common) {
113
- objects['system.adapter.admin.0'].common.enabled = false;
114
- }
115
- if (objects['system.adapter.admin.1'] && objects['system.adapter.admin.1'].common) {
116
- objects['system.adapter.admin.1'].common.enabled = false;
117
- }
118
-
119
- fs.writeFileSync(`${dataDir}objects.json.original`, JSON.stringify(objects));
120
- console.log('Store original objects.json');
121
- }
122
-
123
- if (fs.existsSync(`${dataDir}states.json`)) {
124
- try {
125
- const f = fs.readFileSync(`${dataDir}states.json`);
126
- fs.writeFileSync(`${dataDir}states.json.original`, f);
127
- console.log('Store original states.json');
128
- } catch (err) {
129
- console.log('no states.json found - ignore');
130
- }
131
- }
132
-
133
- if (fs.existsSync(`${dataDir}objects.jsonl`)) {
134
- loadJSONLDB();
135
- const db = new JSONLDB(`${dataDir}objects.jsonl`);
136
- await db.open();
137
-
138
- const admin0 = db.get('system.adapter.admin.0');
139
- if (admin0) {
140
- if (admin0.common) {
141
- admin0.common.enabled = false;
142
- db.set('system.adapter.admin.0', admin0);
143
- }
144
- }
145
-
146
- const admin1 = db.get('system.adapter.admin.1');
147
- if (admin1) {
148
- if (admin1.common) {
149
- admin1.common.enabled = false;
150
- db.set('system.adapter.admin.1', admin1);
151
- }
152
- }
153
- await db.close();
154
-
155
- const f = fs.readFileSync(dataDir + 'objects.jsonl');
156
- fs.writeFileSync(`${dataDir}objects.jsonl.original`, f);
157
- console.log('Store original objects.jsonl');
158
- }
159
-
160
- if (fs.existsSync(`${dataDir}states.jsonl`)) {
161
- const f = fs.readFileSync(`${dataDir}states.jsonl`);
162
- fs.writeFileSync(`${dataDir}states.jsonl.original`, f);
163
- console.log('Store original states.jsonl');
164
- }
165
- }
166
-
167
- function restoreOriginalFiles() {
168
- console.log('restoreOriginalFiles...');
169
- const dataDir = `${rootDir}tmp/${appName}-data/`;
170
-
171
- if (fs.existsSync(`${dataDir}objects.json.original`)) {
172
- const f = fs.readFileSync(`${dataDir}objects.json.original`);
173
- fs.writeFileSync(`${dataDir}objects.json`, f);
174
- }
175
- if (fs.existsSync(`${dataDir}objects.json.original`)) {
176
- const f = fs.readFileSync(`${dataDir}states.json.original`);
177
- fs.writeFileSync(`${dataDir}states.json`, f);
178
- }
179
-
180
- if (fs.existsSync(dataDir + 'objects.jsonl.original')) {
181
- const f = fs.readFileSync(dataDir + 'objects.jsonl.original');
182
- fs.writeFileSync(dataDir + 'objects.jsonl', f);
183
- }
184
- if (fs.existsSync(dataDir + 'objects.jsonl.original')) {
185
- const f = fs.readFileSync(dataDir + 'states.jsonl.original');
186
- fs.writeFileSync(dataDir + 'states.jsonl', f);
187
- }
188
- }
189
-
190
- async function checkIsAdapterInstalled(cb, counter, customName) {
191
- customName = customName || pkg.name.split('.').pop();
192
- counter = counter || 0;
193
- const dataDir = `${rootDir}tmp/${appName}-data/`;
194
- console.log('checkIsAdapterInstalled...');
195
-
196
- try {
197
- if (fs.existsSync(`${dataDir}objects.json`)) {
198
- const f = fs.readFileSync(`${dataDir}objects.json`);
199
- const objects = JSON.parse(f.toString());
200
- if (objects[`system.adapter.${customName}.0`]) {
201
- console.log('checkIsAdapterInstalled: ready!');
202
- setTimeout(function () {
203
- cb && cb();
204
- }, 100);
205
- return;
206
- } else {
207
- console.warn('checkIsAdapterInstalled: still not ready');
208
- }
209
- } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
210
- loadJSONLDB();
211
- const db = new JSONLDB(`${dataDir}objects.jsonl`);
212
- try {
213
- await db.open();
214
- } catch (err) {
215
- if (err.message.includes('Failed to lock DB file')) {
216
- console.log('checkIsAdapterInstalled: DB still opened ...');
217
- }
218
- throw err;
219
- }
220
-
221
- const obj = db.get(`system.adapter.${customName}.0`);
222
- await db.close();
223
-
224
- if (obj) {
225
- console.log('checkIsAdapterInstalled: ready!');
226
- setTimeout(() => cb && cb(), 100);
227
- return;
228
- } else {
229
- console.warn('checkIsAdapterInstalled: still not ready');
230
- }
231
- } else {
232
- console.error(`checkIsAdapterInstalled: No objects file found in datadir ${dataDir}`);
233
- }
234
-
235
- } catch (err) {
236
- console.log(`checkIsAdapterInstalled: catch ${err}`);
237
- }
238
-
239
- if (counter > 20) {
240
- console.error('checkIsAdapterInstalled: Cannot install!');
241
- cb && cb('Cannot install');
242
- } else {
243
- console.log('checkIsAdapterInstalled: wait...');
244
- setTimeout(function() {
245
- checkIsAdapterInstalled(cb, counter + 1);
246
- }, 1000);
247
- }
248
- }
249
-
250
- async function checkIsControllerInstalled(cb, counter) {
251
- counter = counter || 0;
252
- const dataDir = `${rootDir}tmp/${appName}-data/`;
253
-
254
- console.log('checkIsControllerInstalled...');
255
- try {
256
- if (fs.existsSync(dataDir + 'objects.json')) {
257
- const f = fs.readFileSync(dataDir + 'objects.json');
258
- const objects = JSON.parse(f.toString());
259
- if (objects['system.certificates']) {
260
- console.log('checkIsControllerInstalled: installed!');
261
- setTimeout(() => cb && cb(), 100);
262
- return;
263
- }
264
- } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
265
- loadJSONLDB();
266
- const db = new JSONLDB(`${dataDir}objects.jsonl`);
267
- try {
268
- await db.open();
269
- } catch (err) {
270
- if (err.message.includes('Failed to lock DB file')) {
271
- console.log('checkIsControllerInstalled: DB still opened ...');
272
- }
273
- throw err;
274
- }
275
-
276
- const obj = db.get('system.certificates');
277
- await db.close();
278
-
279
- if (obj) {
280
- console.log('checkIsControllerInstalled: installed!');
281
- setTimeout(() => cb && cb(), 100);
282
- return;
283
- }
284
-
285
- } else {
286
- console.error(`checkIsControllerInstalled: No objects file found in datadir ${dataDir}`);
287
- }
288
- } catch (err) {
289
- // ignore
290
- }
291
-
292
- if (counter > 20) {
293
- console.log('checkIsControllerInstalled: Cannot install!');
294
- cb && cb('Cannot install');
295
- } else {
296
- console.log('checkIsControllerInstalled: wait...');
297
- setTimeout(() => checkIsControllerInstalled(cb, counter + 1), 1000);
298
- }
299
- }
300
-
301
- function installAdapter(customName, cb) {
302
- if (typeof customName === 'function') {
303
- cb = customName;
304
- customName = null;
305
- }
306
- customName = customName || pkg.name.split('.').pop();
307
- console.log('Install adapter...');
308
- const startFile = `node_modules/${appName}.js-controller/${appName}.js`;
309
- // make first install
310
- if (debug) {
311
- child_process.execSync(`node ${startFile} add ${customName} --enabled false`, {
312
- cwd: rootDir + 'tmp',
313
- stdio: [0, 1, 2]
314
- });
315
- checkIsAdapterInstalled(error => {
316
- error && console.error(error);
317
- console.log('Adapter installed.');
318
- cb && cb();
319
- });
320
- } else {
321
- // add controller
322
- const _pid = child_process.fork(startFile, ['add', customName, '--enabled', 'false'], {
323
- cwd: `${rootDir}tmp`,
324
- stdio: [0, 1, 2, 'ipc']
325
- });
326
-
327
- waitForEnd(_pid, () =>
328
- checkIsAdapterInstalled(error => {
329
- error && console.error(error);
330
- console.log('Adapter installed.');
331
- cb && cb();
332
- }));
333
- }
334
- }
335
-
336
- function waitForEnd(_pid, cb) {
337
- if (!_pid) {
338
- cb(-1, -1);
339
- return;
340
- }
341
- _pid.on('exit', (code, signal) => {
342
- if (_pid) {
343
- _pid = null;
344
- cb(code, signal);
345
- }
346
- });
347
- _pid.on('close', (code, signal) => {
348
- if (_pid) {
349
- _pid = null;
350
- cb(code, signal);
351
- }
352
- });
353
- }
354
-
355
- function installJsController(cb) {
356
- console.log('installJsController...');
357
- if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`) ||
358
- !fs.existsSync(`${rootDir}tmp/${appName}-data`)) {
359
- // try to detect appName.js-controller in node_modules/appName.js-controller
360
- // travis CI installs js-controller into node_modules
361
- if (fs.existsSync(`${rootDir}node_modules/${appName}.js-controller`)) {
362
- console.log(`installJsController: no js-controller => copy it from "${rootDir}node_modules/${appName}.js-controller"`);
363
- // copy all
364
- // stop controller
365
- console.log('Stop controller if running...');
366
- let _pid;
367
- if (debug) {
368
- // start controller
369
- _pid = child_process.exec(`node ${appName}.js stop`, {
370
- cwd: `${rootDir}node_modules/${appName}.js-controller`,
371
- stdio: [0, 1, 2]
372
- });
373
- } else {
374
- _pid = child_process.fork(`${appName}.js`, ['stop'], {
375
- cwd: `${rootDir}node_modules/${appName}.js-controller`,
376
- stdio: [0, 1, 2, 'ipc']
377
- });
378
- }
379
-
380
- waitForEnd(_pid, () => {
381
- // copy all files into
382
- !fs.existsSync(`${rootDir}tmp`) && fs.mkdirSync(`${rootDir}tmp`);
383
- !fs.existsSync(`${rootDir}tmp/node_modules`) && fs.mkdirSync(`${rootDir}tmp/node_modules`);
384
-
385
- if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`)){
386
- console.log('Copy js-controller...');
387
- copyFolderRecursiveSync(`${rootDir}node_modules/${appName}.js-controller`, `${rootDir}tmp/node_modules/`);
388
- }
389
-
390
- console.log('Setup js-controller...');
391
- let __pid;
392
- if (debug) {
393
- // start controller
394
- _pid = child_process.exec(`node ${appName}.js setup first --console`, {
395
- cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
396
- stdio: [0, 1, 2]
397
- });
398
- } else {
399
- __pid = child_process.fork(`${appName}.js`, ['setup', 'first', '--console'], {
400
- cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
401
- stdio: [0, 1, 2, 'ipc']
402
- });
403
- }
404
- waitForEnd(__pid, () =>
405
- checkIsControllerInstalled(() => {
406
- // change ports for object and state DBs
407
- const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
408
- config.objects.port = 19001;
409
- config.states.port = 19000;
410
-
411
- // TEST WISE!
412
- //config.objects.type = 'jsonl';
413
- //config.states.type = 'jsonl';
414
- fs.writeFileSync(`${rootDir}tmp/${appName}-data/${appName}.json`, JSON.stringify(config, null, 2));
415
- console.log('Setup finished.');
416
-
417
- copyAdapterToController();
418
-
419
- installAdapter(async () => {
420
- await storeOriginalFiles();
421
- cb && cb(true);
422
- });
423
- }));
424
- });
425
- } else {
426
- // check if port 9000 is free, else admin adapter will be added to running instance
427
- const client = new require('net').Socket();
428
- client.on('error', () => {});
429
- client.connect(9000, '127.0.0.1', () => {
430
- console.error('Cannot initiate fisrt run of test, because one instance of application is running on this PC. Stop it and repeat.');
431
- process.exit(0);
432
- });
433
-
434
- setTimeout(() => {
435
- client.destroy();
436
- if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`)) {
437
- console.log('installJsController: no js-controller => install dev build from npm');
438
-
439
- child_process.execSync(`npm install ${appName}.js-controller@dev --prefix ./ --production`, {
440
- cwd: rootDir + 'tmp/',
441
- stdio: [0, 1, 2]
442
- });
443
- } else {
444
- console.log('Setup js-controller...');
445
- if (debug) {
446
- // start controller
447
- child_process.exec(`node ${appName}.js setup first`, {
448
- cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
449
- stdio: [0, 1, 2]
450
- });
451
- } else {
452
- child_process.fork(`${appName}.js`, ['setup', 'first'], {
453
- cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
454
- stdio: [0, 1, 2, 'ipc']
455
- });
456
- }
457
- }
458
-
459
- // let npm install admin and run setup
460
- checkIsControllerInstalled(() => {
461
- let _pid;
462
-
463
- if (fs.existsSync(`${rootDir}node_modules/${appName}.js-controller/${appName}.js`)) {
464
- _pid = child_process.fork(`${appName}.js`, ['stop'], {
465
- cwd: `${rootDir}node_modules/${appName}.js-controller`,
466
- stdio: [0, 1, 2, 'ipc']
467
- });
468
- }
469
-
470
- waitForEnd(_pid, () => {
471
- // change ports for object and state DBs
472
- const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
473
- config.objects.port = 19001;
474
- config.states.port = 19000;
475
-
476
- // TEST WISE!
477
- //config.objects.type = 'jsonl';
478
- //config.states.type = 'jsonl';
479
- fs.writeFileSync(`${rootDir}tmp/${appName}-data/${appName}.json`, JSON.stringify(config, null, 2));
480
-
481
- copyAdapterToController();
482
-
483
- installAdapter(async () => {
484
- await storeOriginalFiles();
485
- cb && cb(true);
486
- });
487
- });
488
- });
489
- }, 1000);
490
- }
491
- } else {
492
- setTimeout(() => {
493
- console.log('installJsController: js-controller installed');
494
- cb && cb(false);
495
- }, 0);
496
- }
497
- }
498
-
499
- function copyAdapterToController() {
500
- console.log('Copy adapter...');
501
- // Copy adapter to tmp/node_modules/appName.adapter
502
- copyFolderRecursiveSync(rootDir, `${rootDir}tmp/node_modules/`, ['.idea', 'test', 'tmp', '.git', appName + '.js-controller']);
503
- console.log('Adapter copied.');
504
- }
505
-
506
- function clearControllerLog() {
507
- const dirPath = rootDir + 'tmp/log';
508
- let files;
509
- try {
510
- if (fs.existsSync(dirPath)) {
511
- console.log('Clear controller log...');
512
- files = fs.readdirSync(dirPath);
513
- } else {
514
- console.log('Create controller log directory...');
515
- files = [];
516
- fs.mkdirSync(dirPath);
517
- }
518
- } catch(e) {
519
- console.error(`Cannot read "${dirPath}"`);
520
- return;
521
- }
522
- if (files.length > 0) {
523
- try {
524
- for (let i = 0; i < files.length; i++) {
525
- const filePath = `${dirPath}/${files[i]}`;
526
- fs.unlinkSync(filePath);
527
- }
528
- console.log('Controller log cleared');
529
- } catch (err) {
530
- console.error(`cannot clear log: ${err}`);
531
- }
532
- }
533
- }
534
-
535
- function clearDB() {
536
- const dirPath = `${rootDir}tmp/iobroker-data/sqlite`;
537
- let files;
538
- try {
539
- if (fs.existsSync(dirPath)) {
540
- console.log('Clear sqlite DB...');
541
- files = fs.readdirSync(dirPath);
542
- } else {
543
- console.log('Create controller log directory...');
544
- files = [];
545
- fs.mkdirSync(dirPath);
546
- }
547
- } catch(e) {
548
- console.error(`Cannot read "${dirPath}"`);
549
- return;
550
- }
551
- if (files.length > 0) {
552
- try {
553
- for (let i = 0; i < files.length; i++) {
554
- const filePath = `${dirPath}/${files[i]}`;
555
- fs.unlinkSync(filePath);
556
- }
557
- console.log('Clear sqlite DB');
558
- } catch (err) {
559
- console.error(`cannot clear DB: ${err}`);
560
- }
561
- }
562
- }
563
-
564
- function setupController(cb) {
565
- installJsController(async isInited => {
566
- try {
567
- clearControllerLog();
568
- clearDB();
569
-
570
- if (!isInited) {
571
- restoreOriginalFiles();
572
- copyAdapterToController();
573
- }
574
- // read system.config object
575
- const dataDir = `${rootDir}tmp/${appName}-data/`;
576
-
577
- if (fs.existsSync(`${dataDir}objects.json`)) {
578
- let objs;
579
- try {
580
- objs = fs.readFileSync(`${dataDir}objects.json`);
581
- objs = JSON.parse(objs);
582
- } catch (e) {
583
- console.log('ERROR reading/parsing system configuration. Ignore');
584
- objs = {'system.config': {}};
585
- }
586
- if (!objs || !objs['system.config']) {
587
- objs = {'system.config': {}};
588
- }
589
-
590
- systemConfig = objs['system.config'];
591
- cb && cb(objs['system.config']);
592
- } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
593
- loadJSONLDB();
594
- const db = new JSONLDB(`${dataDir}objects.jsonl`);
595
- await db.open();
596
-
597
- const config = db.get('system.config');
598
- systemConfig = config || {};
599
-
600
- await db.close();
601
-
602
- cb && cb(systemConfig);
603
- } else {
604
- console.error(`read SystemConfig: No objects file found in datadir ${dataDir}`);
605
- }
606
- } catch (err) {
607
- console.error(`setupController: ${err}`);
608
- }
609
- });
610
- }
611
-
612
- async function getSecret() {
613
- const dataDir = `${rootDir}tmp/${appName}-data/`;
614
-
615
- if (systemConfig) {
616
- return systemConfig.native.secret;
617
- }
618
- if (fs.existsSync(`${dataDir}objects.json`)) {
619
- let objs;
620
- try {
621
- objs = fs.readFileSync(`${dataDir}objects.json`);
622
- objs = JSON.parse(objs);
623
- } catch (e) {
624
- console.warn(`Could not load secret. Reason: ${e}`);
625
- return null;
626
- }
627
- if (!objs || !objs['system.config']) {
628
- objs = {'system.config': {}};
629
- }
630
-
631
- return objs['system.config'].native.secre;
632
- } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
633
- loadJSONLDB();
634
- const db = new JSONLDB(`${dataDir}objects.jsonl`);
635
- await db.open();
636
-
637
- let config = db.get('system.config');
638
- config = config || {};
639
-
640
- await db.close();
641
-
642
- return config.native.secret;
643
- } else {
644
- console.error(`read secret: No objects file found in datadir ${dataDir}`);
645
- }
646
-
647
- }
648
-
649
- function encrypt (key, value) {
650
- let result = '';
651
- for (let i = 0; i < value.length; ++i) {
652
- result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
653
- }
654
- return result;
655
- }
656
-
657
- function startAdapter(objects, states, callback) {
658
- if (adapterStarted) {
659
- console.log('Adapter already started ...');
660
- callback && callback(objects, states);
661
- return;
662
- }
663
- adapterStarted = true;
664
- console.log('startAdapter...');
665
- if (fs.existsSync(`${rootDir}tmp/node_modules/${pkg.name}/${pkg.main}`)) {
666
- try {
667
- if (debug) {
668
- // start controller
669
- pid = child_process.exec(`node node_modules/${pkg.name}/${pkg.main} --console silly`, {
670
- cwd: rootDir + 'tmp',
671
- stdio: [0, 1, 2]
672
- });
673
- } else {
674
- // start controller
675
- pid = child_process.fork(`node_modules/${pkg.name}/${pkg.main}`, ['--console', 'silly'], {
676
- cwd: rootDir + 'tmp',
677
- stdio: [0, 1, 2, 'ipc']
678
- });
679
- }
680
- } catch (error) {
681
- console.error(JSON.stringify(error));
682
- }
683
- } else {
684
- console.error(`Cannot find: ${rootDir}tmp/node_modules/${pkg.name}/${pkg.main}`);
685
- }
686
- callback && callback(objects, states);
687
- }
688
-
689
- function startController(isStartAdapter, onObjectChange, onStateChange, callback) {
690
- if (typeof isStartAdapter === 'function') {
691
- callback = onStateChange;
692
- onStateChange = onObjectChange;
693
- onObjectChange = isStartAdapter;
694
- isStartAdapter = true;
695
- }
696
-
697
- if (onStateChange === undefined) {
698
- callback = onObjectChange;
699
- onObjectChange = undefined;
700
- }
701
-
702
- if (pid) {
703
- console.error('Controller is already started!');
704
- } else {
705
- console.log('startController...');
706
- try {
707
- const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
708
-
709
- adapterStarted = false;
710
- let isObjectConnected;
711
- let isStatesConnected;
712
-
713
- // rootDir + 'tmp/node_modules
714
- const objPath = require.resolve(`@iobroker/db-objects-${config.objects.type}`, {
715
- paths: [ rootDir + 'tmp/node_modules', rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
716
- });
717
- console.log(`Objects Path: ${objPath}`);
718
- const Objects = require(objPath).Server;
719
- objects = new Objects({
720
- connection: {
721
- 'type': config.objects.type,
722
- 'host': '127.0.0.1',
723
- 'port': 19001,
724
- 'user': '',
725
- 'pass': '',
726
- 'noFileCache': false,
727
- 'connectTimeout': 2000
728
- },
729
- logger: {
730
- silly: msg => console.log(msg),
731
- debug: msg => console.log(msg),
732
- info: msg => console.log(msg),
733
- warn: msg => console.warn(msg),
734
- error: msg => console.error(msg)
735
- },
736
- connected: () => {
737
- isObjectConnected = true;
738
- if (isStatesConnected) {
739
- console.log('startController: started!');
740
- if (isStartAdapter) {
741
- startAdapter(objects, states, callback);
742
- } else {
743
- if (callback) {
744
- callback(objects, states);
745
- callback = null;
746
- }
747
- }
748
- }
749
- },
750
- change: onObjectChange
751
- });
752
-
753
- // Just open in memory DB itself
754
- const statePath = require.resolve(`@iobroker/db-states-${config.states.type}`, {
755
- paths: [ `${rootDir}tmp/node_modules`, rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
756
- });
757
- console.log(`States Path: ${statePath}`);
758
- const States = require(statePath).Server;
759
- states = new States({
760
- connection: {
761
- type: config.states.type,
762
- host: '127.0.0.1',
763
- port: 19000,
764
- options: {
765
- auth_pass: null,
766
- retry_max_delay: 15000
767
- }
768
- },
769
- logger: {
770
- silly: function (msg) {
771
- console.log(msg);
772
- },
773
- debug: function (msg) {
774
- console.log(msg);
775
- },
776
- info: function (msg) {
777
- console.log(msg);
778
- },
779
- warn: function (msg) {
780
- console.log(msg);
781
- },
782
- error: function (msg) {
783
- console.log(msg);
784
- }
785
- },
786
- connected: function () {
787
- isStatesConnected = true;
788
- if (isObjectConnected) {
789
- console.log('startController: started!!');
790
- if (isStartAdapter) {
791
- startAdapter(objects, states, callback);
792
- } else {
793
- if (callback) {
794
- callback(objects, states);
795
- callback = null;
796
- }
797
- }
798
- }
799
- },
800
- change: onStateChange
801
- });
802
- } catch (err) {
803
- console.log(err);
804
- }
805
- }
806
- }
807
-
808
- function stopAdapter(cb) {
809
- if (!pid) {
810
- console.error('Controller is not running!');
811
- cb && setTimeout(() => cb(false), 0);
812
- } else {
813
- adapterStarted = false;
814
- pid.on('exit', (code, signal) => {
815
- if (pid) {
816
- console.log(`child process terminated due to receipt of signal ${signal}`);
817
- cb && cb();
818
- pid = null;
819
- }
820
- });
821
-
822
- pid.on('close', (/* code, signal */) => {
823
- if (pid) {
824
- cb && cb();
825
- pid = null;
826
- }
827
- });
828
-
829
- pid.kill('SIGTERM');
830
- }
831
- }
832
-
833
- function _stopController() {
834
- if (objects) {
835
- objects.destroy();
836
- objects = null;
837
- }
838
- if (states) {
839
- states.destroy();
840
- states = null;
841
- }
842
- }
843
-
844
- function stopController(cb) {
845
- let timeout;
846
- if (objects) {
847
- console.log(`Set system.adapter.${pkg.name}.0`);
848
- objects.setObject(`system.adapter.${pkg.name}.0`, {
849
- common: {
850
- enabled: false
851
- }
852
- });
853
- }
854
-
855
- stopAdapter(() => {
856
- if (timeout) {
857
- clearTimeout(timeout);
858
- timeout = null;
859
- }
860
-
861
- _stopController();
862
-
863
- if (cb) {
864
- cb(true);
865
- cb = null;
866
- }
867
- });
868
-
869
- timeout = setTimeout(() => {
870
- timeout = null;
871
- console.log('child process NOT terminated');
872
-
873
- _stopController();
874
-
875
- if (cb) {
876
- cb(false);
877
- cb = null;
878
- }
879
- pid = null;
880
- }, 5000);
881
- }
882
-
883
- // Setup the adapter
884
- async function setAdapterConfig(common, native, instance) {
885
- const id = `system.adapter.${adapterName.split('.').pop()}.${instance || 0}`;
886
- if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.json`)) {
887
- const objects = JSON.parse(fs.readFileSync(`${rootDir}tmp/${appName}-data/objects.json`).toString());
888
- if (common) {
889
- objects[id].common = common;
890
- }
891
- if (native) {
892
- objects[id].native = native;
893
- }
894
- fs.writeFileSync(`${rootDir}tmp/${appName}-data/objects.json`, JSON.stringify(objects));
895
- } else if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.jsonl`)) {
896
- loadJSONLDB();
897
- const db = new JSONLDB(`${rootDir}tmp/${appName}-data/objects.jsonl`);
898
- await db.open();
899
-
900
- const obj = db.get(id);
901
- if (common) {
902
- obj.common = common;
903
- }
904
- if (native) {
905
- obj.native = native;
906
- }
907
- db.set(id, obj);
908
-
909
- await db.close();
910
- } else {
911
- console.error(`setAdapterConfig: No objects file found in datadir ${rootDir}tmp/${appName}-data/`);
912
- }
913
- }
914
-
915
- // Read config of the adapter
916
- async function getAdapterConfig(instance) {
917
- const id = `system.adapter.${adapterName.split('.').pop()}.${instance || 0}`;
918
- if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.json`)) {
919
- const objects = JSON.parse(fs.readFileSync(`${rootDir}tmp/${appName}-data/objects.json`).toString());
920
- return objects[id];
921
- } else if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.jsonl`)) {
922
- loadJSONLDB();
923
- const db = new JSONLDB(`${rootDir}tmp/${appName}-data/objects.jsonl`);
924
- await db.open();
925
-
926
- const obj = db.get(id);
927
-
928
- await db.close();
929
- return obj;
930
- } else {
931
- console.error(`getAdapterConfig: No objects file found in datadir ${rootDir}tmp/${appName}-data/`);
932
- }
933
- }
934
-
935
- if (typeof module !== undefined && module.parent) {
936
- module.exports.getAdapterConfig = getAdapterConfig;
937
- module.exports.setAdapterConfig = setAdapterConfig;
938
- module.exports.startController = startController;
939
- module.exports.stopController = stopController;
940
- module.exports.setupController = setupController;
941
- module.exports.stopAdapter = stopAdapter;
942
- module.exports.startAdapter = startAdapter;
943
- module.exports.installAdapter = installAdapter;
944
- module.exports.appName = appName;
945
- module.exports.adapterName = adapterName;
946
- module.exports.adapterStarted = adapterStarted;
947
- module.exports.getSecret = getSecret;
948
- module.exports.encrypt = encrypt;
949
- }
1
+ /* jshint -W097 */
2
+ /* jshint strict: false */
3
+ /* jslint node: true */
4
+
5
+ // check if tmp directory exists
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const child_process = require('child_process');
9
+ const rootDir = path.normalize(`${__dirname}/../../../`);
10
+ const pkg = require(`${rootDir}package.json`);
11
+ const debug = typeof v8debug === 'object';
12
+ pkg.main = pkg.main || 'main.js';
13
+
14
+ let JSONLDB;
15
+
16
+ let adapterName = path.normalize(rootDir).replace(/\\/g, '/').split('/');
17
+ adapterName = adapterName[adapterName.length - 2];
18
+ let adapterStarted = false;
19
+
20
+ function getAppName() {
21
+ const parts = rootDir.replace(/\\/g, '/').split('/');
22
+ parts.pop();
23
+ return parts.pop().split('.')[0];
24
+ }
25
+
26
+ function loadJSONLDB() {
27
+ if (!JSONLDB) {
28
+ const dbPath = require.resolve('@alcalzone/jsonl-db', {
29
+ paths: [`${rootDir}tmp/node_modules`, rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
30
+ });
31
+ console.log(`JSONLDB path: ${dbPath}`);
32
+ try {
33
+ const { JsonlDB } = require(dbPath);
34
+ JSONLDB = JsonlDB;
35
+ } catch (err) {
36
+ console.log(`Jsonl require error: ${err}`);
37
+ }
38
+ }
39
+ }
40
+
41
+ const appName = getAppName().toLowerCase();
42
+
43
+ let objects;
44
+ let states;
45
+
46
+ let pid = null;
47
+
48
+ let systemConfig = null;
49
+
50
+ function copyFileSync(source, target) {
51
+
52
+ let targetFile = target;
53
+
54
+ //if target is a directory a new file with the same name will be created
55
+ if (fs.existsSync(target) && fs.lstatSync( target ).isDirectory() ) {
56
+ targetFile = path.join(target, path.basename(source));
57
+ }
58
+
59
+ try {
60
+ fs.writeFileSync(targetFile, fs.readFileSync(source));
61
+ } catch (err) {
62
+ console.log(`file copy error: ${source} -> ${targetFile} (error ignored)`);
63
+ }
64
+ }
65
+
66
+ function copyFolderRecursiveSync(source, target, ignore) {
67
+ let files = [];
68
+
69
+ let base = path.basename(source);
70
+ if (base === adapterName) {
71
+ base = pkg.name;
72
+ }
73
+ //check if folder needs to be created or integrated
74
+ const targetFolder = path.join(target, base);
75
+ if (!fs.existsSync(targetFolder)) {
76
+ fs.mkdirSync(targetFolder);
77
+ }
78
+
79
+ //copy
80
+ if (fs.lstatSync(source).isDirectory()) {
81
+ files = fs.readdirSync(source);
82
+ files.forEach(file => {
83
+ if (ignore && ignore.includes(file)) {
84
+ return;
85
+ }
86
+
87
+ const curSource = path.join(source, file);
88
+ const curTarget = path.join(targetFolder, file);
89
+ if (fs.lstatSync(curSource).isDirectory()) {
90
+ // ignore grunt files
91
+ if (file.includes('grunt') || file === 'chai' || file === 'mocha') {
92
+ return;
93
+ }
94
+ copyFolderRecursiveSync(curSource, targetFolder, ignore);
95
+ } else {
96
+ copyFileSync(curSource, curTarget);
97
+ }
98
+ });
99
+ }
100
+ }
101
+
102
+ !fs.existsSync(`${rootDir}tmp`) && fs.mkdirSync(`${rootDir}tmp`);
103
+
104
+
105
+ async function storeOriginalFiles() {
106
+ console.log('Store original files...');
107
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
108
+
109
+ if (fs.existsSync(dataDir + 'objects.json')) {
110
+ const f = fs.readFileSync(`${dataDir}objects.json`);
111
+ const objects = JSON.parse(f.toString());
112
+ if (objects['system.adapter.admin.0'] && objects['system.adapter.admin.0'].common) {
113
+ objects['system.adapter.admin.0'].common.enabled = false;
114
+ }
115
+ if (objects['system.adapter.admin.1'] && objects['system.adapter.admin.1'].common) {
116
+ objects['system.adapter.admin.1'].common.enabled = false;
117
+ }
118
+
119
+ fs.writeFileSync(`${dataDir}objects.json.original`, JSON.stringify(objects));
120
+ console.log('Store original objects.json');
121
+ }
122
+
123
+ if (fs.existsSync(`${dataDir}states.json`)) {
124
+ try {
125
+ const f = fs.readFileSync(`${dataDir}states.json`);
126
+ fs.writeFileSync(`${dataDir}states.json.original`, f);
127
+ console.log('Store original states.json');
128
+ } catch (err) {
129
+ console.log('no states.json found - ignore');
130
+ }
131
+ }
132
+
133
+ if (fs.existsSync(`${dataDir}objects.jsonl`)) {
134
+ loadJSONLDB();
135
+ const db = new JSONLDB(`${dataDir}objects.jsonl`);
136
+ await db.open();
137
+
138
+ const admin0 = db.get('system.adapter.admin.0');
139
+ if (admin0) {
140
+ if (admin0.common) {
141
+ admin0.common.enabled = false;
142
+ db.set('system.adapter.admin.0', admin0);
143
+ }
144
+ }
145
+
146
+ const admin1 = db.get('system.adapter.admin.1');
147
+ if (admin1) {
148
+ if (admin1.common) {
149
+ admin1.common.enabled = false;
150
+ db.set('system.adapter.admin.1', admin1);
151
+ }
152
+ }
153
+ await db.close();
154
+
155
+ const f = fs.readFileSync(dataDir + 'objects.jsonl');
156
+ fs.writeFileSync(`${dataDir}objects.jsonl.original`, f);
157
+ console.log('Store original objects.jsonl');
158
+ }
159
+
160
+ if (fs.existsSync(`${dataDir}states.jsonl`)) {
161
+ const f = fs.readFileSync(`${dataDir}states.jsonl`);
162
+ fs.writeFileSync(`${dataDir}states.jsonl.original`, f);
163
+ console.log('Store original states.jsonl');
164
+ }
165
+ }
166
+
167
+ function restoreOriginalFiles() {
168
+ console.log('restoreOriginalFiles...');
169
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
170
+
171
+ if (fs.existsSync(`${dataDir}objects.json.original`)) {
172
+ const f = fs.readFileSync(`${dataDir}objects.json.original`);
173
+ fs.writeFileSync(`${dataDir}objects.json`, f);
174
+ }
175
+ if (fs.existsSync(`${dataDir}objects.json.original`)) {
176
+ const f = fs.readFileSync(`${dataDir}states.json.original`);
177
+ fs.writeFileSync(`${dataDir}states.json`, f);
178
+ }
179
+
180
+ if (fs.existsSync(dataDir + 'objects.jsonl.original')) {
181
+ const f = fs.readFileSync(dataDir + 'objects.jsonl.original');
182
+ fs.writeFileSync(dataDir + 'objects.jsonl', f);
183
+ }
184
+ if (fs.existsSync(dataDir + 'objects.jsonl.original')) {
185
+ const f = fs.readFileSync(dataDir + 'states.jsonl.original');
186
+ fs.writeFileSync(dataDir + 'states.jsonl', f);
187
+ }
188
+ }
189
+
190
+ async function checkIsAdapterInstalled(cb, counter, customName) {
191
+ customName = customName || pkg.name.split('.').pop();
192
+ counter = counter || 0;
193
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
194
+ console.log('checkIsAdapterInstalled...');
195
+
196
+ try {
197
+ if (fs.existsSync(`${dataDir}objects.json`)) {
198
+ const f = fs.readFileSync(`${dataDir}objects.json`);
199
+ const objects = JSON.parse(f.toString());
200
+ if (objects[`system.adapter.${customName}.0`]) {
201
+ console.log('checkIsAdapterInstalled: ready!');
202
+ setTimeout(function () {
203
+ cb && cb();
204
+ }, 100);
205
+ return;
206
+ } else {
207
+ console.warn('checkIsAdapterInstalled: still not ready');
208
+ }
209
+ } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
210
+ loadJSONLDB();
211
+ const db = new JSONLDB(`${dataDir}objects.jsonl`);
212
+ try {
213
+ await db.open();
214
+ } catch (err) {
215
+ if (err.message.includes('Failed to lock DB file')) {
216
+ console.log('checkIsAdapterInstalled: DB still opened ...');
217
+ }
218
+ throw err;
219
+ }
220
+
221
+ const obj = db.get(`system.adapter.${customName}.0`);
222
+ await db.close();
223
+
224
+ if (obj) {
225
+ console.log('checkIsAdapterInstalled: ready!');
226
+ setTimeout(() => cb && cb(), 100);
227
+ return;
228
+ } else {
229
+ console.warn('checkIsAdapterInstalled: still not ready');
230
+ }
231
+ } else {
232
+ console.error(`checkIsAdapterInstalled: No objects file found in datadir ${dataDir}`);
233
+ }
234
+
235
+ } catch (err) {
236
+ console.log(`checkIsAdapterInstalled: catch ${err}`);
237
+ }
238
+
239
+ if (counter > 20) {
240
+ console.error('checkIsAdapterInstalled: Cannot install!');
241
+ cb && cb('Cannot install');
242
+ } else {
243
+ console.log('checkIsAdapterInstalled: wait...');
244
+ setTimeout(function() {
245
+ checkIsAdapterInstalled(cb, counter + 1);
246
+ }, 1000);
247
+ }
248
+ }
249
+
250
+ async function checkIsControllerInstalled(cb, counter) {
251
+ counter = counter || 0;
252
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
253
+
254
+ console.log('checkIsControllerInstalled...');
255
+ try {
256
+ if (fs.existsSync(dataDir + 'objects.json')) {
257
+ const f = fs.readFileSync(dataDir + 'objects.json');
258
+ const objects = JSON.parse(f.toString());
259
+ if (objects['system.certificates']) {
260
+ console.log('checkIsControllerInstalled: installed!');
261
+ setTimeout(() => cb && cb(), 100);
262
+ return;
263
+ }
264
+ } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
265
+ loadJSONLDB();
266
+ const db = new JSONLDB(`${dataDir}objects.jsonl`);
267
+ try {
268
+ await db.open();
269
+ } catch (err) {
270
+ if (err.message.includes('Failed to lock DB file')) {
271
+ console.log('checkIsControllerInstalled: DB still opened ...');
272
+ }
273
+ throw err;
274
+ }
275
+
276
+ const obj = db.get('system.certificates');
277
+ await db.close();
278
+
279
+ if (obj) {
280
+ console.log('checkIsControllerInstalled: installed!');
281
+ setTimeout(() => cb && cb(), 100);
282
+ return;
283
+ }
284
+
285
+ } else {
286
+ console.error(`checkIsControllerInstalled: No objects file found in datadir ${dataDir}`);
287
+ }
288
+ } catch (err) {
289
+ // ignore
290
+ }
291
+
292
+ if (counter > 20) {
293
+ console.log('checkIsControllerInstalled: Cannot install!');
294
+ cb && cb('Cannot install');
295
+ } else {
296
+ console.log('checkIsControllerInstalled: wait...');
297
+ setTimeout(() => checkIsControllerInstalled(cb, counter + 1), 1000);
298
+ }
299
+ }
300
+
301
+ function installAdapter(customName, cb) {
302
+ if (typeof customName === 'function') {
303
+ cb = customName;
304
+ customName = null;
305
+ }
306
+ customName = customName || pkg.name.split('.').pop();
307
+ console.log('Install adapter...');
308
+ const startFile = `node_modules/${appName}.js-controller/${appName}.js`;
309
+ // make first install
310
+ if (debug) {
311
+ child_process.execSync(`node ${startFile} add ${customName} --enabled false`, {
312
+ cwd: rootDir + 'tmp',
313
+ stdio: [0, 1, 2]
314
+ });
315
+ checkIsAdapterInstalled(error => {
316
+ error && console.error(error);
317
+ console.log('Adapter installed.');
318
+ cb && cb();
319
+ });
320
+ } else {
321
+ // add controller
322
+ const _pid = child_process.fork(startFile, ['add', customName, '--enabled', 'false'], {
323
+ cwd: `${rootDir}tmp`,
324
+ stdio: [0, 1, 2, 'ipc']
325
+ });
326
+
327
+ waitForEnd(_pid, () =>
328
+ checkIsAdapterInstalled(error => {
329
+ error && console.error(error);
330
+ console.log('Adapter installed.');
331
+ cb && cb();
332
+ }));
333
+ }
334
+ }
335
+
336
+ function waitForEnd(_pid, cb) {
337
+ if (!_pid) {
338
+ cb(-1, -1);
339
+ return;
340
+ }
341
+ _pid.on('exit', (code, signal) => {
342
+ if (_pid) {
343
+ _pid = null;
344
+ cb(code, signal);
345
+ }
346
+ });
347
+ _pid.on('close', (code, signal) => {
348
+ if (_pid) {
349
+ _pid = null;
350
+ cb(code, signal);
351
+ }
352
+ });
353
+ }
354
+
355
+ function installJsController(cb) {
356
+ console.log('installJsController...');
357
+ if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`) ||
358
+ !fs.existsSync(`${rootDir}tmp/${appName}-data`)) {
359
+ // try to detect appName.js-controller in node_modules/appName.js-controller
360
+ // travis CI installs js-controller into node_modules
361
+ if (fs.existsSync(`${rootDir}node_modules/${appName}.js-controller`)) {
362
+ console.log(`installJsController: no js-controller => copy it from "${rootDir}node_modules/${appName}.js-controller"`);
363
+ // copy all
364
+ // stop controller
365
+ console.log('Stop controller if running...');
366
+ let _pid;
367
+ if (debug) {
368
+ // start controller
369
+ _pid = child_process.exec(`node ${appName}.js stop`, {
370
+ cwd: `${rootDir}node_modules/${appName}.js-controller`,
371
+ stdio: [0, 1, 2]
372
+ });
373
+ } else {
374
+ _pid = child_process.fork(`${appName}.js`, ['stop'], {
375
+ cwd: `${rootDir}node_modules/${appName}.js-controller`,
376
+ stdio: [0, 1, 2, 'ipc']
377
+ });
378
+ }
379
+
380
+ waitForEnd(_pid, () => {
381
+ // copy all files into
382
+ !fs.existsSync(`${rootDir}tmp`) && fs.mkdirSync(`${rootDir}tmp`);
383
+ !fs.existsSync(`${rootDir}tmp/node_modules`) && fs.mkdirSync(`${rootDir}tmp/node_modules`);
384
+
385
+ if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`)){
386
+ console.log('Copy js-controller...');
387
+ copyFolderRecursiveSync(`${rootDir}node_modules/${appName}.js-controller`, `${rootDir}tmp/node_modules/`);
388
+ }
389
+
390
+ console.log('Setup js-controller...');
391
+ let __pid;
392
+ if (debug) {
393
+ // start controller
394
+ _pid = child_process.exec(`node ${appName}.js setup first --console`, {
395
+ cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
396
+ stdio: [0, 1, 2]
397
+ });
398
+ } else {
399
+ __pid = child_process.fork(`${appName}.js`, ['setup', 'first', '--console'], {
400
+ cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
401
+ stdio: [0, 1, 2, 'ipc']
402
+ });
403
+ }
404
+ waitForEnd(__pid, () =>
405
+ checkIsControllerInstalled(() => {
406
+ // change ports for object and state DBs
407
+ const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
408
+ config.objects.port = 19001;
409
+ config.states.port = 19000;
410
+
411
+ // TEST WISE!
412
+ //config.objects.type = 'jsonl';
413
+ //config.states.type = 'jsonl';
414
+ fs.writeFileSync(`${rootDir}tmp/${appName}-data/${appName}.json`, JSON.stringify(config, null, 2));
415
+ console.log('Setup finished.');
416
+
417
+ copyAdapterToController();
418
+
419
+ installAdapter(async () => {
420
+ await storeOriginalFiles();
421
+ cb && cb(true);
422
+ });
423
+ }));
424
+ });
425
+ } else {
426
+ // check if port 9000 is free, else admin adapter will be added to running instance
427
+ const client = new require('net').Socket();
428
+ client.on('error', () => {});
429
+ client.connect(9000, '127.0.0.1', () => {
430
+ console.error('Cannot initiate fisrt run of test, because one instance of application is running on this PC. Stop it and repeat.');
431
+ process.exit(0);
432
+ });
433
+
434
+ setTimeout(() => {
435
+ client.destroy();
436
+ if (!fs.existsSync(`${rootDir}tmp/node_modules/${appName}.js-controller`)) {
437
+ console.log('installJsController: no js-controller => install dev build from npm');
438
+
439
+ child_process.execSync(`npm install ${appName}.js-controller@dev --prefix ./ --production`, {
440
+ cwd: rootDir + 'tmp/',
441
+ stdio: [0, 1, 2]
442
+ });
443
+ } else {
444
+ console.log('Setup js-controller...');
445
+ if (debug) {
446
+ // start controller
447
+ child_process.exec(`node ${appName}.js setup first`, {
448
+ cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
449
+ stdio: [0, 1, 2]
450
+ });
451
+ } else {
452
+ child_process.fork(`${appName}.js`, ['setup', 'first'], {
453
+ cwd: `${rootDir}tmp/node_modules/${appName}.js-controller`,
454
+ stdio: [0, 1, 2, 'ipc']
455
+ });
456
+ }
457
+ }
458
+
459
+ // let npm install admin and run setup
460
+ checkIsControllerInstalled(() => {
461
+ let _pid;
462
+
463
+ if (fs.existsSync(`${rootDir}node_modules/${appName}.js-controller/${appName}.js`)) {
464
+ _pid = child_process.fork(`${appName}.js`, ['stop'], {
465
+ cwd: `${rootDir}node_modules/${appName}.js-controller`,
466
+ stdio: [0, 1, 2, 'ipc']
467
+ });
468
+ }
469
+
470
+ waitForEnd(_pid, () => {
471
+ // change ports for object and state DBs
472
+ const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
473
+ config.objects.port = 19001;
474
+ config.states.port = 19000;
475
+
476
+ // TEST WISE!
477
+ //config.objects.type = 'jsonl';
478
+ //config.states.type = 'jsonl';
479
+ fs.writeFileSync(`${rootDir}tmp/${appName}-data/${appName}.json`, JSON.stringify(config, null, 2));
480
+
481
+ copyAdapterToController();
482
+
483
+ installAdapter(async () => {
484
+ await storeOriginalFiles();
485
+ cb && cb(true);
486
+ });
487
+ });
488
+ });
489
+ }, 1000);
490
+ }
491
+ } else {
492
+ setTimeout(() => {
493
+ console.log('installJsController: js-controller installed');
494
+ cb && cb(false);
495
+ }, 0);
496
+ }
497
+ }
498
+
499
+ function copyAdapterToController() {
500
+ console.log('Copy adapter...');
501
+ // Copy adapter to tmp/node_modules/appName.adapter
502
+ copyFolderRecursiveSync(rootDir, `${rootDir}tmp/node_modules/`, ['.idea', 'test', 'tmp', '.git', appName + '.js-controller']);
503
+ console.log('Adapter copied.');
504
+ }
505
+
506
+ function clearControllerLog() {
507
+ const dirPath = rootDir + 'tmp/log';
508
+ let files;
509
+ try {
510
+ if (fs.existsSync(dirPath)) {
511
+ console.log('Clear controller log...');
512
+ files = fs.readdirSync(dirPath);
513
+ } else {
514
+ console.log('Create controller log directory...');
515
+ files = [];
516
+ fs.mkdirSync(dirPath);
517
+ }
518
+ } catch(e) {
519
+ console.error(`Cannot read "${dirPath}"`);
520
+ return;
521
+ }
522
+ if (files.length > 0) {
523
+ try {
524
+ for (let i = 0; i < files.length; i++) {
525
+ const filePath = `${dirPath}/${files[i]}`;
526
+ fs.unlinkSync(filePath);
527
+ }
528
+ console.log('Controller log cleared');
529
+ } catch (err) {
530
+ console.error(`cannot clear log: ${err}`);
531
+ }
532
+ }
533
+ }
534
+
535
+ function clearDB() {
536
+ const dirPath = `${rootDir}tmp/iobroker-data/sqlite`;
537
+ let files;
538
+ try {
539
+ if (fs.existsSync(dirPath)) {
540
+ console.log('Clear sqlite DB...');
541
+ files = fs.readdirSync(dirPath);
542
+ } else {
543
+ console.log('Create controller log directory...');
544
+ files = [];
545
+ fs.mkdirSync(dirPath);
546
+ }
547
+ } catch(e) {
548
+ console.error(`Cannot read "${dirPath}"`);
549
+ return;
550
+ }
551
+ if (files.length > 0) {
552
+ try {
553
+ for (let i = 0; i < files.length; i++) {
554
+ const filePath = `${dirPath}/${files[i]}`;
555
+ fs.unlinkSync(filePath);
556
+ }
557
+ console.log('Clear sqlite DB');
558
+ } catch (err) {
559
+ console.error(`cannot clear DB: ${err}`);
560
+ }
561
+ }
562
+ }
563
+
564
+ function setupController(cb) {
565
+ installJsController(async isInited => {
566
+ try {
567
+ clearControllerLog();
568
+ clearDB();
569
+
570
+ if (!isInited) {
571
+ restoreOriginalFiles();
572
+ copyAdapterToController();
573
+ }
574
+ // read system.config object
575
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
576
+
577
+ if (fs.existsSync(`${dataDir}objects.json`)) {
578
+ let objs;
579
+ try {
580
+ objs = fs.readFileSync(`${dataDir}objects.json`);
581
+ objs = JSON.parse(objs);
582
+ } catch (e) {
583
+ console.log('ERROR reading/parsing system configuration. Ignore');
584
+ objs = {'system.config': {}};
585
+ }
586
+ if (!objs || !objs['system.config']) {
587
+ objs = {'system.config': {}};
588
+ }
589
+
590
+ systemConfig = objs['system.config'];
591
+ cb && cb(objs['system.config']);
592
+ } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
593
+ loadJSONLDB();
594
+ const db = new JSONLDB(`${dataDir}objects.jsonl`);
595
+ await db.open();
596
+
597
+ const config = db.get('system.config');
598
+ systemConfig = config || {};
599
+
600
+ await db.close();
601
+
602
+ cb && cb(systemConfig);
603
+ } else {
604
+ console.error(`read SystemConfig: No objects file found in datadir ${dataDir}`);
605
+ }
606
+ } catch (err) {
607
+ console.error(`setupController: ${err}`);
608
+ }
609
+ });
610
+ }
611
+
612
+ async function getSecret() {
613
+ const dataDir = `${rootDir}tmp/${appName}-data/`;
614
+
615
+ if (systemConfig) {
616
+ return systemConfig.native.secret;
617
+ }
618
+ if (fs.existsSync(`${dataDir}objects.json`)) {
619
+ let objs;
620
+ try {
621
+ objs = fs.readFileSync(`${dataDir}objects.json`);
622
+ objs = JSON.parse(objs);
623
+ } catch (e) {
624
+ console.warn(`Could not load secret. Reason: ${e}`);
625
+ return null;
626
+ }
627
+ if (!objs || !objs['system.config']) {
628
+ objs = {'system.config': {}};
629
+ }
630
+
631
+ return objs['system.config'].native.secre;
632
+ } else if (fs.existsSync(`${dataDir}objects.jsonl`)) {
633
+ loadJSONLDB();
634
+ const db = new JSONLDB(`${dataDir}objects.jsonl`);
635
+ await db.open();
636
+
637
+ let config = db.get('system.config');
638
+ config = config || {};
639
+
640
+ await db.close();
641
+
642
+ return config.native.secret;
643
+ } else {
644
+ console.error(`read secret: No objects file found in datadir ${dataDir}`);
645
+ }
646
+
647
+ }
648
+
649
+ function encrypt (key, value) {
650
+ let result = '';
651
+ for (let i = 0; i < value.length; ++i) {
652
+ result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
653
+ }
654
+ return result;
655
+ }
656
+
657
+ function startAdapter(objects, states, callback) {
658
+ if (adapterStarted) {
659
+ console.log('Adapter already started ...');
660
+ callback && callback(objects, states);
661
+ return;
662
+ }
663
+ adapterStarted = true;
664
+ console.log('startAdapter...');
665
+ if (fs.existsSync(`${rootDir}tmp/node_modules/${pkg.name}/${pkg.main}`)) {
666
+ try {
667
+ if (debug) {
668
+ // start controller
669
+ pid = child_process.exec(`node node_modules/${pkg.name}/${pkg.main} --console silly`, {
670
+ cwd: rootDir + 'tmp',
671
+ stdio: [0, 1, 2]
672
+ });
673
+ } else {
674
+ // start controller
675
+ pid = child_process.fork(`node_modules/${pkg.name}/${pkg.main}`, ['--console', 'silly'], {
676
+ cwd: rootDir + 'tmp',
677
+ stdio: [0, 1, 2, 'ipc']
678
+ });
679
+ }
680
+ } catch (error) {
681
+ console.error(JSON.stringify(error));
682
+ }
683
+ } else {
684
+ console.error(`Cannot find: ${rootDir}tmp/node_modules/${pkg.name}/${pkg.main}`);
685
+ }
686
+ callback && callback(objects, states);
687
+ }
688
+
689
+ function startController(isStartAdapter, onObjectChange, onStateChange, callback) {
690
+ if (typeof isStartAdapter === 'function') {
691
+ callback = onStateChange;
692
+ onStateChange = onObjectChange;
693
+ onObjectChange = isStartAdapter;
694
+ isStartAdapter = true;
695
+ }
696
+
697
+ if (onStateChange === undefined) {
698
+ callback = onObjectChange;
699
+ onObjectChange = undefined;
700
+ }
701
+
702
+ if (pid) {
703
+ console.error('Controller is already started!');
704
+ } else {
705
+ console.log('startController...');
706
+ try {
707
+ const config = require(`${rootDir}tmp/${appName}-data/${appName}.json`);
708
+
709
+ adapterStarted = false;
710
+ let isObjectConnected;
711
+ let isStatesConnected;
712
+
713
+ // rootDir + 'tmp/node_modules
714
+ const objPath = require.resolve(`@iobroker/db-objects-${config.objects.type}`, {
715
+ paths: [ rootDir + 'tmp/node_modules', rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
716
+ });
717
+ console.log(`Objects Path: ${objPath}`);
718
+ const Objects = require(objPath).Server;
719
+ objects = new Objects({
720
+ connection: {
721
+ 'type': config.objects.type,
722
+ 'host': '127.0.0.1',
723
+ 'port': 19001,
724
+ 'user': '',
725
+ 'pass': '',
726
+ 'noFileCache': false,
727
+ 'connectTimeout': 2000
728
+ },
729
+ logger: {
730
+ silly: msg => console.log(msg),
731
+ debug: msg => console.log(msg),
732
+ info: msg => console.log(msg),
733
+ warn: msg => console.warn(msg),
734
+ error: msg => console.error(msg)
735
+ },
736
+ connected: () => {
737
+ isObjectConnected = true;
738
+ if (isStatesConnected) {
739
+ console.log('startController: started!');
740
+ if (isStartAdapter) {
741
+ startAdapter(objects, states, callback);
742
+ } else {
743
+ if (callback) {
744
+ callback(objects, states);
745
+ callback = null;
746
+ }
747
+ }
748
+ }
749
+ },
750
+ change: onObjectChange
751
+ });
752
+
753
+ // Just open in memory DB itself
754
+ const statePath = require.resolve(`@iobroker/db-states-${config.states.type}`, {
755
+ paths: [ `${rootDir}tmp/node_modules`, rootDir, `${rootDir}tmp/node_modules/${appName}.js-controller`]
756
+ });
757
+ console.log(`States Path: ${statePath}`);
758
+ const States = require(statePath).Server;
759
+ states = new States({
760
+ connection: {
761
+ type: config.states.type,
762
+ host: '127.0.0.1',
763
+ port: 19000,
764
+ options: {
765
+ auth_pass: null,
766
+ retry_max_delay: 15000
767
+ }
768
+ },
769
+ logger: {
770
+ silly: function (msg) {
771
+ console.log(msg);
772
+ },
773
+ debug: function (msg) {
774
+ console.log(msg);
775
+ },
776
+ info: function (msg) {
777
+ console.log(msg);
778
+ },
779
+ warn: function (msg) {
780
+ console.log(msg);
781
+ },
782
+ error: function (msg) {
783
+ console.log(msg);
784
+ }
785
+ },
786
+ connected: function () {
787
+ isStatesConnected = true;
788
+ if (isObjectConnected) {
789
+ console.log('startController: started!!');
790
+ if (isStartAdapter) {
791
+ startAdapter(objects, states, callback);
792
+ } else {
793
+ if (callback) {
794
+ callback(objects, states);
795
+ callback = null;
796
+ }
797
+ }
798
+ }
799
+ },
800
+ change: onStateChange
801
+ });
802
+ } catch (err) {
803
+ console.log(err);
804
+ }
805
+ }
806
+ }
807
+
808
+ function stopAdapter(cb) {
809
+ if (!pid) {
810
+ console.error('Controller is not running!');
811
+ cb && setTimeout(() => cb(false), 0);
812
+ } else {
813
+ adapterStarted = false;
814
+ pid.on('exit', (code, signal) => {
815
+ if (pid) {
816
+ console.log(`child process terminated due to receipt of signal ${signal}`);
817
+ cb && cb();
818
+ pid = null;
819
+ }
820
+ });
821
+
822
+ pid.on('close', (/* code, signal */) => {
823
+ if (pid) {
824
+ cb && cb();
825
+ pid = null;
826
+ }
827
+ });
828
+
829
+ pid.kill('SIGTERM');
830
+ }
831
+ }
832
+
833
+ function _stopController() {
834
+ if (objects) {
835
+ objects.destroy();
836
+ objects = null;
837
+ }
838
+ if (states) {
839
+ states.destroy();
840
+ states = null;
841
+ }
842
+ }
843
+
844
+ function stopController(cb) {
845
+ let timeout;
846
+ if (objects) {
847
+ console.log(`Set system.adapter.${pkg.name}.0`);
848
+ objects.setObject(`system.adapter.${pkg.name}.0`, {
849
+ common: {
850
+ enabled: false
851
+ }
852
+ });
853
+ }
854
+
855
+ stopAdapter(() => {
856
+ if (timeout) {
857
+ clearTimeout(timeout);
858
+ timeout = null;
859
+ }
860
+
861
+ _stopController();
862
+
863
+ if (cb) {
864
+ cb(true);
865
+ cb = null;
866
+ }
867
+ });
868
+
869
+ timeout = setTimeout(() => {
870
+ timeout = null;
871
+ console.log('child process NOT terminated');
872
+
873
+ _stopController();
874
+
875
+ if (cb) {
876
+ cb(false);
877
+ cb = null;
878
+ }
879
+ pid = null;
880
+ }, 5000);
881
+ }
882
+
883
+ // Setup the adapter
884
+ async function setAdapterConfig(common, native, instance) {
885
+ const id = `system.adapter.${adapterName.split('.').pop()}.${instance || 0}`;
886
+ if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.json`)) {
887
+ const objects = JSON.parse(fs.readFileSync(`${rootDir}tmp/${appName}-data/objects.json`).toString());
888
+ if (common) {
889
+ objects[id].common = common;
890
+ }
891
+ if (native) {
892
+ objects[id].native = native;
893
+ }
894
+ fs.writeFileSync(`${rootDir}tmp/${appName}-data/objects.json`, JSON.stringify(objects));
895
+ } else if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.jsonl`)) {
896
+ loadJSONLDB();
897
+ const db = new JSONLDB(`${rootDir}tmp/${appName}-data/objects.jsonl`);
898
+ await db.open();
899
+
900
+ const obj = db.get(id);
901
+ if (common) {
902
+ obj.common = common;
903
+ }
904
+ if (native) {
905
+ obj.native = native;
906
+ }
907
+ db.set(id, obj);
908
+
909
+ await db.close();
910
+ } else {
911
+ console.error(`setAdapterConfig: No objects file found in datadir ${rootDir}tmp/${appName}-data/`);
912
+ }
913
+ }
914
+
915
+ // Read config of the adapter
916
+ async function getAdapterConfig(instance) {
917
+ const id = `system.adapter.${adapterName.split('.').pop()}.${instance || 0}`;
918
+ if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.json`)) {
919
+ const objects = JSON.parse(fs.readFileSync(`${rootDir}tmp/${appName}-data/objects.json`).toString());
920
+ return objects[id];
921
+ } else if (fs.existsSync(`${rootDir}tmp/${appName}-data/objects.jsonl`)) {
922
+ loadJSONLDB();
923
+ const db = new JSONLDB(`${rootDir}tmp/${appName}-data/objects.jsonl`);
924
+ await db.open();
925
+
926
+ const obj = db.get(id);
927
+
928
+ await db.close();
929
+ return obj;
930
+ } else {
931
+ console.error(`getAdapterConfig: No objects file found in datadir ${rootDir}tmp/${appName}-data/`);
932
+ }
933
+ }
934
+
935
+ if (typeof module !== undefined && module.parent) {
936
+ module.exports.getAdapterConfig = getAdapterConfig;
937
+ module.exports.setAdapterConfig = setAdapterConfig;
938
+ module.exports.startController = startController;
939
+ module.exports.stopController = stopController;
940
+ module.exports.setupController = setupController;
941
+ module.exports.stopAdapter = stopAdapter;
942
+ module.exports.startAdapter = startAdapter;
943
+ module.exports.installAdapter = installAdapter;
944
+ module.exports.appName = appName;
945
+ module.exports.adapterName = adapterName;
946
+ module.exports.adapterStarted = adapterStarted;
947
+ module.exports.getSecret = getSecret;
948
+ module.exports.encrypt = encrypt;
949
+ }