/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/iobroker.cloud@6.0.1/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 __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.CloudAdapter=void 0;const adapter_core_1=require("@iobroker/adapter-core"),socketCloud_1=__importDefault(require("./lib/socketCloud")),axios_1=__importDefault(require("axios")),ws_1=__importDefault(require("ws"));global.WebSocket=ws_1.default;const socket_io_client_1=__importDefault(require("socket.io-client")),TEXT_PING_TIMEOUT="Ping timeout";class CloudAdapter extends adapter_core_1.Adapter{redirectRunning=!1;socket=null;ioSocket=null;pingTimer=null;cloudConnected=!1;connectTimer=null;uuid=null;waiting=!1;apikey="";server="http://localhost:8082";adminServer="http://localhost:8081";lovelaceServer="http://localhost:8091";webSupportsConfig=!1;checkedNames=new Set;timeouts={terminate:null,onCloudWait:null,detectDisconnect:null,redirect:null,onCloudStop:null,createAppKey:null,readAppKey:null};constructor(e={}){super({...e,name:"cloud",unload:e=>this.onUnload(e),message:e=>this.onMessage(e),stateChange:(e,t)=>this.onStateChange(e,t),ready:()=>this.main(),objectChange:(e,t)=>this.onObjectChange(e,t)}),this.on("log",(e=>{this.apikey?.startsWith("@pro_")&&this.ioSocket?.send(this.socket,"log",e)}))}onUnload(e){this.connectTimer&&(clearInterval(this.connectTimer),this.connectTimer=null),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),Object.keys(this.timeouts).forEach((e=>{this.timeouts[e]&&(clearTimeout(this.timeouts[e]),this.timeouts[e]=null)}));try{this.socket?.close(),this.ioSocket=null}catch{}e()}onObjectChange(e,t){if(e===this.config.instance){this.webSupportsConfig=t?.common.version.split(".")[0]>="7";const e=this.getConnectionString(t,"web");e!==this.server&&(this.server=e,this.log.info("Reconnect because web instance "+(t?.common?.enabled?"started":"stopped")),this.startConnect(!0))}else if(e===this.config.allowAdmin){const e=this.getConnectionString(t,"admin");e!==this.adminServer&&(this.adminServer=e,this.log.info("Reconnect because admin instance "+(t?.common?.enabled?"started":"stopped")),this.startConnect(!0))}else if(e===this.config.lovelace){const e=this.getConnectionString(t,"lovelace");e!==this.lovelaceServer&&(this.lovelaceServer=e,this.log.info("Reconnect because lovelace instance "+(t?.common?.enabled?"started":"stopped")),this.startConnect(!0))}this.ioSocket?.send(this.socket,"objectChange",e,t)}async onStateChange(e,t){if(e.endsWith("remote.command")){if(t?.val)try{const e=JSON.parse(t.val);if(e.deviceName&&e.name){const t=`devices.${e.deviceName}`;if(!this.checkedNames.has(t)){await this.getObjectAsync(t)||(await this.setObjectAsync(t,{type:"device",common:{name:e.deviceName,statusStates:{onlineId:`${this.namespace}.devices.${e.deviceName}.alive`}},native:{}}),await this.setObjectAsync(`${t}.alive`,{type:"state",common:{name:"If app is running and connected",write:!1,read:!0,type:"boolean",role:"indicator.reachable"},native:{}}),await this.setStateAsync(`${t}.alive`,{val:!0,ack:!0,expire:60})),this.checkedNames.add(t)}if(!this.checkedNames.has(`${t}.${e.name}`)){if(!await this.getObjectAsync(`${t}.${e.name}`)){const s={_id:`${this.namespace}.devices.${e.deviceName}.${e.name}`,type:"state",common:{name:e.name,type:typeof e.value,read:!0,write:!1,role:"state"},native:{}};"batteryState"===e.name?s.common.states={0:"unknown",1:"unplugged",2:"charging",3:"full"}:"batteryLevel"===e.name?(s.common.role="battery",s.common.unit="%",s.common.min=0,s.common.max=100):"brightness"===e.name&&(s.common.role="level.brightness",s.common.unit="%",s.common.min=0,s.common.max=100),await this.setObjectAsync(`${t}.${e.name}`,s)}if("currentLocation"===e.name){if(!await this.getObjectAsync(`${t}.position`)){const s={_id:`${this.namespace}.${t}.position`,type:"state",common:{name:e.name,type:"string",read:!0,write:!1,role:"value.gps"},native:{}};await this.setObjectAsync(`${t}.position`,s)}}this.checkedNames.add(`${t}.${e.name}`)}if("alive"===e.name)await this.setStateAsync(`${t}.${e.name}`,{val:e.value,expire:60,ack:!0});else if(await this.setStateAsync(`${t}.${e.name}`,e.value,!0),"currentLocation"===e.name)try{const s=JSON.parse(e.value);await this.setStateAsync(`${t}.position`,`${s?.coords?.longitude};${s?.coords?.latitude}`,!0)}catch{this.log.error(`Cannot parse location: ${e.value}`)}}}catch{this.log.warn(`Cannot parse command: ${t.val}`)}}else this.socket&&(e===`${this.namespace}.services.ifttt`&&t&&!t.ack?this.sendDataToIFTTT({id:e,val:t.val,ack:!1}):this.ioSocket?.send(this.socket,"stateChange",e,t))}async readVisuAppInstructions(e){let t=null;if(e.instance)t=await this.getForeignObjectAsync(`system.adapter.${e.instance}`);else{const e=(await this.getObjectViewAsync("system","instance",{startkey:"system.adapter.web.",endkey:"system.adapter.web.香"})).rows.map((e=>e.value));for(let s=0;s<e.length;s++){const i=e[s];if(i.common.enabled){t=i;break}}null===t&&e.length&&(t=e[0])}if(t){const s=t.native,i=[];if("0.0.0.0"===s?.bind){const e=await this.getForeignObjectAsync(`system.host.${t?.common.host}`);if(e?.native?.hardware?.networkInterfaces){const t=e.native.hardware.networkInterfaces;Object.keys(t).forEach((e=>{t[e]?.forEach((e=>{"IPv4"!==e.family||e.internal||i.push(`${e.address}/${e.netmask}`)}))}))}}else i.push(s?.bind);if(s?.auth&&s?.secure)return{error:"error_ssl"};const o=`iotConfig|port:${s?.port}|ips:${i.join(",")}|cu:${e.login||this.config.login}|cp:${e.pass||this.config.pass}|https:${!!s?.secure}|auth:${!!s?.auth}`;return{qrCode:btoa(o)}}return{error:"error_no_web"}}async onMessage(e){if(e)switch(e.command){case"ifttt":this.sendDataToIFTTT(e.message);break;case"getIFTTTLink":if("string"==typeof e.message)return void(e.callback&&this.sendTo(e.from,e.command,"invalid config",e.callback));if(e.message.useCredentials)this._readAppKeyFromCloud(e.message.server,e.message.login,e.message.pass,((t,s)=>{const i=`https://${e.message.server}/ifttt/${s}`;e.callback&&this.sendTo(e.from,e.command,i,e.callback)}));else{const t=`https://${e.message.apikey.startsWith("@pro_")?"iobroker.pro":"iobroker.net"}/ifttt/${e.message.apikey}`;e.callback&&this.sendTo(e.from,e.command,t,e.callback)}break;case"getServiceLink":if("string"==typeof e.message)return void(e.callback&&this.sendTo(e.from,e.command,"invalid config",e.callback));if(e.message.useCredentials)this._readAppKeyFromCloud(e.message.server,e.message.login,e.message.pass,((t,s)=>{const i=`https://${e.message.server}/service/custom_<NAME>/${s}/<data>`;e.callback&&this.sendTo(e.from,e.command,i,e.callback)}));else{const t=`https://${e.message.apikey.startsWith("@pro_")?"iobroker.pro":"iobroker.net"}/service/custom_<NAME>/${e.message.apikey}/<data>`;e.callback&&this.sendTo(e.from,e.command,t,e.callback)}break;case"qrCode":if("object"==typeof e.message){const t=await this.readVisuAppInstructions(e.message);e.callback&&this.sendTo(e.from,e.command,t.error?t:t.qrCode,e.callback)}break;case"cmdStdout":case"cmdStderr":case"cmdExit":case"getHostInfo":this.ioSocket?.send(this.socket,e.command,e.message.id,e.message.data);break;case"tts":if(e.callback){const t={text:"object"==typeof e.message?e.message.text:e.message,apiKey:this.apikey,textType:e.message.textType||"text",voiceId:e.message.voiceId||"Marlene",engine:e.message.engine};axios_1.default.post(`${this.config.cloudUrl.replace(/:(\d+)$/,":3001")}/api/v1/polly`,t,{headers:{"Content-Type":"application/json"},responseType:"arraybuffer"}).then((t=>{if(e.callback)if(t.data){const s=Buffer.from(t.data,"binary").toString("base64");this.sendTo(e.from,e.command,{base64:s},e.callback)}else this.sendTo(e.from,e.command,{error:"no data"},e.callback)})).catch((t=>{e.callback&&this.sendTo(e.from,e.command,{error:t.response&&t.response.data||t.toString()},e.callback)}))}break;default:this.log.warn(`Unknown command_: ${e.command}`)}}getConnectionString(e,t){let s=null;if(e?.common&&e.native){if(e.native.auth)return this.log.error(`Cannot activate ${e._id.replace("system.adapter.","")} for cloud, because authentication is enabled. Please create extra instance for cloud`),s;if(e.native.secure)return this.log.error(`Cannot activate ${e._id.replace("system.adapter.","")} for cloud, because HTTPs is enabled. Please create extra instance for cloud`),s;if(!e.common.enabled)return this.log.warn(`Instance ${e._id.replace("system.adapter.","")} not enabled. Please enable adapter instance for cloud`),s;s=`http${e.native.secure?"s":""}://`,s+=e.native.bind&&"0.0.0.0"!==e.native.bind?e.native.bind:"127.0.0.1",s+=`:${e.native.port}`}else s=null,this.log.error(`Unknown instance for ${t} "${e?._id||""}"`);return s}sendDataToIFTTT(e){if(e)if(this.config.iftttKey||"object"==typeof e&&e.key)if("object"!=typeof e)this.ioSocket?.send(this.socket,"ifttt",{id:`${this.namespace}.services.ifttt`,key:this.config.iftttKey,val:e});else if(e.event){const t=e;this.ioSocket?.send(this.socket,"ifttt",{event:t.event,key:t.key||this.config.iftttKey,value1:t.value1,value2:t.value2,value3:t.value3})}else{const t=e;if(void 0===t.val)return void this.log.warn("No value is defined");t.id||=`${this.namespace}.services.ifttt`,this.ioSocket?.send(this.socket,"ifttt",{id:t.id,key:t.key||this.config.iftttKey,val:t.val,ack:t.ack})}else this.log.warn("No IFTTT key is defined");else this.log.warn("No data to send to IFTTT")}pingConnection=()=>{this.timeouts.detectDisconnect||this.cloudConnected&&this.ioSocket&&(this.ioSocket.send(this.socket,"pingg"),this.timeouts.detectDisconnect=setTimeout((()=>{this.timeouts.detectDisconnect=null,this.log.error("Ping timeout"),this.onDisconnect("Ping timeout")}),this.config.pingTimeout))};checkPing(){this.cloudConnected?this.pingTimer||=setInterval(this.pingConnection,3e4):(this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),this.timeouts.detectDisconnect&&(clearTimeout(this.timeouts.detectDisconnect),this.timeouts.detectDisconnect=null))}async controlState(e,t){if(e||="services.ifttt","object"==typeof t)if(t.id){if(t.id===`${this.namespace}.services.ifttt`&&(t.ack=!0),void 0===t.val)throw new Error("No value set");const e=await this.getForeignObjectAsync(t.id);if(!e?.common)throw new Error(`Unknown ID: ${t.id}`);"string"==typeof t.val&&(t.val=t.val.replace(/^@ifttt\s?/,"")),"boolean"===e.common.type?t.val=!0===t.val||"true"===t.val||"on"===t.val||"ON"===t.val||1===t.val||"1"===t.val:"number"===e.common.type&&(t.val=parseFloat(t.val)),await this.setForeignStateAsync(t.id,t.val,t.ack)}else void 0!==t.val?("string"==typeof t.val&&(t.val=t.val.replace(/^@ifttt\s?/,"")),await this.setStateAsync(e,t.val,void 0===t.ack||t.ack)):await this.setStateAsync(e,JSON.stringify(t),!0);else"string"==typeof t&&(t=t.replace(/^@ifttt\s?/,"")),await this.setStateAsync(e,t,!0)}async processIfttt(e){let t,s;if(this.log.debug(`Received IFTTT object: ${JSON.stringify(e)}`),"object"==typeof e&&e.id&&void 0!==e.data)if(t=e.id,"string"==typeof e.data&&"{"===e.data[0])try{s=JSON.parse(e.data)}catch{this.log.debug(`Cannot parse: ${e.data}`)}else s=e.data;else if("string"==typeof e&&"{"===e[0])try{"string"==typeof(e=JSON.parse(e)).id?(t=e.id,s=e.data?e.data:e):s=e}catch{this.log.debug(`Cannot parse: ${JSON.stringify(e)}`),s=e}if(void 0===s&&(s=e),t){let e=await this.getForeignObjectAsync(t);e?await this.controlState(t,s):(e=await this.getForeignObjectAsync(`${this.namespace}.services.${t}`),e?await this.controlState(e._id,s):(await this.setObjectAsync(`services.${t}`,{type:"state",common:{name:"IFTTT value",write:!1,role:"state",read:!0,type:"mixed",desc:"Custom state"},native:{}}),await this.controlState(`${this.namespace}.services.${t}`,s)))}else await this.controlState(void 0,s)}onDisconnect=e=>{"string"==typeof e?this.redirectRunning||this.log.info(`Connection changed: ${e}`):this.log.info("Connection changed: disconnect"),this.cloudConnected&&(this.redirectRunning||this.log.info("Connection lost"),this.cloudConnected=!1,this.setState("info.connection",!1,!0),this.checkPing(),this.config.restartOnDisconnect&&!this.redirectRunning?(this.log.info("Restart adapter by disconnect"),this.timeouts.terminate=setTimeout((()=>{this.timeouts.terminate=null,this.terminate?this.terminate(-100):process.exit(-100)}),1e4)):(this.redirectRunning=!1,this.startConnect()))};onConnect=()=>{this.cloudConnected?this.log.debug("Connection not changed: was cloudConnected"):(this.log.info("Connection changed: connect"),this.cloudConnected=!0,this.setState("info.connection",this.cloudConnected,!0),this.checkPing()),this.connectTimer&&(clearInterval(this.connectTimer),this.connectTimer=null)};onCloudConnect=e=>{this.log.info(`User accessed from cloud: ${e||""}`),this.setState("info.userOnCloud",!0,!0)};onCloudDisconnect=(e,t)=>{this.log.info(`User disconnected from cloud: ${e||""} ${t||""}`),this.setState("info.userOnCloud",!1,!0)};onCloudWait=e=>{this.waiting=!0,this.log.info(`Server asked to wait for ${e||60} seconds`),this.socket&&(this.socket.disconnect(),this.socket.off(),this.socket=null),this.connectTimer&&(clearInterval(this.connectTimer),this.connectTimer=null),this.timeouts.onCloudWait=setTimeout((()=>{this.timeouts.onCloudWait=null,this.waiting=!1,this.startConnect(!0)}),1e3*(e||60))};onCloudRedirect=async e=>{if(e)if(e.url)if(e.notSave)this.redirectRunning=!0,this.log.info(`Adapter redirected temporally to "${e.url}" ${this.config.cloudUrl.includes("https://iobroker.pro:")?"in 30 seconds":"in one minute"}. Reason: ${e&&e.reason?e.reason:"command from server"}`),this.config.cloudUrl=e.url,this.socket&&(this.socket.disconnect(),this.socket.off()),this.startConnect();else{this.log.info(`Adapter redirected continuously to "${e.url}". Reason: ${e?.reason?e.reason:"command from server"}`);try{const t=await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);t&&(t.native.cloudUrl=e.url,this.timeouts.redirect=setTimeout((()=>{this.timeouts.redirect=null,this.setForeignObject(t._id,t,(t=>{t&&this.log.error(`redirectAdapter [setForeignObject]: ${t}`),this.config.cloudUrl=e.url,this.socket&&(this.socket.disconnect(),this.socket.off()),this.startConnect()}))}),3e3))}catch(e){this.log.error(`redirectAdapter [getForeignObject]: ${e}`)}}else this.log.error("Received redirect, but no URL.");else this.log.info("Received invalid redirect command from server")};onCloudError=e=>{this.log.error(`Cloud says: ${e}`)};onCloudStop=()=>{this.getForeignObject(`system.adapter.${this.namespace}`,((e,t)=>{e&&this.log.error(`[onCloudStop]: ${e}`),t?(t.common.enabled=!1,this.timeouts.onCloudStop=setTimeout((()=>{this.timeouts.onCloudStop=null,this.setForeignObject(t._id,t,(e=>{e&&this.log.error(`[setForeignObject]: ${e}`),this.terminate?this.terminate():process.exit()}))}),5e3)):this.terminate?this.terminate():process.exit()}))};startConnect(e){this.waiting||(this.connectTimer&&(clearInterval(this.connectTimer),this.connectTimer=null),this.connectTimer=setInterval((()=>this.connect()),this.config.cloudUrl.includes("https://iobroker.pro:")?3e4:6e4),e&&this.connect())}initConnect(){this.ioSocket=new socketCloud_1.default(this.socket,{apikey:this.apikey,uuid:this.uuid,version:this.version},this,this.lovelaceServer),this.ioSocket.on("connect",this.onConnect),this.ioSocket.on("disconnect",this.onDisconnect),this.ioSocket.on("cloudError",this.onCloudError),this.ioSocket.on("cloudConnect",this.onCloudConnect),this.ioSocket.on("cloudDisconnect",this.onCloudDisconnect),this.ioSocket.on("connectWait",this.onCloudWait),this.ioSocket.on("cloudRedirect",this.onCloudRedirect),this.ioSocket.on("cloudStop",this.onCloudStop)}answerWithReason(e,t,s){e?this.getForeignObjectAsync(e).catch((()=>null)).then((s=>{this.getConnectionString(s,t)&&(s?.common.enabled?this.log.error(`${t} instance "${e}" not available.`):this.log.error(`${t} instance "${e}" not activated.`))})):this.log.error(`${t} instance not defined. Please specify the lovelace instance in settings`),s&&s(`${t} is inactive`,404,{},`${t} is inactive`)}patchIndexHtml(e){const t=(e="string"==typeof e?e:e.toString("utf-8")).split("\n"),s=[];let i=[];const o=[];let n=!1;for(let e=0;e<t.length;e++)n?!0===n?t[e].includes("];")?(n="after",i.push(t[e])):i.push(t[e]):"after"===n&&o.push(t[e]):t[e].startsWith("list = [")?(n=!0,i.push(t[e])):s.push(t[e]);try{const e=JSON.parse(i.join("\n").trim().replace(/list = /,"").replace(/;$/,"")),t=[];for(const s of e)if(!t.find((e=>e.link===s.link))){if(this.config.onlyViewer&&("admin/index.html"===s.link||s.link.includes("edit.html")))continue;t.push(s)}i=`list = ${JSON.stringify(t,null,2)};`.split("\n")}catch(t){return this.log.error(`Cannot parse list from index.html: ${t}`),Buffer.from(e)}return Buffer.from(`${s.join("\n")}\n${i.join("\n")}\n${o.join("\n")}`)}async connect(){if(!this.waiting){if(this.config.allowAdmin){const e=await this.getForeignObjectAsync(this.config.allowAdmin).catch((()=>null));e&&(this.adminServer=this.getConnectionString(e,"admin"))}if(this.config.lovelace){const e=await this.getForeignObjectAsync(this.config.lovelace).catch((()=>null));e&&(this.lovelaceServer=this.getConnectionString(e,"lovelace"))}if(this.config.instance){const e=await this.getForeignObjectAsync(this.config.instance).catch((()=>null));e&&(this.webSupportsConfig=e.common.version.split(".")[0]>="7",this.server=this.getConnectionString(e,"web"))}this.log.debug(`Connection attempt to ${this.config.cloudUrl} ...`),this.socket&&(this.socket.disconnect(),this.socket.off()),this.socket=(0,socket_io_client_1.default)(this.config.cloudUrl,{transports:["websocket"],autoConnect:!0,reconnection:!this.config.restartOnDisconnect,rejectUnauthorized:!this.config.allowSelfSignedCertificate,randomizationFactor:.9,reconnectionDelay:6e4,timeout:parseInt(this.config.connectionTimeout,10)||1e4,reconnectionDelayMax:12e4}),(this.server||this.lovelaceServer||this.adminServer)&&this.initConnect(),this.socket.on("connect_error",(e=>this.log.error(`Error while connecting to cloud: ${e}`))),this.socket.on("pongg",(()=>{this.timeouts.detectDisconnect&&(clearTimeout(this.timeouts.detectDisconnect),this.timeouts.detectDisconnect=null)})),this.socket.on("method",((e,t,s)=>{e.startsWith("/lovelace/")?(e=e.replace(/^\/lovelace\//,"/"),this.lovelaceServer?(0,axios_1.default)({url:this.lovelaceServer+e,method:t.method,data:t.body,validateStatus:e=>e<400}).then((e=>s(null,e.status,e.headers,JSON.stringify(e.data)))).catch((t=>{t.response?(this.log.error(`Cannot request lovelace pages "${e}": ${t.response.data||t.response.status}`),s(t.response.data||t.response.status,t.response.status||501,t.response.headers,JSON.stringify(t.response.data))):(this.log.error(`Cannot request lovelace pages "${e}": ${t.code}`),s(t.code,501,{},JSON.stringify({error:"unexpected error"})))})):this.answerWithReason(this.config.lovelace,"lovelace",s)):(this.log.error(`Unexpected request: ${e}`),this.server?(0,axios_1.default)({url:this.server+e,method:t.method,data:t.body,validateStatus:e=>e<400}).then((e=>s(null,e.status,e.headers,JSON.stringify(e.data)))).catch((t=>{t.response?(this.log.error(`Cannot request web pages "${this.server}${e}": ${t.response.data||t.response.status}`),s(t.response.data||t.response.status,t.response.status||501,t.response.headers,JSON.stringify(t.response.data))):(this.log.error(`Cannot request web pages "${this.server}${e}": ${t.code}`),s(t.code,501,{},JSON.stringify({error:"unexpected error"})))})):this.answerWithReason(this.config.instance,"web",s))})),this.socket.on("html",((e,t)=>{try{e.match(/^\/admin\//)?this.adminServer&&this.config.allowAdmin?((e=e.substring(6)).includes("loginBackgroundImage")&&console.log("AAA"),"/@@loginBackgroundImage@@"===e&&(e="/files/admin.0/login-bg.png"),axios_1.default.get(this.adminServer+e,{responseType:"arraybuffer",validateStatus:e=>e<400,maxRedirects:0}).then((e=>t(null,e.status,e.headers,e.data))).catch((e=>{e.response?(this.log.error(`Cannot request admin pages: ${e.response.data||e.response.status}`),t(e.code,e.response.status||501,e.response.headers,e.response.data)):(this.log.error("Cannot request admin pages: no response"),t("no response",501,{},"no response from admin"))}))):(this.answerWithReason(this.config.allowAdmin,"admin"),t("Enable admin in cloud settings. And only pro.",404,{},"Enable admin in cloud settings. And only pro.")):e.startsWith("/adapter/")||e.startsWith("/lib/js/ace-")||e.startsWith("/lib/js/cron")||e.startsWith("/lib/js/jqGrid")?this.adminServer&&this.config.allowAdmin?axios_1.default.get(this.adminServer+e,{responseType:"arraybuffer",validateStatus:e=>e<400,maxRedirects:0}).then((e=>t(null,e.status,e.headers,e.data))).catch((e=>{e.response?(this.log.error(`Cannot request admin pages: ${e.response.data||e.response.status}`),t(e.code,e.response.status||501,e.response.headers,e.response.data)):(this.log.error("Cannot request admin pages: no response"),t("no response",501,{},"no response from admin"))})):(this.answerWithReason(this.config.allowAdmin,"admin"),t("Enable admin in cloud settings. And only pro.",404,{},"Enable admin in cloud settings. And only pro.")):e.startsWith("/lovelace/")?this.lovelaceServer&&this.config.lovelace?(e=e.replace(/^\/lovelace\//,"/"),axios_1.default.get(this.lovelaceServer+e,{responseType:"arraybuffer",validateStatus:e=>e<400,maxRedirects:0}).then((e=>t(null,e.status,e.headers,e.data))).catch((s=>{s.response?(this.log.error(`Cannot request lovelace pages "${this.lovelaceServer+e}": ${s.response.data||s.response.status}`),t(s.code,s.response.status||501,s.response.headers,s.response.data)):(this.log.error(`Cannot request lovelace pages "${this.lovelaceServer+e}": no response`),t("no response",501,{},"no response from lovelace"))}))):this.answerWithReason(this.config.lovelace,"lovelace",t):this.server?axios_1.default.get(this.server+e,{responseType:"arraybuffer",validateStatus:e=>e<400,maxRedirects:0}).then((s=>{"/"!==e&&"/index.html"!==e||(s.data=this.patchIndexHtml(s.data)),t(null,s.status,s.headers,s.data)})).catch((s=>{s.response?(this.log.error(`Cannot request web pages "${this.server+e}": ${s.response.data||s.response.status}`),t(s.code,s.response.status||501,s.response.headers,s.response.data)):(this.log.error(`Cannot request web pages"${this.server+e}": no response`),t("no response",501,{},"no response from web"))})):this.answerWithReason(this.config.instance,"web",t)}catch(e){this.log.error(`Cannot request: ${e}`),t("Admin or Web are inactive.",404,{},"Admin or Web are inactive.")}})),this.socket.on("ifttt",this.processIfttt),this.socket.on("iftttError",(e=>this.log.error(`Error from IFTTT: ${JSON.stringify(e)}`))),this.socket.on("cloudError",(e=>this.log.error(`Cloud says: ${e}`))),this.socket.on("service",(async(e,t)=>{if(this.log.debug(`service: ${JSON.stringify(e)}`),e?.name)if("ifttt"===e.name&&this.config.iftttKey)await this.processIfttt(e.data),t?.();else{let s=!1;if(e.name.match(/^custom_/)&&(e.name=e.name.substring(7),s=!0),"*"===this.config.allowedServices[0]||this.config.allowedServices.includes(e.name))if(s||"text2command"!==e.name)if(s||"simpleApi"!==e.name&&"simpleapi"!==e.name)if(s){if(!await this.getObjectAsync(`services.custom_${e.name}`))try{await this.setObjectAsync(`services.custom_${e.name}`,{_id:`${this.namespace}.services.custom_${e.name}`,type:"state",common:{name:`Service for ${e.name}`,write:!1,read:!0,type:"mixed",role:"value"},native:{}})}catch(e){return void t?.({result:e.toString()})}try{await this.setStateAsync(`services.custom_${e.name}`,e.data,!1),t?.({result:"Ok"})}catch(e){t?.({result:e.toString()})}}else t?.({error:"not allowed"});else{const s=(e.data||"").split("/");if("get"===s[0]){if(t)try{const e=await this.getForeignStateAsync(s[1]);e?(e.result="Ok",t(e)):t({result:"Not found"})}catch(e){t({error:e.toString()})}}else if("getPlainValue"===s[0]){if(t)try{const e=await this.getForeignStateAsync(s[1]);t(e?{result:"Ok",val:e.val,plain:!0}:{result:"Not found",val:null,plain:!0})}catch(e){t({error:e.toString()})}}else if("set"===s[0]){if(t){const e=s[1].split("?"),i=e[0];let o=e[1];if(void 0===i||void 0===o)return void t({error:"invalid call"});o=o.replace(/^value=/,"");try{const e=await this.getForeignObjectAsync(i);"state"!==e?.type?t({error:"only states can be controlled"}):("boolean"===e.common?.type?await this.setForeignStateAsync(i,"true"===o||"1"===o||"ON"===o||"on"===o):"number"===e.common?.type?await this.setForeignStateAsync(i,parseFloat(o)):await this.setForeignStateAsync(i,o),t({result:"Ok"}))}catch(e){t({error:e.toString()})}}}else t?.({error:"not implemented"})}else void 0!==this.config.text2command&&""!==this.config.text2command?this.setForeignState(`text2command.${this.config.text2command}.text`,decodeURIComponent(e.data),(e=>{t?.({result:e?.toString()||"Ok"})})):(this.log.warn("Received service text2command, but instance is not defined"),t?.({error:"instance is not defined"}));else this.log.warn(`Received service "${e.name}", but it is not found in whitelist`),t?.({error:"blocked"})}else t&&t({error:"no name"})})),this.socket.on("error",(e=>{console.error(`Some error: ${e}`),this.startConnect()}))}}_createAppKey(e){this.log.info("Create new APP-KEY...");const t=`https://${this.config.server}:3001/api/v1/appkeys`;axios_1.default.post(t,null,{headers:{Authorization:`Basic ${Buffer.from(`${this.config.login}:${this.config.pass}`).toString("base64")}`},validateStatus:e=>e<400}).then((s=>{const i=s.data;i?.key?.[0]?(this.log.info(`New APP-KEY is ${i.key[0]}`),e(null,i.key[0])):e(`Cannot create app-key on server "${t}": ${JSON.stringify(i)}`)})).catch((s=>{if("ECONNREFUSED"===s.code)this.log.warn("Server is offline or no connection. Retry in 10 seconds"),this.timeouts.createAppKey=setTimeout((()=>{this.timeouts.createAppKey=null,this._createAppKey(e)}),1e4);else{if(401===s.response?.status)return e(`Invalid user name or password or server (may be it is ${"iobroker.pro"===this.config.server?"iobroker.net":"iobroker.pro"})`);if(s.response?.data){const i=s.response.data;i?.key?.[0]?(this.log.info(`New APP-KEY is ${i.key[0]}`),e(null,i.key[0])):e(`Cannot create app-key on server "${t}": ${s.response?.status||s.response?.data&&JSON.stringify(s.response.data)||"unknown error"}`)}else e(`Cannot create app-key on server "${t}": ${s.code||"unknown error"}`)}}))}_readAppKeyFromCloud(e,t,s,i){if(e||=this.config.server,t||=this.config.login,s||=this.config.pass,!e.length)return void i("Servername not provided. Please check your configuration!");if(!t.length)return void i("Login not provided. Please check your configuration!");if(!s.length)return void i("Password not provided. Please check your configuration!");const o=`https://${e}:3001/api/v1/appkeys`;axios_1.default.get(o,{headers:{Authorization:`Basic ${Buffer.from(`${t}:${s}`).toString("base64")}`},validateStatus:e=>e<400}).then((e=>{const t=e.data;t?.[0]?.key?i(null,t[0].key):t?this._createAppKey(i):i(`Cannot create app-key on server "${o}": ${t?JSON.stringify(t):"key does not exist"}`)})).catch((n=>{if("ECONNREFUSED"===n.code)this.log.warn("Server is offline or no connection. Retry in 10 seconds"),this.timeouts.readAppKey=setTimeout((()=>{this.timeouts.readAppKey=null,this._readAppKeyFromCloud(e,t,s,i)}),1e4);else{if(n.response&&401===n.response.status)return i(`Invalid user name or password or server (may be it is ${"iobroker.pro"===this.config.server?"iobroker.net":"iobroker.pro"})`);if(n.response&&n.response.data){const e=n.response.data;e?.[0]?.key?(this.log.info(`New APP-KEY is ${e[0].key}`),i(null,e[0].key)):i(`Cannot create app-key on server "${o}": ${n.response&&n.response.status||n.response&&n.response.data&&JSON.stringify(n.response.data)||"unknown error"}`)}else i(`Cannot create app-key on server "${o}": ${n.code||"unknown error"}`)}}))}readAppKeyFromCloud(){return new Promise(((e,t)=>this._readAppKeyFromCloud(void 0,void 0,void 0,((s,i)=>s?t(new Error(s)):e(i)))))}async main(){if(this.config.pingTimeout=parseInt(this.config.pingTimeout,10)||5e3,this.config.pingTimeout<3e3&&(this.config.pingTimeout=3e3),void 0===this.config.deviceOffLevel&&(this.config.deviceOffLevel=30),this.config.deviceOffLevel=parseFloat(this.config.deviceOffLevel)||0,this.config.concatWord=(this.config.concatWord||"").toString().trim(),this.config.apikey=(this.config.apikey||"").trim(),this.config.replaces=Array.isArray(this.config.replaces)?this.config.replaces:this.config.replaces?.split(",")||null,this.config.cloudUrl=(this.config.cloudUrl||"").toString(),this.config.pass=this.config.pass||"",this.config.login=this.config.login||"",this.config.server=this.config.server||"iobroker.pro",this.config.login!==(this.config.login||"").trim().toLowerCase()&&this.log.error("Please write your login only in lowercase!"),this.config.login&&this.config.pass&&this.config.useCredentials?("iobroker.pro"===this.config.server?this.config.cloudUrl=this.config.cloudUrl.replace("iobroker.net","iobroker.pro"):"iobroker.net"===this.config.server&&(this.config.cloudUrl=this.config.cloudUrl.replace("iobroker.pro","iobroker.net")),this.apikey=await this.readAppKeyFromCloud()):this.apikey=this.config.apikey,this.apikey?.startsWith("@pro_")?this.config.cloudUrl.startsWith("https://iobroker.pro:")||(this.config.cloudUrl="https://iobroker.pro:10555"):(this.config.allowAdmin=!1,this.config.lovelace=!1),this.config.replaces){const e=[];for(let t=0;t<this.config.replaces.length;t++)e.push(`"${this.config.replaces.join(", ")}"`);this.log.debug(`Following strings will be replaced in names: ${e.join(", ")}`)}if("string"==typeof this.config.allowedServices?this.config.allowedServices=(this.config.allowedServices||"").split(/[,\s]+/):Array.isArray(this.config.allowedServices)||(this.config.allowedServices=[]),this.config.allowedServices=this.config.allowedServices.map((e=>e.trim())),await this.setStateAsync("info.connection",!1,!0),this.config.cloudUrl=this.config.cloudUrl||"https://iobroker.net:10555",!this.apikey)return this.log.error("No api-key found. Please get one on https://iobroker.net");if(this.config.iftttKey){await this.subscribeStatesAsync("services.ifttt");try{await this.getObjectAsync("services.ifttt")||await this.setObjectAsync("services.ifttt",{_id:`${this.namespace}.services.ifttt`,type:"state",common:{name:"IFTTT value",write:!0,role:"state",read:!0,type:"mixed",desc:"All written data will be sent to IFTTT. If no state specified all requests from IFTTT will be saved here"},native:{}})}catch(e){this.log.error(e)}}if(this.config.instance&&!this.config.instance.startsWith("system.adapter.")&&(this.config.instance=`system.adapter.${this.config.instance}`),this.config.allowAdmin&&!this.config.allowAdmin.startsWith("system.adapter.")&&(this.config.allowAdmin=`system.adapter.${this.config.allowAdmin}`),this.config.lovelace&&!this.config.lovelace.startsWith("system.adapter.")&&(this.config.lovelace=`system.adapter.${this.config.lovelace}`),this.subscribeStates("smart.*"),this.subscribeStates("remote.command"),this.config.instance)try{await this.subscribeForeignObjectsAsync(this.config.instance)}catch(e){this.log.error(`Cannot subscribe: ${e}`)}if(this.config.allowAdmin)try{await this.subscribeForeignObjectsAsync(this.config.allowAdmin)}catch(e){this.log.error(`Cannot subscribe: ${e}`)}if(this.config.lovelace)try{await this.subscribeForeignObjectsAsync(this.config.lovelace)}catch(e){this.log.error(`Cannot subscribe: ${e}`)}this.log.info(`Connecting with ${this.config.cloudUrl} with "${this.apikey}"`);const e=await this.getForeignObjectAsync("system.meta.uuid");if(e?.native&&(this.uuid=e.native.uuid),!this.uuid)throw new Error("No UUID found");this.startConnect(!0)}}exports.CloudAdapter=CloudAdapter,require.main!==module?module.exports=e=>new CloudAdapter(e):new CloudAdapter;
//# sourceMappingURL=/sm/11172fb304a244eba0d1190ef409d06385dcb85f4aa33dd1dc3745561a0a9cf0.map