@xiboplayer/pwa 0.6.1 → 0.6.2
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/assets/{chunk-config-oTovBPVw.js → chunk-config-BjXWw-V8.js} +2 -2
- package/dist/assets/{chunk-config-oTovBPVw.js.map → chunk-config-BjXWw-V8.js.map} +1 -1
- package/dist/assets/index-BglkPErZ.js +5 -0
- package/dist/assets/index-BglkPErZ.js.map +1 -0
- package/dist/assets/index-BwkVsox3.js +2 -0
- package/dist/assets/{index-D81Qhc3r.js.map → index-BwkVsox3.js.map} +1 -1
- package/dist/assets/{index-BWvWWyDc.js → index-C0mqgU51.js} +2 -2
- package/dist/assets/{index-BWvWWyDc.js.map → index-C0mqgU51.js.map} +1 -1
- package/dist/assets/index-CwIMcVP6.js +13 -0
- package/dist/assets/index-CwIMcVP6.js.map +1 -0
- package/dist/assets/{index-CleHw0Tc.js → index-D4fqdfS-.js} +2 -2
- package/dist/assets/{index-CleHw0Tc.js.map → index-D4fqdfS-.js.map} +1 -1
- package/dist/assets/{index-B6MdC-Qx.js → index-D9EQ-6Wd.js} +2 -2
- package/dist/assets/{index-B6MdC-Qx.js.map → index-D9EQ-6Wd.js.map} +1 -1
- package/dist/assets/index-DnB9w-Dv.js +2 -0
- package/dist/assets/{index-Dj2ND9Mx.js.map → index-DnB9w-Dv.js.map} +1 -1
- package/dist/assets/{index-C3Orblel.js → index-FG4fTI4i.js} +2 -2
- package/dist/assets/{index-C3Orblel.js.map → index-FG4fTI4i.js.map} +1 -1
- package/dist/assets/index-IEsktHaW.js +2 -0
- package/dist/assets/{index-Cq9aOTTR.js.map → index-IEsktHaW.js.map} +1 -1
- package/dist/assets/{index-D_aTOqNE.js → index-so_tPJrr.js} +2 -2
- package/dist/assets/{index-D_aTOqNE.js.map → index-so_tPJrr.js.map} +1 -1
- package/dist/assets/main-DJYbit7N.js +729 -0
- package/dist/assets/main-DJYbit7N.js.map +1 -0
- package/dist/assets/{setup-KpkKDvsj.js → setup-BXLaipeI.js} +2 -2
- package/dist/assets/{setup-KpkKDvsj.js.map → setup-BXLaipeI.js.map} +1 -1
- package/dist/assets/{sync-manager-DEght5gK.js → sync-manager-DMpg8tED.js} +2 -2
- package/dist/assets/{sync-manager-DEght5gK.js.map → sync-manager-DMpg8tED.js.map} +1 -1
- package/dist/assets/widget-html-D6xqg8Sp.js +2 -0
- package/dist/assets/widget-html-D6xqg8Sp.js.map +1 -0
- package/dist/assets/{xmds-client-Dyy8ex-B.js → xmds-client-D6JI3K3_.js} +2 -2
- package/dist/assets/{xmds-client-Dyy8ex-B.js.map → xmds-client-D6JI3K3_.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +13 -13
- package/dist/assets/index-BVIXBw9z.js +0 -13
- package/dist/assets/index-BVIXBw9z.js.map +0 -1
- package/dist/assets/index-Cq9aOTTR.js +0 -2
- package/dist/assets/index-D81Qhc3r.js +0 -2
- package/dist/assets/index-Dj2ND9Mx.js +0 -2
- package/dist/assets/index-leM889oV.js +0 -5
- package/dist/assets/index-leM889oV.js.map +0 -1
- package/dist/assets/main-DvteKhS8.js +0 -729
- package/dist/assets/main-DvteKhS8.js.map +0 -1
- package/dist/assets/widget-html-BAV4ZZd8.js +0 -2
- package/dist/assets/widget-html-BAV4ZZd8.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{PLAYER_API as x,fetchWithRetry as w,createLogger as v}from"./index-leM889oV.js";const f=v("REST");class K{constructor(t){this.config=t,this.schemaVersion=7,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3},this._token=null,this._tokenExpiresAt=0,this._displayId=null,this._etags=new Map,this._responseCache=new Map,f.info("Using REST transport")}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${x}`:(this.config.restApiUrl||`${this.config.cmsUrl}${x}`).replace(/\/+$/,"")}_isProxyMode(){var t;return typeof window<"u"&&(((t=window.electronAPI)==null?void 0:t.isElectron)||window.location.hostname==="localhost")}async _authenticate(){const t=`${this.getRestBaseUrl()}/auth`;f.debug("Authenticating...");const e=await w(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!e.ok){const n=await e.text().catch(()=>"");throw new Error(`Auth failed: ${e.status} ${e.statusText} ${n}`)}const r=await e.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,f.info(`Authenticated as display ${this._displayId}`)}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,e={}){const r=await this._getToken(),n=new URL(`${this.getRestBaseUrl()}${t}`);for(const[d,g]of Object.entries(e))n.searchParams.set(d,String(g));const l=t,a={Authorization:`Bearer ${r}`},i=this._etags.get(l);i&&(a["If-None-Match"]=i),f.debug(`GET ${t}`,e);const u=await w(n.toString(),{method:"GET",headers:a},this.retryOptions);if(u.status===401)return this._token=null,this.restGet(t,e);if(u.status===304){const d=this._responseCache.get(l);if(d)return f.debug(`${t} → 304 (using cache)`),d}if(!u.ok){const d=await u.text().catch(()=>"");throw new Error(`REST GET ${t} failed: ${u.status} ${u.statusText} ${d}`)}const s=u.headers.get("ETag");s&&this._etags.set(l,s);const c=u.headers.get("Content-Type")||"";let o;return c.includes("application/json")?o=await u.json():o=await u.text(),this._responseCache.set(l,o),o}async restSend(t,e,r={}){const n=await this._getToken(),l=new URL(`${this.getRestBaseUrl()}${e}`);f.debug(`${t} ${e}`);const a=await w(l.toString(),{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)},this.retryOptions);if(a.status===401)return this._token=null,this.restSend(t,e,r);if(!a.ok){const u=await a.text().catch(()=>"");throw new Error(`REST ${t} ${e} failed: ${a.status} ${a.statusText} ${u}`)}return(a.headers.get("Content-Type")||"").includes("application/json")?await a.json():await a.text()}async registerDisplay(){await this._getToken();const t=typeof navigator<"u"?`${navigator.platform} ${navigator.userAgent}`:"unknown",e=await this.restSend("POST","/displays",{displayName:this.config.displayName,clientType:this.config.clientType||"linux",clientVersion:this.config.clientVersion||"0.1.0",clientCode:this.config.clientCode||1,operatingSystem:t,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel,xmrPubKey:this.config.xmrPubKey||""});return this._parseRegisterDisplayJson(e)}_parseRegisterDisplayJson(t){const e=t.display||t,r=e["@attributes"]||{},n=r.code||e.code,l=r.message||e.message||"";if(n!=="READY")return{code:n,message:l,settings:null};const a={};let i=[],u=[];for(const[g,y]of Object.entries(e))if(!(g==="@attributes"||g==="file")){if(g==="commands"){Array.isArray(y)&&(u=y.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(g==="tags"){const p=h=>typeof h=="object"?h.tag||h.value||"":String(h);if(Array.isArray(y))i=y.map(p).filter(Boolean);else if(y&&typeof y=="object"){const h=p(y);h&&(i=[h])}else typeof y=="string"&&y&&(i=[y]);continue}a[g]=typeof y=="object"?JSON.stringify(y):String(y)}const s=r.checkRf||"",c=r.checkSchedule||"",o={date:r.date||e.date||null,timezone:r.timezone||e.timezone||null,status:r.status||e.status||null,localDate:r.localDate||e.localDate||null,version_instructions:r.version_instructions||e.version_instructions||null},d=e.syncGroup?{syncGroup:String(e.syncGroup),syncPublisherPort:parseInt(e.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(e.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(e.syncVideoPauseDelay||"100",10),isLead:String(e.syncGroup)==="lead"}:null;return{code:n,message:l,settings:a,tags:i,commands:u,displayAttrs:o,checkRf:s,checkSchedule:c,syncConfig:d}}async requiredFiles(){const t=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(t)}_parseRequiredFilesV2(t){const e=[];for(const r of t.media||[])e.push({type:r.type||"media",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:r.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.layouts||[])e.push({type:"layout",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.widgets||[])e.push({type:"dataset",id:r.id!=null?String(r.id):null,size:0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:r.updateInterval||0});for(const r of t.dependencies||[])e.push({type:"static",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:r.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:e,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(t,e,r){return this.restGet(`/widgets/${t}/${e}/${r}`)}async notifyStatus(t){var e;if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate))try{const r=await navigator.storage.estimate();t.availableSpace=r.quota-r.usage,t.totalSpace=r.quota}catch{}return!t.timeZone&&typeof Intl<"u"&&(t.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),t.statusDialog||(t.statusDialog=`Current Layout: ${t.currentLayoutId||"None"}`),this.restSend("PUT",`/displays/${this._displayId}/status`,{statusData:t})}async mediaInventory(t){const e=Array.isArray(t)?{inventoryItems:t}:{inventory:t};return this.restSend("PUT",`/displays/${this._displayId}/inventory`,e)}async blackList(t,e,r){return f.warn(`BlackList not available in v2 API (${e}/${t}: ${r})`),!1}async submitLog(t,e=null){const r=Array.isArray(t)?{logs:t}:{logXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/logs`,r);return(n==null?void 0:n.success)===!0}async submitScreenShot(t){const e=await this.restSend("POST",`/displays/${this._displayId}/screenshot`,{screenshot:t});return(e==null?void 0:e.success)===!0}async submitStats(t,e=null){try{const r=Array.isArray(t)?{stats:t}:{statXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/stats`,r),l=(n==null?void 0:n.success)===!0;return f.info(`SubmitStats result: ${l}`),l}catch(r){throw f.error("SubmitStats failed:",r),r}}async reportFaults(t){const e=await this.restSend("POST",`/displays/${this._displayId}/faults`,{fault:t});return(e==null?void 0:e.success)===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(t,e){var r;try{const a=`${typeof window<"u"&&(((r=window.electronAPI)==null?void 0:r.isElectron)||window.location.hostname==="localhost")?"":t.replace(/\/+$/,"")}${x}/health`,i=await w(a,{method:"GET"},e||{maxRetries:0});if(!i.ok)return!1;const u=await i.json();return u.version===2&&u.status==="ok"}catch{return!1}}}function S(b){const t=[];for(const e of b.children)e.tagName==="criteria"&&t.push({metric:e.getAttribute("metric")||"",condition:e.getAttribute("condition")||"",type:e.getAttribute("type")||"string",value:e.textContent||""});return t}function $(b){const e=new DOMParser().parseFromString(b,"text/xml"),r={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},n=e.querySelector("schedule");if(n){const s=Array.from(n.children).filter(c=>c.tagName==="dependants");for(const c of s)if(c.parentElement===n)for(const o of c.querySelectorAll("file"))o.textContent&&r.dependants.push(o.textContent)}const l=e.querySelector("default");if(l){r.default=l.getAttribute("file");const s=l.querySelectorAll("dependants > file");s.length>0&&(r.defaultDependants=[...s].map(c=>c.textContent))}for(const s of e.querySelectorAll("campaign")){const c={id:s.getAttribute("id"),priority:parseInt(s.getAttribute("priority")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s),layouts:[]};for(const o of s.querySelectorAll("layout")){const d=o.getAttribute("file"),g=o.querySelectorAll("dependants > file");c.layouts.push({id:String(d),file:d,fromdt:o.getAttribute("fromdt")||c.fromdt,todt:o.getAttribute("todt")||c.todt,scheduleid:c.scheduleid,priority:c.priority,campaignId:c.id,maxPlaysPerHour:parseInt(o.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:o.getAttribute("isGeoAware")==="1",geoLocation:o.getAttribute("geoLocation")||"",syncEvent:o.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(o.getAttribute("shareOfVoice")||"0"),duration:parseInt(o.getAttribute("duration")||"0"),cyclePlayback:o.getAttribute("cyclePlayback")==="1",groupKey:o.getAttribute("groupKey")||null,playCount:parseInt(o.getAttribute("playCount")||"0"),dependants:g.length>0?[...g].map(y=>y.textContent):[],criteria:S(o)})}r.campaigns.push(c)}for(const s of e.querySelectorAll("schedule > layout")){const c=s.getAttribute("file"),o=s.querySelectorAll("dependants > file");r.layouts.push({id:String(c),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),priority:parseInt(s.getAttribute("priority")||"0"),campaignId:null,maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),duration:parseInt(s.getAttribute("duration")||"0"),cyclePlayback:s.getAttribute("cyclePlayback")==="1",groupKey:s.getAttribute("groupKey")||null,playCount:parseInt(s.getAttribute("playCount")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,dependants:o.length>0?[...o].map(d=>d.textContent):[],criteria:S(s)})}const a=e.querySelector("overlays");if(a)for(const s of a.querySelectorAll("overlay")){const c=s.getAttribute("file");r.overlays.push({id:String(c),duration:parseInt(s.getAttribute("duration")||"60"),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s)})}const i=e.querySelector("actions");if(i)for(const s of i.querySelectorAll("action"))r.actions.push({actionType:s.getAttribute("actionType")||"",triggerCode:s.getAttribute("triggerCode")||"",layoutCode:s.getAttribute("layoutCode")||"",commandCode:s.getAttribute("commandCode")||"",duration:parseInt(s.getAttribute("duration")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||""});for(const s of e.querySelectorAll("schedule > command"))r.commands.push({code:s.getAttribute("code")||"",date:s.getAttribute("date")||""});const u=e.querySelector("dataConnectors");if(u)for(const s of u.querySelectorAll("connector"))r.dataConnectors.push({id:s.getAttribute("id")||"",dataConnectorId:s.getAttribute("dataConnectorId")||"",dataSetId:s.getAttribute("dataSetId")||"",dataKey:s.getAttribute("dataKey")||"",dataParams:s.getAttribute("dataParams")||"",js:s.getAttribute("js")||"",url:s.getAttribute("url")||"",updateInterval:parseInt(s.getAttribute("updateInterval")||"300",10)});return r}const A=v("XMDS");class C{constructor(t){this.config=t,this.schemaVersion=5,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(t,e){const r=Object.entries(e).map(([n,l])=>{const a=String(l).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return`<${n} xsi:type="xsd:string">${a}</${n}>`}).join(`
|
|
1
|
+
import{PLAYER_API as x,fetchWithRetry as w,createLogger as v}from"./index-BglkPErZ.js";const f=v("REST");class K{constructor(t){this.config=t,this.schemaVersion=7,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3},this._token=null,this._tokenExpiresAt=0,this._displayId=null,this._etags=new Map,this._responseCache=new Map,f.info("Using REST transport")}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${x}`:(this.config.restApiUrl||`${this.config.cmsUrl}${x}`).replace(/\/+$/,"")}_isProxyMode(){var t;return typeof window<"u"&&(((t=window.electronAPI)==null?void 0:t.isElectron)||window.location.hostname==="localhost")}async _authenticate(){const t=`${this.getRestBaseUrl()}/auth`;f.debug("Authenticating...");const e=await w(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!e.ok){const n=await e.text().catch(()=>"");throw new Error(`Auth failed: ${e.status} ${e.statusText} ${n}`)}const r=await e.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,f.info(`Authenticated as display ${this._displayId}`)}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,e={}){const r=await this._getToken(),n=new URL(`${this.getRestBaseUrl()}${t}`);for(const[d,g]of Object.entries(e))n.searchParams.set(d,String(g));const l=t,a={Authorization:`Bearer ${r}`},i=this._etags.get(l);i&&(a["If-None-Match"]=i),f.debug(`GET ${t}`,e);const u=await w(n.toString(),{method:"GET",headers:a},this.retryOptions);if(u.status===401)return this._token=null,this.restGet(t,e);if(u.status===304){const d=this._responseCache.get(l);if(d)return f.debug(`${t} → 304 (using cache)`),d}if(!u.ok){const d=await u.text().catch(()=>"");throw new Error(`REST GET ${t} failed: ${u.status} ${u.statusText} ${d}`)}const s=u.headers.get("ETag");s&&this._etags.set(l,s);const c=u.headers.get("Content-Type")||"";let o;return c.includes("application/json")?o=await u.json():o=await u.text(),this._responseCache.set(l,o),o}async restSend(t,e,r={}){const n=await this._getToken(),l=new URL(`${this.getRestBaseUrl()}${e}`);f.debug(`${t} ${e}`);const a=await w(l.toString(),{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(r)},this.retryOptions);if(a.status===401)return this._token=null,this.restSend(t,e,r);if(!a.ok){const u=await a.text().catch(()=>"");throw new Error(`REST ${t} ${e} failed: ${a.status} ${a.statusText} ${u}`)}return(a.headers.get("Content-Type")||"").includes("application/json")?await a.json():await a.text()}async registerDisplay(){await this._getToken();const t=typeof navigator<"u"?`${navigator.platform} ${navigator.userAgent}`:"unknown",e=await this.restSend("POST","/displays",{displayName:this.config.displayName,clientType:this.config.clientType||"linux",clientVersion:this.config.clientVersion||"0.1.0",clientCode:this.config.clientCode||1,operatingSystem:t,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel,xmrPubKey:this.config.xmrPubKey||""});return this._parseRegisterDisplayJson(e)}_parseRegisterDisplayJson(t){const e=t.display||t,r=e["@attributes"]||{},n=r.code||e.code,l=r.message||e.message||"";if(n!=="READY")return{code:n,message:l,settings:null};const a={};let i=[],u=[];for(const[g,y]of Object.entries(e))if(!(g==="@attributes"||g==="file")){if(g==="commands"){Array.isArray(y)&&(u=y.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(g==="tags"){const p=h=>typeof h=="object"?h.tag||h.value||"":String(h);if(Array.isArray(y))i=y.map(p).filter(Boolean);else if(y&&typeof y=="object"){const h=p(y);h&&(i=[h])}else typeof y=="string"&&y&&(i=[y]);continue}a[g]=typeof y=="object"?JSON.stringify(y):String(y)}const s=r.checkRf||"",c=r.checkSchedule||"",o={date:r.date||e.date||null,timezone:r.timezone||e.timezone||null,status:r.status||e.status||null,localDate:r.localDate||e.localDate||null,version_instructions:r.version_instructions||e.version_instructions||null},d=e.syncGroup?{syncGroup:String(e.syncGroup),syncPublisherPort:parseInt(e.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(e.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(e.syncVideoPauseDelay||"100",10),isLead:String(e.syncGroup)==="lead"}:null;return{code:n,message:l,settings:a,tags:i,commands:u,displayAttrs:o,checkRf:s,checkSchedule:c,syncConfig:d}}async requiredFiles(){const t=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(t)}_parseRequiredFilesV2(t){const e=[];for(const r of t.media||[])e.push({type:r.type||"media",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:r.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.layouts||[])e.push({type:"layout",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(const r of t.widgets||[])e.push({type:"dataset",id:r.id!=null?String(r.id):null,size:0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:r.updateInterval||0});for(const r of t.dependencies||[])e.push({type:"static",id:r.id!=null?String(r.id):null,size:r.fileSize||0,md5:r.md5||null,download:"http",path:r.url||null,saveAs:null,fileType:r.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:e,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(t,e,r){return this.restGet(`/widgets/${t}/${e}/${r}`)}async notifyStatus(t){var e;if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate))try{const r=await navigator.storage.estimate();t.availableSpace=r.quota-r.usage,t.totalSpace=r.quota}catch{}return!t.timeZone&&typeof Intl<"u"&&(t.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),t.statusDialog||(t.statusDialog=`Current Layout: ${t.currentLayoutId||"None"}`),this.restSend("PUT",`/displays/${this._displayId}/status`,{statusData:t})}async mediaInventory(t){const e=Array.isArray(t)?{inventoryItems:t}:{inventory:t};return this.restSend("PUT",`/displays/${this._displayId}/inventory`,e)}async blackList(t,e,r){return f.warn(`BlackList not available in v2 API (${e}/${t}: ${r})`),!1}async submitLog(t,e=null){const r=Array.isArray(t)?{logs:t}:{logXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/logs`,r);return(n==null?void 0:n.success)===!0}async submitScreenShot(t){const e=await this.restSend("POST",`/displays/${this._displayId}/screenshot`,{screenshot:t});return(e==null?void 0:e.success)===!0}async submitStats(t,e=null){try{const r=Array.isArray(t)?{stats:t}:{statXml:t},n=await this.restSend("POST",`/displays/${this._displayId}/stats`,r),l=(n==null?void 0:n.success)===!0;return f.info(`SubmitStats result: ${l}`),l}catch(r){throw f.error("SubmitStats failed:",r),r}}async reportFaults(t){const e=await this.restSend("POST",`/displays/${this._displayId}/faults`,{fault:t});return(e==null?void 0:e.success)===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(t,e){var r;try{const a=`${typeof window<"u"&&(((r=window.electronAPI)==null?void 0:r.isElectron)||window.location.hostname==="localhost")?"":t.replace(/\/+$/,"")}${x}/health`,i=await w(a,{method:"GET"},e||{maxRetries:0});if(!i.ok)return!1;const u=await i.json();return u.version===2&&u.status==="ok"}catch{return!1}}}function S(b){const t=[];for(const e of b.children)e.tagName==="criteria"&&t.push({metric:e.getAttribute("metric")||"",condition:e.getAttribute("condition")||"",type:e.getAttribute("type")||"string",value:e.textContent||""});return t}function $(b){const e=new DOMParser().parseFromString(b,"text/xml"),r={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},n=e.querySelector("schedule");if(n){const s=Array.from(n.children).filter(c=>c.tagName==="dependants");for(const c of s)if(c.parentElement===n)for(const o of c.querySelectorAll("file"))o.textContent&&r.dependants.push(o.textContent)}const l=e.querySelector("default");if(l){r.default=l.getAttribute("file");const s=l.querySelectorAll("dependants > file");s.length>0&&(r.defaultDependants=[...s].map(c=>c.textContent))}for(const s of e.querySelectorAll("campaign")){const c={id:s.getAttribute("id"),priority:parseInt(s.getAttribute("priority")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s),layouts:[]};for(const o of s.querySelectorAll("layout")){const d=o.getAttribute("file"),g=o.querySelectorAll("dependants > file");c.layouts.push({id:String(d),file:d,fromdt:o.getAttribute("fromdt")||c.fromdt,todt:o.getAttribute("todt")||c.todt,scheduleid:c.scheduleid,priority:c.priority,campaignId:c.id,maxPlaysPerHour:parseInt(o.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:o.getAttribute("isGeoAware")==="1",geoLocation:o.getAttribute("geoLocation")||"",syncEvent:o.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(o.getAttribute("shareOfVoice")||"0"),duration:parseInt(o.getAttribute("duration")||"0"),cyclePlayback:o.getAttribute("cyclePlayback")==="1",groupKey:o.getAttribute("groupKey")||null,playCount:parseInt(o.getAttribute("playCount")||"0"),dependants:g.length>0?[...g].map(y=>y.textContent):[],criteria:S(o)})}r.campaigns.push(c)}for(const s of e.querySelectorAll("schedule > layout")){const c=s.getAttribute("file"),o=s.querySelectorAll("dependants > file");r.layouts.push({id:String(c),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),scheduleid:s.getAttribute("scheduleid"),priority:parseInt(s.getAttribute("priority")||"0"),campaignId:null,maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(s.getAttribute("shareOfVoice")||"0"),duration:parseInt(s.getAttribute("duration")||"0"),cyclePlayback:s.getAttribute("cyclePlayback")==="1",groupKey:s.getAttribute("groupKey")||null,playCount:parseInt(s.getAttribute("playCount")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,dependants:o.length>0?[...o].map(d=>d.textContent):[],criteria:S(s)})}const a=e.querySelector("overlays");if(a)for(const s of a.querySelectorAll("overlay")){const c=s.getAttribute("file");r.overlays.push({id:String(c),duration:parseInt(s.getAttribute("duration")||"60"),file:c,fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||"",syncEvent:s.getAttribute("syncEvent")==="1",maxPlaysPerHour:parseInt(s.getAttribute("maxPlaysPerHour")||"0"),recurrenceType:s.getAttribute("recurrenceType")||null,recurrenceDetail:parseInt(s.getAttribute("recurrenceDetail")||"0")||null,recurrenceRepeatsOn:s.getAttribute("recurrenceRepeatsOn")||null,recurrenceRange:s.getAttribute("recurrenceRange")||null,criteria:S(s)})}const i=e.querySelector("actions");if(i)for(const s of i.querySelectorAll("action"))r.actions.push({actionType:s.getAttribute("actionType")||"",triggerCode:s.getAttribute("triggerCode")||"",layoutCode:s.getAttribute("layoutCode")||"",commandCode:s.getAttribute("commandCode")||"",duration:parseInt(s.getAttribute("duration")||"0"),fromdt:s.getAttribute("fromdt"),todt:s.getAttribute("todt"),priority:parseInt(s.getAttribute("priority")||"0"),scheduleid:s.getAttribute("scheduleid"),isGeoAware:s.getAttribute("isGeoAware")==="1",geoLocation:s.getAttribute("geoLocation")||""});for(const s of e.querySelectorAll("schedule > command"))r.commands.push({code:s.getAttribute("code")||"",date:s.getAttribute("date")||""});const u=e.querySelector("dataConnectors");if(u)for(const s of u.querySelectorAll("connector"))r.dataConnectors.push({id:s.getAttribute("id")||"",dataConnectorId:s.getAttribute("dataConnectorId")||"",dataSetId:s.getAttribute("dataSetId")||"",dataKey:s.getAttribute("dataKey")||"",dataParams:s.getAttribute("dataParams")||"",js:s.getAttribute("js")||"",url:s.getAttribute("url")||"",updateInterval:parseInt(s.getAttribute("updateInterval")||"300",10)});return r}const A=v("XMDS");class C{constructor(t){this.config=t,this.schemaVersion=5,this.retryOptions=t.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(t,e){const r=Object.entries(e).map(([n,l])=>{const a=String(l).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return`<${n} xsi:type="xsd:string">${a}</${n}>`}).join(`
|
|
2
2
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
3
3
|
<soap:Envelope
|
|
4
4
|
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
|
@@ -13,4 +13,4 @@ import{PLAYER_API as x,fetchWithRetry as w,createLogger as v}from"./index-leM889
|
|
|
13
13
|
</tns:${t}>
|
|
14
14
|
</soap:Body>
|
|
15
15
|
</soap:Envelope>`}rewriteXmdsUrl(t){var e;return typeof window<"u"&&((e=window.electronAPI)!=null&&e.isElectron||window.location.hostname==="localhost")?`/xmds-proxy?cms=${encodeURIComponent(t)}`:`${t}/xmds.php`}async call(t,e={}){const r=this.rewriteXmdsUrl(this.config.cmsUrl),n=`${r}${r.includes("?")?"&":"?"}v=${this.schemaVersion}&method=${t}`,l=this.buildEnvelope(t,e);A.debug(`${t}`,e),A.debug(`URL: ${n}`);const a=await w(n,{method:"POST",headers:{"Content-Type":"text/xml; charset=utf-8"},body:l},this.retryOptions);if(!a.ok)throw new Error(`XMDS ${t} failed: ${a.status} ${a.statusText}`);const i=await a.text();return this.parseResponse(i,t)}parseResponse(t,e){var s,c;const n=new DOMParser().parseFromString(t,"text/xml");let l=n.querySelector("Fault");if(l||(l=Array.from(n.querySelectorAll("*")).find(o=>o.localName==="Fault"||o.tagName.endsWith(":Fault"))),l){const o=((s=l.querySelector("faultstring"))==null?void 0:s.textContent)||((c=Array.from(l.querySelectorAll("*")).find(d=>d.localName==="faultstring"))==null?void 0:c.textContent)||"Unknown SOAP fault";throw new Error(`SOAP Fault: ${o}`)}const a=`${e}Response`;let i=n.querySelector(a);if(i||(i=Array.from(n.querySelectorAll("*")).find(o=>o.localName===a||o.tagName.endsWith(":"+a))),!i)throw new Error(`No ${a} element in SOAP response`);const u=i.firstElementChild;return u?u.textContent:null}async registerDisplay(){const t=`${navigator.platform} ${navigator.userAgent}`,e=await this.call("RegisterDisplay",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,displayName:this.config.displayName,clientType:this.config.clientType||"linux",clientVersion:this.config.clientVersion||"0.1.0",clientCode:this.config.clientCode||"1",operatingSystem:t,macAddress:this.config.macAddress||"n/a",xmrChannel:this.config.xmrChannel||"",xmrPubKey:this.config.xmrPubKey||"",licenceResult:"licensed"});return this.parseRegisterDisplayResponse(e)}parseRegisterDisplayResponse(t){const n=new DOMParser().parseFromString(t,"text/xml").querySelector("display");if(!n)throw new Error("Invalid RegisterDisplay response: no <display> element");const l=n.getAttribute("code"),a=n.getAttribute("message");if(l!=="READY")return{code:l,message:a,settings:null};const i={},u=[],s=[];for(const p of n.children){const h=p.tagName.toLowerCase();if(h!=="file"){if(h==="commands"){for(const m of p.querySelectorAll("command"))s.push({commandCode:m.getAttribute("code")||m.getAttribute("commandCode")||"",commandString:m.getAttribute("commandString")||""});continue}if(h==="tags"){for(const m of p.querySelectorAll("tag"))m.textContent&&u.push(m.textContent);continue}i[p.tagName]=p.textContent}}const c=n.getAttribute("checkRf")||"",o=n.getAttribute("checkSchedule")||"",d={date:n.getAttribute("date")||null,timezone:n.getAttribute("timezone")||null,status:n.getAttribute("status")||null,localDate:n.getAttribute("localDate")||null,version_instructions:n.getAttribute("version_instructions")||null},g=i.syncGroup||null,y=g?{syncGroup:g,syncPublisherPort:parseInt(i.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(i.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||"100",10),isLead:g==="lead"}:null;return{code:l,message:a,settings:i,tags:u,commands:s,displayAttrs:d,checkRf:c,checkSchedule:o,syncConfig:y}}async requiredFiles(){const t=await this.call("RequiredFiles",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return this.parseRequiredFilesResponse(t)}parseRequiredFilesResponse(t){const r=new DOMParser().parseFromString(t,"text/xml"),n=[];for(const i of r.querySelectorAll("file"))n.push({type:i.getAttribute("type"),id:i.getAttribute("id"),size:parseInt(i.getAttribute("size")||"0"),md5:i.getAttribute("md5"),download:i.getAttribute("download"),path:i.getAttribute("path"),saveAs:i.getAttribute("saveAs")||null,fileType:i.getAttribute("fileType")||null,code:i.getAttribute("code"),layoutid:i.getAttribute("layoutid"),regionid:i.getAttribute("regionid"),mediaid:i.getAttribute("mediaid")});const l=[],a=r.querySelector("purge");if(a)for(const i of a.querySelectorAll("item"))l.push({id:i.getAttribute("id"),storedAs:i.getAttribute("storedAs")});return{files:n,purge:l}}async schedule(){const t=await this.call("Schedule",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return $(t)}async getResource(t,e,r){return await this.call("GetResource",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,layoutId:String(t),regionId:String(e),mediaId:String(r)})}async notifyStatus(t){var e;if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate))try{const r=await navigator.storage.estimate();t.availableSpace=r.quota-r.usage,t.totalSpace=r.quota}catch{}return!t.timeZone&&typeof Intl<"u"&&(t.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),t.statusDialog||(t.statusDialog=`Current Layout: ${t.currentLayoutId||"None"}`),await this.call("NotifyStatus",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,status:JSON.stringify(t)})}async mediaInventory(t){return await this.call("MediaInventory",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaInventory:t})}async blackList(t,e,r){try{const n=await this.call("BlackList",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaId:String(t),type:e||"media",reason:r||"Failed to render"});return A.info(`BlackListed ${e}/${t}: ${r}`),n==="true"}catch(n){return A.warn("BlackList failed:",n),!1}}async submitLog(t,e=null){return await this.call("SubmitLog",{serverKey:this.config.cmsKey,hardwareKey:e||this.config.hardwareKey,logXml:t})==="true"}async submitScreenShot(t){return await this.call("SubmitScreenShot",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,screenShot:t})==="true"}async reportFaults(t){return this.call("ReportFaults",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,fault:t})}async getWeather(){return this.call("GetWeather",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})}async submitStats(t,e=null){try{const n=await this.call("SubmitStats",{serverKey:this.config.cmsKey,hardwareKey:e||this.config.hardwareKey,statXml:t})==="true";return A.info(`SubmitStats result: ${n}`),n}catch(r){throw A.error("SubmitStats failed:",r),r}}}export{K as R,C as X,$ as p};
|
|
16
|
-
//# sourceMappingURL=xmds-client-
|
|
16
|
+
//# sourceMappingURL=xmds-client-D6JI3K3_.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xmds-client-Dyy8ex-B.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js"],"sourcesContent":["/**\n * REST transport client for Xibo CMS Player API.\n *\n * Uses the Player API REST endpoints with JWT auth, resource-oriented URLs,\n * and native JSON responses (no XML parsing required).\n *\n * - JWT bearer token auth (single POST /auth → token for all requests)\n * - Resource-oriented URLs (/displays/{id}/schedule vs /schedule)\n * - Native JSON schedule (no client-side XML parsing)\n * - Categorized required files (media/layouts/widgets)\n * - CDN/reverse proxy compatible (GET with cache headers)\n *\n * Same public API as XmdsClient — drop-in replacement.\n */\nimport { createLogger, fetchWithRetry, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('REST');\n\nexport class RestClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 7;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n\n // JWT auth state\n this._token = null;\n this._tokenExpiresAt = 0;\n this._displayId = null;\n\n // ETag-based HTTP caching\n this._etags = new Map();\n this._responseCache = new Map();\n\n log.info('Using REST transport');\n }\n\n // ─── Transport helpers ──────────────────────────────────────────\n\n /**\n * Get the REST API base URL.\n * In proxy mode (Electron/Chromium), returns the local relative path so\n * requests go through the Express proxy's mirror routes.\n * In direct mode (standalone PWA), returns the full CMS URL.\n */\n getRestBaseUrl() {\n if (this._isProxyMode()) {\n return `${window.location.origin}${PLAYER_API}`;\n }\n const base = this.config.restApiUrl || `${this.config.cmsUrl}${PLAYER_API}`;\n return base.replace(/\\/+$/, '');\n }\n\n /**\n * Check if running behind the local proxy (Electron or Chromium kiosk).\n */\n _isProxyMode() {\n return typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost');\n }\n\n // ─── JWT auth ─────────────────────────────────────────────────\n\n /**\n * Authenticate with the CMS and obtain a JWT token.\n * Called automatically before the first authenticated request.\n */\n async _authenticate() {\n const url = `${this.getRestBaseUrl()}/auth`;\n\n log.debug('Authenticating...');\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n }),\n }, this.retryOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`Auth failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const data = await response.json();\n this._token = data.token;\n this._displayId = data.displayId;\n // Refresh 60s before expiry to avoid edge-case rejections\n this._tokenExpiresAt = Date.now() + (data.expiresIn - 60) * 1000;\n\n log.info(`Authenticated as display ${this._displayId}`);\n }\n\n /**\n * Get a valid JWT token, refreshing if expired or missing.\n */\n async _getToken() {\n if (!this._token || Date.now() >= this._tokenExpiresAt) {\n await this._authenticate();\n }\n return this._token;\n }\n\n /**\n * Make an authenticated GET request with ETag caching.\n */\n async restGet(path, queryParams = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, String(value));\n }\n\n const cacheKey = path;\n const headers = { 'Authorization': `Bearer ${token}` };\n const cachedEtag = this._etags.get(cacheKey);\n if (cachedEtag) {\n headers['If-None-Match'] = cachedEtag;\n }\n\n log.debug(`GET ${path}`, queryParams);\n\n const response = await fetchWithRetry(url.toString(), {\n method: 'GET',\n headers,\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restGet(path, queryParams);\n }\n\n if (response.status === 304) {\n const cached = this._responseCache.get(cacheKey);\n if (cached) {\n log.debug(`${path} → 304 (using cache)`);\n return cached;\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST GET ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const etag = response.headers.get('ETag');\n if (etag) {\n this._etags.set(cacheKey, etag);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n let data;\n if (contentType.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n this._responseCache.set(cacheKey, data);\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n\n log.debug(`${method} ${path}`);\n\n const response = await fetchWithRetry(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restSend(method, path, body);\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST ${method} ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return await response.json();\n }\n return await response.text();\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings.\n * POST /displays → JSON with display settings\n */\n async registerDisplay() {\n // Auth first to get displayId\n await this._getToken();\n\n const os = typeof navigator !== 'undefined'\n ? `${navigator.platform} ${navigator.userAgent}`\n : 'unknown';\n\n const json = await this.restSend('POST', '/displays', {\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || 1,\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel,\n xmrPubKey: this.config.xmrPubKey || '',\n });\n\n return this._parseRegisterDisplayJson(json);\n }\n\n /**\n * Parse register display JSON response.\n * Same output format as XmdsClient.\n */\n _parseRegisterDisplayJson(json) {\n const display = json.display || json;\n const attrs = display['@attributes'] || {};\n const code = attrs.code || display.code;\n const message = attrs.message || display.message || '';\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n let tags = [];\n let commands = [];\n for (const [key, value] of Object.entries(display)) {\n if (key === '@attributes' || key === 'file') continue;\n if (key === 'commands') {\n if (Array.isArray(value)) {\n commands = value.map(c => ({\n commandCode: c.code || c.commandCode || '',\n commandString: c.commandString || ''\n }));\n }\n continue;\n }\n if (key === 'tags') {\n const extractTag = (t) => typeof t === 'object' ? (t.tag || t.value || '') : String(t);\n if (Array.isArray(value)) {\n tags = value.map(extractTag).filter(Boolean);\n } else if (value && typeof value === 'object') {\n const t = extractTag(value);\n if (t) tags = [t];\n } else if (typeof value === 'string' && value) {\n tags = [value];\n }\n continue;\n }\n settings[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n const checkRf = attrs.checkRf || '';\n const checkSchedule = attrs.checkSchedule || '';\n\n const displayAttrs = {\n date: attrs.date || display.date || null,\n timezone: attrs.timezone || display.timezone || null,\n status: attrs.status || display.status || null,\n localDate: attrs.localDate || display.localDate || null,\n version_instructions: attrs.version_instructions || display.version_instructions || null,\n };\n\n const syncConfig = display.syncGroup ? {\n syncGroup: String(display.syncGroup),\n syncPublisherPort: parseInt(display.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(display.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(display.syncVideoPauseDelay || '100', 10),\n isLead: String(display.syncGroup) === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download.\n * GET /displays/{id}/media → categorized JSON (no XML parsing)\n */\n async requiredFiles() {\n const json = await this.restGet(`/displays/${this._displayId}/media`);\n return this._parseRequiredFilesV2(json);\n }\n\n /**\n * Parse v2 categorized required files into the same flat format\n * that the download pipeline expects.\n *\n * v2 server returns: { media: [...], layouts: [...], widgets: [...] }\n * We flatten back to: { files: [...], purge: [] }\n */\n _parseRequiredFilesV2(json) {\n const files = [];\n\n // Media files (images, videos)\n for (const m of json.media || []) {\n files.push({\n type: m.type || 'media',\n id: m.id != null ? String(m.id) : null,\n size: m.fileSize || 0,\n md5: m.md5 || null,\n download: 'http',\n path: m.url || null,\n saveAs: m.saveAs || null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Layout files\n for (const l of json.layouts || []) {\n files.push({\n type: 'layout',\n id: l.id != null ? String(l.id) : null,\n size: l.fileSize || 0,\n md5: l.md5 || null,\n download: 'http',\n path: l.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Widget data files (datasets — dynamic API, not static media)\n for (const w of json.widgets || []) {\n files.push({\n type: 'dataset',\n id: w.id != null ? String(w.id) : null,\n size: 0,\n md5: w.md5 || null,\n download: 'http',\n path: w.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n updateInterval: w.updateInterval || 0,\n });\n }\n\n // Dependencies (fonts, CSS, JS bundles) — pre-classified as 'static'\n for (const d of json.dependencies || []) {\n files.push({\n type: 'static',\n id: d.id != null ? String(d.id) : null,\n size: d.fileSize || 0,\n md5: d.md5 || null,\n download: 'http',\n path: d.url || null,\n saveAs: null,\n fileType: d.type || null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n return { files, purge: [] };\n }\n\n /**\n * Schedule - get layout schedule.\n * GET /displays/{id}/schedule → native JSON (no XML parsing needed!)\n *\n * The v2 server returns the same structure as parseScheduleResponse(),\n * so we return it directly.\n */\n async schedule() {\n return this.restGet(`/displays/${this._displayId}/schedule`);\n }\n\n /**\n * GetResource - get rendered widget HTML.\n * GET /widgets/{layoutId}/{regionId}/{mediaId} → HTML string\n */\n async getResource(layoutId, regionId, mediaId) {\n return this.restGet(`/widgets/${layoutId}/${regionId}/${mediaId}`);\n }\n\n /**\n * NotifyStatus - report current status.\n * PUT /displays/{id}/status → JSON acknowledgement\n */\n async notifyStatus(status) {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return this.restSend('PUT', `/displays/${this._displayId}/status`, {\n statusData: status,\n });\n }\n\n /**\n * MediaInventory - report downloaded files.\n * PUT /displays/{id}/inventory → JSON acknowledgement\n */\n async mediaInventory(inventoryXml) {\n const body = Array.isArray(inventoryXml)\n ? { inventoryItems: inventoryXml }\n : { inventory: inventoryXml };\n return this.restSend('PUT', `/displays/${this._displayId}/inventory`, body);\n }\n\n /**\n * BlackList - report broken media to CMS.\n * Not in v2 API — falls back to v1 behavior (no-op with warning).\n */\n async blackList(mediaId, type, reason) {\n log.warn(`BlackList not available in v2 API (${type}/${mediaId}: ${reason})`);\n return false;\n }\n\n /**\n * SubmitLog - submit player logs to CMS.\n * POST /displays/{id}/logs → JSON acknowledgement\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const body = Array.isArray(logXml) ? { logs: logXml } : { logXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/logs`, body);\n return result?.success === true;\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS.\n * POST /displays/{id}/screenshot → JSON acknowledgement\n */\n async submitScreenShot(base64Image) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/screenshot`, {\n screenshot: base64Image,\n });\n return result?.success === true;\n }\n\n /**\n * SubmitStats - submit proof of play statistics.\n * POST /displays/{id}/stats → JSON acknowledgement\n */\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const body = Array.isArray(statsXml) ? { stats: statsXml } : { statXml: statsXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/stats`, body);\n const success = result?.success === true;\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts.\n * POST /displays/{id}/faults → JSON acknowledgement\n */\n async reportFaults(faultJson) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/faults`, {\n fault: faultJson,\n });\n return result?.success === true;\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria.\n * GET /displays/{id}/weather → JSON weather data\n */\n async getWeather() {\n return this.restGet(`/displays/${this._displayId}/weather`);\n }\n\n // ─── Static helpers ───────────────────────────────────────────\n\n /**\n * Probe whether the CMS supports API v2.\n * GET /api/v2/player/health → { version: 2, status: \"ok\" }\n *\n * @param {string} cmsUrl - CMS base URL\n * @param {Object} [retryOptions] - Retry options for fetch\n * @returns {Promise<boolean>} true if v2 is available\n */\n static async isAvailable(cmsUrl, retryOptions) {\n try {\n // In proxy mode, probe the local proxy's forward route instead of the CMS directly (avoids CORS)\n const isProxy = typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron || window.location.hostname === 'localhost');\n const base = isProxy ? '' : cmsUrl.replace(/\\/+$/, '');\n const url = `${base}${PLAYER_API}/health`;\n const response = await fetchWithRetry(url, { method: 'GET' }, retryOptions || { maxRetries: 0 });\n if (!response.ok) return false;\n const data = await response.json();\n return data.version === 2 && data.status === 'ok';\n } catch {\n return false;\n }\n }\n}\n","/**\n * Shared schedule XML parser used by both RestClient and XmdsClient.\n *\n * Both transports return the same XML structure for the Schedule endpoint,\n * so the parsing logic lives here to avoid duplication.\n */\n\n/**\n * Parse criteria child elements from a layout/overlay element.\n * Criteria are conditions that must be met for the item to display.\n *\n * XML format: <criteria metric=\"dayOfWeek\" condition=\"equals\" type=\"string\">Monday</criteria>\n *\n * @param {Element} parentEl - Parent XML element containing <criteria> children\n * @returns {Array<{metric: string, condition: string, type: string, value: string}>}\n */\nfunction parseCriteria(parentEl) {\n const criteria = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'criteria') continue;\n criteria.push({\n metric: child.getAttribute('metric') || '',\n condition: child.getAttribute('condition') || '',\n type: child.getAttribute('type') || 'string',\n value: child.textContent || ''\n });\n }\n return criteria;\n}\n\n/**\n * Parse Schedule XML response into a normalized schedule object.\n *\n * @param {string} xml - Raw XML string from CMS schedule endpoint\n * @returns {Object} Parsed schedule with default, layouts, campaigns, overlays, actions, commands, dataConnectors\n */\nexport function parseScheduleResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const schedule = {\n default: null,\n defaultDependants: [],\n dependants: [], // Global dependants that gate ALL layouts\n layouts: [],\n campaigns: [],\n overlays: [],\n actions: [],\n commands: [],\n dataConnectors: []\n };\n\n // Parse global dependants (root-level <dependants> — must be cached before any layout plays)\n const scheduleEl = doc.querySelector('schedule');\n if (scheduleEl) {\n const globalDeps = Array.from(scheduleEl.children).filter(\n el => el.tagName === 'dependants'\n );\n for (const depContainer of globalDeps) {\n // Skip if this is nested inside <default>, <layout>, etc.\n if (depContainer.parentElement !== scheduleEl) continue;\n for (const fileEl of depContainer.querySelectorAll('file')) {\n if (fileEl.textContent) schedule.dependants.push(fileEl.textContent);\n }\n }\n }\n\n const defaultEl = doc.querySelector('default');\n if (defaultEl) {\n schedule.default = defaultEl.getAttribute('file');\n // Parse dependants — files that must be cached before this layout plays\n const defaultDeps = defaultEl.querySelectorAll('dependants > file');\n if (defaultDeps.length > 0) {\n schedule.defaultDependants = [...defaultDeps].map(el => el.textContent);\n }\n }\n\n // Parse campaigns (groups of layouts with shared priority)\n for (const campaignEl of doc.querySelectorAll('campaign')) {\n const campaign = {\n id: campaignEl.getAttribute('id'),\n priority: parseInt(campaignEl.getAttribute('priority') || '0'),\n fromdt: campaignEl.getAttribute('fromdt'),\n todt: campaignEl.getAttribute('todt'),\n scheduleid: campaignEl.getAttribute('scheduleid'),\n maxPlaysPerHour: parseInt(campaignEl.getAttribute('maxPlaysPerHour') || '0'),\n shareOfVoice: parseInt(campaignEl.getAttribute('shareOfVoice') || '0'),\n isGeoAware: campaignEl.getAttribute('isGeoAware') === '1',\n geoLocation: campaignEl.getAttribute('geoLocation') || '',\n syncEvent: campaignEl.getAttribute('syncEvent') === '1',\n recurrenceType: campaignEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(campaignEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: campaignEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: campaignEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(campaignEl),\n layouts: []\n };\n\n // Parse layouts within this campaign\n for (const layoutEl of campaignEl.querySelectorAll('layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n campaign.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n // Layouts in campaigns inherit timing from campaign level\n fromdt: layoutEl.getAttribute('fromdt') || campaign.fromdt,\n todt: layoutEl.getAttribute('todt') || campaign.todt,\n scheduleid: campaign.scheduleid,\n priority: campaign.priority, // Priority at campaign level\n campaignId: campaign.id,\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n schedule.campaigns.push(campaign);\n }\n\n // Parse standalone layouts (not in campaigns)\n for (const layoutEl of doc.querySelectorAll('schedule > layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n schedule.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n fromdt: layoutEl.getAttribute('fromdt'),\n todt: layoutEl.getAttribute('todt'),\n scheduleid: layoutEl.getAttribute('scheduleid'),\n priority: parseInt(layoutEl.getAttribute('priority') || '0'),\n campaignId: null, // Standalone layout\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n recurrenceType: layoutEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(layoutEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: layoutEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: layoutEl.getAttribute('recurrenceRange') || null,\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n // Parse overlay layouts (appear on top of main layouts)\n const overlaysContainer = doc.querySelector('overlays');\n if (overlaysContainer) {\n for (const overlayEl of overlaysContainer.querySelectorAll('overlay')) {\n const fileId = overlayEl.getAttribute('file');\n schedule.overlays.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n duration: parseInt(overlayEl.getAttribute('duration') || '60'),\n file: fileId,\n fromdt: overlayEl.getAttribute('fromdt'),\n todt: overlayEl.getAttribute('todt'),\n priority: parseInt(overlayEl.getAttribute('priority') || '0'),\n scheduleid: overlayEl.getAttribute('scheduleid'),\n isGeoAware: overlayEl.getAttribute('isGeoAware') === '1',\n geoLocation: overlayEl.getAttribute('geoLocation') || '',\n syncEvent: overlayEl.getAttribute('syncEvent') === '1',\n maxPlaysPerHour: parseInt(overlayEl.getAttribute('maxPlaysPerHour') || '0'),\n recurrenceType: overlayEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(overlayEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: overlayEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: overlayEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(overlayEl)\n });\n }\n }\n\n // Parse action events (scheduled triggers)\n const actionsContainer = doc.querySelector('actions');\n if (actionsContainer) {\n for (const actionEl of actionsContainer.querySelectorAll('action')) {\n schedule.actions.push({\n actionType: actionEl.getAttribute('actionType') || '',\n triggerCode: actionEl.getAttribute('triggerCode') || '',\n layoutCode: actionEl.getAttribute('layoutCode') || '',\n commandCode: actionEl.getAttribute('commandCode') || '',\n duration: parseInt(actionEl.getAttribute('duration') || '0'),\n fromdt: actionEl.getAttribute('fromdt'),\n todt: actionEl.getAttribute('todt'),\n priority: parseInt(actionEl.getAttribute('priority') || '0'),\n scheduleid: actionEl.getAttribute('scheduleid'),\n isGeoAware: actionEl.getAttribute('isGeoAware') === '1',\n geoLocation: actionEl.getAttribute('geoLocation') || ''\n });\n }\n }\n\n // Parse server commands (remote control)\n for (const cmdEl of doc.querySelectorAll('schedule > command')) {\n schedule.commands.push({\n code: cmdEl.getAttribute('code') || '',\n date: cmdEl.getAttribute('date') || ''\n });\n }\n\n // Parse data connectors (real-time data sources for widgets)\n // Spec: <dataConnectors><connector dataSetId=\"\" dataParams=\"\" js=\"\"/></dataConnectors>\n const dataConnectorsContainer = doc.querySelector('dataConnectors');\n if (dataConnectorsContainer) {\n for (const dcEl of dataConnectorsContainer.querySelectorAll('connector')) {\n schedule.dataConnectors.push({\n id: dcEl.getAttribute('id') || '',\n dataConnectorId: dcEl.getAttribute('dataConnectorId') || '',\n dataSetId: dcEl.getAttribute('dataSetId') || '',\n dataKey: dcEl.getAttribute('dataKey') || '',\n dataParams: dcEl.getAttribute('dataParams') || '',\n js: dcEl.getAttribute('js') || '',\n url: dcEl.getAttribute('url') || '',\n updateInterval: parseInt(dcEl.getAttribute('updateInterval') || '300', 10)\n });\n }\n }\n\n return schedule;\n}\n","/**\n * XMDS SOAP transport client for Xibo CMS.\n *\n * Uses the traditional SOAP/XML endpoint (xmds.php) for full protocol\n * compatibility with all Xibo CMS versions.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry } from '@xiboplayer/utils';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('XMDS');\n\nexport class XmdsClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 5;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n }\n\n // ─── SOAP transport helpers ─────────────────────────────────────\n\n /**\n * Build SOAP envelope for a given method and parameters\n */\n buildEnvelope(method, params) {\n const paramElements = Object.entries(params)\n .map(([key, value]) => {\n const escaped = String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n return `<${key} xsi:type=\"xsd:string\">${escaped}</${key}>`;\n })\n .join('\\n ');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soap:Envelope\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:tns=\"urn:xmds\"\n xmlns:types=\"urn:xmds/encodedTypes\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <tns:${method}>\n ${paramElements}\n </tns:${method}>\n </soap:Body>\n</soap:Envelope>`;\n }\n\n /**\n * Rewrite XMDS URL for local proxy.\n * If running inside a local wrapper (Electron, Chromium kiosk), use the\n * local proxy to avoid CORS.\n * Detection: preload.js exposes window.electronAPI.isElectron = true,\n * or fallback to checking localhost (any local wrapper port).\n */\n rewriteXmdsUrl(cmsUrl) {\n if (typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost')) {\n const encodedCmsUrl = encodeURIComponent(cmsUrl);\n return `/xmds-proxy?cms=${encodedCmsUrl}`;\n }\n\n return `${cmsUrl}/xmds.php`;\n }\n\n /**\n * Call XMDS SOAP method\n */\n async call(method, params = {}) {\n const xmdsUrl = this.rewriteXmdsUrl(this.config.cmsUrl);\n const url = `${xmdsUrl}${xmdsUrl.includes('?') ? '&' : '?'}v=${this.schemaVersion}&method=${method}`;\n const body = this.buildEnvelope(method, params);\n\n log.debug(`${method}`, params);\n log.debug(`URL: ${url}`);\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n body\n }, this.retryOptions);\n\n if (!response.ok) {\n throw new Error(`XMDS ${method} failed: ${response.status} ${response.statusText}`);\n }\n\n const xml = await response.text();\n return this.parseResponse(xml, method);\n }\n\n /**\n * Parse SOAP response\n */\n parseResponse(xml, method) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n // Check for SOAP fault (handle namespace prefix like soap:Fault)\n let fault = doc.querySelector('Fault');\n if (!fault) {\n fault = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === 'Fault' || el.tagName.endsWith(':Fault')\n );\n }\n if (fault) {\n const faultString = fault.querySelector('faultstring')?.textContent\n || Array.from(fault.querySelectorAll('*')).find(el => el.localName === 'faultstring')?.textContent\n || 'Unknown SOAP fault';\n throw new Error(`SOAP Fault: ${faultString}`);\n }\n\n // Extract response element (handle namespace prefixes like ns1:MethodResponse)\n const responseTag = `${method}Response`;\n let responseEl = doc.querySelector(responseTag);\n if (!responseEl) {\n responseEl = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === responseTag || el.tagName.endsWith(':' + responseTag)\n );\n }\n\n if (!responseEl) {\n throw new Error(`No ${responseTag} element in SOAP response`);\n }\n\n const returnEl = responseEl.firstElementChild;\n if (!returnEl) {\n return null;\n }\n\n return returnEl.textContent;\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n */\n async registerDisplay() {\n const os = `${navigator.platform} ${navigator.userAgent}`;\n\n const xml = await this.call('RegisterDisplay', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || '1',\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed'\n });\n\n return this.parseRegisterDisplayResponse(xml);\n }\n\n /**\n * Parse RegisterDisplay XML response\n */\n parseRegisterDisplayResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const display = doc.querySelector('display');\n if (!display) {\n throw new Error('Invalid RegisterDisplay response: no <display> element');\n }\n\n const code = display.getAttribute('code');\n const message = display.getAttribute('message');\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n const tags = [];\n const commands = [];\n for (const child of display.children) {\n const name = child.tagName.toLowerCase();\n if (name === 'file') continue;\n if (name === 'commands') {\n // Parse <commands><command code=\"xyz\" commandString=\"args\"/></commands>\n for (const cmdEl of child.querySelectorAll('command')) {\n commands.push({\n commandCode: cmdEl.getAttribute('code') || cmdEl.getAttribute('commandCode') || '',\n commandString: cmdEl.getAttribute('commandString') || ''\n });\n }\n continue;\n }\n if (name === 'tags') {\n // Parse <tags><tag>value</tag>...</tags> into array\n for (const tagEl of child.querySelectorAll('tag')) {\n if (tagEl.textContent) tags.push(tagEl.textContent);\n }\n continue;\n }\n settings[child.tagName] = child.textContent;\n }\n\n const checkRf = display.getAttribute('checkRf') || '';\n const checkSchedule = display.getAttribute('checkSchedule') || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: display.getAttribute('date') || null,\n timezone: display.getAttribute('timezone') || null,\n status: display.getAttribute('status') || null,\n localDate: display.getAttribute('localDate') || null,\n version_instructions: display.getAttribute('version_instructions') || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n const syncGroupVal = settings.syncGroup || null;\n const syncConfig = syncGroupVal ? {\n syncGroup: syncGroupVal,\n syncPublisherPort: parseInt(settings.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(settings.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(settings.syncVideoPauseDelay || '100', 10),\n isLead: syncGroupVal === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n */\n async requiredFiles() {\n const xml = await this.call('RequiredFiles', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return this.parseRequiredFilesResponse(xml);\n }\n\n /**\n * Parse RequiredFiles XML response\n */\n parseRequiredFilesResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const files = [];\n for (const fileEl of doc.querySelectorAll('file')) {\n files.push({\n type: fileEl.getAttribute('type'),\n id: fileEl.getAttribute('id'),\n size: parseInt(fileEl.getAttribute('size') || '0'),\n md5: fileEl.getAttribute('md5'),\n download: fileEl.getAttribute('download'),\n path: fileEl.getAttribute('path'),\n saveAs: fileEl.getAttribute('saveAs') || null,\n fileType: fileEl.getAttribute('fileType') || null,\n code: fileEl.getAttribute('code'),\n layoutid: fileEl.getAttribute('layoutid'),\n regionid: fileEl.getAttribute('regionid'),\n mediaid: fileEl.getAttribute('mediaid')\n });\n }\n\n // Parse purge block — files CMS wants the player to delete\n const purgeItems = [];\n const purgeEl = doc.querySelector('purge');\n if (purgeEl) {\n for (const itemEl of purgeEl.querySelectorAll('item')) {\n purgeItems.push({\n id: itemEl.getAttribute('id'),\n storedAs: itemEl.getAttribute('storedAs')\n });\n }\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n */\n async schedule() {\n const xml = await this.call('Schedule', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n */\n async getResource(layoutId, regionId, mediaId) {\n const xml = await this.call('GetResource', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId)\n });\n\n return xml;\n }\n\n /**\n * NotifyStatus - report current status\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n // Enrich with storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return await this.call('NotifyStatus', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n status: JSON.stringify(status)\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n */\n async mediaInventory(inventoryXml) {\n return await this.call('MediaInventory', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaInventory: inventoryXml\n });\n }\n\n /**\n * BlackList - report broken media to CMS\n * @param {string} mediaId - The media file ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const xml = await this.call('BlackList', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render'\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return xml === 'true';\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS for remote debugging\n * @param {string} logXml - XML string containing log entries\n * @returns {Promise<boolean>} - true if logs were successfully submitted\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const xml = await this.call('SubmitLog', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n logXml: logXml\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS for display verification\n * @param {string} base64Image - Base64-encoded PNG image data\n * @returns {Promise<boolean>} - true if screenshot was successfully submitted\n */\n async submitScreenShot(base64Image) {\n const xml = await this.call('SubmitScreenShot', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n screenShot: base64Image\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * @param {string} statsXml - XML-encoded stats string\n * @returns {Promise<boolean>} - true if stats were successfully submitted\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n return this.call('ReportFaults', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n fault: faultJson\n });\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * @returns {Promise<string>} Weather data XML from CMS\n */\n async getWeather() {\n return this.call('GetWeather', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const xml = await this.call('SubmitStats', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n statXml: statsXml\n });\n\n const success = xml === 'true';\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","url","response","fetchWithRetry","errorBody","data","path","queryParams","token","key","value","cacheKey","headers","cachedEtag","cached","etag","contentType","method","body","os","json","display","attrs","code","message","settings","tags","commands","c","extractTag","t","checkRf","checkSchedule","displayAttrs","syncConfig","files","m","l","w","d","layoutId","regionId","mediaId","status","estimate","inventoryXml","type","reason","logXml","hardwareKeyOverride","result","base64Image","statsXml","success","error","faultJson","cmsUrl","retryOptions","parseCriteria","parentEl","criteria","child","parseScheduleResponse","xml","doc","schedule","scheduleEl","globalDeps","el","depContainer","fileEl","defaultEl","defaultDeps","campaignEl","campaign","layoutEl","fileId","depEls","overlaysContainer","overlayEl","actionsContainer","actionEl","cmdEl","dataConnectorsContainer","dcEl","XmdsClient","params","paramElements","escaped","xmdsUrl","fault","faultString","_b","responseTag","responseEl","returnEl","name","tagEl","syncGroupVal","purgeItems","purgeEl","itemEl"],"mappings":"uFAgBA,MAAMA,EAAMC,EAAa,MAAM,EAExB,MAAMC,CAAW,CACtB,YAAYC,EAAQ,CAClB,KAAK,OAASA,EACd,KAAK,cAAgB,EACrB,KAAK,aAAeA,EAAO,cAAgB,CAAE,WAAY,EAAG,YAAa,GAAI,EAG7E,KAAK,OAAS,KACd,KAAK,gBAAkB,EACvB,KAAK,WAAa,KAGlB,KAAK,OAAS,IAAI,IAClB,KAAK,eAAiB,IAAI,IAE1BH,EAAI,KAAK,sBAAsB,CACjC,CAUA,gBAAiB,CACf,OAAI,KAAK,eACA,GAA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K,eAAgB,CAC/B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,YACzB,MAAOA,CACb,CAAK,CACH,CAMA,MAAM,YAAa,CACjB,OAAO,KAAK,KAAK,aAAc,CAC7B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,WAC/B,CAAK,CACH,CAEA,MAAM,YAAYH,EAAUH,EAAsB,KAAM,CACtD,GAAI,CAOF,MAAMI,EANM,MAAM,KAAK,KAAK,cAAe,CACzC,UAAW,KAAK,OAAO,OACvB,YAAaJ,GAAuB,KAAK,OAAO,YAChD,QAASG,CACjB,CAAO,IAEuB,OACxB,OAAAzD,EAAI,KAAK,uBAAuB0D,CAAO,EAAE,EAClCA,CACT,OAASC,EAAO,CACd,MAAA3D,EAAI,MAAM,sBAAuB2D,CAAK,EAChCA,CACR,CACF,CACF"}
|
|
1
|
+
{"version":3,"file":"xmds-client-D6JI3K3_.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js"],"sourcesContent":["/**\n * REST transport client for Xibo CMS Player API.\n *\n * Uses the Player API REST endpoints with JWT auth, resource-oriented URLs,\n * and native JSON responses (no XML parsing required).\n *\n * - JWT bearer token auth (single POST /auth → token for all requests)\n * - Resource-oriented URLs (/displays/{id}/schedule vs /schedule)\n * - Native JSON schedule (no client-side XML parsing)\n * - Categorized required files (media/layouts/widgets)\n * - CDN/reverse proxy compatible (GET with cache headers)\n *\n * Same public API as XmdsClient — drop-in replacement.\n */\nimport { createLogger, fetchWithRetry, PLAYER_API } from '@xiboplayer/utils';\n\nconst log = createLogger('REST');\n\nexport class RestClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 7;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n\n // JWT auth state\n this._token = null;\n this._tokenExpiresAt = 0;\n this._displayId = null;\n\n // ETag-based HTTP caching\n this._etags = new Map();\n this._responseCache = new Map();\n\n log.info('Using REST transport');\n }\n\n // ─── Transport helpers ──────────────────────────────────────────\n\n /**\n * Get the REST API base URL.\n * In proxy mode (Electron/Chromium), returns the local relative path so\n * requests go through the Express proxy's mirror routes.\n * In direct mode (standalone PWA), returns the full CMS URL.\n */\n getRestBaseUrl() {\n if (this._isProxyMode()) {\n return `${window.location.origin}${PLAYER_API}`;\n }\n const base = this.config.restApiUrl || `${this.config.cmsUrl}${PLAYER_API}`;\n return base.replace(/\\/+$/, '');\n }\n\n /**\n * Check if running behind the local proxy (Electron or Chromium kiosk).\n */\n _isProxyMode() {\n return typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost');\n }\n\n // ─── JWT auth ─────────────────────────────────────────────────\n\n /**\n * Authenticate with the CMS and obtain a JWT token.\n * Called automatically before the first authenticated request.\n */\n async _authenticate() {\n const url = `${this.getRestBaseUrl()}/auth`;\n\n log.debug('Authenticating...');\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n }),\n }, this.retryOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`Auth failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const data = await response.json();\n this._token = data.token;\n this._displayId = data.displayId;\n // Refresh 60s before expiry to avoid edge-case rejections\n this._tokenExpiresAt = Date.now() + (data.expiresIn - 60) * 1000;\n\n log.info(`Authenticated as display ${this._displayId}`);\n }\n\n /**\n * Get a valid JWT token, refreshing if expired or missing.\n */\n async _getToken() {\n if (!this._token || Date.now() >= this._tokenExpiresAt) {\n await this._authenticate();\n }\n return this._token;\n }\n\n /**\n * Make an authenticated GET request with ETag caching.\n */\n async restGet(path, queryParams = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, String(value));\n }\n\n const cacheKey = path;\n const headers = { 'Authorization': `Bearer ${token}` };\n const cachedEtag = this._etags.get(cacheKey);\n if (cachedEtag) {\n headers['If-None-Match'] = cachedEtag;\n }\n\n log.debug(`GET ${path}`, queryParams);\n\n const response = await fetchWithRetry(url.toString(), {\n method: 'GET',\n headers,\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restGet(path, queryParams);\n }\n\n if (response.status === 304) {\n const cached = this._responseCache.get(cacheKey);\n if (cached) {\n log.debug(`${path} → 304 (using cache)`);\n return cached;\n }\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST GET ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const etag = response.headers.get('ETag');\n if (etag) {\n this._etags.set(cacheKey, etag);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n let data;\n if (contentType.includes('application/json')) {\n data = await response.json();\n } else {\n data = await response.text();\n }\n\n this._responseCache.set(cacheKey, data);\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}) {\n const token = await this._getToken();\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n\n log.debug(`${method} ${path}`);\n\n const response = await fetchWithRetry(url.toString(), {\n method,\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`,\n },\n body: JSON.stringify(body),\n }, this.retryOptions);\n\n // Token expired mid-flight — re-auth and retry once\n if (response.status === 401) {\n this._token = null;\n return this.restSend(method, path, body);\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST ${method} ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return await response.json();\n }\n return await response.text();\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings.\n * POST /displays → JSON with display settings\n */\n async registerDisplay() {\n // Auth first to get displayId\n await this._getToken();\n\n const os = typeof navigator !== 'undefined'\n ? `${navigator.platform} ${navigator.userAgent}`\n : 'unknown';\n\n const json = await this.restSend('POST', '/displays', {\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || 1,\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel,\n xmrPubKey: this.config.xmrPubKey || '',\n });\n\n return this._parseRegisterDisplayJson(json);\n }\n\n /**\n * Parse register display JSON response.\n * Same output format as XmdsClient.\n */\n _parseRegisterDisplayJson(json) {\n const display = json.display || json;\n const attrs = display['@attributes'] || {};\n const code = attrs.code || display.code;\n const message = attrs.message || display.message || '';\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n let tags = [];\n let commands = [];\n for (const [key, value] of Object.entries(display)) {\n if (key === '@attributes' || key === 'file') continue;\n if (key === 'commands') {\n if (Array.isArray(value)) {\n commands = value.map(c => ({\n commandCode: c.code || c.commandCode || '',\n commandString: c.commandString || ''\n }));\n }\n continue;\n }\n if (key === 'tags') {\n const extractTag = (t) => typeof t === 'object' ? (t.tag || t.value || '') : String(t);\n if (Array.isArray(value)) {\n tags = value.map(extractTag).filter(Boolean);\n } else if (value && typeof value === 'object') {\n const t = extractTag(value);\n if (t) tags = [t];\n } else if (typeof value === 'string' && value) {\n tags = [value];\n }\n continue;\n }\n settings[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n const checkRf = attrs.checkRf || '';\n const checkSchedule = attrs.checkSchedule || '';\n\n const displayAttrs = {\n date: attrs.date || display.date || null,\n timezone: attrs.timezone || display.timezone || null,\n status: attrs.status || display.status || null,\n localDate: attrs.localDate || display.localDate || null,\n version_instructions: attrs.version_instructions || display.version_instructions || null,\n };\n\n const syncConfig = display.syncGroup ? {\n syncGroup: String(display.syncGroup),\n syncPublisherPort: parseInt(display.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(display.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(display.syncVideoPauseDelay || '100', 10),\n isLead: String(display.syncGroup) === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download.\n * GET /displays/{id}/media → categorized JSON (no XML parsing)\n */\n async requiredFiles() {\n const json = await this.restGet(`/displays/${this._displayId}/media`);\n return this._parseRequiredFilesV2(json);\n }\n\n /**\n * Parse v2 categorized required files into the same flat format\n * that the download pipeline expects.\n *\n * v2 server returns: { media: [...], layouts: [...], widgets: [...] }\n * We flatten back to: { files: [...], purge: [] }\n */\n _parseRequiredFilesV2(json) {\n const files = [];\n\n // Media files (images, videos)\n for (const m of json.media || []) {\n files.push({\n type: m.type || 'media',\n id: m.id != null ? String(m.id) : null,\n size: m.fileSize || 0,\n md5: m.md5 || null,\n download: 'http',\n path: m.url || null,\n saveAs: m.saveAs || null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Layout files\n for (const l of json.layouts || []) {\n files.push({\n type: 'layout',\n id: l.id != null ? String(l.id) : null,\n size: l.fileSize || 0,\n md5: l.md5 || null,\n download: 'http',\n path: l.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n // Widget data files (datasets — dynamic API, not static media)\n for (const w of json.widgets || []) {\n files.push({\n type: 'dataset',\n id: w.id != null ? String(w.id) : null,\n size: 0,\n md5: w.md5 || null,\n download: 'http',\n path: w.url || null,\n saveAs: null,\n fileType: null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n updateInterval: w.updateInterval || 0,\n });\n }\n\n // Dependencies (fonts, CSS, JS bundles) — pre-classified as 'static'\n for (const d of json.dependencies || []) {\n files.push({\n type: 'static',\n id: d.id != null ? String(d.id) : null,\n size: d.fileSize || 0,\n md5: d.md5 || null,\n download: 'http',\n path: d.url || null,\n saveAs: null,\n fileType: d.type || null,\n code: null,\n layoutid: null,\n regionid: null,\n mediaid: null,\n });\n }\n\n return { files, purge: [] };\n }\n\n /**\n * Schedule - get layout schedule.\n * GET /displays/{id}/schedule → native JSON (no XML parsing needed!)\n *\n * The v2 server returns the same structure as parseScheduleResponse(),\n * so we return it directly.\n */\n async schedule() {\n return this.restGet(`/displays/${this._displayId}/schedule`);\n }\n\n /**\n * GetResource - get rendered widget HTML.\n * GET /widgets/{layoutId}/{regionId}/{mediaId} → HTML string\n */\n async getResource(layoutId, regionId, mediaId) {\n return this.restGet(`/widgets/${layoutId}/${regionId}/${mediaId}`);\n }\n\n /**\n * NotifyStatus - report current status.\n * PUT /displays/{id}/status → JSON acknowledgement\n */\n async notifyStatus(status) {\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return this.restSend('PUT', `/displays/${this._displayId}/status`, {\n statusData: status,\n });\n }\n\n /**\n * MediaInventory - report downloaded files.\n * PUT /displays/{id}/inventory → JSON acknowledgement\n */\n async mediaInventory(inventoryXml) {\n const body = Array.isArray(inventoryXml)\n ? { inventoryItems: inventoryXml }\n : { inventory: inventoryXml };\n return this.restSend('PUT', `/displays/${this._displayId}/inventory`, body);\n }\n\n /**\n * BlackList - report broken media to CMS.\n * Not in v2 API — falls back to v1 behavior (no-op with warning).\n */\n async blackList(mediaId, type, reason) {\n log.warn(`BlackList not available in v2 API (${type}/${mediaId}: ${reason})`);\n return false;\n }\n\n /**\n * SubmitLog - submit player logs to CMS.\n * POST /displays/{id}/logs → JSON acknowledgement\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const body = Array.isArray(logXml) ? { logs: logXml } : { logXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/logs`, body);\n return result?.success === true;\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS.\n * POST /displays/{id}/screenshot → JSON acknowledgement\n */\n async submitScreenShot(base64Image) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/screenshot`, {\n screenshot: base64Image,\n });\n return result?.success === true;\n }\n\n /**\n * SubmitStats - submit proof of play statistics.\n * POST /displays/{id}/stats → JSON acknowledgement\n */\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const body = Array.isArray(statsXml) ? { stats: statsXml } : { statXml: statsXml };\n const result = await this.restSend('POST', `/displays/${this._displayId}/stats`, body);\n const success = result?.success === true;\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts.\n * POST /displays/{id}/faults → JSON acknowledgement\n */\n async reportFaults(faultJson) {\n const result = await this.restSend('POST', `/displays/${this._displayId}/faults`, {\n fault: faultJson,\n });\n return result?.success === true;\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria.\n * GET /displays/{id}/weather → JSON weather data\n */\n async getWeather() {\n return this.restGet(`/displays/${this._displayId}/weather`);\n }\n\n // ─── Static helpers ───────────────────────────────────────────\n\n /**\n * Probe whether the CMS supports API v2.\n * GET /api/v2/player/health → { version: 2, status: \"ok\" }\n *\n * @param {string} cmsUrl - CMS base URL\n * @param {Object} [retryOptions] - Retry options for fetch\n * @returns {Promise<boolean>} true if v2 is available\n */\n static async isAvailable(cmsUrl, retryOptions) {\n try {\n // In proxy mode, probe the local proxy's forward route instead of the CMS directly (avoids CORS)\n const isProxy = typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron || window.location.hostname === 'localhost');\n const base = isProxy ? '' : cmsUrl.replace(/\\/+$/, '');\n const url = `${base}${PLAYER_API}/health`;\n const response = await fetchWithRetry(url, { method: 'GET' }, retryOptions || { maxRetries: 0 });\n if (!response.ok) return false;\n const data = await response.json();\n return data.version === 2 && data.status === 'ok';\n } catch {\n return false;\n }\n }\n}\n","/**\n * Shared schedule XML parser used by both RestClient and XmdsClient.\n *\n * Both transports return the same XML structure for the Schedule endpoint,\n * so the parsing logic lives here to avoid duplication.\n */\n\n/**\n * Parse criteria child elements from a layout/overlay element.\n * Criteria are conditions that must be met for the item to display.\n *\n * XML format: <criteria metric=\"dayOfWeek\" condition=\"equals\" type=\"string\">Monday</criteria>\n *\n * @param {Element} parentEl - Parent XML element containing <criteria> children\n * @returns {Array<{metric: string, condition: string, type: string, value: string}>}\n */\nfunction parseCriteria(parentEl) {\n const criteria = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'criteria') continue;\n criteria.push({\n metric: child.getAttribute('metric') || '',\n condition: child.getAttribute('condition') || '',\n type: child.getAttribute('type') || 'string',\n value: child.textContent || ''\n });\n }\n return criteria;\n}\n\n/**\n * Parse Schedule XML response into a normalized schedule object.\n *\n * @param {string} xml - Raw XML string from CMS schedule endpoint\n * @returns {Object} Parsed schedule with default, layouts, campaigns, overlays, actions, commands, dataConnectors\n */\nexport function parseScheduleResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const schedule = {\n default: null,\n defaultDependants: [],\n dependants: [], // Global dependants that gate ALL layouts\n layouts: [],\n campaigns: [],\n overlays: [],\n actions: [],\n commands: [],\n dataConnectors: []\n };\n\n // Parse global dependants (root-level <dependants> — must be cached before any layout plays)\n const scheduleEl = doc.querySelector('schedule');\n if (scheduleEl) {\n const globalDeps = Array.from(scheduleEl.children).filter(\n el => el.tagName === 'dependants'\n );\n for (const depContainer of globalDeps) {\n // Skip if this is nested inside <default>, <layout>, etc.\n if (depContainer.parentElement !== scheduleEl) continue;\n for (const fileEl of depContainer.querySelectorAll('file')) {\n if (fileEl.textContent) schedule.dependants.push(fileEl.textContent);\n }\n }\n }\n\n const defaultEl = doc.querySelector('default');\n if (defaultEl) {\n schedule.default = defaultEl.getAttribute('file');\n // Parse dependants — files that must be cached before this layout plays\n const defaultDeps = defaultEl.querySelectorAll('dependants > file');\n if (defaultDeps.length > 0) {\n schedule.defaultDependants = [...defaultDeps].map(el => el.textContent);\n }\n }\n\n // Parse campaigns (groups of layouts with shared priority)\n for (const campaignEl of doc.querySelectorAll('campaign')) {\n const campaign = {\n id: campaignEl.getAttribute('id'),\n priority: parseInt(campaignEl.getAttribute('priority') || '0'),\n fromdt: campaignEl.getAttribute('fromdt'),\n todt: campaignEl.getAttribute('todt'),\n scheduleid: campaignEl.getAttribute('scheduleid'),\n maxPlaysPerHour: parseInt(campaignEl.getAttribute('maxPlaysPerHour') || '0'),\n shareOfVoice: parseInt(campaignEl.getAttribute('shareOfVoice') || '0'),\n isGeoAware: campaignEl.getAttribute('isGeoAware') === '1',\n geoLocation: campaignEl.getAttribute('geoLocation') || '',\n syncEvent: campaignEl.getAttribute('syncEvent') === '1',\n recurrenceType: campaignEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(campaignEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: campaignEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: campaignEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(campaignEl),\n layouts: []\n };\n\n // Parse layouts within this campaign\n for (const layoutEl of campaignEl.querySelectorAll('layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n campaign.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n // Layouts in campaigns inherit timing from campaign level\n fromdt: layoutEl.getAttribute('fromdt') || campaign.fromdt,\n todt: layoutEl.getAttribute('todt') || campaign.todt,\n scheduleid: campaign.scheduleid,\n priority: campaign.priority, // Priority at campaign level\n campaignId: campaign.id,\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n schedule.campaigns.push(campaign);\n }\n\n // Parse standalone layouts (not in campaigns)\n for (const layoutEl of doc.querySelectorAll('schedule > layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n schedule.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n fromdt: layoutEl.getAttribute('fromdt'),\n todt: layoutEl.getAttribute('todt'),\n scheduleid: layoutEl.getAttribute('scheduleid'),\n priority: parseInt(layoutEl.getAttribute('priority') || '0'),\n campaignId: null, // Standalone layout\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n recurrenceType: layoutEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(layoutEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: layoutEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: layoutEl.getAttribute('recurrenceRange') || null,\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n // Parse overlay layouts (appear on top of main layouts)\n const overlaysContainer = doc.querySelector('overlays');\n if (overlaysContainer) {\n for (const overlayEl of overlaysContainer.querySelectorAll('overlay')) {\n const fileId = overlayEl.getAttribute('file');\n schedule.overlays.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n duration: parseInt(overlayEl.getAttribute('duration') || '60'),\n file: fileId,\n fromdt: overlayEl.getAttribute('fromdt'),\n todt: overlayEl.getAttribute('todt'),\n priority: parseInt(overlayEl.getAttribute('priority') || '0'),\n scheduleid: overlayEl.getAttribute('scheduleid'),\n isGeoAware: overlayEl.getAttribute('isGeoAware') === '1',\n geoLocation: overlayEl.getAttribute('geoLocation') || '',\n syncEvent: overlayEl.getAttribute('syncEvent') === '1',\n maxPlaysPerHour: parseInt(overlayEl.getAttribute('maxPlaysPerHour') || '0'),\n recurrenceType: overlayEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(overlayEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: overlayEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: overlayEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(overlayEl)\n });\n }\n }\n\n // Parse action events (scheduled triggers)\n const actionsContainer = doc.querySelector('actions');\n if (actionsContainer) {\n for (const actionEl of actionsContainer.querySelectorAll('action')) {\n schedule.actions.push({\n actionType: actionEl.getAttribute('actionType') || '',\n triggerCode: actionEl.getAttribute('triggerCode') || '',\n layoutCode: actionEl.getAttribute('layoutCode') || '',\n commandCode: actionEl.getAttribute('commandCode') || '',\n duration: parseInt(actionEl.getAttribute('duration') || '0'),\n fromdt: actionEl.getAttribute('fromdt'),\n todt: actionEl.getAttribute('todt'),\n priority: parseInt(actionEl.getAttribute('priority') || '0'),\n scheduleid: actionEl.getAttribute('scheduleid'),\n isGeoAware: actionEl.getAttribute('isGeoAware') === '1',\n geoLocation: actionEl.getAttribute('geoLocation') || ''\n });\n }\n }\n\n // Parse server commands (remote control)\n for (const cmdEl of doc.querySelectorAll('schedule > command')) {\n schedule.commands.push({\n code: cmdEl.getAttribute('code') || '',\n date: cmdEl.getAttribute('date') || ''\n });\n }\n\n // Parse data connectors (real-time data sources for widgets)\n // Spec: <dataConnectors><connector dataSetId=\"\" dataParams=\"\" js=\"\"/></dataConnectors>\n const dataConnectorsContainer = doc.querySelector('dataConnectors');\n if (dataConnectorsContainer) {\n for (const dcEl of dataConnectorsContainer.querySelectorAll('connector')) {\n schedule.dataConnectors.push({\n id: dcEl.getAttribute('id') || '',\n dataConnectorId: dcEl.getAttribute('dataConnectorId') || '',\n dataSetId: dcEl.getAttribute('dataSetId') || '',\n dataKey: dcEl.getAttribute('dataKey') || '',\n dataParams: dcEl.getAttribute('dataParams') || '',\n js: dcEl.getAttribute('js') || '',\n url: dcEl.getAttribute('url') || '',\n updateInterval: parseInt(dcEl.getAttribute('updateInterval') || '300', 10)\n });\n }\n }\n\n return schedule;\n}\n","/**\n * XMDS SOAP transport client for Xibo CMS.\n *\n * Uses the traditional SOAP/XML endpoint (xmds.php) for full protocol\n * compatibility with all Xibo CMS versions.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry } from '@xiboplayer/utils';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('XMDS');\n\nexport class XmdsClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 5;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n }\n\n // ─── SOAP transport helpers ─────────────────────────────────────\n\n /**\n * Build SOAP envelope for a given method and parameters\n */\n buildEnvelope(method, params) {\n const paramElements = Object.entries(params)\n .map(([key, value]) => {\n const escaped = String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n return `<${key} xsi:type=\"xsd:string\">${escaped}</${key}>`;\n })\n .join('\\n ');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soap:Envelope\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:tns=\"urn:xmds\"\n xmlns:types=\"urn:xmds/encodedTypes\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <tns:${method}>\n ${paramElements}\n </tns:${method}>\n </soap:Body>\n</soap:Envelope>`;\n }\n\n /**\n * Rewrite XMDS URL for local proxy.\n * If running inside a local wrapper (Electron, Chromium kiosk), use the\n * local proxy to avoid CORS.\n * Detection: preload.js exposes window.electronAPI.isElectron = true,\n * or fallback to checking localhost (any local wrapper port).\n */\n rewriteXmdsUrl(cmsUrl) {\n if (typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n window.location.hostname === 'localhost')) {\n const encodedCmsUrl = encodeURIComponent(cmsUrl);\n return `/xmds-proxy?cms=${encodedCmsUrl}`;\n }\n\n return `${cmsUrl}/xmds.php`;\n }\n\n /**\n * Call XMDS SOAP method\n */\n async call(method, params = {}) {\n const xmdsUrl = this.rewriteXmdsUrl(this.config.cmsUrl);\n const url = `${xmdsUrl}${xmdsUrl.includes('?') ? '&' : '?'}v=${this.schemaVersion}&method=${method}`;\n const body = this.buildEnvelope(method, params);\n\n log.debug(`${method}`, params);\n log.debug(`URL: ${url}`);\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n body\n }, this.retryOptions);\n\n if (!response.ok) {\n throw new Error(`XMDS ${method} failed: ${response.status} ${response.statusText}`);\n }\n\n const xml = await response.text();\n return this.parseResponse(xml, method);\n }\n\n /**\n * Parse SOAP response\n */\n parseResponse(xml, method) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n // Check for SOAP fault (handle namespace prefix like soap:Fault)\n let fault = doc.querySelector('Fault');\n if (!fault) {\n fault = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === 'Fault' || el.tagName.endsWith(':Fault')\n );\n }\n if (fault) {\n const faultString = fault.querySelector('faultstring')?.textContent\n || Array.from(fault.querySelectorAll('*')).find(el => el.localName === 'faultstring')?.textContent\n || 'Unknown SOAP fault';\n throw new Error(`SOAP Fault: ${faultString}`);\n }\n\n // Extract response element (handle namespace prefixes like ns1:MethodResponse)\n const responseTag = `${method}Response`;\n let responseEl = doc.querySelector(responseTag);\n if (!responseEl) {\n responseEl = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === responseTag || el.tagName.endsWith(':' + responseTag)\n );\n }\n\n if (!responseEl) {\n throw new Error(`No ${responseTag} element in SOAP response`);\n }\n\n const returnEl = responseEl.firstElementChild;\n if (!returnEl) {\n return null;\n }\n\n return returnEl.textContent;\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n */\n async registerDisplay() {\n const os = `${navigator.platform} ${navigator.userAgent}`;\n\n const xml = await this.call('RegisterDisplay', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'linux',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || '1',\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed'\n });\n\n return this.parseRegisterDisplayResponse(xml);\n }\n\n /**\n * Parse RegisterDisplay XML response\n */\n parseRegisterDisplayResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const display = doc.querySelector('display');\n if (!display) {\n throw new Error('Invalid RegisterDisplay response: no <display> element');\n }\n\n const code = display.getAttribute('code');\n const message = display.getAttribute('message');\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n const tags = [];\n const commands = [];\n for (const child of display.children) {\n const name = child.tagName.toLowerCase();\n if (name === 'file') continue;\n if (name === 'commands') {\n // Parse <commands><command code=\"xyz\" commandString=\"args\"/></commands>\n for (const cmdEl of child.querySelectorAll('command')) {\n commands.push({\n commandCode: cmdEl.getAttribute('code') || cmdEl.getAttribute('commandCode') || '',\n commandString: cmdEl.getAttribute('commandString') || ''\n });\n }\n continue;\n }\n if (name === 'tags') {\n // Parse <tags><tag>value</tag>...</tags> into array\n for (const tagEl of child.querySelectorAll('tag')) {\n if (tagEl.textContent) tags.push(tagEl.textContent);\n }\n continue;\n }\n settings[child.tagName] = child.textContent;\n }\n\n const checkRf = display.getAttribute('checkRf') || '';\n const checkSchedule = display.getAttribute('checkSchedule') || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: display.getAttribute('date') || null,\n timezone: display.getAttribute('timezone') || null,\n status: display.getAttribute('status') || null,\n localDate: display.getAttribute('localDate') || null,\n version_instructions: display.getAttribute('version_instructions') || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n const syncGroupVal = settings.syncGroup || null;\n const syncConfig = syncGroupVal ? {\n syncGroup: syncGroupVal,\n syncPublisherPort: parseInt(settings.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(settings.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(settings.syncVideoPauseDelay || '100', 10),\n isLead: syncGroupVal === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n */\n async requiredFiles() {\n const xml = await this.call('RequiredFiles', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return this.parseRequiredFilesResponse(xml);\n }\n\n /**\n * Parse RequiredFiles XML response\n */\n parseRequiredFilesResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const files = [];\n for (const fileEl of doc.querySelectorAll('file')) {\n files.push({\n type: fileEl.getAttribute('type'),\n id: fileEl.getAttribute('id'),\n size: parseInt(fileEl.getAttribute('size') || '0'),\n md5: fileEl.getAttribute('md5'),\n download: fileEl.getAttribute('download'),\n path: fileEl.getAttribute('path'),\n saveAs: fileEl.getAttribute('saveAs') || null,\n fileType: fileEl.getAttribute('fileType') || null,\n code: fileEl.getAttribute('code'),\n layoutid: fileEl.getAttribute('layoutid'),\n regionid: fileEl.getAttribute('regionid'),\n mediaid: fileEl.getAttribute('mediaid')\n });\n }\n\n // Parse purge block — files CMS wants the player to delete\n const purgeItems = [];\n const purgeEl = doc.querySelector('purge');\n if (purgeEl) {\n for (const itemEl of purgeEl.querySelectorAll('item')) {\n purgeItems.push({\n id: itemEl.getAttribute('id'),\n storedAs: itemEl.getAttribute('storedAs')\n });\n }\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n */\n async schedule() {\n const xml = await this.call('Schedule', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n */\n async getResource(layoutId, regionId, mediaId) {\n const xml = await this.call('GetResource', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId)\n });\n\n return xml;\n }\n\n /**\n * NotifyStatus - report current status\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n // Enrich with storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return await this.call('NotifyStatus', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n status: JSON.stringify(status)\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n */\n async mediaInventory(inventoryXml) {\n return await this.call('MediaInventory', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaInventory: inventoryXml\n });\n }\n\n /**\n * BlackList - report broken media to CMS\n * @param {string} mediaId - The media file ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const xml = await this.call('BlackList', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render'\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return xml === 'true';\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS for remote debugging\n * @param {string} logXml - XML string containing log entries\n * @returns {Promise<boolean>} - true if logs were successfully submitted\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const xml = await this.call('SubmitLog', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n logXml: logXml\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS for display verification\n * @param {string} base64Image - Base64-encoded PNG image data\n * @returns {Promise<boolean>} - true if screenshot was successfully submitted\n */\n async submitScreenShot(base64Image) {\n const xml = await this.call('SubmitScreenShot', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n screenShot: base64Image\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * @param {string} statsXml - XML-encoded stats string\n * @returns {Promise<boolean>} - true if stats were successfully submitted\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n return this.call('ReportFaults', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n fault: faultJson\n });\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * @returns {Promise<string>} Weather data XML from CMS\n */\n async getWeather() {\n return this.call('GetWeather', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const xml = await this.call('SubmitStats', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n statXml: statsXml\n });\n\n const success = xml === 'true';\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","url","response","fetchWithRetry","errorBody","data","path","queryParams","token","key","value","cacheKey","headers","cachedEtag","cached","etag","contentType","method","body","os","json","display","attrs","code","message","settings","tags","commands","c","extractTag","t","checkRf","checkSchedule","displayAttrs","syncConfig","files","m","l","w","d","layoutId","regionId","mediaId","status","estimate","inventoryXml","type","reason","logXml","hardwareKeyOverride","result","base64Image","statsXml","success","error","faultJson","cmsUrl","retryOptions","parseCriteria","parentEl","criteria","child","parseScheduleResponse","xml","doc","schedule","scheduleEl","globalDeps","el","depContainer","fileEl","defaultEl","defaultDeps","campaignEl","campaign","layoutEl","fileId","depEls","overlaysContainer","overlayEl","actionsContainer","actionEl","cmdEl","dataConnectorsContainer","dcEl","XmdsClient","params","paramElements","escaped","xmdsUrl","fault","faultString","_b","responseTag","responseEl","returnEl","name","t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qB2D,CAAK,EAC5B,EACT,CACF,CAOA,MAAM,UAAUN,EAAQC,EAAsB,KAAM,CAOlD,OANY,MAAM,KAAK,KAAK,YAAa,CACvC,UAAW,KAAK,OAAO,OACvB,YAAaA,GAAuB,KAAK,OAAO,YAChD,OAAQD,CACd,CAAK,IAEc,MACjB,CAOA,MAAM,iBAAiBG,EAAa,CAOlC,OANY,MAAM,KAAK,KAAK,mBAAoB,CAC9C,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,YACzB,WAAYA,CAClB,CAAK,IAEc,MACjB,CAYA,MAAM,aAAaI,EAAW,CAC5B,OAAO,KAAK,KAAK,eAAgB,CAC/B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,YACzB,MAAOA,CACb,CAAK,CACH,CAMA,MAAM,YAAa,CACjB,OAAO,KAAK,KAAK,aAAc,CAC7B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,WAC/B,CAAK,CACH,CAEA,MAAM,YAAYH,EAAUH,EAAsB,KAAM,CACtD,GAAI,CAOF,MAAMI,EANM,MAAM,KAAK,KAAK,cAAe,CACzC,UAAW,KAAK,OAAO,OACvB,YAAaJ,GAAuB,KAAK,OAAO,YAChD,QAASG,CACjB,CAAO,IAEuB,OACxB,OAAAzD,EAAI,KAAK,uBAAuB0D,CAAO,EAAE,EAClCA,CACT,OAASC,EAAO,CACd,MAAA3D,EAAI,MAAM,sBAAuB2D,CAAK,EAChCA,CACR,CACF,CACF"}
|
package/dist/index.html
CHANGED
|
@@ -94,10 +94,10 @@
|
|
|
94
94
|
height: 100%;
|
|
95
95
|
}
|
|
96
96
|
</style>
|
|
97
|
-
<script type="module" crossorigin src="./assets/main-
|
|
97
|
+
<script type="module" crossorigin src="./assets/main-DJYbit7N.js"></script>
|
|
98
98
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
99
|
-
<link rel="modulepreload" crossorigin href="./assets/index-
|
|
100
|
-
<link rel="modulepreload" crossorigin href="./assets/widget-html-
|
|
99
|
+
<link rel="modulepreload" crossorigin href="./assets/index-BglkPErZ.js">
|
|
100
|
+
<link rel="modulepreload" crossorigin href="./assets/widget-html-D6xqg8Sp.js">
|
|
101
101
|
</head>
|
|
102
102
|
<body>
|
|
103
103
|
<!-- Status overlay -->
|
package/dist/setup.html
CHANGED
|
@@ -287,10 +287,10 @@
|
|
|
287
287
|
color: #444;
|
|
288
288
|
}
|
|
289
289
|
</style>
|
|
290
|
-
<script type="module" crossorigin src="./assets/setup-
|
|
290
|
+
<script type="module" crossorigin src="./assets/setup-BXLaipeI.js"></script>
|
|
291
291
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
292
|
-
<link rel="modulepreload" crossorigin href="./assets/index-
|
|
293
|
-
<link rel="modulepreload" crossorigin href="./assets/xmds-client-
|
|
292
|
+
<link rel="modulepreload" crossorigin href="./assets/index-BglkPErZ.js">
|
|
293
|
+
<link rel="modulepreload" crossorigin href="./assets/xmds-client-D6JI3K3_.js">
|
|
294
294
|
</head>
|
|
295
295
|
<body>
|
|
296
296
|
<div class="container">
|
package/dist/sw-pwa.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{D as C}from"./assets/widget-html-
|
|
1
|
+
import{D as C}from"./assets/widget-html-D6xqg8Sp.js";import{VERSION as S}from"./assets/index-FG4fTI4i.js";import{c as v,R,M as T,B as i}from"./assets/chunk-config-BjXWw-V8.js";import{createLogger as E}from"./assets/index-BglkPErZ.js";const o="2026-03-04T00:15:13.038Z",s=E("SW"),c=v(s),d=c.chunkSize,N=c.threshold,O=c.concurrency;s.info("Loading modular Service Worker:",o);const u=new C({concurrency:O,chunkSize:d,chunksPerFile:2}),A=new R(u),W=new T(u,{chunkSize:d,chunkStorageThreshold:N});async function I(e){const t=new URL(e.request.url),n=t.pathname.replace(i+"/ic",""),a=e.request.method;s.info("Interactive Control request:",a,n);let l=null;if(a==="POST"||a==="PUT")try{l=await e.request.text()}catch{}const h=await self.clients.matchAll({type:"window"});if(h.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const f=h[0];try{const r=await new Promise((m,g)=>{const p=new MessageChannel,w=setTimeout(()=>g(new Error("IC timeout")),5e3);p.port1.onmessage=y=>{clearTimeout(w),m(y.data)},f.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:n,search:t.search,body:l},[p.port2])});return new Response(r.body||"",{status:r.status||200,headers:{"Content-Type":r.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(r){return s.error("IC handler error:",r),new Response(JSON.stringify({error:r.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",e=>{s.info("Installing... Version:",o),e.waitUntil((async()=>{if(self.registration.active)try{const n=await(await caches.open("xibo-sw-version")).match("version");if(n){const a=await n.text();if(a===o){s.info("Same version already active, skipping activation to preserve streams");return}s.info("Version changed:",a,"→",o)}}catch{}return s.info("New version, activating immediately"),self.skipWaiting()})())});self.addEventListener("activate",e=>{s.info("Activating... Version:",o,"| @xiboplayer/cache:",S),e.waitUntil(caches.keys().then(t=>Promise.all(t.filter(n=>n.startsWith("xibo-")&&n!=="xibo-sw-version").map(n=>(s.info("Deleting legacy cache:",n),caches.delete(n))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(o)),s.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{s.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(n=>{n.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",e=>{const t=new URL(e.request.url);if(t.pathname.startsWith(i+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&e.request.method==="GET"){if(t.pathname.startsWith(i+"/ic/")){e.respondWith(I(e));return}e.respondWith(A.handleRequest(e))}});self.addEventListener("message",e=>{e.waitUntil(W.handleMessage(e).then(t=>{var n;(n=e.ports[0])==null||n.postMessage(t)}))});s.info("Modular Service Worker ready");
|
|
2
2
|
//# sourceMappingURL=sw-pwa.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xiboplayer/pwa",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"description": "Lightweight PWA Xibo Player with RendererLite",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -10,18 +10,18 @@
|
|
|
10
10
|
"html2canvas": "^1.4.1",
|
|
11
11
|
"nanoevents": "^9.0.0",
|
|
12
12
|
"xml2js": "^0.6.2",
|
|
13
|
-
"@xiboplayer/
|
|
14
|
-
"@xiboplayer/
|
|
15
|
-
"@xiboplayer/
|
|
16
|
-
"@xiboplayer/
|
|
17
|
-
"@xiboplayer/
|
|
18
|
-
"@xiboplayer/
|
|
19
|
-
"@xiboplayer/
|
|
20
|
-
"@xiboplayer/
|
|
21
|
-
"@xiboplayer/
|
|
22
|
-
"@xiboplayer/
|
|
23
|
-
"@xiboplayer/
|
|
24
|
-
"@xiboplayer/
|
|
13
|
+
"@xiboplayer/crypto": "0.6.2",
|
|
14
|
+
"@xiboplayer/renderer": "0.6.2",
|
|
15
|
+
"@xiboplayer/schedule": "0.6.2",
|
|
16
|
+
"@xiboplayer/stats": "0.6.2",
|
|
17
|
+
"@xiboplayer/settings": "0.6.2",
|
|
18
|
+
"@xiboplayer/sw": "0.6.2",
|
|
19
|
+
"@xiboplayer/sync": "0.6.2",
|
|
20
|
+
"@xiboplayer/xmds": "0.6.2",
|
|
21
|
+
"@xiboplayer/xmr": "0.6.2",
|
|
22
|
+
"@xiboplayer/core": "0.6.2",
|
|
23
|
+
"@xiboplayer/cache": "0.6.2",
|
|
24
|
+
"@xiboplayer/utils": "0.6.2"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/node": "^22.10.5",
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{createLogger as w}from"./index-leM889oV.js";const m="0.6.1",$={version:m},c=w("@xiboplayer/stats"),D="xibo-player-stats",v=1,b="stats";class L{constructor(){this.db=null,this.inProgressStats=new Map}async init(){if(this.db){c.debug("Stats collector already initialized");return}return new Promise((r,t)=>{if(typeof indexedDB>"u"){const e=new Error("IndexedDB not available");c.error("IndexedDB not available - stats will not be persisted"),t(e);return}const s=indexedDB.open(D,v);s.onerror=()=>{const e=new Error(`Failed to open IndexedDB: ${s.error}`);c.error("Failed to open stats database:",s.error),t(e)},s.onsuccess=()=>{this.db=s.result,c.info("Stats database initialized"),r()},s.onupgradeneeded=e=>{const n=e.target.result;n.objectStoreNames.contains(b)||(n.createObjectStore(b,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),c.info("Stats store created"))}})}async startLayout(r,t,s){if(!this.db){c.warn("Stats database not initialized");return}if((s==null?void 0:s.enableStat)===!1){c.debug(`Stats disabled for layout ${r} (enableStat=false)`);return}const e=`layout-${r}`;if(this.inProgressStats.has(e)){const o=this.inProgressStats.get(e);o.end=new Date,o.duration=Math.floor((o.end-o.start)/1e3),await this._saveStatSplit(o),this.inProgressStats.delete(e),c.debug(`Layout ${r} replay - ended previous cycle (${o.duration}s)`)}const n={type:"layout",layoutId:r,scheduleId:t,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(e,n),c.debug(`Started tracking layout ${r} (schedule ${t})`)}async endLayout(r,t){if(!this.db){c.warn("Stats database not initialized");return}const s=`layout-${r}`,e=this.inProgressStats.get(s);if(!e){c.debug(`Layout ${r} not found in progress (may have been ended by replay)`);return}e.end=new Date,e.duration=Math.floor((e.end-e.start)/1e3);try{await this._saveStatSplit(e),this.inProgressStats.delete(s),c.debug(`Ended tracking layout ${r} (${e.duration}s)`)}catch(n){throw c.error(`Failed to save layout stat ${r}:`,n),n}}async startWidget(r,t,s,e,n){if(!this.db){c.warn("Stats database not initialized");return}if((n==null?void 0:n.enableStat)===!1){c.debug(`Stats disabled for widget ${r} (enableStat=false)`);return}const o=`media-${r}-${t}`;if(this.inProgressStats.has(o)){const d=this.inProgressStats.get(o);d.end=new Date,d.duration=Math.floor((d.end-d.start)/1e3),await this._saveStatSplit(d),this.inProgressStats.delete(o),c.debug(`Widget ${r} replay - ended previous cycle (${d.duration}s)`)}const a={type:"media",mediaId:r,widgetId:e||null,layoutId:t,scheduleId:s,start:new Date,end:null,duration:0,count:1,submitted:0};this.inProgressStats.set(o,a),c.debug(`Started tracking widget ${r} in layout ${t}`)}async endWidget(r,t,s){if(!this.db){c.warn("Stats database not initialized");return}const e=`media-${r}-${t}`,n=this.inProgressStats.get(e);if(!n){c.debug(`Widget ${r} not found in progress (expected during layout transitions)`);return}n.end=new Date,n.duration=Math.floor((n.end-n.start)/1e3);try{await this._saveStatSplit(n),this.inProgressStats.delete(e),c.debug(`Ended tracking widget ${r} (${n.duration}s)`)}catch(o){throw c.error(`Failed to save widget stat ${r}:`,o),o}}async recordEvent(r,t,s,e){if(!this.db){c.warn("Stats database not initialized");return}const n=new Date,o={type:"event",tag:r,layoutId:t,widgetId:s,scheduleId:e,start:n,end:n,duration:0,count:1,submitted:0};try{await this._saveStat(o),c.debug(`Recorded event '${r}' for widget ${s} in layout ${t}`)}catch(a){throw c.error(`Failed to record event '${r}':`,a),a}}async getStatsForSubmission(r=50){return this.db?new Promise((t,s)=>{const a=this.db.transaction([b],"readonly").objectStore(b).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(d.push(h.value),h.continue()):(c.debug(`Retrieved ${d.length} unsubmitted stats`),t(d))},a.onerror=()=>{c.error("Failed to retrieve stats:",a.error),s(new Error(`Failed to retrieve stats: ${a.error}`))}}):(c.warn("Stats database not initialized"),[])}async clearSubmittedStats(r){if(!this.db){c.warn("Stats database not initialized");return}if(!(!r||r.length===0))return new Promise((t,s)=>{const e=this.db.transaction([b],"readwrite"),n=e.objectStore(b);let o=0;r.forEach(a=>{if(a.id){const d=n.delete(a.id);d.onsuccess=()=>{o++},d.onerror=()=>{c.error(`Failed to delete stat ${a.id}:`,d.error)}}}),e.oncomplete=()=>{c.debug(`Deleted ${o} submitted stats`),t()},e.onerror=()=>{c.error("Failed to delete submitted stats:",e.error),s(new Error(`Failed to delete stats: ${e.error}`))}})}async getAggregatedStatsForSubmission(r=50){const t=await this.getStatsForSubmission(r);if(t.length===0)return[];const s=new Map;for(const e of t){const n=e.start instanceof Date?e.start.toISOString().slice(0,13):new Date(e.start).toISOString().slice(0,13),o=`${e.type}|${e.layoutId}|${e.mediaId||""}|${e.widgetId||""}|${e.tag||""}|${e.scheduleId}|${n}`;if(s.has(o)){const a=s.get(o);a.count+=e.count||1,a.duration+=e.duration||0;const d=e.start instanceof Date?e.start:new Date(e.start),u=e.end instanceof Date?e.end:new Date(e.end||e.start);d<a.start&&(a.start=d),u>a.end&&(a.end=u),a._rawIds.push(e.id)}else s.set(o,{...e,start:e.start instanceof Date?e.start:new Date(e.start),end:e.end instanceof Date?e.end:new Date(e.end||e.start),count:e.count||1,_rawIds:[e.id]})}return Array.from(s.values())}async getAllStats(){return this.db?new Promise((r,t)=>{const n=this.db.transaction([b],"readonly").objectStore(b).getAll();n.onsuccess=()=>{r(n.result)},n.onerror=()=>{c.error("Failed to get all stats:",n.error),t(new Error(`Failed to get all stats: ${n.error}`))}}):(c.warn("Stats database not initialized"),[])}async clearAllStats(){if(!this.db){c.warn("Stats database not initialized");return}return new Promise((r,t)=>{const n=this.db.transaction([b],"readwrite").objectStore(b).clear();n.onsuccess=()=>{c.debug("Cleared all stats"),this.inProgressStats.clear(),r()},n.onerror=()=>{c.error("Failed to clear all stats:",n.error),t(new Error(`Failed to clear stats: ${n.error}`))}})}async _saveStat(r){return new Promise((t,s)=>{const n=this.db.transaction([b],"readwrite").objectStore(b),o=n.add(r);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(c.error("IndexedDB quota exceeded - cleaning old stats"),this._cleanOldStats().then(()=>{const a=n.add(r);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}_splitAtHourBoundaries(r){const t=r.start,s=r.end;if(t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()&&t.getHours()===s.getHours())return[r];const e=[];let n=new Date(t.getTime());for(;n<s;){const o=new Date(n.getTime());o.setMinutes(0,0,0),o.setHours(o.getHours()+1);const a=o<s?o:s,d=Math.floor((a-n)/1e3);e.push({...r,start:new Date(n.getTime()),end:new Date(a.getTime()),duration:d,count:1}),n=a}return e}async _saveStatSplit(r){const t=this._splitAtHourBoundaries(r);for(const s of t)await this._saveStat(s)}async _cleanOldStats(){if(this.db)return new Promise((r,t)=>{const e=this.db.transaction([b],"readwrite").objectStore(b),o=e.index("submitted").openCursor(1),a=[];o.onsuccess=d=>{const u=d.target.result;u&&a.length<100?(a.push(u.value.id),u.continue()):(a.forEach(h=>{e.delete(h)}),c.info(`Cleaned ${a.length} old stats due to quota`),r())},o.onerror=()=>{c.error("Failed to clean old stats:",o.error),t(o.error)}})}}function E(i){return!i||i.length===0?"<stats></stats>":`<stats>
|
|
2
|
-
${i.map(t=>{const s=S(t.start),e=S(t.end||t.start),n=[`type="${f(t.type)}"`,`fromdt="${f(s)}"`,`todt="${f(e)}"`,`scheduleid="${t.scheduleId}"`,`layoutid="${t.layoutId}"`];return t.type==="media"&&(t.mediaId&&n.push(`mediaid="${t.mediaId}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),t.type==="event"&&(t.tag&&n.push(`tag="${f(t.tag)}"`),t.widgetId&&n.push(`widgetid="${t.widgetId}"`)),n.push(`count="${t.count}"`),n.push(`duration="${t.duration}"`),` <stat ${n.join(" ")} />`}).join(`
|
|
3
|
-
`)}
|
|
4
|
-
</stats>`}function S(i){i instanceof Date||(i=new Date(i));const r=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),e=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${r}-${t}-${s} ${e}:${n}:${o}`}function f(i){return typeof i!="string"?i:i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const l=w("@xiboplayer/stats"),F="xibo-player-logs",P=1,g="logs";class _{constructor(){this.db=null,this._reportedFaults=new Map}async init(){if(this.db){l.debug("Log reporter already initialized");return}return new Promise((r,t)=>{if(typeof indexedDB>"u"){const e=new Error("IndexedDB not available");l.error("IndexedDB not available - logs will not be persisted"),t(e);return}const s=indexedDB.open(F,P);s.onerror=()=>{const e=new Error(`Failed to open IndexedDB: ${s.error}`);l.error("Failed to open logs database:",s.error),t(e)},s.onsuccess=()=>{this.db=s.result,l.info("Logs database initialized"),r()},s.onupgradeneeded=e=>{const n=e.target.result;n.objectStoreNames.contains(g)||(n.createObjectStore(g,{keyPath:"id",autoIncrement:!0}).createIndex("submitted","submitted",{unique:!1}),l.info("Logs store created"))}})}async log(r,t,s="PLAYER",e=null){if(!this.db){console.warn("[LogReporter] Database not initialized, dropping log entry");return}["error","warning","audit","info","debug"].includes(r)||(r="info");const o={level:r,message:t,category:s,timestamp:new Date,submitted:0};e&&(e.alertType&&(o.alertType=e.alertType),e.eventType&&(o.eventType=e.eventType));try{await this._saveLog(o)}catch(a){throw console.error("[LogReporter] Failed to save log entry:",a),a}}async reportFault(r,t,s=3e5){const e=this._reportedFaults.get(r);e&&Date.now()-e<s||(this._reportedFaults.set(r,Date.now()),await this.log("error",t,"event",{alertType:"Player Fault",eventType:r}),l.info(`Fault reported: ${r} - ${t}`))}async getFaultsForSubmission(r=10){return this.db?new Promise((t,s)=>{const a=this.db.transaction([g],"readonly").objectStore(g).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(h.value.alertType==="Player Fault"&&d.push(h.value),h.continue()):t(d)},a.onerror=()=>{l.error("Failed to retrieve faults:",a.error),s(new Error(`Failed to retrieve faults: ${a.error}`))}}):[]}async error(r,t="PLAYER"){return this.log("error",r,t)}async audit(r,t="PLAYER"){return this.log("audit",r,t)}async info(r,t="PLAYER"){return this.log("info",r,t)}async debug(r,t="PLAYER"){return this.log("debug",r,t)}async getLogsForSubmission(r=50){return this.db?new Promise((t,s)=>{const a=this.db.transaction([g],"readonly").objectStore(g).index("submitted").openCursor(IDBKeyRange.only(0)),d=[];a.onsuccess=u=>{const h=u.target.result;h&&d.length<r?(d.push(h.value),h.continue()):(l.debug(`Retrieved ${d.length} unsubmitted logs (limit: ${r})`),t(d))},a.onerror=()=>{l.error("Failed to retrieve logs:",a.error),s(new Error(`Failed to retrieve logs: ${a.error}`))}}):(l.warn("Logs database not initialized"),[])}async _countUnsubmitted(){return new Promise(r=>{try{const n=this.db.transaction([g],"readonly").objectStore(g).index("submitted").count(IDBKeyRange.only(0));n.onsuccess=()=>r(n.result),n.onerror=()=>r(0)}catch{r(0)}})}async clearSubmittedLogs(r){if(!this.db){l.warn("Logs database not initialized");return}if(!(!r||r.length===0))return new Promise((t,s)=>{const e=this.db.transaction([g],"readwrite"),n=e.objectStore(g);let o=0;r.forEach(a=>{if(a.id){const d=n.delete(a.id);d.onsuccess=()=>{o++},d.onerror=()=>{l.error(`Failed to delete log ${a.id}:`,d.error)}}}),e.oncomplete=()=>{l.debug(`Deleted ${o} submitted logs`),t()},e.onerror=()=>{l.error("Failed to delete submitted logs:",e.error),s(new Error(`Failed to delete logs: ${e.error}`))}})}async getAllLogs(){return this.db?new Promise((r,t)=>{const n=this.db.transaction([g],"readonly").objectStore(g).getAll();n.onsuccess=()=>{r(n.result)},n.onerror=()=>{l.error("Failed to get all logs:",n.error),t(new Error(`Failed to get all logs: ${n.error}`))}}):(l.warn("Logs database not initialized"),[])}async clearAllLogs(){if(!this.db){l.warn("Logs database not initialized");return}return new Promise((r,t)=>{const n=this.db.transaction([g],"readwrite").objectStore(g).clear();n.onsuccess=()=>{l.debug("Cleared all logs"),r()},n.onerror=()=>{l.error("Failed to clear all logs:",n.error),t(new Error(`Failed to clear logs: ${n.error}`))}})}async _saveLog(r){return new Promise((t,s)=>{const n=this.db.transaction([g],"readwrite").objectStore(g),o=n.add(r);o.onsuccess=()=>{t(o.result)},o.onerror=()=>{o.error.name==="QuotaExceededError"?(console.warn("[LogReporter] IndexedDB quota exceeded - cleaning old logs"),this._cleanOldLogs().then(()=>{const a=n.add(r);a.onsuccess=()=>t(a.result),a.onerror=()=>s(a.error)}).catch(s)):s(o.error)}})}async _cleanOldLogs(){if(this.db)return new Promise((r,t)=>{const e=this.db.transaction([g],"readwrite").objectStore(g),o=e.index("submitted").openCursor(1),a=[];o.onsuccess=d=>{const u=d.target.result;u&&a.length<100?(a.push(u.value.id),u.continue()):(a.forEach(h=>{e.delete(h)}),console.log(`[LogReporter] Cleaned ${a.length} old logs due to quota`),r())},o.onerror=()=>{console.error("[LogReporter] Failed to clean old logs:",o.error),t(o.error)}})}}function R(i){return!i||i.length===0?"<logs></logs>":`<logs>
|
|
5
|
-
${i.map(t=>{const s=y(t.timestamp),e=t.level==="error"||t.level==="audit"?t.level:"audit",n=[`date="${p(s)}"`,`category="${p(e)}"`];t.alertType&&n.push(`alertType="${p(t.alertType)}"`),t.eventType&&n.push(`eventType="${p(t.eventType)}"`);const o=p(t.thread||"main"),a=p(t.method||t.category||"PLAYER"),d=p(t.message),u=p(String(t.scheduleId||"0"));return` <log ${n.join(" ")}>
|
|
6
|
-
<thread>${o}</thread>
|
|
7
|
-
<method>${a}</method>
|
|
8
|
-
<message>${d}</message>
|
|
9
|
-
<scheduleID>${u}</scheduleID>
|
|
10
|
-
</log>`}).join(`
|
|
11
|
-
`)}
|
|
12
|
-
</logs>`}function q(i){return!i||i.length===0?"[]":JSON.stringify(i.map(r=>({code:r.eventType||"UNKNOWN",reason:r.message||"",date:y(r.timestamp),layoutId:r.scheduleId||0})))}function y(i){i instanceof Date||(i=new Date(i));const r=i.getFullYear(),t=String(i.getMonth()+1).padStart(2,"0"),s=String(i.getDate()).padStart(2,"0"),e=String(i.getHours()).padStart(2,"0"),n=String(i.getMinutes()).padStart(2,"0"),o=String(i.getSeconds()).padStart(2,"0");return`${r}-${t}-${s} ${e}:${n}:${o}`}function p(i){return typeof i!="string"?i:i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const T=$.version;export{_ as LogReporter,L as StatsCollector,T as VERSION,q as formatFaults,R as formatLogs,E as formatStats};
|
|
13
|
-
//# sourceMappingURL=index-BVIXBw9z.js.map
|