/**
 * Minified by jsDelivr using Terser v5.48.0.
 * Original file: /npm/iobroker.backitup@4.0.3/build/main.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var o=Object.getOwnPropertyDescriptor(t,i);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,o)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),__setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),__importStar=this&&this.__importStar||function(){var e=function(t){return e=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},e(t)};return function(t){if(t&&t.__esModule)return t;var i={};if(null!=t)for(var s=e(t),o=0;o<s.length;o++)"default"!==s[o]&&__createBinding(i,t,s[o]);return __setModuleDefault(i,t),i}}(),__importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const node_fs_1=require("node:fs"),node_path_1=require("node:path"),adapter_core_1=require("@iobroker/adapter-core"),schedule=__importStar(require("node-schedule")),tools=__importStar(require("./lib/tools")),execute_1=__importDefault(require("./lib/execute")),systemCheck=__importStar(require("./lib/systemCheck")),tokenRefresher_1=__importDefault(require("./lib/tokenRefresher")),bashDir=(0,node_path_1.join)((0,adapter_core_1.getAbsoluteDefaultDataDir)(),"backitup").replace(/\\/g,"/");let http,https;function decrypt(e,t){let i="";for(let s=0;s<t.length;s++)i+=String.fromCharCode(e[s%e.length].charCodeAt(0)^t.charCodeAt(s));return i}function serverPort(e){return e.address().port}class BackItUp extends adapter_core_1.Adapter{timerOutput;timerOutput2;timerUmount1;timerUmount2;timerMain;slaveTimeOut;waitToSlaveBackup;dlServer;ulServer;systemLang="de";backupConfig={};backupTimeSchedules=[];taskRunning=!1;dropBoxTokenRefresher=null;constructor(e={}){super({...e,name:"backitup"}),this.on("stateChange",this.onStateChange.bind(this)),this.on("ready",this.onReady.bind(this)),this.on("unload",this.onUnload.bind(this)),this.on("message",this.onMessage.bind(this))}async onStateChange(e,t){if(this.dropBoxTokenRefresher?.onStateChange(e,t),e===`${this.namespace}.info.dropboxTokens`&&(await this.updateAccessTokens(this.backupConfig),this.log.debug("Config Update for Dropbox Token")),t&&(!0===t.val||"true"===t.val)&&!t.ack&&(e===`${this.namespace}.oneClick.iobroker`||e===`${this.namespace}.oneClick.ccu`)){const t=await systemCheck.storageSizeCheck(this,"backitup",this.log),i=e.split(".").pop();if(!0===t?.ready||!0===this.config.cifsEnabled){let e;try{e=JSON.parse(JSON.stringify(this.backupConfig[i])),e.enabled=!0,e.deleteBackupAfter=0}catch(e){this.log.warn(`backup error: ${e.stack}`),this.log.warn(`backup error: ${e} ... please check your config and try again!!`)}this.startBackup(e,e=>{e?this.log.error(`[${i}] ${e}`):this.log.debug(`[${i}] exec: done`),this.timerOutput=setTimeout(()=>{this.readRunResult(i,()=>{this.config.onedriveEnabled&&"Single"===this.config.hostType&&this.renewOnedriveToken()})},500),this.setState(`oneClick.${i}`,!1,!0),this.config.slaveInstance&&"iobroker"===i&&"Master"===this.config.hostType&&(this.log.debug("Slave backup from BackItUp-Master is started ..."),this.startSlaveBackup(this.config.slaveInstance[0],null))})}else this.log.error(`A local backup is currently not possible. The storage space is currently only ${t&&t.diskFree?t.diskFree:null} MB`),systemCheck.systemMessage(this,tools._("A local backup is currently not possible. Please check your System!",this.systemLang)),this.setState(`oneClick.${i}`,!1,!0),this.setState("output.line",`[EXIT] ${tools._("A local backup is currently not possible. Please check your System!",this.systemLang)}`,!0)}}async onReady(){try{await this.main()}catch{}}onUnload(e){try{if(this.dropBoxTokenRefresher?.destroy(),this.log.info("cleaned everything up..."),clearTimeout(this.timerOutput2),clearTimeout(this.timerOutput),clearTimeout(this.timerUmount1),clearTimeout(this.timerUmount2),clearTimeout(this.timerMain),clearTimeout(this.slaveTimeOut),clearTimeout(this.waitToSlaveBackup),this.dlServer){try{this.dlServer.closeAllConnections()}catch(e){this.log.debug(`Download server Connections could not be closed: ${e}`)}try{this.dlServer.close()}catch(e){this.log.debug(`Download server Connections could not be closed: ${e}`)}}if(this.ulServer){try{this.ulServer.closeAllConnections()}catch(e){this.log.debug(`Upload server connections could not be closed: ${e}`)}try{this.ulServer.close()}catch(e){this.log.debug(`Upload server connections could not be closed: ${e}`)}}}catch(e){console.log(`Cannot unload: ${e}`)}e()}async onMessage(e){if(e)switch(e.command){case"list":try{const t=require("./lib/list").default;this.log.debug("Reading backup list..."),await this.updateAccessTokens(this.backupConfig),t(e.message,this.backupConfig,this.log,t=>{this.log.debug(`Backup list was read: ${JSON.stringify(t)}`),e.callback&&this.sendTo(e.from,e.command,t,e.callback)})}catch{this.log.debug("Backup list cannot be read ...")}break;case"authGoogleDrive":{const t=require("./lib/googleDriveLib").default;if(e.callback){(new t).getAuthorizeUrl().then(t=>this.sendTo(e.from,e.command,{url:t},e.callback))}break}case"authDropbox":e.callback&&tokenRefresher_1.default.getAuthUrl("https://oauth2.iobroker.in/dropbox").then(t=>this.sendTo(e.from,e.command,{url:t},e.callback));break;case"authOnedrive":{const t=require("./lib/oneDriveLib").default;if(e.message&&e.message.code){(new t).getRefreshToken(e.message.code,this.log).then(t=>this.sendTo(e.from,e.command,{done:!0,json:t},e.callback)).catch(t=>this.sendTo(e.from,e.command,{error:t},e.callback))}else if(e.callback){(new t).getAuthorizeUrl(this.log).then(t=>this.sendTo(e.from,e.command,{url:t},e.callback)).catch(t=>this.sendTo(e.from,e.command,{error:t},e.callback))}break}case"restore":if(e.message){e.message.stopIOB&&await this.getCerts(e.from),this.log.info(`DATA: ${JSON.stringify(e.message)}`),await this.updateAccessTokens(this.backupConfig);require("./lib/restore").restore(this,this.backupConfig,e.message.type,e.message.fileName,e.message.currentTheme,e.message.currentProtocol,bashDir,this.log,t=>e.callback&&this.sendTo(e.from,e.command,t,e.callback))}else e.callback&&this.invalidParameters(e);break;case"uploadFile":if(e.message&&e.message.protocol){if(this.ulServer&&this.ulServer._connectionKey&&this.ulServer.listening)this.log.debug(`Upload server is running on Port ${serverPort(this.ulServer)}...`);else{"https:"===e.message.protocol&&await this.getCerts(e.from);try{this.ulFileServer(e.message.protocol)}catch{this.log.debug("Upload server cannot started")}}try{this.sendTo(e.from,e.command,{listenPort:serverPort(this.ulServer)},e.callback)}catch(t){this.sendTo(e.from,e.command,{e:t},e.callback)}}else e.callback&&this.invalidParameters(e);break;case"getFile":if(e.message&&e.message.type&&e.message.fileName&&e.message.protocol){if(this.dlServer&&this.dlServer._connectionKey&&this.dlServer.listening)this.log.debug(`Download server is running on port ${serverPort(this.dlServer)}...`);else{"https:"===e.message.protocol&&await this.getCerts(e.from);try{this.dlFileServer(e.message.protocol)}catch{this.log.debug("Downloadserver cannot started")}}const t=e.message.fileName.split("/").pop();if("local"!==e.message.type){const i=(0,node_path_1.join)(tools.getIobDir(),"backups"),s=(0,node_path_1.join)(i,t),o=require("./lib/restore");await this.updateAccessTokens(this.backupConfig),o.getFile(this.backupConfig,e.message.type,e.message.fileName,s,this.log,i=>{if(!i&&(0,node_fs_1.existsSync)(s))try{this.sendTo(e.from,e.command,{fileName:t,listenPort:serverPort(this.dlServer)},e.callback)}catch(t){this.sendTo(e.from,e.command,{error:t},e.callback)}else this.log.warn(`File ${s} not found`)})}else if((0,node_fs_1.existsSync)(e.message.fileName))try{this.sendTo(e.from,e.command,{fileName:t,listenPort:serverPort(this.dlServer)},e.callback)}catch(t){this.sendTo(e.from,e.command,{error:t},e.callback)}}else e.callback&&this.invalidParameters(e);break;case"serverClose":e.message&&e.message.downloadFinish&&!e.message.uploadFinish?(this.log.debug("Download finished..."),this.sendTo(e.from,e.command,{serverClose:!0},e.callback)):e.message&&e.message.uploadFinish&&!e.message.downloadFinish?(this.log.debug("Upload finished..."),this.sendTo(e.from,e.command,{serverClose:!0},e.callback)):e.callback&&this.invalidParameters(e);break;case"getTelegramUser":if(e&&e.message){const t=e.message.config.instance?e.message.config.instance:this.config.telegramInstance;this.getForeignState(`${t}.communicate.users`,(t,i)=>{if(t&&this.log.error(t),i&&i.val)try{this.sendTo(e.from,e.command,i.val,e.callback)}catch(t){t&&this.log.error(t),this.log.error("Cannot parse stored user IDs from Telegram!")}})}break;case"getSystemInfo":if(e){let t=process.platform,i=!1;if((0,node_fs_1.existsSync)("/opt/scripts/.docker_config/.thisisdocker"))t="docker",(0,node_fs_1.existsSync)("/opt/scripts/.docker_config/.backitup")&&(i=!0);else{process.platform.startsWith("win")&&(t="win")}try{this.sendTo(e.from,e.command,{systemOS:t,dockerDB:i,backupDir:(0,node_path_1.join)(tools.getIobDir(),"backups")},e.callback)}catch(e){e&&this.log.error(e)}}break;case"getFileSystemInfo":if(e){const t=await systemCheck.storageSizeCheck(this,"backitup",this.log);if(t)try{this.sendTo(e.from,e.command,t,e.callback)}catch(e){e&&this.log.error(e)}}break;case"testWebDAV":if(e.message){const{createClient:t}=await import("webdav"),i=new(require("node:https").Agent)({rejectUnauthorized:Boolean(e.message.config.signedCertificates)});t(e.message.config.host,{username:e.message.config.username,password:e.message.config.password,maxBodyLength:1/0,httpsAgent:i}).getDirectoryContents("").then(t=>e.callback&&this.sendTo(e.from,e.command,t,e.callback)).catch(t=>this.sendTo(e.from,e.command,{error:JSON.stringify(t.message)},e.callback))}break;case"slaveBackup":if(e?.message)if("Slave"===this.config.hostType){this.log.debug("Slave Backup started ...");const t="iobroker";let i;try{i=JSON.parse(JSON.stringify(this.backupConfig[t])),i.enabled=!0,i.deleteBackupAfter=e.message.config.deleteAfter?e.message.config.deleteAfter:0}catch(e){this.log.warn(`backup error: ${e} ... please check your config and try again!!`)}this.startBackup(i,i=>{i?this.log.error(`[${t}] ${i}`):this.log.debug(`[${t}] exec: done`);const s=t=>{if(null!==t)try{this.sendTo(e.from,e.command,t,e.callback)}catch(e){e&&this.log.error(e),this.log.error("slave Backup not finish!")}};this.timerOutput=setTimeout(()=>this.readRunResult(t,e=>{s(e),this.config.onedriveEnabled&&this.renewOnedriveToken()},s),500),this.setState(`oneClick.${t}`,!1,!0)})}else this.log.warn("Your BackItUp Instance is not configured as a slave"),this.sendTo(e.from,e.command,"not configured as a slave",e.callback);break;case"slaveInstance":if(e&&"slaveInstance"===e.command&&e.message&&e.message.instance){const t=[],i=await this.getObjectViewAsync("system","instance",{startkey:`system.adapter.${e.message.instance}.`,endkey:`system.adapter.${e.message.instance}.香`}).catch(e=>this.log.error(e));i&&i.rows&&0!=i.rows.length&&i.rows.forEach(e=>{e.id.replace("system.adapter.","")!=this.namespace&&t.push({label:e.id.replace("system.adapter.",""),value:e.id.replace("system.adapter.","")})}),this.sendTo(e.from,e.command,t,e.callback)}break;case"getLog":{const t=(0,node_path_1.join)(bashDir,`${this.namespace}.log`).replace(/\\/g,"/");if((0,node_fs_1.existsSync)(t)&&(e?.message.backupName||e?.message.timestamp)){const i=(0,node_fs_1.readFileSync)(t,"utf8"),s=JSON.parse(i),o=e?.message.backupName?e.message.backupName:null,n=e?.message.timestamp;let r=!1;s.forEach((t,i)=>{Object.prototype.hasOwnProperty.call(t,n)?(r=!0,this.log.debug("Printing logs of previous backup"),this.sendTo(e.from,e.command,t[n],e.callback)):null!==o&&Object.prototype.hasOwnProperty.call(t,o)?(r=!0,this.log.debug("Printing logs of previous backup"),this.sendTo(e.from,e.command,t[o],e.callback)):s.length-1!=i||r||(this.log.debug("No Backuplogs found"),this.sendTo(e.from,e.command,tools._("No log is available for this backup",this.systemLang),e.callback))})}break}}}async updateAccessTokens(e){if(this.dropBoxTokenRefresher)try{const t=await this.dropBoxTokenRefresher.getAccessToken();Object.keys(e).forEach(i=>{e[i]&&"object"==typeof e[i]&&(e[i].dropbox?e[i].dropbox.accessToken=t:Object.keys(e[i]).forEach(s=>{e[i][s]?.dropbox&&(e[i][s].dropbox.accessToken=t)}))})}catch(e){this.log.error(`Cannot get access tokens for DropBox: ${e}`)}}async startBackup(e,t){if(this.taskRunning)setTimeout(()=>{this.startBackup(e,t)},1e4);else{this.taskRunning=!0;try{(0,execute_1.default)(this,e,e=>{this.taskRunning=!1,t?.(e)}),this.log.debug("Backup has started ...")}catch(e){this.log.warn(`Backup error: ${e.stack}`),this.log.warn(`Backup error: ${e} ... please check your config and and try again!!`)}}}readRunResult(e,t,i){this.getState("output.line",(s,o)=>{o&&"[EXIT] 0"===o.val?(this.setState(`history.${e}Success`,!0,!0),this.setState(`history.${e}LastTime`,tools.getTimeString(this.systemLang),!0),t?.(o.val)):(this.setState(`history.${e}LastTime`,`error: ${tools.getTimeString(this.systemLang)}`,!0),this.setState(`history.${e}Success`,!1,!0),i?.(o?.val?o.val:null))})}invalidParameters(e){this.sendTo(e.from,e.command,{error:"Invalid parameters"},e.callback)}async checkStates(){const e=await this.getStateAsync("history.html");e&&null!==e.val||await this.setStateAsync("history.html",{val:`<span class="backup-type-total">${tools._("No backups yet",this.systemLang)}</span>`,ack:!0});const t=await this.getStateAsync("history.iobrokerLastTime");t&&null!==t.val||await this.setStateAsync("history.iobrokerLastTime",{val:tools._("No backups yet",this.systemLang),ack:!0});const i=await this.getStateAsync("history.ccuLastTime");i&&null!==i.val||await this.setStateAsync("history.ccuLastTime",{val:tools._("No backups yet",this.systemLang),ack:!0});const s=await this.getStateAsync("oneClick.iobroker");s&&null!==s.val&&!0!==s.val||await this.setStateAsync("oneClick.iobroker",{val:!1,ack:!0});const o=await this.getStateAsync("oneClick.ccu");o&&null!==o.val&&!0!==o.val||await this.setStateAsync("oneClick.ccu",{val:!1,ack:!0});const n=await this.getStateAsync("history.ccuSuccess");n&&null!==n.val||await this.setStateAsync("history.ccuSuccess",{val:!1,ack:!0});const r=await this.getStateAsync("history.iobrokerSuccess");r&&null!==r.val||await this.setStateAsync("history.iobrokerSuccess",{val:!1,ack:!0});const a=await this.getStateAsync("history.json");a&&null!==a.val||await this.setStateAsync("history.json",{val:"[]",ack:!0})}createBackupSchedule(){for(const e in this.backupConfig){if(!Object.prototype.hasOwnProperty.call(this.backupConfig,e))continue;const t=this.backupConfig[e];if(!0===t.enabled||"true"===t.enabled){const i=t.ownCron?t.cronjob:t.time.split(":"),s=t.ownCron?`with Cronjob "${t.cronjob}"`:`at ${t.time} every ${t.everyXDays} day(s)`;this.log.info(`[${e}] backup will be activated ${s}`),this.backupTimeSchedules[e]&&this.backupTimeSchedules[e].cancel();const o=t.ownCron?i:`10 ${i[1]} ${i[0]} */${t.everyXDays} * * `;this.backupTimeSchedules[e]=schedule.scheduleJob(o,async()=>{const t=await systemCheck.storageSizeCheck(this,"backitup",this.log);t&&t.ready&&!0===t.ready||!0===this.config.cifsEnabled?(this.setState(`oneClick.${e}`,!0,!0),this.startBackup(this.backupConfig[e],t=>{t?this.log.error(`[${e}] ${t}`):this.log.debug(`[${e}] exec: done`),this.timerOutput2=setTimeout(()=>this.readRunResult(e,()=>{this.config.onedriveEnabled&&"Single"===this.config.hostType&&this.renewOnedriveToken()}),500),this.nextBackup(!1,e),this.setState(`oneClick.${e}`,!1,!0),this.config.slaveInstance&&"iobroker"===e&&"Master"===this.config.hostType&&(this.log.debug("Slave backup from BackItUp-Master is started ..."),this.startSlaveBackup(this.config.slaveInstance[0],null))})):(this.log.error(`A local backup is currently not possible. The storage space is currently only ${t&&t.diskFree?t.diskFree:null} MB`),systemCheck.systemMessage(this,tools._("A local backup is currently not possible. Please check your System!",this.systemLang)))}),t.debugging&&this.log.debug(`[${e}] ${o}`)}else this.backupTimeSchedules[e]&&(this.log.info(`[${e}] backup deactivated`),this.backupTimeSchedules[e].cancel(),this.backupTimeSchedules[e]=null)}}async initConfig(e){const t=this.systemLang;let i;"CIFS"===this.config.cifsMount&&(this.config.cifsMount=""),void 0===this.config.redisEnabled&&(this.config.redisEnabled=this.config.backupRedis);try{i=(0,node_path_1.resolve)(__dirname,"../../iobroker.js-controller/iobroker.js")}catch(e){this.log.error(`Unable to read iobroker path: +${e}`)}this.decryptEvents(e);const s=this.config.minimalNameSuffix?this.config.minimalNameSuffix.replace(/[.;, ]/g,"_"):"",o=this.config.ignoreErrors,n=this.config.notificationsType,r=this.config.notificationEnabled,a={enabled:r,notificationsType:n,type:"message",instance:this.config.telegramInstance,SilentNotice:this.config.telegramSilentNotice,NoticeType:this.config.telegramNoticeType,User:this.config.telegramUser,onlyError:this.config.telegramOnlyError,telegramWaiting:1e3*this.config.telegramWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},c={enabled:r,notificationsType:n,type:"message",instance:this.config.whatsappInstance,NoticeType:this.config.whatsappNoticeType,onlyError:this.config.whatsappOnlyError,whatsappWaiting:1e3*this.config.whatsappWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},l={enabled:r,notificationsType:n,type:"message",instance:this.config.gotifyInstance,NoticeType:this.config.gotifyNoticeType,onlyError:this.config.gotifyOnlyError,gotifyWaiting:1e3*this.config.gotifyWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},h={enabled:r,notificationsType:n,type:"message",instance:this.config.signalInstance,NoticeType:this.config.signalNoticeType,onlyError:this.config.signalOnlyError,signalWaiting:1e3*this.config.signalWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},g={enabled:r,notificationsType:n,type:"message",instance:this.config.matrixInstance,NoticeType:this.config.matrixNoticeType,onlyError:this.config.matrixOnlyError,matrixWaiting:1e3*this.config.matrixWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},d={enabled:r,notificationsType:n,type:"message",instance:this.config.discordInstance,NoticeType:this.config.discordNoticeType,target:this.config.discordTarget,onlyError:this.config.discordOnlyError,discordWaiting:1e3*this.config.discordWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},f={enabled:r,notificationsType:n,type:"message",instance:this.config.pushoverInstance,SilentNotice:this.config.pushoverSilentNotice,NoticeType:this.config.pushoverNoticeType,deviceID:this.config.pushoverDeviceID,onlyError:this.config.pushoverOnlyError,pushoverWaiting:1e3*this.config.pushoverWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},u={enabled:r,notificationsType:n,type:"message",instance:this.config.emailInstance,NoticeType:this.config.emailNoticeType,emailReceiver:this.config.emailReceiver,emailSender:this.config.emailSender,onlyError:this.config.emailOnlyError,emailWaiting:1e3*this.config.emailWaitToSend,hostName:s,ignoreErrors:o,systemLang:t},p={type:"message",ignoreErrors:o,bashDir:bashDir,entriesNumber:this.config.historyEntriesNumber,systemLang:t},b={enabled:!0,type:"message",entriesNumber:this.config.historyEntriesNumber,ignoreErrors:o,systemLang:t},m={enabled:!0,type:"message",entriesNumber:this.config.historyEntriesNumber,ignoreErrors:o,systemLang:t},y={enabled:this.config.ftpEnabled,type:"storage",source:this.config.restoreSource,host:this.config.ftpHost,debugging:this.config.debugLevel,deleteOldBackup:this.config.ftpDeleteOldBackup,ftpDeleteAfter:this.config.ftpDeleteAfter,advancedDelete:this.config.advancedDelete,ownDir:this.config.ftpOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.ftpOwnDir?null:this.config.ftpDir,dirMinimal:this.config.ftpMinimalDir,user:this.config.ftpUser,pass:this.config.ftpPassword||"",port:this.config.ftpPort||21,secure:this.config.ftpSecure||!1,signedCertificates:!1!==this.config.ftpSignedCertificates,ignoreErrors:o};let k="";if(this.config.dropboxEnabled){this.dropBoxTokenRefresher=new tokenRefresher_1.default(this,"info.dropboxTokens","https://oauth2.iobroker.in/dropbox");try{k=await this.dropBoxTokenRefresher.getAccessToken()}catch(e){this.log.error(`No DropBox token found: ${e}`)}}const v={enabled:this.config.dropboxEnabled,type:"storage",source:this.config.restoreSource,debugging:this.config.debugLevel,deleteOldBackup:this.config.dropboxDeleteOldBackup,dropboxDeleteAfter:this.config.dropboxDeleteAfter,advancedDelete:this.config.advancedDelete,accessToken:"custom"===this.config.dropboxTokenType?this.config.dropboxAccessToken:k,dropboxAccessJson:this.config.dropboxAccessJson,dropboxTokenType:this.config.dropboxTokenType,ownDir:this.config.dropboxOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.dropboxOwnDir?null:this.config.dropboxDir,dirMinimal:this.config.dropboxMinimalDir,ignoreErrors:o},S={enabled:this.config.onedriveEnabled,type:"storage",source:this.config.restoreSource,debugging:this.config.debugLevel,deleteOldBackup:this.config.onedriveDeleteOldBackup,onedriveDeleteAfter:this.config.onedriveDeleteAfter,advancedDelete:this.config.advancedDelete,onedriveAccessJson:this.config.onedriveAccessJson,ownDir:this.config.onedriveOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.onedriveOwnDir?null:this.config.onedriveDir,dirMinimal:this.config.onedriveMinimalDir,ignoreErrors:o},_={enabled:this.config.webdavEnabled,type:"storage",source:this.config.restoreSource,debugging:this.config.debugLevel,deleteOldBackup:this.config.webdavDeleteOldBackup,webdavDeleteAfter:this.config.webdavDeleteAfter,advancedDelete:this.config.advancedDelete,username:this.config.webdavUsername,pass:this.config.webdavPassword||"",url:this.config.webdavURL,ownDir:this.config.webdavOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.webdavOwnDir?null:this.config.webdavDir,dirMinimal:this.config.webdavMinimalDir,signedCertificates:this.config.webdavSignedCertificates,ignoreErrors:o},D={enabled:this.config.googledriveEnabled,type:"storage",source:this.config.restoreSource,debugging:this.config.debugLevel,deleteOldBackup:this.config.googledriveDeleteOldBackup,googledriveDeleteAfter:this.config.googledriveDeleteAfter,advancedDelete:this.config.advancedDelete,accessJson:this.config.googledriveAccessTokens||this.config.googledriveAccessJson,newToken:!!this.config.googledriveAccessTokens,ownDir:this.config.googledriveOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.googledriveOwnDir?null:this.config.googledriveDir,dirMinimal:this.config.googledriveMinimalDir,ignoreErrors:o},T={enabled:this.config.cifsEnabled,mountType:this.config.connectType,type:"storage",source:this.config.restoreSource,mount:this.config.cifsMount,debugging:this.config.debugLevel,fileDir:bashDir,wakeOnLAN:this.config.wakeOnLAN,macAd:this.config.macAd,wolTime:this.config.wolWait,wolPort:this.config.wolPort||9,wolExtra:this.config.wolExtra,smb:this.config.smbType,sudo:this.config.sudoMount,cifsDomain:this.config.cifsDomain,clientInodes:this.config.noserverino,cacheLoose:this.config.cacheLoose,deleteOldBackup:this.config.cifsDeleteOldBackup,ownDir:this.config.cifsOwnDir,bkpType:this.config.restoreType,dir:!0===this.config.cifsOwnDir?null:this.config.cifsDir,dirMinimal:this.config.cifsMinimalDir,user:this.config.cifsUser,pass:this.config.cifsPassword||"",expertMount:this.config.expertMount,ignoreErrors:o},w=e=>({ftp:Object.assign({},y,!0===this.config.ftpOwnDir?{dir:this.config[`ftp${e}Dir`]}:{}),cifs:Object.assign({},T,!0===this.config.cifsOwnDir?{dir:this.config[`cifs${e}Dir`]}:{}),dropbox:Object.assign({},v,!0===this.config.dropboxOwnDir?{dir:this.config[`dropbox${e}Dir`]}:{}),onedrive:Object.assign({},S,!0===this.config.onedriveOwnDir?{dir:this.config[`onedrive${e}Dir`]}:{}),webdav:Object.assign({},_,!0===this.config.webdavOwnDir?{dir:this.config[`webdav${e}Dir`]}:{}),googledrive:Object.assign({},D,!0===this.config.googledriveOwnDir?{dir:this.config[`googledrive${e}Dir`]}:{})}),x=this.config.minimalNameSuffix.replace(/[.;, ]/g,"_"),$="Slave"===this.config.hostType?this.config.slaveNameSuffix:"",E=this.config.hostType,B=(0,node_path_1.join)(tools.getIobDir(),"iobroker-data");this.backupConfig.iobroker={name:"iobroker",type:"creator",workDir:i,enabled:this.config.minimalEnabled,time:this.config.minimalTime,cronjob:this.config.iobrokerCronJob,ownCron:this.config.iobrokerCron,debugging:this.config.debugLevel,slaveBackup:this.config.hostType,everyXDays:this.config.minimalEveryXDays,nameSuffix:x,deleteBackupAfter:this.config.minimalDeleteAfter,...w("Minimal"),ignoreErrors:o,mysql:{enabled:void 0===this.config.mySqlEnabled||this.config.mySqlEnabled,type:"creator",...w("Minimal"),nameSuffix:x,mysqlQuick:this.config.mysqlQuick,slaveSuffix:$,hostType:E,mysqlSingleTransaction:this.config.mysqlSingleTransaction,dbName:this.config.mySqlName,user:this.config.mySqlUser,pass:this.config.mySqlPassword||"",deleteBackupAfter:this.config.mySqlDeleteAfter,host:this.config.mySqlHost,port:this.config.mySqlPort,mySqlEvents:this.config.mySqlEvents,mySqlMulti:this.config.mySqlMulti,ignoreErrors:o,skipSSL:this.config.mysqlSkipSSL,exe:this.config.mySqlDumpExe},sqlite:{enabled:void 0===this.config.sqliteEnabled||this.config.sqliteEnabled,type:"creator",...w("Minimal"),nameSuffix:x,slaveSuffix:$,hostType:E,deleteBackupAfter:this.config.sqliteDeleteAfter,ignoreErrors:o,filePth:this.config.sqlitePath,exe:this.config.sqliteDumpExe},dir:tools.getIobDir(),influxDB:{enabled:void 0===this.config.influxDBEnabled||this.config.influxDBEnabled,type:"creator",...w("Minimal"),nameSuffix:x,slaveSuffix:$,hostType:E,deleteBackupAfter:this.config.influxDBDeleteAfter,dbName:this.config.influxDBName,host:this.config.influxDBHost,port:this.config.influxDBPort?this.config.influxDBPort:"1.x"==this.config.influxDBVersion?8088:8086,dbversion:this.config.influxDBVersion,token:this.config.influxDBToken,protocol:this.config.influxDBProtocol,exe:this.config.influxDBDumpExe,dbType:this.config.influxDBType,influxDBEvents:this.config.influxDBEvents,influxDBMulti:this.config.influxDBMulti,ignoreErrors:o,deleteDataBase:this.config.deleteOldDataBase},pgsql:{enabled:void 0===this.config.pgSqlEnabled||this.config.pgSqlEnabled,type:"creator",...w("Minimal"),nameSuffix:x,slaveSuffix:$,hostType:E,dbName:this.config.pgSqlName,user:this.config.pgSqlUser,pass:this.config.pgSqlPassword||"",deleteBackupAfter:this.config.pgSqlDeleteAfter,host:this.config.pgSqlHost,port:this.config.pgSqlPort,pgSqlEvents:this.config.pgSqlEvents,pgSqlMulti:this.config.pgSqlMulti,ignoreErrors:o,exe:this.config.pgSqlDumpExe},redis:{enabled:this.config.redisEnabled,type:"creator",...w("Minimal"),aof:this.config.redisAOFactive,nameSuffix:x,slaveSuffix:$,hostType:E,path:this.config.redisPath||"/var/lib/redis",redisType:this.config.redisType,host:this.config.redisHost,port:this.config.redisPort,user:this.config.redisUser,pass:this.config.redisPassword||"",ignoreErrors:o},historyDB:{enabled:this.config.historyEnabled,type:"creator",...w("Minimal"),path:this.config.historyPath,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},zigbee:{enabled:this.config.zigbeeEnabled,type:"creator",...w("Minimal"),path:B,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},esphome:{enabled:this.config.esphomeEnabled,type:"creator",...w("Minimal"),path:B,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},zigbee2mqtt:{enabled:this.config.zigbee2mqttEnabled,type:"creator",...w("Minimal"),path:this.config.zigbee2mqttPath,z2mType:this.config.zigbee2mqttType,z2mUsername:this.config.zigbee2mqttUser,z2mPassword:this.config.zigbee2mqttPassword,z2mUrl:this.config.zigbee2mqttHost,z2mPort:this.config.zigbee2mqttPort,z2mBaseTopic:this.config.zigbee2mqttBaseTopic,z2mAuth:this.config.zigbee2mqttAuth,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},nodered:{enabled:this.config.noderedEnabled,type:"creator",...w("Minimal"),path:B,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},yahka:{enabled:this.config.yahkaEnabled,type:"creator",...w("Minimal"),path:B,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},jarvis:{enabled:this.config.jarvisEnabled,type:"creator",...w("Minimal"),path:B,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o},javascripts:{enabled:this.config.javascriptsEnabled,type:"creator",...w("Minimal"),slaveSuffix:$,hostType:E,nameSuffix:x,ignoreErrors:o},grafana:{enabled:this.config.grafanaEnabled,type:"creator",...w("Minimal"),host:this.config.grafanaHost,port:this.config.grafanaPort,protocol:this.config.grafanaProtocol,apiKey:this.config.grafanaApiKey,nameSuffix:x,slaveSuffix:$,hostType:E,ignoreErrors:o,signedCertificates:"https"!=this.config.grafanaProtocol||this.config.grafanaSignedCertificates},historyHTML:b,historyJSON:m,telegram:a,email:u,pushover:f,whatsapp:c,gotify:l,signal:h,matrix:g,discord:d,notification:p},this.backupConfig.ccu={name:"ccu",type:"creator",enabled:this.config.ccuEnabled,time:this.config.ccuTime,cronjob:this.config.ccuCronJob,ownCron:this.config.ccuCron,debugging:this.config.debugLevel,everyXDays:this.config.ccuEveryXDays,nameSuffix:this.config.ccuNameSuffix,deleteBackupAfter:this.config.ccuDeleteAfter,signedCertificates:this.config.ccuSignedCertificates,ignoreErrors:o,...w("Ccu"),historyHTML:b,historyJSON:m,telegram:a,email:u,pushover:f,whatsapp:c,gotify:l,signal:h,matrix:g,discord:d,notification:p,host:this.config.ccuHost,user:this.config.ccuUser,usehttps:this.config.ccuUsehttps,pass:this.config.ccuPassword||"",ccuEvents:this.config.ccuEvents,ccuMulti:this.config.ccuMulti}}readLogFile(){try{const e=(0,node_path_1.join)(tools.getIobDir(),"backups","logs.txt").replace(/\\/g,"/");if((0,node_fs_1.existsSync)(e)){this.log.debug("Printing logs of previous backup");const t=(0,node_fs_1.readFileSync)(e).toString().split("\n");t.forEach((e,i)=>t[i]=e.replace(/\r$|^\r/,"")),t.forEach(e=>{(e=e.trim())&&(e.startsWith("[ERROR]")?this.log.error(e):this.log.debug(e),this.setState("output.line",e,!0))}),this.setState("output.line","[EXIT] 0",!0),(0,node_fs_1.unlinkSync)(e)}}catch(e){this.log.warn(`Cannot read log file: ${e}`)}}createBashScripts(){const e=process.platform.startsWith("win");(0,node_fs_1.existsSync)(bashDir)||((0,node_fs_1.mkdirSync)(bashDir),this.log.debug("BackItUp data-directory created"));const t=(0,node_path_1.join)(bashDir,`${this.namespace}.log`);if((0,node_fs_1.existsSync)(t)||(0,node_fs_1.writeFileSync)(t,"[]"),e){this.log.debug(`BackItUp has recognized a ${process.platform} system`);try{(0,node_fs_1.writeFileSync)(`${bashDir}/stopIOB.bat`,`start "" "${(0,node_path_1.join)(bashDir,"external.bat")}"`)}catch(e){this.log.error(`cannot create stopIOB.bat: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/external.bat`,`cd "${(0,node_path_1.join)(tools.getIobDir())}"\ncall iobroker stop\ntimeout /T 15\nif exist "${(0,node_path_1.join)(bashDir,".redis.info")}" (\nredis-server --service-stop\n)\nif exist "${(0,node_path_1.join)(bashDir,".redis.info")}" (\ncd "${(0,node_path_1.join)(__dirname,"lib")}"\n) else (\ncd "${(0,node_path_1.join)(bashDir)}"\n)\nnode restore.js`),(0,node_fs_1.chmodSync)(`${bashDir}/external.bat`,508)}catch(e){this.log.error(`cannot create external.sh: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/startIOB.bat`,`if exist "${(0,node_path_1.join)(bashDir,".redis.info")}" (\nredis-server --service-start\n)\ncd "${(0,node_path_1.join)(tools.getIobDir())}"\ncall iobroker host this\ncall iobroker start\nif exist "${(0,node_path_1.join)(bashDir,".startAll")}" (\ncd "${(0,node_path_1.join)(tools.getIobDir(),"node_modules/iobroker.js-controller")}"\nnode iobroker.js start all\n)`)}catch(e){this.log.error(`cannot create startIOB.bat: ${e}Please run "iobroker fix"`)}}else if((0,node_fs_1.existsSync)("/opt/scripts/.docker_config/.thisisdocker")){this.log.debug("BackItUp has recognized a Docker system");try{(0,node_fs_1.writeFileSync)(`${bashDir}/stopIOB.sh`,`#!/bin/bash\n# iobroker stop for restore\nbash ${bashDir}/external.sh`),(0,node_fs_1.chmodSync)(`${bashDir}/stopIOB.sh`,508)}catch(e){this.log.error(`cannot create stopIOB.sh: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/startIOB.sh`,`#!/bin/bash\n# iobroker start after restore\nif [ -f ${bashDir}/.startAll ]; then\ncd "${(0,node_path_1.join)(tools.getIobDir())}"\niobroker start all;\nfi\nsleep 6\nbash /opt/scripts/maintenance.sh off -y`),(0,node_fs_1.chmodSync)(`${bashDir}/startIOB.sh`,508)}catch(e){this.log.error(`cannot create startIOB.sh: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/external.sh`,`#!/bin/bash\n# restore\nbash /opt/scripts/maintenance.sh on -y -kbn\nsleep 3\nif [ -f ${bashDir}/.redis.info ]; then\ncd "${(0,node_path_1.join)(__dirname,"lib")}"\nelse\ncd "${bashDir}"\nfi\nnode restore.js`),(0,node_fs_1.chmodSync)(`${bashDir}/external.sh`,508)}catch(e){this.log.error(`cannot create external.sh: ${e}Please run "iobroker fix"`)}}else{this.log.debug(`BackItUp has recognized a ${process.platform} system`);try{(0,node_fs_1.writeFileSync)(`${bashDir}/stopIOB.sh`,`# iobroker stop for restore\nsudo systemd-run --uid=iobroker bash ${bashDir}/external.sh`),(0,node_fs_1.chmodSync)(`${bashDir}/stopIOB.sh`,508)}catch(e){this.log.error(`cannot create stopIOB.sh: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/startIOB.sh`,`# iobroker start after restore\nif [ -f ${bashDir}/.redis.info ]; then\nredis-cli shutdown nosave && echo "[DEBUG] [redis] Redis restart successfully"\nfi\nif [ -f ${bashDir}/.startAll ]; then\ncd "${(0,node_path_1.join)(tools.getIobDir())}"\nbash iobroker start all && echo "[EXIT] **** iobroker start upload all now... ****"\nfi\ncd "${(0,node_path_1.join)(tools.getIobDir())}"\nbash iobroker host this && echo "[DEBUG] [iobroker] Host this successfully"\nbash iobroker start && echo "[EXIT] **** iobroker restart now... ****"`),(0,node_fs_1.chmodSync)(`${bashDir}/startIOB.sh`,508)}catch(e){this.log.error(`cannot create startIOB.sh: ${e}Please run "iobroker fix"`)}try{(0,node_fs_1.writeFileSync)(`${bashDir}/external.sh`,`# restore\ncd "${(0,node_path_1.join)(tools.getIobDir())}"\nbash iobroker stop && echo "[DEBUG] [iobroker] iobroker stop successfully"\nif [ -f ${bashDir}/.redis.info ]; then\ncd "${(0,node_path_1.join)(__dirname,"lib")}"\nelse\ncd "${bashDir}"\nfi\nnode restore.js`),(0,node_fs_1.chmodSync)(`${bashDir}/external.sh`,508)}catch(e){this.log.error(`cannot create external.sh: ${e}Please run "iobroker fix"`)}}}umount(){const e=(0,node_path_1.join)(tools.getIobDir(),"backups"),t=require("node:child_process");(0,node_fs_1.existsSync)(`${bashDir}/.mount`)&&t.exec(`mount | grep -o "${e}"`,(i,s)=>{s.includes(e)?(this.log.debug("mount activ... umount in 2 Seconds!!"),this.timerUmount1=setTimeout(()=>t.exec(`${this.config.sudoMount?"sudo umount":"umount"} ${e}`,i=>{i?(this.log.debug("umount: device is busy... wait 5 Minutes!!"),this.timerUmount2=setTimeout(()=>t.exec(`${this.config.sudoMount?"sudo umount":"umount"} -l ${e}`,e=>{e?this.log.error(e):(this.log.debug("umount successfully completed"),this.removeMountMarker())}),3e5)):(this.log.debug("umount successfully completed"),this.removeMountMarker())}),2e3)):this.log.debug("mount inactiv!!")})}removeMountMarker(){try{(0,node_fs_1.existsSync)(`${bashDir}/.mount`)&&(0,node_fs_1.unlinkSync)(`${bashDir}/.mount`)}catch{this.log.debug('file ".mount" not deleted ...')}}createBackupDir(){if(!(0,node_fs_1.existsSync)((0,node_path_1.join)(tools.getIobDir(),"backups")))try{(0,node_fs_1.mkdirSync)((0,node_path_1.join)(tools.getIobDir(),"backups")),this.log.debug("Created BackupDir")}catch(e){this.log.warn(`Backup folder not created: ${e}! Please run "iobroker fix" and try again or create the backup folder manually!!`)}}deleteHideFiles(){(0,node_fs_1.existsSync)(`${bashDir}/.redis.info`)&&(0,node_fs_1.unlinkSync)(`${bashDir}/.redis.info`)}delTmp(){if((0,node_fs_1.existsSync)((0,node_path_1.join)(tools.getIobDir(),"backups/tmp")))try{(0,node_fs_1.rmdirSync)((0,node_path_1.join)(tools.getIobDir(),"backups/tmp")),this.log.debug("delete tmp files")}catch(e){this.log.warn(`can not delete tmp files: ${e}Please run "iobroker fix" and try again or delete the tmp folder manually!!`)}}setStartAll(){if(this.config.startAllRestore&&!(0,node_fs_1.existsSync)(`${bashDir}/.startAll`))try{(0,node_fs_1.writeFileSync)(`${bashDir}/.startAll`,"Start all Adapter after Restore"),this.log.debug("Start all Adapter after Restore enabled")}catch(e){this.log.warn(`can not create startAll files: ${e}Please run "iobroker fix" and try again`)}else if(!this.config.startAllRestore&&(0,node_fs_1.existsSync)(`${bashDir}/.startAll`))try{(0,node_fs_1.unlinkSync)(`${bashDir}/.startAll`),this.log.debug("Start all Adapter after Restore disabled")}catch(e){this.log.warn(`can not delete startAll file: ${e}Please run "iobroker fix" and try again`)}}getName(e,t,i){try{const s=e.split("_");parseInt(s[0],10).toString()!==s[0]&&s.shift();const o="cifs"===i?"NAS":i;return this.log.debug(e?`detect backup file ${t} from ${o}: ${e}`:"No backup name was found"),new Date(s[0],parseInt(s[1],10)-1,parseInt(s[2].split("-")[0],10),parseInt(s[2].split("-")[1],10),parseInt(s[3],10))}catch(e){e&&this.log.warn("No backup name was found")}}async detectLatestBackupFile(){try{let e=Object.keys(this.backupConfig.iobroker).filter(e=>"object"==typeof this.backupConfig.iobroker[e]&&"storage"===this.backupConfig.iobroker[e].type&&!0===this.backupConfig.iobroker[e].enabled);await this.updateAccessTokens(this.backupConfig);let t=null;const i=require("./lib/list").default;try{t=e.map(e=>new Promise(t=>i(e,this.backupConfig,this.log,i=>{let s=null;if(i&&i.data&&"undefined"!==i.data){let t=0,o=i.data;Object.keys(o).forEach(i=>{const n=o[i];n?.iobroker&&n.iobroker.filter(e=>e.size).forEach(i=>{t++;const o=this.getName(i.name,t,e);(!s||s.date<o)&&(s=i,s.date=o,s.storage=e)})}),i=null,o=null}t(s)})))}catch(e){this.log.warn(`No backup file was found: ${e}`)}Promise.all(t).then(e=>{let t,i=e.filter(e=>e);if(i.length){if(i.sort((e,t)=>e.date>t.date?1:e.date<t.date?-1:0),t=i[0],void 0!==t.date)try{t.date=t.date.toISOString()}catch(e){this.log.warn(`No backup file date was found: ${e}`)}}else t=null;this.setState("info.latestBackup",t?JSON.stringify(t):"",!0),this.log.debug(t?`detect last backup file: ${t.name}`:"No backup file was found"),i=null}),t=null,e=null}catch(e){this.log.warn(`No backup file was found: ${e}`)}}async nextBackup(e,t){const{CronExpressionParser:i}=await import("cron-parser");if(this.config.ccuEnabled&&e||"ccu"===t){const e=this.config.ccuCron?this.config.ccuCronJob:this.config.ccuTime.split(":"),t=this.config.ccuCron?e:`00 ${e[1]} ${e[0]} */${this.config.ccuEveryXDays} * *`;try{const e={currentDate:new Date},s=i.parse(t,e).next();await this.setStateAsync("info.ccuNextTime",tools.getNextTimeString(this.systemLang,s),!0)}catch(e){this.log.warn(`Your configured CCU cronjob is not correct: ${e}`)}}else this.config.ccuEnabled||await this.setStateAsync("info.ccuNextTime","none",!0);if(this.config.minimalEnabled&&e||"iobroker"===t){const e=this.config.iobrokerCron?this.config.iobrokerCronJob:this.config.minimalTime.split(":"),t=this.config.iobrokerCron?e:`00 ${e[1]} ${e[0]} */${this.config.minimalEveryXDays} * *`;try{const e={currentDate:new Date},s=i.parse(t,e).next();await this.setStateAsync("info.iobrokerNextTime",tools.getNextTimeString(this.systemLang,s),!0)}catch(e){this.log.warn(`Your configured iobroker cronjob is not correct: ${e}`)}}else this.config.minimalEnabled||await this.setStateAsync("info.iobrokerNextTime","none",!0)}async startSlaveBackup(e,t){let i=1e3;null==t&&(t=0);try{const t=await this.getForeignStateAsync(`system.adapter.${e}.alive`);t&&!1===t.val&&(i=1e4,this.log.debug(`Try to start ${e}`),await this.setForeignStateAsync(`system.adapter.${e}.alive`,!0))}catch(e){this.log.error(`error on slave State: ${e}`)}this.waitToSlaveBackup=setTimeout(async()=>{try{const i=await this.getForeignStateAsync(`system.adapter.${e}.alive`),s=()=>{if(t++,this.config.slaveInstance.length>1&&t!=this.config.slaveInstance.length){const e=t;this.slaveTimeOut=setTimeout(()=>{this.startSlaveBackup(this.config.slaveInstance[e],e)},3e3)}else this.log.debug("slave backups are completed"),this.config.onedriveEnabled&&this.renewOnedriveToken()};if(i&&i.val&&!0===i.val){const t=await this.sendToAsync(e,"slaveBackup",{config:{deleteAfter:this.config.minimalDeleteAfter}});t?this.log.debug(`Slave Backup from ${e} is finish with result: ${t}`):this.log.debug(`Slave Backup error from ${e}`),this.config.stopSlaveAfter&&(await this.setForeignStateAsync(`system.adapter.${e}.alive`,!1),this.log.debug(`${e} is stopped after backup`)),s()}else this.log.warn(`${e} is not running. The slave backup for this instance is not possible`),s()}catch(e){this.log.error(`error on slave Backup: ${e}`)}},i)}decryptEvents(e){if(this.config.ccuEvents&&this.config.ccuMulti)for(let t=0;t<this.config.ccuEvents.length;t++)if(this.config.ccuEvents[t].pass){const i=this.config.ccuEvents[t].pass;this.config.ccuEvents[t].pass=i?decrypt(e,i):""}if(this.config.mySqlEvents&&this.config.mySqlMulti)for(let t=0;t<this.config.mySqlEvents.length;t++)if(this.config.mySqlEvents[t].pass){const i=this.config.mySqlEvents[t].pass;this.config.mySqlEvents[t].pass=i?decrypt(e,i):""}if(this.config.pgSqlEvents&&this.config.pgSqlMulti)for(let t=0;t<this.config.pgSqlEvents.length;t++)if(this.config.pgSqlEvents[t].pass){const i=this.config.pgSqlEvents[t].pass;this.config.pgSqlEvents[t].pass=i?decrypt(e,i):""}}clearBashDir(){if((0,node_fs_1.existsSync)(bashDir)){const e=require("fs-extra"),t=(0,node_path_1.join)(bashDir,"restore");try{(0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"restore.js"))&&(0,node_fs_1.unlinkSync)((0,node_path_1.join)(bashDir,"restore.js")),(0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"restore.json"))&&(0,node_fs_1.unlinkSync)((0,node_path_1.join)(bashDir,"restore.json")),(0,node_fs_1.existsSync)(t)&&e.removeSync(t),(0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"iob.key"))&&(0,node_fs_1.unlinkSync)((0,node_path_1.join)(bashDir,"iob.key")),(0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"iob.crt"))&&(0,node_fs_1.unlinkSync)((0,node_path_1.join)(bashDir,"iob.crt"))}catch(e){this.log.debug(`old restore files could not be deleted: ${e}`)}}}async getCerts(e){const t=await this.getForeignObjectAsync(e);if(t&&t.native&&t.native.certPrivate&&t.native.certPublic){const e=await this.getForeignObjectAsync("system.certificates");if(e&&e.native&&e.native.certificates)try{const i=e.native.certificates,s=i[`${t.native.certPrivate}`],o=i[`${t.native.certPublic}`];s.startsWith("/")&&(0,node_fs_1.existsSync)((0,node_path_1.join)(s))?(0,node_fs_1.writeFileSync)((0,node_path_1.join)(bashDir,"iob.key"),(0,node_fs_1.readFileSync)((0,node_path_1.join)(s),"utf8")):(0,node_fs_1.writeFileSync)((0,node_path_1.join)(bashDir,"iob.key"),s),o.startsWith("/")&&(0,node_fs_1.existsSync)((0,node_path_1.join)(o))?(0,node_fs_1.writeFileSync)((0,node_path_1.join)(bashDir,"iob.crt"),(0,node_fs_1.readFileSync)((0,node_path_1.join)(o),"utf8")):(0,node_fs_1.writeFileSync)((0,node_path_1.join)(bashDir,"iob.crt"),o)}catch{this.log.debug("no certificates found")}}}readServerCerts(){let e="",t="";if((0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"iob.key"))&&(0,node_fs_1.existsSync)((0,node_path_1.join)(bashDir,"iob.crt")))try{e=(0,node_fs_1.readFileSync)((0,node_path_1.join)(bashDir,"iob.key"),"utf8"),t=(0,node_fs_1.readFileSync)((0,node_path_1.join)(bashDir,"iob.crt"),"utf8")}catch{this.log.debug("no certificates found")}return{key:e,cert:t}}dlFileServer(e){const t=require("express"),i=t();if(this.dlServer&&this.dlServer._connectionKey){try{this.dlServer.closeAllConnections()}catch(e){this.log.debug(`Download server Connections could not be closed: ${e}`)}try{this.dlServer.close()}catch(e){this.log.debug(`Download server Connections could not be closed: ${e}`)}}const s=(0,node_fs_1.existsSync)("/opt/scripts/.docker_config/.thisisdocker")?9081:0;let o;if(i.use(t.static((0,node_path_1.join)(tools.getIobDir(),"backups"))),"https:"===e){https=https||require("node:https");const{key:e,cert:t}=this.readServerCerts();try{o=https.createServer({key:e,cert:t},i)}catch(e){this.log.debug(`The https server cannot be created: ${e}`)}}else{http=http||require("node:http");try{o=http.createServer(i)}catch(e){this.log.debug(`The http server cannot be created: ${e}`)}}try{this.dlServer=o.listen(s),this.log.debug(`Download ${e.replace(":","")} server started on port ${serverPort(this.dlServer)}`)}catch{this.log.debug("Download server cannot be started")}}ulFileServer(e){const t=require("express"),i=require("multer"),s=require("cors");try{this.ulServer.closeAllConnections()}catch{this.log.debug("Upload server connections could not be closed")}try{this.ulServer.close()}catch{this.log.debug("Upload server connections could not be closed")}const o=(0,node_fs_1.existsSync)("/opt/scripts/.docker_config/.thisisdocker")?9082:0,n=(0,node_path_1.join)(tools.getIobDir(),"backups"),r=t();r.use(s());const a=i.diskStorage({destination:(e,t,i)=>i(null,n),filename:(e,t,i)=>{this.log.debug(`Upload from ${t.originalname} started...`),i(null,t.originalname)}}),c=i({storage:a});let l;if(r.post("/",c.single("files"),(e,t)=>{this.log.debug(e.file),t.json({message:"File(s) uploaded successfully"})}),"https:"===e){https=https||require("node:https");const{key:e,cert:t}=this.readServerCerts();try{l=https.createServer({key:e,cert:t},r)}catch(e){this.log.debug(`The https upload server cannot be created: ${e}`)}}else{http=http||require("node:http");try{l=http.createServer(r)}catch(e){this.log.debug(`The http upload server cannot be created: ${e}`)}}try{this.ulServer=l.listen(o),this.log.debug(`Upload ${e.replace(":","")} server started on port ${serverPort(this.ulServer)}`)}catch{this.log.debug("Upload server cannot be started")}}async renewOnedriveToken(){const e=new(0,require("./lib/oneDriveLib").default),t=new Date;let i=NaN;if(""!=this.config.onedriveLastTokenRenew){const e=new Date(this.config.onedriveLastTokenRenew);i=parseInt(String((t.getTime()-e.getTime())/864e5))}i>=30||!this.config.onedriveLastTokenRenew?(this.log.debug("Renew Onedrive Refresh-Token"),e.renewToken(this.config.onedriveAccessJson,this.log).then(e=>{this.extendForeignObject(`system.adapter.${this.namespace}`,{native:{onedriveAccessJson:e,onedriveLastTokenRenew:`${`0${t.getMonth()+1}`.slice(-2)}/${`0${t.getDate()}`.slice(-2)}/${t.getFullYear()}`}})}).catch(e=>{this.log.error(e?JSON.stringify(e):"An update of the Onedrive refresh token has failed. Please check your system!"),this.registerNotification("backitup","onedriveWarn",e?JSON.stringify(e):"An update of the Onedrive refresh token has failed. Please check your system!")})):this.log.debug(`Renew Onedrive Refresh-Token in ${30-i} days`)}async main(){this.createBashScripts(),this.readLogFile(),(0,node_fs_1.existsSync)((0,node_path_1.join)(tools.getIobDir(),"backups"))||this.createBackupDir(),(0,node_fs_1.existsSync)(`${bashDir}/.redis.info`)&&this.deleteHideFiles(),(0,node_fs_1.existsSync)((0,node_path_1.join)(tools.getIobDir(),"backups/tmp"))&&this.delTmp(),this.clearBashDir(),this.timerMain=setTimeout(()=>{(0,node_fs_1.existsSync)(`${bashDir}/.mount`)&&this.umount(),this.config.startAllRestore&&!(0,node_fs_1.existsSync)(`${bashDir}/.startAll`)&&this.setStartAll()},1e4),this.getForeignObject("system.config",async(e,t)=>{t?.common?.language&&(this.systemLang=t.common.language),await this.initConfig(t?.native?.secret||"Zgfr56gFe87jJOM"),this.checkStates(),"Slave"!==this.config.hostType&&(this.createBackupSchedule(),this.nextBackup(!0,null),this.detectLatestBackupFile())}),this.subscribeStates("oneClick.*"),this.subscribeStates("info.dropboxTokens")}}require.main!==module?module.exports=e=>new BackItUp(e):new BackItUp;
//# sourceMappingURL=/sm/dc9791fecea17a4f02e9d7a00703d0260ad126d0233d7c7128a91a856fcfefb0.map