forked from simatec/ioBroker.backitup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
871 lines (804 loc) · 38.7 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
/* jshint -W097 */
/* jshint strict: false */
/*jslint node: true */
'use strict';
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const schedule = require('node-schedule');
const fs = require('fs');
const path = require('path');
const adapterName = require('./package.json').name.split('.').pop();
const tools = require('./lib/tools');
const executeScripts = require('./lib/execute');
const list = require('./lib/list');
const restore = require('./lib/restore');
const GoogleDrive = require('./lib/googleDriveLib');
let adapter;
let timerOutput;
let timerOutput2;
let timerUmount1;
let timerUmount2;
let timerMain;
let systemLang = 'de'; // system language
const backupConfig = {};
const backupTimeSchedules = []; // Array für die Backup Zeiten
let taskRunning = false;
/**
* Decrypt the password/value with given key
* @param {string} key - Secret key
* @param {string} value - value to decript
* @returns {string}
*/
function decrypt(key, value) {
let result = '';
for (let i = 0; i < value.length; i++) {
result += String.fromCharCode(key[i % key.length].charCodeAt(0) ^ value.charCodeAt(i));
}
return result;
}
function startBackup(config, cb) {
if (taskRunning) {
return setTimeout(startBackup, 10000, config, cb);
} else {
taskRunning = true;
try {
executeScripts(adapter, config, err => {
taskRunning = false;
cb && cb(err);
});
adapter.log.debug('Backup has started ...');
} catch (e) {
adapter.log.warn('Backup error: ' + e + ' ... please check your config and and try again!!');
}
}
}
function startAdapter(options) {
options = options || {};
Object.assign(options, { name: adapterName });
adapter = new utils.Adapter(options);
adapter.on('stateChange', (id, state) => {
if (state && (state.val === true || state.val === 'true') && !state.ack) {
if (id === adapter.namespace + '.oneClick.iobroker' ||
id === adapter.namespace + '.oneClick.ccu') {
const type = id.split('.').pop();
let config;
try {
config = JSON.parse(JSON.stringify(backupConfig[type]));
config.enabled = true;
config.deleteBackupAfter = 0; // do not delete files by custom backup
} catch (e) {
adapter.log.warn('backup error: ' + e + ' ... please check your config and try again!!');
}
startBackup(config, err => {
if (err) {
adapter.log.error(`[${type}] ${err}`);
} else {
adapter.log.debug(`[${type}] exec: done`);
}
timerOutput = setTimeout(() =>
adapter.getState('output.line', (err, state) => {
if (state && state.val === '[EXIT] 0') {
adapter.setState('history.' + type + 'Success', true, true);
adapter.setState(`history.${type}LastTime`, tools.getTimeString(systemLang), true);
} else {
adapter.setState(`history.${type}LastTime`, 'error: ' + tools.getTimeString(systemLang), true);
adapter.setState('history.' + type + 'Success', false, true);
}
}), 500);
adapter.setState('oneClick.' + type, false, true);
});
}
}
});
adapter.on('ready', () => main(adapter));
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', (callback) => {
try {
adapter.log.info('cleaned everything up...');
clearTimeout(timerOutput2);
clearTimeout(timerOutput);
clearTimeout(timerUmount1);
clearTimeout(timerUmount2);
clearTimeout(timerMain);
callback();
} catch (e) {
callback();
}
});
adapter.on('message', obj => {
if (obj) {
switch (obj.command) {
case 'list':
try {
list(obj.message, backupConfig, adapter.log, res => obj.callback && adapter.sendTo(obj.from, obj.command, res, obj.callback));
adapter.log.debug('Backup list be read ...');
} catch (e) {
adapter.log.debug('Backup list cannot be read ...');
}
break;
case 'authGoogleDrive':
if (obj.message && obj.message.code) {
const google = new GoogleDrive();
google.getToken(obj.message.code)
.then(json => adapter.sendTo(obj.from, obj.command, { done: true, json: JSON.stringify(json) }, obj.callback))
.catch(err => adapter.sendTo(obj.from, obj.command, { error: err }, obj.callback));
} else if (obj.callback) {
const google = new GoogleDrive();
google.getAuthorizeUrl().then(url =>
adapter.sendTo(obj.from, obj.command, { url }, obj.callback));
}
break;
case 'restore':
if (obj.message) {
restore(adapter, backupConfig, obj.message.type, obj.message.fileName, adapter.log, res => obj.callback && adapter.sendTo(obj.from, obj.command, res, obj.callback));
} else if (obj.callback) {
obj.callback({ error: 'Invalid parameters' });
}
break;
case 'getTelegramUser':
adapter.getForeignState(adapter.config.telegramInstance + '.communicate.users', (err, state) => {
err && adapter.log.error(err);
if (state && state.val) {
try {
adapter.sendTo(obj.from, obj.command, state.val, obj.callback);
} catch (err) {
err && adapter.log.error(err);
adapter.log.error('Cannot parse stored user IDs from Telegram!');
}
}
});
break;
}
}
});
return adapter;
}
function checkStates() {
// Fill empty data points with default values
adapter.getState('history.html', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.html', {
val: '<span class="backup-type-total">' + tools._('No backups yet', systemLang) + '</span>',
ack: true
});
}
});
adapter.getState('history.iobrokerLastTime', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.iobrokerLastTime', { val: tools._('No backups yet', systemLang), ack: true });
}
});
adapter.getState('history.ccuLastTime', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.ccuLastTime', { val: tools._('No backups yet', systemLang), ack: true });
}
});
adapter.getState('oneClick.iobroker', (err, state) => {
if (!state || state.val === null) {
adapter.setState('oneClick.iobroker', { val: false, ack: true });
}
});
adapter.getState('oneClick.ccu', (err, state) => {
if (!state || state.val === null) {
adapter.setState('oneClick.ccu', { val: false, ack: true });
}
});
adapter.getState('history.ccuSuccess', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.ccuSuccess', { val: false, ack: true });
}
});
adapter.getState('history.iobrokerSuccess', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.iobrokerSuccess', { val: false, ack: true });
}
});
adapter.getState('history.json', (err, state) => {
if (!state || state.val === null) {
adapter.setState('history.json', { val: '[]', ack: true });
}
});
}
// function to create Backup schedules (Backup time)
function createBackupSchedule() {
for (const type in backupConfig) {
if (!backupConfig.hasOwnProperty(type)) continue;
const config = backupConfig[type];
if (config.enabled === true || config.enabled === 'true') {
let time = config.time.split(':');
adapter.log.info(`[${type}] backup was activated at ${config.time} every ${config.everyXDays} day(s)`);
if (backupTimeSchedules[type]) {
backupTimeSchedules[type].cancel();
}
const cron = '10 ' + time[1] + ' ' + time[0] + ' */' + config.everyXDays + ' * * ';
backupTimeSchedules[type] = schedule.scheduleJob(cron, () => {
adapter.setState('oneClick.' + type, true, true);
startBackup(backupConfig[type], err => {
if (err) {
adapter.log.error(`[${type}] ${err}`);
} else {
adapter.log.debug(`[${type}] exec: done`);
}
timerOutput2 = setTimeout(() =>
adapter.getState('output.line', (err, state) => {
if (state && state.val === '[EXIT] 0') {
adapter.setState('history.' + type + 'Success', true, true);
adapter.setState(`history.${type}LastTime`, tools.getTimeString(systemLang), true);
} else {
adapter.setState(`history.${type}LastTime`, 'error: ' + tools.getTimeString(systemLang), true);
adapter.setState('history.' + type + 'Success', false, true);
}
}), 500);
nextBackup(0, false, type);
adapter.setState('oneClick.' + type, false, true);
});
});
if (config.debugging) {
adapter.log.debug(`[${type}] ${cron}`);
}
} else if (backupTimeSchedules[type]) {
adapter.log.info(`[${type}] backup deactivated`);
backupTimeSchedules[type].cancel();
backupTimeSchedules[type] = null;
}
}
}
function initConfig(secret) {
// compatibility
if (adapter.config.cifsMount === 'CIFS') {
adapter.config.cifsMount = '';
}
if (adapter.config.redisEnabled === undefined) {
adapter.config.redisEnabled = adapter.config.backupRedis
}
const telegram = {
enabled: adapter.config.notificationEnabled,
notificationsType: adapter.config.notificationsType,
type: 'message',
instance: adapter.config.telegramInstance,
SilentNotice: adapter.config.telegramSilentNotice,
NoticeType: adapter.config.telegramNoticeType,
User: adapter.config.telegramUser,
onlyError: adapter.config.telegramOnlyError,
telegramWaiting: adapter.config.telegramWaitToSend * 1000,
systemLang
};
const whatsapp = {
enabled: adapter.config.notificationEnabled,
notificationsType: adapter.config.notificationsType,
type: 'message',
instance: adapter.config.whatsappInstance,
NoticeType: adapter.config.whatsappNoticeType,
onlyError: adapter.config.whatsappOnlyError,
whatsappWaiting: adapter.config.whatsappWaitToSend * 1000,
systemLang
};
const pushover = {
enabled: adapter.config.notificationEnabled,
notificationsType: adapter.config.notificationsType,
type: 'message',
instance: adapter.config.pushoverInstance,
SilentNotice: adapter.config.pushoverSilentNotice,
NoticeType: adapter.config.pushoverNoticeType,
deviceID: adapter.config.pushoverDeviceID,
onlyError: adapter.config.pushoverOnlyError,
pushoverWaiting: adapter.config.pushoverWaitToSend * 1000,
systemLang
};
const email = {
enabled: adapter.config.notificationEnabled,
notificationsType: adapter.config.notificationsType,
type: 'message',
instance: adapter.config.emailInstance,
NoticeType: adapter.config.emailNoticeType,
emailReceiver: adapter.config.emailReceiver,
emailSender: adapter.config.emailSender,
onlyError: adapter.config.emailOnlyError,
emailWaiting: adapter.config.emailWaitToSend * 1000,
systemLang
};
const history = {
enabled: true,
type: 'message',
entriesNumber: adapter.config.historyEntriesNumber,
systemLang
};
const ftp = {
enabled: adapter.config.ftpEnabled,
type: 'storage',
source: adapter.config.restoreSource,
host: adapter.config.ftpHost, // ftp-host
debugging: adapter.config.debugLevel,
deleteOldBackup: adapter.config.ftpDeleteOldBackup, // Delete old Backups from FTP
ownDir: adapter.config.ftpOwnDir,
bkpType: adapter.config.restoreType,
dir: (adapter.config.ftpOwnDir === true) ? null : adapter.config.ftpDir, // directory on FTP server
dirMinimal: adapter.config.ftpMinimalDir,
user: adapter.config.ftpUser, // username for FTP Server
pass: adapter.config.ftpPassword ? decrypt(secret, adapter.config.ftpPassword) : '', // password for FTP Server
port: adapter.config.ftpPort || 21 // FTP port
};
const dropbox = {
enabled: adapter.config.dropboxEnabled,
type: 'storage',
source: adapter.config.restoreSource,
debugging: adapter.config.debugLevel,
deleteOldBackup: adapter.config.dropboxDeleteOldBackup, // Delete old Backups from Dropbox
accessToken: adapter.config.dropboxAccessToken,
ownDir: adapter.config.dropboxOwnDir,
bkpType: adapter.config.restoreType,
dir: (adapter.config.dropboxOwnDir === true) ? null : adapter.config.dropboxDir,
dirMinimal: adapter.config.dropboxMinimalDir
};
const googledrive = {
enabled: adapter.config.googledriveEnabled,
type: 'storage',
source: adapter.config.restoreSource,
debugging: adapter.config.debugLevel,
deleteOldBackup: adapter.config.googledriveDeleteOldBackup, // Delete old Backups from google drive
accessJson: adapter.config.googledriveAccessJson,
ownDir: adapter.config.googledriveOwnDir,
bkpType: adapter.config.restoreType,
dir: (adapter.config.googledriveOwnDir === true) ? null : adapter.config.googledriveDir,
dirMinimal: adapter.config.googledriveMinimalDir
};
const cifs = {
enabled: adapter.config.cifsEnabled,
mountType: adapter.config.connectType,
type: 'storage',
source: adapter.config.restoreSource,
mount: adapter.config.cifsMount,
debugging: adapter.config.debugLevel,
fileDir: __dirname,
wakeOnLAN: adapter.config.wakeOnLAN,
macAd: adapter.config.macAd,
wolTime: adapter.config.wolWait,
smb: adapter.config.smbType,
sudo: adapter.config.sudoMount,
cifsDomain: adapter.config.cifsDomain,
deleteOldBackup: adapter.config.cifsDeleteOldBackup, //Delete old Backups from Network Disk
ownDir: adapter.config.cifsOwnDir,
bkpType: adapter.config.restoreType,
dir: (adapter.config.cifsOwnDir === true) ? null : adapter.config.cifsDir, // specify if CIFS mount should be used
dirMinimal: adapter.config.cifsMinimalDir,
user: adapter.config.cifsUser, // specify if CIFS mount should be used
pass: adapter.config.cifsPassword ? decrypt(secret, adapter.config.cifsPassword) : '' // password for NAS Server
};
// TODO: Not used anywere
const mysql = {
enabled: adapter.config.mySqlEnabled === undefined ? true : adapter.config.mySqlEnabled,
type: 'creator',
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
nameSuffix: adapter.config.minimalNameSuffix, // names addition, appended to the file name
mysqlQuick: adapter.config.mysqlQuick,
mysqlSingleTransaction: adapter.config.mysqlSingleTransaction,
dbName: adapter.config.mySqlName, // database name
user: adapter.config.mySqlUser, // database user
pass: adapter.config.mySqlPassword ? decrypt(secret, adapter.config.mySqlPassword) : '', // database password
deleteBackupAfter: adapter.config.mySqlDeleteAfter, // delete old backupfiles after x days
host: adapter.config.mySqlHost, // database host
port: adapter.config.mySqlPort, // database port
exe: adapter.config.mySqlDumpExe // path to mysqldump
};
// Configurations for standard-IoBroker backup
backupConfig.iobroker = {
name: 'iobroker',
type: 'creator',
enabled: adapter.config.minimalEnabled,
time: adapter.config.minimalTime,
debugging: adapter.config.debugLevel,
everyXDays: adapter.config.minimalEveryXDays,
nameSuffix: adapter.config.minimalNameSuffix, // names addition, appended to the file name
deleteBackupAfter: adapter.config.minimalDeleteAfter, // delete old backupfiles after x days
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
mysql: {
enabled: adapter.config.mySqlEnabled === undefined ? true : adapter.config.mySqlEnabled,
type: 'creator',
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
nameSuffix: adapter.config.minimalNameSuffix, // names addition, appended to the file name
mysqlQuick: adapter.config.mysqlQuick,
mysqlSingleTransaction: adapter.config.mysqlSingleTransaction,
dbName: adapter.config.mySqlName, // database name
user: adapter.config.mySqlUser, // database user
pass: adapter.config.mySqlPassword ? decrypt(secret, adapter.config.mySqlPassword) : '', // database password
deleteBackupAfter: adapter.config.mySqlDeleteAfter, // delete old backupfiles after x days
host: adapter.config.mySqlHost, // database host
port: adapter.config.mySqlPort, // database port
exe: adapter.config.mySqlDumpExe // path to mysqldump
},
dir: tools.getIobDir(),
redis: {
enabled: adapter.config.redisEnabled,
type: 'creator',
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
path: adapter.config.redisPath || '/var/lib/redis', // specify Redis path
},
historyDB: {
enabled: adapter.config.historyEnabled,
type: 'creator',
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
path: adapter.config.historyPath,
},
zigbee: {
enabled: adapter.config.zigbeeEnabled,
type: 'creator',
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpMinimalDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsMinimalDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxMinimalDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveMinimalDir } : {}),
path: tools.getIobDir() + '/iobroker-data', // specify zigbee path
},
history,
telegram,
email,
pushover,
whatsapp,
};
// Configurations for CCU / pivCCU / RaspberryMatic backup
backupConfig.ccu = {
name: 'ccu',
type: 'creator',
enabled: adapter.config.ccuEnabled,
time: adapter.config.ccuTime,
debugging: adapter.config.debugLevel,
everyXDays: adapter.config.ccuEveryXDays,
nameSuffix: adapter.config.ccuNameSuffix, // names addition, appended to the file name
deleteBackupAfter: adapter.config.ccuDeleteAfter, // delete old backupfiles after x days
ftp: Object.assign({}, ftp, (adapter.config.ftpOwnDir === true) ? { dir: adapter.config.ftpCcuDir } : {}),
cifs: Object.assign({}, cifs, (adapter.config.cifsOwnDir === true) ? { dir: adapter.config.cifsCcuDir } : {}),
dropbox: Object.assign({}, dropbox, (adapter.config.dropboxOwnDir === true) ? { dir: adapter.config.dropboxCcuDir } : {}),
googledrive: Object.assign({}, googledrive, (adapter.config.googledriveOwnDir === true) ? { dir: adapter.config.googledriveCcuDir } : {}),
history,
telegram,
email,
pushover,
whatsapp,
host: adapter.config.ccuHost, // IP-address CCU
user: adapter.config.ccuUser, // username CCU
pass: adapter.config.ccuPassword ? decrypt(secret, adapter.config.ccuPassword) : '', // password der CCU
};
}
function readLogFile() {
try {
const logName = path.join(tools.getIobDir(), 'backups', 'logs.txt').replace(/\\/g, '/');
if (fs.existsSync(logName)) {
adapter.log.debug(`Printing logs of previous backup`);
const text = fs.readFileSync(logName).toString();
const lines = text.split('\n');
lines.forEach((line, i) => lines[i] = line.replace(/\r$|^\r/, ''));
lines.forEach(line => {
line = line.trim();
if (line) {
//if (line.startsWith('[DEBUG] [total/total] Packed ')) return;
if (line.startsWith('[ERROR]')) {
adapter.log.error(line);
} else {
adapter.log.debug(line);
}
adapter.setState('output.line', line);
}
});
adapter.setState('output.line', '[EXIT] 0');
fs.unlinkSync(logName);
// make the messaging
config.afterBackup = true;
executeScripts(adapter, config, err => {
});
}
} catch (e) {
adapter.log.warn(`Cannot read log file: ${e}`);
}
}
function createBashScripts() {
const isWin = process.platform.startsWith('win');
if (isWin) {
if (!fs.existsSync(__dirname + '/lib/stopIOB.bat')) {
try {
fs.writeFileSync(__dirname + '/lib/stopIOB.bat', `cd "${path.join(tools.getIobDir())}"\ncall iobroker stop\ntimeout /T 10\nif exist "${path.join(__dirname, 'lib/.redis.info')}" (\nredis-server --service-stop\n)\ncd "${path.join(__dirname, 'lib')}"\nnode restore.js`);
} catch (e) {
adapter.log.error('cannot create stopIOB.bat: ' + e + 'Please run "iobroker fix"');
}
}
if (!fs.existsSync(__dirname + '/lib/startIOB.bat')) {
try {
fs.writeFileSync(__dirname + '/lib/startIOB.bat', `if exist "${path.join(__dirname, 'lib/.redis.info')}" (\nredis-server --service-start\n)\ncd "${path.join(tools.getIobDir())}"\niobroker host this\ncall iobroker start\nif exist "${path.join(__dirname, 'lib/.startAll')}" (\ncd "${path.join(tools.getIobDir(), 'node_modules/iobroker.js-controller')}"\nnode iobroker.js start all\n)`);
} catch (e) {
adapter.log.error('cannot create startIOB.bat: ' + e + 'Please run "iobroker fix"');
}
}
} else {
if (!fs.existsSync(__dirname + '/lib/stopIOB.sh')) {
try {
fs.writeFileSync(__dirname + '/lib/stopIOB.sh', `# iobroker stop for restore\nsudo systemd-run --uid=iobroker bash ${path.join(__dirname, 'lib')}/external.sh`);
fs.chmodSync(__dirname + '/lib/stopIOB.sh', 508);
} catch (e) {
adapter.log.error('cannot create stopIOB.sh: ' + e + 'Please run "iobroker fix"');
}
}
if (!fs.existsSync(__dirname + '/lib/startIOB.sh')) {
try {
fs.writeFileSync(__dirname + '/lib/startIOB.sh', `# iobroker start after restore\nif [ -f ${path.join(__dirname, 'lib')}/.redis.info ] ; then\nsudo systemctl start redis-server\nfi\niobroker host this\nif [ -f ${path.join(__dirname, 'lib')}\.startAll ] ; then\ncd "${path.join(tools.getIobDir())}"\niobroker start all\nfi\ncd "${path.join(tools.getIobDir())}"\nbash iobroker start`);
fs.chmodSync(__dirname + '/lib/startIOB.sh', 508);
} catch (e) {
adapter.log.error('cannot create startIOB.sh: ' + e + 'Please run "iobroker fix"');
}
}
if (!fs.existsSync(__dirname + '/lib/external.sh')) {
try {
fs.writeFileSync(__dirname + '/lib/external.sh', `# restore\nif [ -f ${path.join(__dirname, 'lib')}/.redis.info ] ; then\nsudo systemctl stop redis-server\nfi\ncd "${path.join(tools.getIobDir())}"\nbash iobroker stop;\ncd "${path.join(__dirname, 'lib')}"\nnode restore.js`);
fs.chmodSync(__dirname + '/lib/external.sh', 508);
} catch (e) {
adapter.log.error('cannot create external.sh: ' + e + 'Please run "iobroker fix"');
}
}
}
}
// umount after restore
function umount() {
const backupDir = path.join(tools.getIobDir(), 'backups');
const child_process = require('child_process');
if (fs.existsSync(__dirname + '/.mount')) {
child_process.exec(`mount | grep -o "${backupDir}"`, (error, stdout, stderr) => {
if (stdout.indexOf(backupDir) !== -1) {
adapter.log.debug('mount activ... umount in 2 Seconds!!');
timerUmount1 = setTimeout(() =>
child_process.exec(`${adapter.config.sudoMount ? 'sudo umount' : 'umount'} ${backupDir}`, (error, stdout, stderr) => {
if (error) {
adapter.log.debug('umount: device is busy... wait 5 Minutes!!');
timerUmount2 = setTimeout(() =>
child_process.exec(`${adapter.config.sudoMount ? 'sudo umount' : 'umount'} ${backupDir}`, (error, stdout, stderr) => {
if (error) {
adapter.log.error(error);
} else {
adapter.log.debug('umount successfully completed');
try {
fs.existsSync(__dirname + '/.mount') && fs.unlinkSync(__dirname + '/.mount');
} catch (e) {
adapter.log.debug('file ".mount" not deleted ...');
}
}
}), 300000);
} else {
adapter.log.debug('umount successfully completed');
try {
fs.existsSync(__dirname + '/.mount') && fs.unlinkSync(__dirname + '/.mount');
} catch (e) {
adapter.log.debug('file ".mount" not deleted ...');
}
}
}), 2000);
} else {
adapter.log.debug('mount inactiv!!');
}
});
}
}
// Create Backupdir on first start
function createBackupDir() {
if (!fs.existsSync(path.join(tools.getIobDir(), 'backups'))) {
try {
fs.mkdirSync(path.join(tools.getIobDir(), 'backups'));
adapter.log.debug('Created BackupDir');
} catch (e) {
adapter.log.warn('Backup folder not created: ' + e + 'Please run "iobroker fix" and try again or create the backup folder manually!!');
}
}
}
// delete Hide Files after restore
function deleteHideFiles() {
fs.existsSync(__dirname + '/lib/.redis.info') && fs.unlinkSync(__dirname + '/lib/.redis.info');
}
// delete temp dir after restore
function delTmp() {
if (fs.existsSync(path.join(tools.getIobDir(), 'backups/tmp'))) {
try {
fs.rmdirSync(path.join(tools.getIobDir(), 'backups/tmp'));
adapter.log.debug('delete tmp files');
} catch (e) {
adapter.log.warn('can not delete tmp files: ' + e + 'Please run "iobroker fix" and try again or delete the tmp folder manually!!');
}
}
}
// set start Options after restore
function setStartAll() {
if (adapter.config.startAllRestore == true && !fs.existsSync(__dirname + '/lib/.startAll')) {
try {
fs.writeFileSync(__dirname + '/lib/.startAll', 'Start all Adapter after Restore');
adapter.log.debug('Start all Adapter after Restore enabled');
} catch (e) {
adapter.log.warn('can not create startAll files: ' + e + 'Please run "iobroker fix" and try again');
}
} else if (adapter.config.startAllRestore == false && fs.existsSync(__dirname + '/lib/.startAll')) {
try {
fs.unlinkSync(__dirname + '/lib/.startAll');
adapter.log.debug('Start all Adapter after Restore disabled');
} catch (e) {
adapter.log.warn('can not delete startAll file: ' + e + 'Please run "iobroker fix" and try again');
}
}
}
function getName(name, filenumbers) {
try {
const parts = name.split('_');
if (parseInt(parts[0], 10).toString() !== parts[0]) {
parts.shift();
}
adapter.log.debug(name ? 'detect backup file ' + filenumbers + ': ' + name : 'No backup name was found');
return new Date(
parts[0],
parseInt(parts[1], 10) - 1,
parseInt(parts[2].split('-')[0], 10),
parseInt(parts[2].split('-')[1], 10),
parseInt(parts[3], 10));
} catch (err) {
if (err) {
adapter.log.warn('No backup name was found');
}
}
}
function detectLatestBackupFile(adapter) {
// get all 'storage' types that enabled
try {
const stores = Object.keys(backupConfig.iobroker)
.filter(attr =>
typeof backupConfig.iobroker[attr] === 'object' &&
backupConfig.iobroker[attr].type === 'storage' &&
backupConfig.iobroker[attr].enabled);
// read one time all stores to detect if some backups detected
const promises = stores.map(storage => new Promise(resolve =>
list(storage, backupConfig, adapter.log, result => {
// find newest file
let file = null;
if (result && result.data && result.data !== 'undefined') {
let filenumbers = 0;
const data = result.data;
Object.keys(data).forEach(type => {
data[type].iobroker && data[type].iobroker
.filter(f => f.size)
.forEach(f => {
filenumbers++;
const date = getName(f.name, filenumbers);
if (!file || file.date < date) {
file = f;
file.date = date;
file.storage = storage;
}
});
});
}
resolve(file);
})));
// find the newest file between storages
Promise.all(promises)
.then(results => {
results = results.filter(f => f);
let file;
if (results.length) {
results.sort((a, b) => {
if (a.date > b.date) {
return 1;
} else if (a.date < b.date) {
return -1;
} else {
return 0;
}
});
file = results[0];
if (file.date !== undefined) {
try {
file.date = file.date.toISOString();
} catch (e) {
adapter.log.warn('No backup file date was found: ' + e);
}
}
} else {
file = null;
}
// this information will be used by admin at the first start if some backup was detected and we can restore from it instead of new configuration
adapter.setState('info.latestBackup', file ? JSON.stringify(file) : '', true);
adapter.log.debug(file ? 'detect last backup file: ' + file.name : 'No backup file was found');
});
} catch (e) {
adapter.log.warn('No backup file was found');
}
}
function delOldObjects() {
adapter.getState('history.minimalSuccess', (err, state) => {
if (state) {
adapter.delObject('history.minimalSuccess');
}
});
adapter.getState('history.minimalLastTime', (err, state) => {
if (state) {
adapter.delObject('history.minimalLastTime');
}
});
adapter.getState('history.totalLastTime', (err, state) => {
if (state) {
adapter.delObject('history.totalLastTime');
}
});
adapter.getState('history.totalSuccess', (err, state) => {
if (state) {
adapter.delObject('history.totalSuccess');
}
});
adapter.getState('oneClick.minimal', (err, state) => {
if (state) {
adapter.delObject('oneClick.minimal');
}
});
adapter.getState('oneClick.total', (err, state) => {
if (state) {
adapter.delObject('oneClick.total');
}
});
}
function nextBackup(diffDays, setMain, type, date) {
date = date || new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let currentTime = (hours + ':' + minutes);
if (adapter.config.ccuEnabled == true && setMain == true || type == 'ccu') {
if (adapter.config.ccuTime < currentTime) {
diffDays = 0;
}
let everyXDays = (parseFloat(adapter.config.ccuEveryXDays) - diffDays);
adapter.setState(`info.ccuNextTime`, tools.getNextTimeString(systemLang, adapter.config.ccuTime, parseFloat(everyXDays)), true);
diffDays = 1;
} else if (adapter.config.ccuEnabled == false) {
adapter.setState(`info.ccuNextTime`, 'none', true);
}
if (adapter.config.minimalEnabled == true && setMain == true || type == 'iobroker') {
if (adapter.config.minimalTime < currentTime) {
diffDays = 0;
}
let everyXDays = (parseFloat(adapter.config.minimalEveryXDays) - diffDays);
adapter.setState(`info.iobrokerNextTime`, tools.getNextTimeString(systemLang, adapter.config.minimalTime, parseFloat(everyXDays)), true);
} else if (adapter.config.minimalEnabled == false) {
adapter.setState(`info.iobrokerNextTime`, 'none', true);
}
}
function main(adapter) {
createBashScripts();
readLogFile();
createBackupDir();
deleteHideFiles();
delTmp();
delOldObjects();
timerMain = setTimeout(function () {
umount();
setStartAll();
}, 10000);
adapter.getForeignObject('system.config', (err, obj) => {
systemLang = obj.common.language;
initConfig((obj && obj.native && obj.native.secret) || 'Zgfr56gFe87jJOM');
checkStates();
createBackupSchedule();
nextBackup(1, true, null);
detectLatestBackupFile(adapter);
});
// subscribe on all variables of this adapter instance with pattern "adapterName.X.memory*"
adapter.subscribeStates('oneClick.*');
}
// If started as allInOne/compact mode => return function to create instance
if (module && module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}