@sebbo2002/vestaboard2mqtt 6.0.4-develop.4 → 6.0.4-develop.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/start.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{a as o}from"../chunk-Z36WS5HL.js";o.run().catch(e=>{console.log(e),process.exit(1)});
2
+ import{a as o}from"../chunk-KRLCDDZM.js";o.run().catch(e=>{console.log(e),process.exit(1)});
3
3
  //# sourceMappingURL=start.js.map
@@ -11,7 +11,7 @@ var gu=Object.create;var hr=Object.defineProperty;var yu=Object.getOwnPropertyDe
11
11
  `+r)),t.removeListener("error",Vn),t.destroy()}function Sg(t){return t.trim()}});var Zl=g((Mm,Jl)=>{"use strict";var nr=jn();nr.createWebSocketStream=zl();nr.Server=Xl();nr.Receiver=Pn();nr.Sender=In();Jl.exports=nr});var Kn=g((qm,Hn)=>{"use strict";var{Buffer:sr}=b("buffer"),eu=Zl(),or=me()("mqttjs:ws"),Eg=ei(),xg=Ne().Transform,Tg=["rejectUnauthorized","ca","cert","key","pfx","passphrase"],tu=typeof process<"u"&&process.title==="browser"||typeof __webpack_require__=="function";function ru(t,e){let r=t.protocol+"://"+t.hostname+":"+t.port+t.path;return typeof t.transformWsUrl=="function"&&(r=t.transformWsUrl(r,t,e)),r}function iu(t){let e=t;return t.hostname||(e.hostname="localhost"),t.port||(t.protocol==="wss"?e.port=443:e.port=80),t.path||(e.path="/"),t.wsOptions||(e.wsOptions={}),!tu&&t.protocol==="wss"&&Tg.forEach(function(r){Object.prototype.hasOwnProperty.call(t,r)&&!Object.prototype.hasOwnProperty.call(t.wsOptions,r)&&(e.wsOptions[r]=t[r])}),e}function Cg(t){let e=iu(t);if(e.hostname||(e.hostname=e.host),!e.hostname){if(typeof document>"u")throw new Error("Could not determine host. Specify host manually.");let r=new URL(document.URL);e.hostname=r.hostname,e.port||(e.port=r.port)}return e.objectMode===void 0&&(e.objectMode=!(e.binary===!0||e.binary===void 0)),e}function Pg(t,e,r){or("createWebSocket"),or("protocol: "+r.protocolId+" "+r.protocolVersion);let i=r.protocolId==="MQIsdp"&&r.protocolVersion===3?"mqttv3.1":"mqtt";return or("creating new Websocket for url: "+e+" and protocol: "+i),new eu(e,[i],r.wsOptions)}function Og(t,e){let r=e.protocolId==="MQIsdp"&&e.protocolVersion===3?"mqttv3.1":"mqtt",i=ru(e,t),n=new WebSocket(i,[r]);return n.binaryType="arraybuffer",n}function Ig(t,e){or("streamBuilder");let r=iu(e),i=ru(r,t),n=Pg(t,i,r),s=eu.createWebSocketStream(n,r.wsOptions);return s.url=i,n.on("close",()=>{s.destroy()}),s}function Rg(t,e){or("browserStreamBuilder");let r,n=Cg(e).browserBufferSize||1024*512,s=e.browserBufferTimeout||1e3,o=!e.objectMode,a=Og(t,e),u=f(e,v,w);e.objectMode||(u._writev=y),u.on("close",()=>{a.close()});let l=typeof a.addEventListener<"u";a.readyState===a.OPEN?r=u:(r=r=Eg(void 0,void 0,e),e.objectMode||(r._writev=y),l?a.addEventListener("open",h):a.onopen=h),r.socket=a,l?(a.addEventListener("close",c),a.addEventListener("error",d),a.addEventListener("message",m)):(a.onclose=c,a.onerror=d,a.onmessage=m);function f(P,U,z){let W=new xg({objectModeMode:P.objectMode});return W._write=U,W._flush=z,W}function h(){r.setReadable(u),r.setWritable(u),r.emit("connect")}function c(){r.end(),r.destroy()}function d(P){r.destroy(P)}function m(P){let U=P.data;U instanceof ArrayBuffer?U=sr.from(U):U=sr.from(U,"utf8"),u.push(U)}function y(P,U){let z=new Array(P.length);for(let W=0;W<P.length;W++)typeof P[W].chunk=="string"?z[W]=sr.from(P[W],"utf8"):z[W]=P[W].chunk;this._write(sr.concat(z),"binary",U)}function v(P,U,z){a.bufferedAmount>n&&setTimeout(v,s,P,U,z),o&&typeof P=="string"&&(P=sr.from(P,"utf8"));try{a.send(P)}catch(W){return z(W)}z()}function w(P){a.close(),P()}return r}tu?Hn.exports=Rg:Hn.exports=Ig});var au=g((Nm,ar)=>{"use strict";var su=cn(),Ag=Ir(),Bg=b("url"),kg=dr(),nu=me()("mqttjs"),te={};typeof process<"u"&&process.title!=="browser"||typeof __webpack_require__!="function"?(te.mqtt=hn(),te.tcp=hn(),te.ssl=Xr(),te.tls=Xr(),te.mqtts=Xr()):(te.wx=gn(),te.wxs=gn(),te.ali=_n(),te.alis=_n());te.ws=Kn();te.wss=Kn();function Lg(t){let e;t.auth&&(e=t.auth.match(/^(.+):(.+)$/),e?(t.username=e[1],t.password=e[2]):t.username=t.auth)}function ou(t,e){if(nu("connecting to an MQTT broker..."),typeof t=="object"&&!e&&(e=t,t=null),e=e||{},t){let n=Bg.parse(t,!0);if(n.port!=null&&(n.port=Number(n.port)),e=kg(n,e),e.protocol===null)throw new Error("Missing protocol");e.protocol=e.protocol.replace(/:$/,"")}if(Lg(e),e.query&&typeof e.query.clientId=="string"&&(e.clientId=e.query.clientId),e.cert&&e.key)if(e.protocol){if(["mqtts","wss","wxs","alis"].indexOf(e.protocol)===-1)switch(e.protocol){case"mqtt":e.protocol="mqtts";break;case"ws":e.protocol="wss";break;case"wx":e.protocol="wxs";break;case"ali":e.protocol="alis";break;default:throw new Error('Unknown protocol for secure connection: "'+e.protocol+'"!')}}else throw new Error("Missing secure protocol key");if(!te[e.protocol]){let n=["mqtts","wss"].indexOf(e.protocol)!==-1;e.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter(function(s,o){return n&&o%2===0?!1:typeof te[s]=="function"})[0]}if(e.clean===!1&&!e.clientId)throw new Error("Missing clientId for unclean clients");e.protocol&&(e.defaultProtocol=e.protocol);function r(n){return e.servers&&((!n._reconnectCount||n._reconnectCount===e.servers.length)&&(n._reconnectCount=0),e.host=e.servers[n._reconnectCount].host,e.port=e.servers[n._reconnectCount].port,e.protocol=e.servers[n._reconnectCount].protocol?e.servers[n._reconnectCount].protocol:e.defaultProtocol,e.hostname=e.host,n._reconnectCount++),nu("calling streambuilder for",e.protocol),te[e.protocol](n,e)}let i=new su(r,e);return i.on("error",function(){}),i}ar.exports=ou;ar.exports.connect=ou;ar.exports.MqttClient=su;ar.exports.Store=Ag});var uu=g((Dm,lu)=>{"use strict";var Mg=Xi().NumberAllocator;function Ye(){if(!(this instanceof Ye))return new Ye;this.numberAllocator=new Mg(1,65535)}Ye.prototype.allocate=function(){return this.lastId=this.numberAllocator.alloc(),this.lastId};Ye.prototype.getLastAllocated=function(){return this.lastId};Ye.prototype.register=function(t){return this.numberAllocator.use(t)};Ye.prototype.deallocate=function(t){this.numberAllocator.free(t)};Ye.prototype.clear=function(){this.numberAllocator.clear()};lu.exports=Ye});var cu=g((Um,pt)=>{"use strict";var fu=cn(),qg=au(),Ng=Ir(),Dg=ln(),Ug=uu();pt.exports.connect=qg;pt.exports.MqttClient=fu;pt.exports.Client=fu;pt.exports.Store=Ng;pt.exports.DefaultMessageIdProvider=Dg;pt.exports.UniqueMessageIdProvider=Ug});var Sv=wu(cu(),1);import Qg from"async-mqtt";import{Vesta as Yg}from"vestaboard-api";import{existsSync as jg}from"fs";import{promises as Fg}from"fs";import{join as Wg}from"path";var{readFile:Vg,writeFile:Hg}=Fg,re=class t{static currentData={};static currentFetch;static file=Wg(process.env.HOME||"~",".vestaboard2mqtt");namespace;constructor(e){this.namespace=e}static async fetch(){if(this.currentFetch)return this.currentFetch;let e=this.fetchFromFile();return this.currentFetch=e,e}static async fetchFromFile(){if(jg(this.file))try{let e=await Vg(this.file,{encoding:"utf8"});this.currentData=JSON.parse(e)}catch(e){console.warn(`Unable to parse cache file: ${e}`)}}static isCacheItemObject(e){return e!==null&&typeof e=="object"&&"updated"in e&&typeof e.updated=="number"&&"value"in e&&typeof e.value<"u"}static async save(){await Hg(this.file,JSON.stringify(this.currentData,null," "))}async delete(e){!t.currentData||!t.currentData[this.namespace]||(delete t.currentData[this.namespace][e],Object.keys(t.currentData[this.namespace]).length===0&&delete t.currentData[this.namespace],await t.save().catch(r=>{console.warn(`Unable to update cache: ${r}`)}))}async get(e,r=0){if(await t.fetch(),!t.currentData||!t.currentData[this.namespace]||!t.currentData[this.namespace][e])return null;let i=t.currentData[this.namespace][e];return!t.isCacheItemObject(i)&&r>0?null:t.isCacheItemObject(i)?r>0&&new Date().getTime()-i.updated>r?null:i.value:i}async set(e,r){if(await t.fetch(),!t.currentData)throw new Error("Unable to set value: currentData is empty!");t.currentData[this.namespace]=t.currentData[this.namespace]||{},t.currentData[this.namespace][e]={updated:new Date().getTime(),value:r},await t.save().catch(i=>{console.warn(`Unable to update cache: ${i}`)})}};var L=class{static get board(){if(this.loaded&&this.data?.board)return this.data.board;throw new Error("Unable to access board config, is config loaded?")}static get calendar(){if(this.loaded&&this.data?.calendar)return this.data.calendar;throw new Error("Unable to access calendar config, is config loaded?")}static get loaded(){return!!this.data&&!!this.cache}static get mqtt(){if(this.loaded&&this.data?.mqtt)return this.data.mqtt;throw new Error("Unable to access mqtt config, is config loaded?")}static cache=new re("config");static data;static async load(){let e=await this.cache.get("default");if(!e)throw new Error("Unable to load configuration, try to run the setup script\u2026");this.data=e}static async save(e){this.data=e,await this.cache.set("default",e)}static async updateDisabled(e){e===this.data?.board.disabled||!this.loaded||!this.data?.mqtt||(this.data.board.disabled=e,await this.save(this.data))}};import{characterCode as hu,emptyBoard as Kg,LINE_LENGTH as zn}from"vestaboard-api/lib/cjs/values.js";var zg=[["\xE4",[1,5]],["\xC4",[1,5]],["\xF6",[15,5]],["\xD6",[15,5]],["\xFC",[21,5]],["\xDC",[21,5]],["\xDF",[19,19]],["\u{1F7E5}",[63]],["\u{1F7E7}",[64]],["\u{1F7E8}",[65]],["\u{1F7E9}",[66]],["\u{1F7E6}",[67]],["\u{1F7EA}",[68]],["\u2B1C\uFE0F",[69]],["\u2B1C",[69]],["\u2B1B\uFE0F",[0]],["\u2B1B",[0]],["\uFE6B",[38]],["\uFF20",[38]],["0\uFE0F\u20E3",[36]],["1\uFE0F\u20E3",[27]],["2\uFE0F\u20E3",[28]],["3\uFE0F\u20E3",[29]],["4\uFE0F\u20E3",[30]],["5\uFE0F\u20E3",[31]],["6\uFE0F\u20E3",[32]],["7\uFE0F\u20E3",[33]],["8\uFE0F\u20E3",[34]],["9\uFE0F\u20E3",[35]],["\u2755",[37]],["\u203C\uFE0F",[37,37]],["\u2757\uFE0F",[37]],["\u2049\uFE0F",[37,60]],["\u26A0\uFE0F",[65]],["#\uFE0F\u20E3",[39]],["\u{1F4B8}",[40]],["\u{1F4B2}",[40]],["\u{1F4B5}",[40]],["\u{1F4B0}",[40]],["$",[40]],["\uFE69",[40]],["\uFF04",[40]],["\u2190",[44]],["\u2192",[44]],["\u27A1",[44]],["\u2B05",[44]],["\u2794",[44]],["\u2194",[44]],["\u2013",[44]],["\u2795",[46]],["+",[46]],["\uFE6A",[54]],["\uFF05",[54]],["\u2753",[60]],["\u2754",[60]],["\u2103",[62,3]],["\u2109",[62,6]]],ge=class t{board;currentLine=null;isFilled=!1;constructor(e=t.newBoardCharArray()){this.board=e}static char2char(e){let r=Object.entries(hu).find(([n])=>e===n);if(r)return[r[1]];let i=zg.find(([n])=>e===n);return i&&Array.isArray(i[1])?i[1]:[60]}static charToString(e){let r=Object.entries(hu).filter(([i])=>i.length<=2).find(([,i])=>i===e);if(r)return r[0].toUpperCase()+" ";switch(e){case 63:return"\u{1F7E5}";case 64:return"\u{1F7E7}";case 65:return"\u{1F7E8}";case 66:return"\u{1F7E9}";case 67:return"\u{1F7E6}";case 68:return"\u{1F7EA}";case 69:return"\u2B1C\uFE0F";default:return" "}}static newBoardCharArray(){return JSON.parse(JSON.stringify(Kg))}static word2chars(e){let r=[];for(let i of e)r.push(...this.char2char(i));return r}center(){let e=[this.board.findIndex(i=>i.find(n=>n!==0)),Math.min(...this.board.map(i=>i.find(n=>n!==0)?i.slice().reverse().findIndex(n=>n!==0):i.length)),this.board.slice().reverse().findIndex(i=>i.find(n=>n!==0)),Math.min(...this.board.map(i=>i.find(n=>n!==0)?i.findIndex(n=>n!==0):i.length))],r=[Math.floor((e[0]+e[2])/2),Math.floor((e[1]+e[3])/2)];if(e[0]!==r[0]){let i=r[0]-e[0];this.board.splice(e[0]<r[0]?0:this.board.length-i,0,...this.board.splice(this.board.length-i,i))}if(e[3]!==r[1]){let i=r[1]-e[3];this.board.forEach(n=>{n.splice(e[3]<r[1]?0:n.length-i,0,...n.splice(n.length-i,i))})}}centerLines(){this.board.forEach(e=>{let r=[e.findIndex(s=>s!==0),e.slice().reverse().findIndex(s=>s!==0)];if(r[0]===-1||r[1]===-1)return;let i=e.slice(r[0],e.length-r[1]),n=Math.floor((r[0]+r[1])/2);e.fill(0,0,n),e.splice(n,i.length,...i),e.fill(0,n+i.length)})}export(){return this.board}isEmpty(){return!this.board.find(e=>e.find(r=>r!==0))}repeat(e,r={}){this.board[r.line||0].fill(t.char2char(e)[0])}toString(){return"#="+"=".repeat(zn*2)+`=#
12
12
  `+this.board.map(e=>"# "+e.map(r=>t.charToString(r)).join("")+` #
13
13
  `).join("")+"#="+"=".repeat(zn*2)+`=#
14
- `}write(e,r={}){let i=0;if(this.isFilled)return;if(r.line==="CURRENT")i=this.currentLine||0;else if(r.line==="NEXT"&&this.currentLine===null)this.currentLine=0,i=this.currentLine;else if(r.line==="NEXT"&&typeof this.currentLine=="number"&&this.currentLine<this.board.length-1)this.currentLine++,i=this.currentLine;else if(r.line==="NEXT"){this.isFilled=!0;return}else r.line!==void 0&&(i=r.line);let n={firstLine:i,firstRow:r.row||0,lastLine:this.board.length-1,lastRow:zn-1},s=[n.firstRow,n.firstLine];e.split(/\s+/).forEach((a,u)=>{u!==0&&s[0]!==n.firstRow&&(this.board[s[1]][s[0]]=0,s[0]++);let l=n.lastRow-s[0]+1,f=t.word2chars(a);f.filter(h=>h===60).length===f.length&&f.length>0||(f.length>l&&f.length<=n.lastRow-n.firstRow+1&&s[1]<n.lastLine&&(s[0]=n.firstRow,s[1]++,l=n.lastRow-s[0]),f.length<=l?(this.board[s[1]].splice(s[0],f.length,...f),s[0]+=f.length):f.length>l&&l>5&&(this.board[s[1]].splice(s[0],l,...f.slice(0,l)),s[0]+=l))}),this.currentLine=s[1]}};import $g from"node-ical";var gt=class{static cache=new re("calendar");parseConfig(e,r,i){let n={};return console.log("parseConfig",i),e==="min-temp"&&Array.isArray(i.temp)?n.temp=[parseInt(r||""),Math.max(...i.temp)]:e==="min-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="max-temp"&&Array.isArray(i.temp)?n.temp=[Math.min(...i.temp),parseInt(r||"")]:e==="max-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="precip"?n.precip=parseInt(r||"",10):e==="locale"&&(n.locale=String(r)),n}parsePayload(e){try{return JSON.parse(e||"")}catch{return{}}}async render(e,r){let i=new ge,n=new Date,s=Object.assign({locale:"en",precip:void 0,temp:void 0},r,e);i.write(n.toLocaleString(s.locale,{weekday:"long"})),i.write(n.toLocaleString(s.locale,{day:"numeric",month:"long"}),{line:"NEXT"}),i.write("",{line:"NEXT"});let o=[];Array.isArray(s.temp)&&o.push(`${Math.min(...s.temp)}-${Math.max(...s.temp)}\xB0C`),typeof s.precip=="number"&&s.precip>0&&o.push(`${s.precip}%`),o.length&&i.write(o.join(", "),{line:"NEXT"}),i.center();let a=new Date;return a.setHours(24,0,0,0),{message:i,validTill:a}}};var lr=class t{static cache=new re("calendar");static getTimeStr(e,r=!1){return this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date,e.start)?"Heute":this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),e.start)?r?"Morgen":"Morgn":e.start.getHours().toString().padStart(2,"\u2B1B\uFE0F")+":"+e.start.getMinutes().toString().padStart(2,"0")}static isMidnight(e){return!e.getHours()&&!e.getMinutes()&&!e.getSeconds()&&!e.getMilliseconds()}static isSameDay(e,r){return e.getFullYear()===r.getFullYear()&&e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()}async fetchURL(e){let r=await t.cache.get(e,6e5);if(!r){let i=await $g.async.fromURL(e);r=Object.values(i).filter(s=>s.type==="VEVENT"&&s.start&&s.end&&s.summary).map(s=>({end:new Date(String(s.end)),start:new Date(String(s.start)),summary:String(s.summary).trim()})).filter(s=>s.end>new Date).sort((s,o)=>s.end.getTime()-o.end.getTime()).slice(0,6),await t.cache.set(e,r)}return r.map(i=>({end:new Date(String(i.end)),start:new Date(String(i.start)),summary:String(i.summary)})).filter(i=>i.end>new Date)}async fetchURLs(e){let r=await Promise.all(e.map(i=>this.fetchURL(i)));return[].concat(...r).filter(i=>i.end>new Date).sort((i,n)=>i.end.getTime()-n.end.getTime())}parseConfig(){return{}}parsePayload(e){return{calendars:(e||"").split(",")}}async render(e){let r=new ge,i=e.calendars.map(o=>L.calendar.urls[o]).filter(Boolean),n=await this.fetchURLs(i).then(o=>o.filter(a=>t.isMidnight(a.start)&&t.isMidnight(a.end)?t.isSameDay(new Date,a.start)||new Date().getHours()>=20&&t.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),a.start):a.start<new Date(new Date().getTime()+1e3*60*60*12)));if(!n.length){let o=new gt,u=await new re("page-config").get("today");return o.render({},u||{})}let s=new Date(new Date().getTime()+1e3*60*10);return n.forEach(o=>{r.write(t.getTimeStr(o,n.length===1),{line:"NEXT"}),r.write(o.summary,{line:"CURRENT",row:6}),r.write("",{line:"NEXT"}),o.end<s&&(s=o.end)}),r.center(),{message:r,validTill:s}}};var ur=class{static cache=new re("calendar");parseConfig(){return{}}parsePayload(e){return e||""}async render(e){let r=new ge;return e.split(`
14
+ `}write(e,r={}){let i=0;if(this.isFilled)return;if(r.line==="CURRENT")i=this.currentLine||0;else if(r.line==="NEXT"&&this.currentLine===null)this.currentLine=0,i=this.currentLine;else if(r.line==="NEXT"&&typeof this.currentLine=="number"&&this.currentLine<this.board.length-1)this.currentLine++,i=this.currentLine;else if(r.line==="NEXT"){this.isFilled=!0;return}else r.line!==void 0&&(i=r.line);let n={firstLine:i,firstRow:r.row||0,lastLine:this.board.length-1,lastRow:zn-1},s=[n.firstRow,n.firstLine];e.split(/\s+/).forEach((a,u)=>{u!==0&&s[0]!==n.firstRow&&(this.board[s[1]][s[0]]=0,s[0]++);let l=n.lastRow-s[0]+1,f=t.word2chars(a);f.filter(h=>h===60).length===f.length&&f.length>0||(f.length>l&&f.length<=n.lastRow-n.firstRow+1&&s[1]<n.lastLine&&(s[0]=n.firstRow,s[1]++,l=n.lastRow-s[0]),f.length<=l?(this.board[s[1]].splice(s[0],f.length,...f),s[0]+=f.length):f.length>l&&l>5&&(this.board[s[1]].splice(s[0],l,...f.slice(0,l)),s[0]+=l))}),this.currentLine=s[1]}};import $g from"node-ical";var gt=class{static cache=new re("calendar");parseConfig(e,r,i){let n={};return console.log("parseConfig",i),e==="min-temp"&&Array.isArray(i.temp)?n.temp=[parseInt(r||""),Math.max(...i.temp)]:e==="min-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="max-temp"&&Array.isArray(i.temp)?n.temp=[Math.min(...i.temp),parseInt(r||"")]:e==="max-temp"?n.temp=[parseInt(r||""),parseInt(r||"")]:e==="precip"?n.precip=parseInt(r||"",10):e==="locale"&&(n.locale=String(r)),n}parsePayload(e){try{return JSON.parse(e||"")}catch{return{}}}async render(e,r){let i=new ge,n=new Date,s=Object.assign({locale:"en",precip:void 0,temp:void 0},r,e);i.write(n.toLocaleString(s.locale,{weekday:"long"})),i.write(n.toLocaleString(s.locale,{day:"numeric",month:"long"}),{line:"NEXT"}),i.write("",{line:"NEXT"});let o=[];Array.isArray(s.temp)&&o.push(`${Math.min(...s.temp)}-${Math.max(...s.temp)}\xB0C`),typeof s.precip=="number"&&s.precip>0&&o.push(`${s.precip}%`),o.length&&i.write(o.join(", "),{line:"NEXT"}),i.center();let a=new Date;return a.setHours(24,0,0,0),{message:i,validTill:a}}};var lr=class t{static cache=new re("calendar");static getTimeStr(e,r=!1){return this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date,e.start)?"Heute":this.isMidnight(e.start)&&this.isMidnight(e.end)&&this.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),e.start)?r?"Morgen":"Morgn":e.start.getHours().toString().padStart(2,"\u2B1B\uFE0F")+":"+e.start.getMinutes().toString().padStart(2,"0")}static isMidnight(e){return!e.getHours()&&!e.getMinutes()&&!e.getSeconds()&&!e.getMilliseconds()}static isSameDay(e,r){return e.getFullYear()===r.getFullYear()&&e.getMonth()===r.getMonth()&&e.getDate()===r.getDate()}async fetchURL(e){let r=await t.cache.get(e,6e5);if(!r){let i=await $g.async.fromURL(e);r=Object.values(i).filter(s=>s&&s.type==="VEVENT"&&s.start&&s.end&&s.summary).map(s=>({end:new Date(String(s.end)),start:new Date(String(s.start)),summary:String(s.summary).trim()})).filter(s=>s.end>new Date).sort((s,o)=>s.end.getTime()-o.end.getTime()).slice(0,6),await t.cache.set(e,r)}return r.map(i=>({end:new Date(String(i.end)),start:new Date(String(i.start)),summary:String(i.summary)})).filter(i=>i.end>new Date)}async fetchURLs(e){let r=await Promise.all(e.map(i=>this.fetchURL(i)));return[].concat(...r).filter(i=>i.end>new Date).sort((i,n)=>i.end.getTime()-n.end.getTime())}parseConfig(){return{}}parsePayload(e){return{calendars:(e||"").split(",")}}async render(e){let r=new ge,i=e.calendars.map(o=>L.calendar.urls[o]).filter(Boolean),n=await this.fetchURLs(i).then(o=>o.filter(a=>t.isMidnight(a.start)&&t.isMidnight(a.end)?t.isSameDay(new Date,a.start)||new Date().getHours()>=20&&t.isSameDay(new Date(new Date().getTime()+1e3*60*60*24),a.start):a.start<new Date(new Date().getTime()+1e3*60*60*12)));if(!n.length){let o=new gt,u=await new re("page-config").get("today");return o.render({},u||{})}let s=new Date(new Date().getTime()+1e3*60*10);return n.forEach(o=>{r.write(t.getTimeStr(o,n.length===1),{line:"NEXT"}),r.write(o.summary,{line:"CURRENT",row:6}),r.write("",{line:"NEXT"}),o.end<s&&(s=o.end)}),r.center(),{message:r,validTill:s}}};var ur=class{static cache=new re("calendar");parseConfig(){return{}}parsePayload(e){return e||""}async render(e){let r=new ge;return e.split(`
15
15
  `).forEach(i=>{r.write(i,{line:"NEXT"})}),r.centerLines(),r.center(),{message:r}}};var Gg={calendar:new lr,message:new ur,today:new gt},fr=Gg;var $n=class t{board;currentMessage;currentTimer;mqtt;pageConfig=new re("page-config");subscriptionIds;constructor(){this.board=new Yg({apiKey:L.board.key,apiSecret:L.board.secret}),this.mqtt=Qg.connect(L.mqtt.url,{will:{payload:"offline",qos:0,retain:!0,topic:L.mqtt.prefix+"/status"}}),this.mqtt.on("connect",()=>{this.mqtt.publish(L.mqtt.prefix+"/status","online",{retain:!0}),this.setupBrokerSubscriptions().catch(e=>{console.error(new Error(`Unable to setup mqtt subscriptions: ${e.stack}`)),process.exit(1)})}),this.mqtt.on("message",(e,r)=>{this.handleMessage(e,r.toString()).catch(i=>{this.debug(`Unable to handle message: ${i.stack}`)})})}static async run(){return await L.load(),new t}debug(e){let r=String(e);this.mqtt.publish(L.mqtt.prefix+"/debug",r),console.log(r)}async handleMessage(e,r){if(![L.mqtt.prefix+"/debug",L.mqtt.prefix+"/status"].includes(e))if(e===L.mqtt.prefix+"/disabled"){let i=["1","true","TRUE"].includes(r);await L.updateDisabled(i),i||(this.debug("Board not disabled anymore, update with latest message"),await this.updateCurrentMessage())}else if(Object.keys(fr).map(i=>L.mqtt.prefix+"/"+i).includes(e)){let i=fr[e.substr(L.mqtt.prefix.length+1)];await this.renderMessage(i,r)}else{let i=Object.entries(fr).find(([u])=>e.startsWith(L.mqtt.prefix+"/"+u+"/"));if(!i){this.debug(`Unknown topic ${e}, I'm sorry`);return}let n=e.substr((L.mqtt.prefix+"/"+i[0]+"/").length),s=await this.pageConfig.get(i[0]),o=i[1].parseConfig(n,r,s||{}),a=Object.assign(s||{},o);await this.pageConfig.set(i[0],a),await this.updateCurrentMessage(),this.debug(`Update config for page module ${i[0]}: ${JSON.stringify(a,null," ")}`)}}async renderMessage(e,r){this.currentMessage={page:e,payload:r};let i=Object.entries(fr).find(([,a])=>a===e);if(L.board.disabled||!i)return;let n=await e.parsePayload(r),s=await this.pageConfig.get(i[0]),o=await e.render(n,s||{});o.message&&await this.sendMessage(o.message),this.currentTimer&&(clearTimeout(this.currentTimer),delete this.currentTimer),o.validTill&&(this.debug(`Set timer for ${o.validTill.toString()} to update message`),this.currentTimer=setTimeout(()=>{this.debug("Here I am again, updating the message now\u2026"),this.renderMessage(e,r).catch(a=>{this.debug(`Unable to update page: ${a}`)})},o.validTill.getTime()-new Date().getTime()))}async sendMessage(e=new ge){let r=e.export();if(!this.subscriptionIds){let i=await this.board.getSubscriptions();this.subscriptionIds=i.map(n=>n._id)}this.debug(`Sending Message:
16
16
 
17
17
  `+e.toString()),await Promise.all(this.subscriptionIds.map(i=>this.board.postMessage(i,r)))}async setupBrokerSubscriptions(){if(!this.mqtt)throw new Error("Unable to setup subscriptions: client not set.");await this.mqtt.subscribe(L.mqtt.prefix+"/#")}async updateCurrentMessage(){this.currentMessage&&await this.renderMessage(this.currentMessage.page,this.currentMessage.payload)}};export{$n as a};
@@ -20,4 +20,4 @@ var gu=Object.create;var hr=Object.defineProperty;var yu=Object.getOwnPropertyDe
20
20
  safe-buffer/index.js:
21
21
  (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
22
22
  */
23
- //# sourceMappingURL=chunk-Z36WS5HL.js.map
23
+ //# sourceMappingURL=chunk-KRLCDDZM.js.map