@xiboplayer/pwa 0.7.1 → 0.7.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-DqswDQz2.js → chunk-config-BqpCSJ87.js} +2 -2
- package/dist/assets/{chunk-config-DqswDQz2.js.map → chunk-config-BqpCSJ87.js.map} +1 -1
- package/dist/assets/{index-Bn7yexJC.js → index-BBp7Yeqp.js} +2 -2
- package/dist/assets/{index-Bn7yexJC.js.map → index-BBp7Yeqp.js.map} +1 -1
- package/dist/assets/{index-DOWqpi1W.js → index-BGzZpdzW.js} +2 -2
- package/dist/assets/{index-DOWqpi1W.js.map → index-BGzZpdzW.js.map} +1 -1
- package/dist/assets/{index-K17x7fv_.js → index-Bj01q2d4.js} +2 -2
- package/dist/assets/{index-K17x7fv_.js.map → index-Bj01q2d4.js.map} +1 -1
- package/dist/assets/{index-Bgo3B90-.js → index-BmnGgxhy.js} +2 -2
- package/dist/assets/{index-Bgo3B90-.js.map → index-BmnGgxhy.js.map} +1 -1
- package/dist/assets/{index-DYMccG7M.js → index-DNyHrXGf.js} +2 -2
- package/dist/assets/{index-DYMccG7M.js.map → index-DNyHrXGf.js.map} +1 -1
- package/dist/assets/{index--0TbPToz.js → index-DPUPuUO8.js} +2 -2
- package/dist/assets/{index--0TbPToz.js.map → index-DPUPuUO8.js.map} +1 -1
- package/dist/assets/index-DwQpyIXq.js +2 -0
- package/dist/assets/{index-xijlgGv2.js.map → index-DwQpyIXq.js.map} +1 -1
- package/dist/assets/{index-CpSQnOTy.js → index-O4mn_OO0.js} +2 -2
- package/dist/assets/{index-CpSQnOTy.js.map → index-O4mn_OO0.js.map} +1 -1
- package/dist/assets/{index-CdHwqlmo.js → index-mYGuS183.js} +2 -2
- package/dist/assets/{index-CdHwqlmo.js.map → index-mYGuS183.js.map} +1 -1
- package/dist/assets/{index-9iMTvtYp.js → index-zursmDNN.js} +2 -2
- package/dist/assets/{index-9iMTvtYp.js.map → index-zursmDNN.js.map} +1 -1
- package/dist/assets/{main-Brs62d3-.js → main-Ddgs1h5h.js} +4 -4
- package/dist/assets/main-Ddgs1h5h.js.map +1 -0
- package/dist/assets/{protocol-detector-TSZru2q-.js → protocol-detector-UOvkmuFn.js} +2 -2
- package/dist/assets/{protocol-detector-TSZru2q-.js.map → protocol-detector-UOvkmuFn.js.map} +1 -1
- package/dist/assets/{setup-C2E5DwAO.js → setup-DcthBcbI.js} +2 -2
- package/dist/assets/{setup-C2E5DwAO.js.map → setup-DcthBcbI.js.map} +1 -1
- package/dist/assets/{sync-manager-C-mx1NcP.js → sync-manager-4de0XUYN.js} +2 -2
- package/dist/assets/{sync-manager-C-mx1NcP.js.map → sync-manager-4de0XUYN.js.map} +1 -1
- package/dist/assets/{widget-html-7qheOFv5.js → widget-html-p3dC5HGH.js} +2 -2
- package/dist/assets/{widget-html-7qheOFv5.js.map → widget-html-p3dC5HGH.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 +16 -14
- package/dist/assets/index-xijlgGv2.js +0 -2
- package/dist/assets/main-Brs62d3-.js.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{PLAYER_API as S,fetchWithRetry as $,createLogger as v}from"./index-Bgo3B90-.js";const m=v("REST");class E{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,this._maxCacheSize=100,m.info("Using REST transport")}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${S}`:(this.config.restApiUrl||`${this.config.cmsUrl}${S}`).replace(/\/+$/,"")}_isProxyMode(){var t;return typeof window<"u"&&(((t=window.electronAPI)==null?void 0:t.isElectron)||window.location.hostname==="localhost")}_cacheSet(t,e,r){if(this._etags.size>=this._maxCacheSize){const n=this._etags.keys().next().value;this._etags.delete(n),this._responseCache.delete(n)}this._etags.set(t,e),this._responseCache.set(t,r)}async _authenticate(){const t=`${this.getRestBaseUrl()}/auth`;m.debug("Authenticating...");const e=await $(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,m.info(`Authenticated as display ${this._displayId}`)}getToken(){return this._token}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,e={},r=!1){const n=await this._getToken(),o=new URL(`${this.getRestBaseUrl()}${t}`);for(const[d,y]of Object.entries(e))o.searchParams.set(d,String(y));const a=t,i={Authorization:`Bearer ${n}`},c=this._etags.get(a);c&&(i["If-None-Match"]=c),m.debug(`GET ${t}`,e);const s=await $(o.toString(),{method:"GET",headers:i},this.retryOptions);if(s.status===401){if(r)throw new Error(`REST GET ${t} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restGet(t,e,!0)}if(s.status===304){const d=this._responseCache.get(a);if(d)return m.debug(`${t} → 304 (using cache)`),d}if(!s.ok){const d=await s.text().catch(()=>"");throw new Error(`REST GET ${t} failed: ${s.status} ${s.statusText} ${d}`)}const u=s.headers.get("Content-Type")||"";let l;u.includes("application/json")?l=await s.json():l=await s.text();const g=s.headers.get("ETag");return g&&this._cacheSet(a,g,l),l}async restSend(t,e,r={},n=!1){const o=await this._getToken(),a=new URL(`${this.getRestBaseUrl()}${e}`);m.debug(`${t} ${e}`);const i=await $(a.toString(),{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(r)},this.retryOptions);if(i.status===401){if(n)throw new Error(`REST ${t} ${e} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restSend(t,e,r,!0)}if(!i.ok){const s=await i.text().catch(()=>"");throw new Error(`REST ${t} ${e} failed: ${i.status} ${i.statusText} ${s}`)}return(i.headers.get("Content-Type")||"").includes("application/json")?await i.json():await i.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||400,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,o=r.message||e.message||"";if(n!=="READY")return{code:n,message:o,settings:null};const a={};let i=[],c=[];for(const[d,y]of Object.entries(e))if(!(d==="@attributes"||d==="file")){if(d==="commands"){Array.isArray(y)&&(c=y.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(d==="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[d]=typeof y=="object"?JSON.stringify(y):String(y)}const s=r.checkRf||"",u=r.checkSchedule||"",l={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},g=e.syncConfig||(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:o,settings:a,tags:i,commands:c,displayAttrs:l,checkRf:s,checkSchedule:u,syncConfig:g}}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 m.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),o=(n==null?void 0:n.success)===!0;return m.info(`SubmitStats result: ${o}`),o}catch(r){throw m.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(/\/+$/,"")}${S}/health`,i=(e==null?void 0:e.timeoutMs)||3e3,c={method:"GET"};typeof AbortSignal<"u"&&AbortSignal.timeout&&(c.signal=AbortSignal.timeout(i));const s=await $(a,c,e||{maxRetries:0});if(!s.ok)return!1;const u=await s.json();return u.version===2&&u.status==="ok"}catch{return!1}}}function C(A){const t=[];for(const e of A.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 R(A){const e=new DOMParser().parseFromString(A,"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(u=>u.tagName==="dependants");for(const u of s)if(u.parentElement===n)for(const l of u.querySelectorAll("file"))l.textContent&&r.dependants.push(l.textContent)}const o=e.querySelector("default");if(o){r.default=o.getAttribute("file");const s=o.querySelectorAll("dependants > file");s.length>0&&(r.defaultDependants=[...s].map(u=>u.textContent))}for(const s of e.querySelectorAll("campaign")){const u={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:C(s),layouts:[]};for(const l of s.querySelectorAll("layout")){const g=l.getAttribute("file"),d=l.querySelectorAll("dependants > file");u.layouts.push({id:String(g),file:g,fromdt:l.getAttribute("fromdt")||u.fromdt,todt:l.getAttribute("todt")||u.todt,scheduleid:u.scheduleid,priority:u.priority,campaignId:u.id,maxPlaysPerHour:parseInt(l.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:l.getAttribute("isGeoAware")==="1",geoLocation:l.getAttribute("geoLocation")||"",syncEvent:l.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(l.getAttribute("shareOfVoice")||"0"),duration:parseInt(l.getAttribute("duration")||"0"),cyclePlayback:l.getAttribute("cyclePlayback")==="1",groupKey:l.getAttribute("groupKey")||null,playCount:parseInt(l.getAttribute("playCount")||"0"),dependants:d.length>0?[...d].map(y=>y.textContent):[],criteria:C(l)})}r.campaigns.push(u)}for(const s of e.querySelectorAll("schedule > layout")){const u=s.getAttribute("file"),l=s.querySelectorAll("dependants > file");r.layouts.push({id:String(u),file:u,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:l.length>0?[...l].map(g=>g.textContent):[],criteria:C(s)})}const a=e.querySelector("overlays");if(a)for(const s of a.querySelectorAll("overlay")){const u=s.getAttribute("file");r.overlays.push({id:String(u),duration:parseInt(s.getAttribute("duration")||"60"),file:u,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:C(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 c=e.querySelector("dataConnectors");if(c)for(const s of c.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 w=v("XMDS");class K{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,o])=>{const a=String(o).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");return`<${n} xsi:type="xsd:string">${a}</${n}>`}).join(`
|
|
1
|
+
import{PLAYER_API as S,fetchWithRetry as $,createLogger as v}from"./index-BmnGgxhy.js";const m=v("REST");class E{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,this._maxCacheSize=100,m.info("Using REST transport")}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${S}`:(this.config.restApiUrl||`${this.config.cmsUrl}${S}`).replace(/\/+$/,"")}_isProxyMode(){var t;return typeof window<"u"&&(((t=window.electronAPI)==null?void 0:t.isElectron)||window.location.hostname==="localhost")}_cacheSet(t,e,r){if(this._etags.size>=this._maxCacheSize){const n=this._etags.keys().next().value;this._etags.delete(n),this._responseCache.delete(n)}this._etags.set(t,e),this._responseCache.set(t,r)}async _authenticate(){const t=`${this.getRestBaseUrl()}/auth`;m.debug("Authenticating...");const e=await $(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,m.info(`Authenticated as display ${this._displayId}`)}getToken(){return this._token}async _getToken(){return(!this._token||Date.now()>=this._tokenExpiresAt)&&await this._authenticate(),this._token}async restGet(t,e={},r=!1){const n=await this._getToken(),o=new URL(`${this.getRestBaseUrl()}${t}`);for(const[d,y]of Object.entries(e))o.searchParams.set(d,String(y));const a=t,i={Authorization:`Bearer ${n}`},c=this._etags.get(a);c&&(i["If-None-Match"]=c),m.debug(`GET ${t}`,e);const s=await $(o.toString(),{method:"GET",headers:i},this.retryOptions);if(s.status===401){if(r)throw new Error(`REST GET ${t} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restGet(t,e,!0)}if(s.status===304){const d=this._responseCache.get(a);if(d)return m.debug(`${t} → 304 (using cache)`),d}if(!s.ok){const d=await s.text().catch(()=>"");throw new Error(`REST GET ${t} failed: ${s.status} ${s.statusText} ${d}`)}const u=s.headers.get("Content-Type")||"";let l;u.includes("application/json")?l=await s.json():l=await s.text();const g=s.headers.get("ETag");return g&&this._cacheSet(a,g,l),l}async restSend(t,e,r={},n=!1){const o=await this._getToken(),a=new URL(`${this.getRestBaseUrl()}${e}`);m.debug(`${t} ${e}`);const i=await $(a.toString(),{method:t,headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify(r)},this.retryOptions);if(i.status===401){if(n)throw new Error(`REST ${t} ${e} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restSend(t,e,r,!0)}if(!i.ok){const s=await i.text().catch(()=>"");throw new Error(`REST ${t} ${e} failed: ${i.status} ${i.statusText} ${s}`)}return(i.headers.get("Content-Type")||"").includes("application/json")?await i.json():await i.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||400,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,o=r.message||e.message||"";if(n!=="READY")return{code:n,message:o,settings:null};const a={};let i=[],c=[];for(const[d,y]of Object.entries(e))if(!(d==="@attributes"||d==="file")){if(d==="commands"){Array.isArray(y)&&(c=y.map(p=>({commandCode:p.code||p.commandCode||"",commandString:p.commandString||""})));continue}if(d==="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[d]=typeof y=="object"?JSON.stringify(y):String(y)}const s=r.checkRf||"",u=r.checkSchedule||"",l={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},g=e.syncConfig||(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:o,settings:a,tags:i,commands:c,displayAttrs:l,checkRf:s,checkSchedule:u,syncConfig:g}}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 m.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),o=(n==null?void 0:n.success)===!0;return m.info(`SubmitStats result: ${o}`),o}catch(r){throw m.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(/\/+$/,"")}${S}/health`,i=(e==null?void 0:e.timeoutMs)||3e3,c={method:"GET"};typeof AbortSignal<"u"&&AbortSignal.timeout&&(c.signal=AbortSignal.timeout(i));const s=await $(a,c,e||{maxRetries:0});if(!s.ok)return!1;const u=await s.json();return u.version===2&&u.status==="ok"}catch{return!1}}}function C(A){const t=[];for(const e of A.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 R(A){const e=new DOMParser().parseFromString(A,"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(u=>u.tagName==="dependants");for(const u of s)if(u.parentElement===n)for(const l of u.querySelectorAll("file"))l.textContent&&r.dependants.push(l.textContent)}const o=e.querySelector("default");if(o){r.default=o.getAttribute("file");const s=o.querySelectorAll("dependants > file");s.length>0&&(r.defaultDependants=[...s].map(u=>u.textContent))}for(const s of e.querySelectorAll("campaign")){const u={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:C(s),layouts:[]};for(const l of s.querySelectorAll("layout")){const g=l.getAttribute("file"),d=l.querySelectorAll("dependants > file");u.layouts.push({id:String(g),file:g,fromdt:l.getAttribute("fromdt")||u.fromdt,todt:l.getAttribute("todt")||u.todt,scheduleid:u.scheduleid,priority:u.priority,campaignId:u.id,maxPlaysPerHour:parseInt(l.getAttribute("maxPlaysPerHour")||"0"),isGeoAware:l.getAttribute("isGeoAware")==="1",geoLocation:l.getAttribute("geoLocation")||"",syncEvent:l.getAttribute("syncEvent")==="1",shareOfVoice:parseInt(l.getAttribute("shareOfVoice")||"0"),duration:parseInt(l.getAttribute("duration")||"0"),cyclePlayback:l.getAttribute("cyclePlayback")==="1",groupKey:l.getAttribute("groupKey")||null,playCount:parseInt(l.getAttribute("playCount")||"0"),dependants:d.length>0?[...d].map(y=>y.textContent):[],criteria:C(l)})}r.campaigns.push(u)}for(const s of e.querySelectorAll("schedule > layout")){const u=s.getAttribute("file"),l=s.querySelectorAll("dependants > file");r.layouts.push({id:String(u),file:u,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:l.length>0?[...l].map(g=>g.textContent):[],criteria:C(s)})}const a=e.querySelector("overlays");if(a)for(const s of a.querySelectorAll("overlay")){const u=s.getAttribute("file");r.overlays.push({id:String(u),duration:parseInt(s.getAttribute("duration")||"60"),file:u,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:C(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 c=e.querySelector("dataConnectors");if(c)for(const s of c.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 w=v("XMDS");class K{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,o])=>{const a=String(o).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 S,fetchWithRetry as $,createLogger as v}from"./index-Bgo3B9
|
|
|
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}`,o=this.buildEnvelope(t,e);w.debug(`${t}`,e),w.debug(`URL: ${n}`);const a=await $(n,{method:"POST",headers:{"Content-Type":"text/xml; charset=utf-8"},body:o},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,u;const n=new DOMParser().parseFromString(t,"text/xml");let o=n.querySelector("Fault");if(o||(o=Array.from(n.querySelectorAll("*")).find(l=>l.localName==="Fault"||l.tagName.endsWith(":Fault"))),o){const l=((s=o.querySelector("faultstring"))==null?void 0:s.textContent)||((u=Array.from(o.querySelectorAll("*")).find(g=>g.localName==="faultstring"))==null?void 0:u.textContent)||"Unknown SOAP fault";throw new Error(`SOAP Fault: ${l}`)}const a=`${e}Response`;let i=n.querySelector(a);if(i||(i=Array.from(n.querySelectorAll("*")).find(l=>l.localName===a||l.tagName.endsWith(":"+a))),!i)throw new Error(`No ${a} element in SOAP response`);const c=i.firstElementChild;return c?c.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||"400",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 o=n.getAttribute("code"),a=n.getAttribute("message");if(o!=="READY")return{code:o,message:a,settings:null};const i={},c=[],s=[];for(const p of n.children){const h=p.tagName.toLowerCase();if(h!=="file"){if(h==="commands"){for(const b of p.querySelectorAll("command"))s.push({commandCode:b.getAttribute("code")||b.getAttribute("commandCode")||"",commandString:b.getAttribute("commandString")||""});continue}if(h==="tags"){for(const b of p.querySelectorAll("tag"))b.textContent&&c.push(b.textContent);continue}i[p.tagName]=p.textContent}}const u=n.getAttribute("checkRf")||"",l=n.getAttribute("checkSchedule")||"",g={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},d=i.syncGroup||null,y=d?{syncGroup:d,syncPublisherPort:parseInt(i.syncPublisherPort||"9590",10),syncSwitchDelay:parseInt(i.syncSwitchDelay||"750",10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||"100",10),isLead:d==="lead"}:null;return{code:o,message:a,settings:i,tags:c,commands:s,displayAttrs:g,checkRf:u,checkSchedule:l,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")){const c={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")};if(c.path&&c.path.includes("xmds.php")){c.cmsDownloadUrl=c.path;const s=c.fileType;s==="L"||c.type==="layout"?c.path=`${S}/layouts/${c.id}`:s==="P"?c.path=`${S}/dependencies/${c.saveAs||c.id}`:c.path=`${S}/media/file/${c.saveAs||c.id}`}n.push(c)}const o=[],a=r.querySelector("purge");if(a)for(const i of a.querySelectorAll("item"))o.push({id:i.getAttribute("id"),storedAs:i.getAttribute("storedAs")});return{files:n,purge:o}}async schedule(){const t=await this.call("Schedule",{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return R(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 w.info(`BlackListed ${e}/${t}: ${r}`),n==="true"}catch(n){return w.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 w.info(`SubmitStats result: ${n}`),n}catch(r){throw w.error("SubmitStats failed:",r),r}}}const I=["registerDisplay","requiredFiles","schedule","getResource","notifyStatus","mediaInventory","blackList","submitLog","submitScreenShot","submitStats","reportFaults","getWeather"];function x(A,t="client"){for(const e of I)if(typeof A[e]!="function")throw new Error(`${t} missing CmsClient method: ${e}()`)}const f=v("Protocol"),P=3e3;class _{constructor(t,e,r,n={}){this.cmsUrl=t,this.RestClient=e,this.XmdsClient=r,this.probeTimeoutMs=n.probeTimeoutMs||P,this.protocol=null,this.lastProbeTime=0}async probe(){const t=await this.RestClient.isAvailable(this.cmsUrl,{maxRetries:0,timeoutMs:this.probeTimeoutMs});return this.lastProbeTime=Date.now(),t}async detect(t,e){if(e==="rest"){this.protocol="rest",f.info("Using REST transport (forced)");const o=new this.RestClient(t);return x(o,"RestClient"),{client:o,protocol:"rest"}}if(e==="xmds"){this.protocol="xmds",f.info("Using XMDS/SOAP transport (forced)");const o=new this.XmdsClient(t);return x(o,"XmdsClient"),{client:o,protocol:"xmds"}}f.info("Probing CMS for REST API availability...");let r=!1;try{r=await this.probe()}catch(o){f.warn("REST probe failed:",(o==null?void 0:o.message)||o)}if(r){this.protocol="rest",f.info("REST transport detected — using PlayerRestApi");const o=new this.RestClient(t);return x(o,"RestClient"),{client:o,protocol:"rest"}}this.protocol="xmds",f.info("REST unavailable — using XMDS/SOAP transport");const n=new this.XmdsClient(t);return x(n,"XmdsClient"),{client:n,protocol:"xmds"}}async reprobe(t){const e=this.protocol;f.info("Re-probing CMS protocol...");let r=!1;try{r=await this.probe()}catch(a){f.warn("Re-probe failed:",(a==null?void 0:a.message)||a)}const n=r?"rest":"xmds";if(n!==e){f.info(`Protocol changed: ${e} → ${n}`),this.protocol=n;const a=r?new this.RestClient(t):new this.XmdsClient(t);return x(a,r?"RestClient":"XmdsClient"),{client:a,protocol:n,changed:!0}}return f.info(`Protocol unchanged: ${n}`),{client:null,protocol:n,changed:!1}}getProtocol(){return this.protocol}}export{I as C,_ as P,E as R,K as X,x as a,R as p};
|
|
16
|
-
//# sourceMappingURL=protocol-detector-
|
|
16
|
+
//# sourceMappingURL=protocol-detector-UOvkmuFn.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol-detector-TSZru2q-.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js","../../../xmds/src/cms-client.js","../../../xmds/src/protocol-detector.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\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 (capped at _maxCacheSize entries)\n this._etags = new Map();\n this._responseCache = new Map();\n this._maxCacheSize = 100;\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 /**\n * Store a response in the ETag cache, evicting the oldest entry if full.\n */\n _cacheSet(path, etag, data) {\n if (this._etags.size >= this._maxCacheSize) {\n const oldest = this._etags.keys().next().value;\n this._etags.delete(oldest);\n this._responseCache.delete(oldest);\n }\n this._etags.set(path, etag);\n this._responseCache.set(path, data);\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 current token synchronously (may be null or expired).\n * @returns {string|null}\n */\n getToken() {\n return this._token;\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 = {}, _retrying = false) {\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 if (_retrying) {\n throw new Error(`REST GET ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restGet(path, queryParams, true);\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 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 const etag = response.headers.get('ETag');\n if (etag) {\n this._cacheSet(cacheKey, etag, data);\n }\n\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}, _retrying = false) {\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 if (_retrying) {\n throw new Error(`REST ${method} ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restSend(method, path, body, true);\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 || 400,\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 // Prefer structured syncConfig from REST module; fall back to flat SOAP fields\n const syncConfig = display.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 ${PLAYER_API}/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 timeoutMs = retryOptions?.timeoutMs || 3000;\n const fetchOptions = { method: 'GET' };\n // Apply timeout via AbortSignal (short timeout avoids delaying startup)\n if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) {\n fetchOptions.signal = AbortSignal.timeout(timeoutMs);\n }\n const response = await fetchWithRetry(url, fetchOptions, 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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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, PLAYER_API } 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 || '400',\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 const file = {\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 // Rewrite XMDS download URLs to local proxy cache-through paths.\n // Store the original CMS URL so the proxy can fetch on cache miss.\n if (file.path && file.path.includes('xmds.php')) {\n file.cmsDownloadUrl = file.path;\n const xmdsType = file.fileType; // L=layout, M=media, P=resource\n if (xmdsType === 'L' || file.type === 'layout') {\n file.path = `${PLAYER_API}/layouts/${file.id}`;\n } else if (xmdsType === 'P') {\n file.path = `${PLAYER_API}/dependencies/${file.saveAs || file.id}`;\n } else {\n file.path = `${PLAYER_API}/media/file/${file.saveAs || file.id}`;\n }\n }\n\n files.push(file);\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CmsClient interface definition — the unified contract for CMS communication.\n *\n * Both RestClient and XmdsClient implement this interface identically.\n * PlayerCore calls these methods without knowing which transport is underneath.\n * ProtocolDetector selects the implementation at startup.\n *\n * This file provides:\n * 1. JSDoc type definitions for the interface\n * 2. CMS_CLIENT_METHODS — canonical list of required methods\n * 3. assertCmsClient() — runtime conformance check\n *\n * @example\n * import { ProtocolDetector, RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(cmsUrl, RestClient, XmdsClient);\n * const { client } = await detector.detect(config);\n * // client implements CmsClient — PlayerCore doesn't care which one\n */\n\n/**\n * @typedef {Object} RegisterDisplayResult\n * @property {string} code - 'READY' or error code\n * @property {string} message - Human-readable status message\n * @property {Object|null} settings - Display settings (null if not READY)\n * @property {string[]} tags - Display tags\n * @property {Array<{commandCode: string, commandString: string}>} commands - Scheduled commands\n * @property {Object} displayAttrs - Server-provided attributes (date, timezone, status)\n * @property {string} checkRf - CRC checksum for RequiredFiles (skip if unchanged)\n * @property {string} checkSchedule - CRC checksum for Schedule (skip if unchanged)\n * @property {Object|null} syncConfig - Multi-display sync configuration\n */\n\n/**\n * @typedef {Object} RequiredFilesResult\n * @property {Array<{type: string, id: string, size: number, md5: string, download: string, path: string, saveAs: string|null}>} files\n * @property {Array<{id: string, storedAs: string}>} purge - Files to delete\n */\n\n/**\n * @typedef {Object} CmsClient\n * @property {() => Promise<RegisterDisplayResult>} registerDisplay\n * @property {() => Promise<RequiredFilesResult>} requiredFiles\n * @property {() => Promise<Object>} schedule\n * @property {(layoutId: string, regionId: string, mediaId: string) => Promise<string>} getResource\n * @property {(status: Object) => Promise<any>} notifyStatus\n * @property {(inventoryXml: string|Array) => Promise<any>} mediaInventory\n * @property {(mediaId: string, type: string, reason: string) => Promise<boolean>} blackList\n * @property {(logXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitLog\n * @property {(base64Image: string) => Promise<boolean>} submitScreenShot\n * @property {(statsXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitStats\n * @property {(faultJson: string|Object) => Promise<boolean>} reportFaults\n * @property {() => Promise<Object>} getWeather\n */\n\n/**\n * Canonical list of methods that every CmsClient implementation must provide.\n * Used for runtime conformance checks and test assertions.\n */\nexport const CMS_CLIENT_METHODS = [\n 'registerDisplay',\n 'requiredFiles',\n 'schedule',\n 'getResource',\n 'notifyStatus',\n 'mediaInventory',\n 'blackList',\n 'submitLog',\n 'submitScreenShot',\n 'submitStats',\n 'reportFaults',\n 'getWeather',\n];\n\n/**\n * Verify that an object implements the CmsClient interface.\n * Throws if any required method is missing or not a function.\n *\n * @param {any} client - Object to check\n * @param {string} [label] - Label for error messages (e.g. 'RestClient')\n * @throws {Error} If the client doesn't conform\n */\nexport function assertCmsClient(client, label = 'client') {\n for (const method of CMS_CLIENT_METHODS) {\n if (typeof client[method] !== 'function') {\n throw new Error(`${label} missing CmsClient method: ${method}()`);\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS Protocol Auto-Detector\n *\n * Probes the CMS to determine which communication protocol to use:\n * - REST/PlayerRestApi — optimized JSON protocol (custom CMS image)\n * - SOAP/XMDS — universal XML protocol (any vanilla Xibo CMS)\n *\n * Detection logic:\n * 1. GET {cmsUrl}${PLAYER_API}/health with a 3-second timeout\n * 2. If 200 + valid JSON → REST\n * 3. If 404/error/timeout → SOAP (fallback)\n *\n * The detected protocol is cached and can be re-probed on connection errors.\n *\n * @example\n * import { ProtocolDetector } from '@xiboplayer/xmds';\n * import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(config.cmsUrl, RestClient, XmdsClient);\n * const xmds = await detector.detect(config);\n * // xmds is either a RestClient or XmdsClient instance\n *\n * // On connection errors, re-probe:\n * const newXmds = await detector.reprobe(config);\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { assertCmsClient } from './cms-client.js';\n\nconst log = createLogger('Protocol');\n\n/** Default probe timeout in milliseconds */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport class ProtocolDetector {\n /**\n * @param {string} cmsUrl - CMS base URL\n * @param {typeof import('./rest-client.js').RestClient} RestClientClass - RestClient constructor\n * @param {typeof import('./xmds-client.js').XmdsClient} XmdsClientClass - XmdsClient constructor\n * @param {Object} [options]\n * @param {number} [options.probeTimeoutMs=3000] - Timeout for health probe\n */\n constructor(cmsUrl, RestClientClass, XmdsClientClass, options = {}) {\n this.cmsUrl = cmsUrl;\n this.RestClient = RestClientClass;\n this.XmdsClient = XmdsClientClass;\n this.probeTimeoutMs = options.probeTimeoutMs || PROBE_TIMEOUT_MS;\n\n /** @type {'rest'|'xmds'|null} Detected protocol (null = not yet probed) */\n this.protocol = null;\n\n /** @type {number} Timestamp of last successful probe */\n this.lastProbeTime = 0;\n }\n\n /**\n * Probe the CMS health endpoint to determine protocol availability.\n * @returns {Promise<boolean>} true if REST/PlayerRestApi is available\n */\n async probe() {\n const available = await this.RestClient.isAvailable(this.cmsUrl, {\n maxRetries: 0,\n timeoutMs: this.probeTimeoutMs,\n });\n this.lastProbeTime = Date.now();\n return available;\n }\n\n /**\n * Detect the best protocol and create the appropriate client.\n * On first call, probes the CMS. On subsequent calls, returns the cached\n * protocol unless reprobe() is called.\n *\n * @param {Object} config - Player configuration (passed to client constructor)\n * @param {string} [forceProtocol] - 'rest'|'xmds' to skip detection\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds'}>}\n */\n async detect(config, forceProtocol) {\n if (forceProtocol === 'rest') {\n this.protocol = 'rest';\n log.info('Using REST transport (forced)');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n if (forceProtocol === 'xmds') {\n this.protocol = 'xmds';\n log.info('Using XMDS/SOAP transport (forced)');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n // Auto-detect\n log.info('Probing CMS for REST API availability...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('REST probe failed:', e?.message || e);\n }\n\n if (isRest) {\n this.protocol = 'rest';\n log.info('REST transport detected — using PlayerRestApi');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n this.protocol = 'xmds';\n log.info('REST unavailable — using XMDS/SOAP transport');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n /**\n * Re-probe the CMS and potentially switch protocols.\n * Called on connection errors to check if the CMS was upgraded/downgraded.\n *\n * @param {Object} config - Player configuration\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds', changed: boolean}>}\n */\n async reprobe(config) {\n const previousProtocol = this.protocol;\n\n log.info('Re-probing CMS protocol...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('Re-probe failed:', e?.message || e);\n }\n\n const newProtocol = isRest ? 'rest' : 'xmds';\n const changed = newProtocol !== previousProtocol;\n\n if (changed) {\n log.info(`Protocol changed: ${previousProtocol} → ${newProtocol}`);\n this.protocol = newProtocol;\n const client = isRest ? new this.RestClient(config) : new this.XmdsClient(config);\n assertCmsClient(client, isRest ? 'RestClient' : 'XmdsClient');\n return { client, protocol: newProtocol, changed: true };\n }\n\n log.info(`Protocol unchanged: ${newProtocol}`);\n return { client: null, protocol: newProtocol, changed: false };\n }\n\n /**\n * Get the currently detected protocol.\n * @returns {'rest'|'xmds'|null}\n */\n getProtocol() {\n return this.protocol;\n }\n}\n"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","path","etag","data","oldest","url","response","fetchWithRetry","errorBody","queryParams","_retrying","token","key","value","cacheKey","headers","cachedEtag","cached","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","timeoutMs","fetchOptions","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","file","xmdsType","purgeItems","purgeEl","itemEl","CMS_CLIENT_METHODS","assertCmsClient","client","label","PROBE_TIMEOUT_MS","ProtocolDetector","RestClientClass","XmdsClientClass","options","available","forceProtocol","isRest","e","previousProtocol","newProtocol"],"mappings":"uFAkBA,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,IAC1B,KAAK,cAAgB,IAErBH,EAAI,KAAK,sBAAsB,CACjC,CAUA,gBAAiB,CACf,OAAI,KAAK,eACA,GAAG,OAAO,SAAS,MAAM,GAAGI,CAAU,IAElC,KAAK,OAAO,YAAc,GAAG,KAAK,OAAO,MAAM,GAAGA,CAAU,IAC7D,QAAQ,OAAQ,EAAE,CAChC,CAKA,cAAe,OACb,OAAO,OAAO,OAAW,QACtBC,EAAA,OAAO,cAAP,YAAAA,EAAoB,aACpB,OAAO,SAAS,WAAa,YAClC,CAKA,UAAUC,EAAMC,EAAMC,EAAM,CAC1B,GAAI,KAAK,OAAO,MAAQ,KAAK,cAAe,CAC1C,MAAMC,EAAS,KAAK,OAAO,KAAI,EAAG,KAAI,EAAG,MACzC,KAAK,OAAO,OAAOA,CAAM,EACzB,KAAK,eAAe,OAAOA,CAAM,CACnC,CACA,KAAK,OAAO,IAAIH,EAAMC,CAAI,E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D,MAAMmH,EAAS,IAAI,KAAK,WAAWhH,CAAM,EACzC,OAAA+G,EAAgBC,EAAQ,YAAY,EAC7B,CAAE,OAAAA,EAAQ,SAAU,MAAM,CACnC,CAEA,KAAK,SAAW,OAChBnH,EAAI,KAAK,8CAA8C,EACvD,MAAMmH,EAAS,IAAI,KAAK,WAAWhH,CAAM,EACzC,OAAA+G,EAAgBC,EAAQ,YAAY,EAC7B,CAAE,OAAAA,EAAQ,SAAU,MAAM,CACnC,CASA,MAAM,QAAQhH,EAAQ,CACpB,MAAM2H,EAAmB,KAAK,SAE9B9H,EAAI,KAAK,4BAA4B,EACrC,IAAI4H,EAAS,GACb,GAAI,CACFA,EAAS,MAAM,KAAK,MAAK,CAC3B,OAASC,EAAG,CACV7H,EAAI,KAAK,oBAAoB6H,GAAA,YAAAA,EAAG,UAAWA,CAAC,CAC9C,CAEA,MAAME,EAAcH,EAAS,OAAS,OAGtC,GAFgBG,IAAgBD,EAEnB,CACX9H,EAAI,KAAK,qBAAqB8H,CAAgB,MAAMC,CAAW,EAAE,EACjE,KAAK,SAAWA,EAChB,MAAMZ,EAASS,EAAS,IAAI,KAAK,WAAWzH,CAAM,EAAI,IAAI,KAAK,WAAWA,CAAM,EAChF,OAAA+G,EAAgBC,EAAQS,EAAS,aAAe,YAAY,EACrD,CAAE,OAAAT,EAAQ,SAAUY,EAAa,QAAS,EAAI,CACvD,CAEA,OAAA/H,EAAI,KAAK,uBAAuB+H,CAAW,EAAE,EACtC,CAAE,OAAQ,KAAM,SAAUA,EAAa,QAAS,EAAK,CAC9D,CAMA,aAAc,CACZ,OAAO,KAAK,QACd,CACF"}
|
|
1
|
+
{"version":3,"file":"protocol-detector-UOvkmuFn.js","sources":["../../../xmds/src/rest-client.js","../../../xmds/src/schedule-parser.js","../../../xmds/src/xmds-client.js","../../../xmds/src/cms-client.js","../../../xmds/src/protocol-detector.js"],"sourcesContent":["// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\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 (capped at _maxCacheSize entries)\n this._etags = new Map();\n this._responseCache = new Map();\n this._maxCacheSize = 100;\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 /**\n * Store a response in the ETag cache, evicting the oldest entry if full.\n */\n _cacheSet(path, etag, data) {\n if (this._etags.size >= this._maxCacheSize) {\n const oldest = this._etags.keys().next().value;\n this._etags.delete(oldest);\n this._responseCache.delete(oldest);\n }\n this._etags.set(path, etag);\n this._responseCache.set(path, data);\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 current token synchronously (may be null or expired).\n * @returns {string|null}\n */\n getToken() {\n return this._token;\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 = {}, _retrying = false) {\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 if (_retrying) {\n throw new Error(`REST GET ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restGet(path, queryParams, true);\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 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 const etag = response.headers.get('ETag');\n if (etag) {\n this._cacheSet(cacheKey, etag, data);\n }\n\n return data;\n }\n\n /**\n * Make an authenticated POST/PUT request with JSON body.\n */\n async restSend(method, path, body = {}, _retrying = false) {\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 if (_retrying) {\n throw new Error(`REST ${method} ${path} failed: 401 Unauthorized (after re-auth)`);\n }\n this._token = null;\n return this.restSend(method, path, body, true);\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 || 400,\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 // Prefer structured syncConfig from REST module; fall back to flat SOAP fields\n const syncConfig = display.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 ${PLAYER_API}/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 timeoutMs = retryOptions?.timeoutMs || 3000;\n const fetchOptions = { method: 'GET' };\n // Apply timeout via AbortSignal (short timeout avoids delaying startup)\n if (typeof AbortSignal !== 'undefined' && AbortSignal.timeout) {\n fetchOptions.signal = AbortSignal.timeout(timeoutMs);\n }\n const response = await fetchWithRetry(url, fetchOptions, 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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\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, PLAYER_API } 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 || '400',\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 const file = {\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 // Rewrite XMDS download URLs to local proxy cache-through paths.\n // Store the original CMS URL so the proxy can fetch on cache miss.\n if (file.path && file.path.includes('xmds.php')) {\n file.cmsDownloadUrl = file.path;\n const xmdsType = file.fileType; // L=layout, M=media, P=resource\n if (xmdsType === 'L' || file.type === 'layout') {\n file.path = `${PLAYER_API}/layouts/${file.id}`;\n } else if (xmdsType === 'P') {\n file.path = `${PLAYER_API}/dependencies/${file.saveAs || file.id}`;\n } else {\n file.path = `${PLAYER_API}/media/file/${file.saveAs || file.id}`;\n }\n }\n\n files.push(file);\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","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CmsClient interface definition — the unified contract for CMS communication.\n *\n * Both RestClient and XmdsClient implement this interface identically.\n * PlayerCore calls these methods without knowing which transport is underneath.\n * ProtocolDetector selects the implementation at startup.\n *\n * This file provides:\n * 1. JSDoc type definitions for the interface\n * 2. CMS_CLIENT_METHODS — canonical list of required methods\n * 3. assertCmsClient() — runtime conformance check\n *\n * @example\n * import { ProtocolDetector, RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(cmsUrl, RestClient, XmdsClient);\n * const { client } = await detector.detect(config);\n * // client implements CmsClient — PlayerCore doesn't care which one\n */\n\n/**\n * @typedef {Object} RegisterDisplayResult\n * @property {string} code - 'READY' or error code\n * @property {string} message - Human-readable status message\n * @property {Object|null} settings - Display settings (null if not READY)\n * @property {string[]} tags - Display tags\n * @property {Array<{commandCode: string, commandString: string}>} commands - Scheduled commands\n * @property {Object} displayAttrs - Server-provided attributes (date, timezone, status)\n * @property {string} checkRf - CRC checksum for RequiredFiles (skip if unchanged)\n * @property {string} checkSchedule - CRC checksum for Schedule (skip if unchanged)\n * @property {Object|null} syncConfig - Multi-display sync configuration\n */\n\n/**\n * @typedef {Object} RequiredFilesResult\n * @property {Array<{type: string, id: string, size: number, md5: string, download: string, path: string, saveAs: string|null}>} files\n * @property {Array<{id: string, storedAs: string}>} purge - Files to delete\n */\n\n/**\n * @typedef {Object} CmsClient\n * @property {() => Promise<RegisterDisplayResult>} registerDisplay\n * @property {() => Promise<RequiredFilesResult>} requiredFiles\n * @property {() => Promise<Object>} schedule\n * @property {(layoutId: string, regionId: string, mediaId: string) => Promise<string>} getResource\n * @property {(status: Object) => Promise<any>} notifyStatus\n * @property {(inventoryXml: string|Array) => Promise<any>} mediaInventory\n * @property {(mediaId: string, type: string, reason: string) => Promise<boolean>} blackList\n * @property {(logXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitLog\n * @property {(base64Image: string) => Promise<boolean>} submitScreenShot\n * @property {(statsXml: string|Array, hardwareKeyOverride?: string) => Promise<boolean>} submitStats\n * @property {(faultJson: string|Object) => Promise<boolean>} reportFaults\n * @property {() => Promise<Object>} getWeather\n */\n\n/**\n * Canonical list of methods that every CmsClient implementation must provide.\n * Used for runtime conformance checks and test assertions.\n */\nexport const CMS_CLIENT_METHODS = [\n 'registerDisplay',\n 'requiredFiles',\n 'schedule',\n 'getResource',\n 'notifyStatus',\n 'mediaInventory',\n 'blackList',\n 'submitLog',\n 'submitScreenShot',\n 'submitStats',\n 'reportFaults',\n 'getWeather',\n];\n\n/**\n * Verify that an object implements the CmsClient interface.\n * Throws if any required method is missing or not a function.\n *\n * @param {any} client - Object to check\n * @param {string} [label] - Label for error messages (e.g. 'RestClient')\n * @throws {Error} If the client doesn't conform\n */\nexport function assertCmsClient(client, label = 'client') {\n for (const method of CMS_CLIENT_METHODS) {\n if (typeof client[method] !== 'function') {\n throw new Error(`${label} missing CmsClient method: ${method}()`);\n }\n }\n}\n","// SPDX-License-Identifier: AGPL-3.0-or-later\n// Copyright (c) 2024-2026 Pau Aliagas <linuxnow@gmail.com>\n/**\n * CMS Protocol Auto-Detector\n *\n * Probes the CMS to determine which communication protocol to use:\n * - REST/PlayerRestApi — optimized JSON protocol (custom CMS image)\n * - SOAP/XMDS — universal XML protocol (any vanilla Xibo CMS)\n *\n * Detection logic:\n * 1. GET {cmsUrl}${PLAYER_API}/health with a 3-second timeout\n * 2. If 200 + valid JSON → REST\n * 3. If 404/error/timeout → SOAP (fallback)\n *\n * The detected protocol is cached and can be re-probed on connection errors.\n *\n * @example\n * import { ProtocolDetector } from '@xiboplayer/xmds';\n * import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n *\n * const detector = new ProtocolDetector(config.cmsUrl, RestClient, XmdsClient);\n * const xmds = await detector.detect(config);\n * // xmds is either a RestClient or XmdsClient instance\n *\n * // On connection errors, re-probe:\n * const newXmds = await detector.reprobe(config);\n */\n\nimport { createLogger } from '@xiboplayer/utils';\nimport { assertCmsClient } from './cms-client.js';\n\nconst log = createLogger('Protocol');\n\n/** Default probe timeout in milliseconds */\nconst PROBE_TIMEOUT_MS = 3000;\n\nexport class ProtocolDetector {\n /**\n * @param {string} cmsUrl - CMS base URL\n * @param {typeof import('./rest-client.js').RestClient} RestClientClass - RestClient constructor\n * @param {typeof import('./xmds-client.js').XmdsClient} XmdsClientClass - XmdsClient constructor\n * @param {Object} [options]\n * @param {number} [options.probeTimeoutMs=3000] - Timeout for health probe\n */\n constructor(cmsUrl, RestClientClass, XmdsClientClass, options = {}) {\n this.cmsUrl = cmsUrl;\n this.RestClient = RestClientClass;\n this.XmdsClient = XmdsClientClass;\n this.probeTimeoutMs = options.probeTimeoutMs || PROBE_TIMEOUT_MS;\n\n /** @type {'rest'|'xmds'|null} Detected protocol (null = not yet probed) */\n this.protocol = null;\n\n /** @type {number} Timestamp of last successful probe */\n this.lastProbeTime = 0;\n }\n\n /**\n * Probe the CMS health endpoint to determine protocol availability.\n * @returns {Promise<boolean>} true if REST/PlayerRestApi is available\n */\n async probe() {\n const available = await this.RestClient.isAvailable(this.cmsUrl, {\n maxRetries: 0,\n timeoutMs: this.probeTimeoutMs,\n });\n this.lastProbeTime = Date.now();\n return available;\n }\n\n /**\n * Detect the best protocol and create the appropriate client.\n * On first call, probes the CMS. On subsequent calls, returns the cached\n * protocol unless reprobe() is called.\n *\n * @param {Object} config - Player configuration (passed to client constructor)\n * @param {string} [forceProtocol] - 'rest'|'xmds' to skip detection\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds'}>}\n */\n async detect(config, forceProtocol) {\n if (forceProtocol === 'rest') {\n this.protocol = 'rest';\n log.info('Using REST transport (forced)');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n if (forceProtocol === 'xmds') {\n this.protocol = 'xmds';\n log.info('Using XMDS/SOAP transport (forced)');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n // Auto-detect\n log.info('Probing CMS for REST API availability...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('REST probe failed:', e?.message || e);\n }\n\n if (isRest) {\n this.protocol = 'rest';\n log.info('REST transport detected — using PlayerRestApi');\n const client = new this.RestClient(config);\n assertCmsClient(client, 'RestClient');\n return { client, protocol: 'rest' };\n }\n\n this.protocol = 'xmds';\n log.info('REST unavailable — using XMDS/SOAP transport');\n const client = new this.XmdsClient(config);\n assertCmsClient(client, 'XmdsClient');\n return { client, protocol: 'xmds' };\n }\n\n /**\n * Re-probe the CMS and potentially switch protocols.\n * Called on connection errors to check if the CMS was upgraded/downgraded.\n *\n * @param {Object} config - Player configuration\n * @returns {Promise<{client: any, protocol: 'rest'|'xmds', changed: boolean}>}\n */\n async reprobe(config) {\n const previousProtocol = this.protocol;\n\n log.info('Re-probing CMS protocol...');\n let isRest = false;\n try {\n isRest = await this.probe();\n } catch (e) {\n log.warn('Re-probe failed:', e?.message || e);\n }\n\n const newProtocol = isRest ? 'rest' : 'xmds';\n const changed = newProtocol !== previousProtocol;\n\n if (changed) {\n log.info(`Protocol changed: ${previousProtocol} → ${newProtocol}`);\n this.protocol = newProtocol;\n const client = isRest ? new this.RestClient(config) : new this.XmdsClient(config);\n assertCmsClient(client, isRest ? 'RestClient' : 'XmdsClient');\n return { client, protocol: newProtocol, changed: true };\n }\n\n log.info(`Protocol unchanged: ${newProtocol}`);\n return { client: null, protocol: newProtocol, changed: false };\n }\n\n /**\n * Get the currently detected protocol.\n * @returns {'rest'|'xmds'|null}\n */\n getProtocol() {\n return this.protocol;\n }\n}\n"],"names":["log","createLogger","RestClient","config","PLAYER_API","_a","path","etag","data","oldest","url","response","fetchWithRetry","errorBody","queryParams","_retrying","token","key","value","cacheKey","headers","cachedEtag","cached","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","timeoutMs","fetchOptions","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","file","xmdsType","purgeItems","purgeEl","itemEl","CMS_CLIENT_METHODS","assertCmsClient","client","label","PROBE_TIMEOUT_MS","ProtocolDetector","RestClientClass","XmdsClientClass","options","available","forceProtocol","isRest","e","previousProtocol","newProtocol"],"mappings":"uFAkBA,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,IAC1B,KAAK,cAAgB,IAErBH,EAAI,KAAK,sBAAsB,CACjC,CAUA,gBAAiB,CACf,OAAI,KAAK,eACA,GAAG,OAAO,SAAS,MAAM,GAAGI,CAAU,IAElC,KAAK,OAAO,YAAc,GAAG,KAAK,OAAO,MAAM,GAAGA,CAAU,IAC7D,QAAQ,OAAQ,EAAE,CAChC,CAKA,cAAe,OACb,OAAO,OAAO,OAAW,QACtBC,EAAA,OAAO,cAAP,YAAAA,EAAoB,aACpB,OAAO,SAAS,WAAa,YAClC,CAKA,UAAUC,EAAMC,EAAMC,EAAM,CAC1B,GAAI,KAAK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|
1
|
-
import"./modulepreload-polyfill-B5Qt9EMX.js";import{config as e}from"./index-
|
|
2
|
-
//# sourceMappingURL=setup-
|
|
1
|
+
import"./modulepreload-polyfill-B5Qt9EMX.js";import{config as e}from"./index-BmnGgxhy.js";import{R as P,X as K}from"./protocol-detector-UOvkmuFn.js";const L="0.7.2";document.getElementById("version-footer").textContent=`Xibo Player v${L}`;const T=document.getElementById("setup-form"),h=document.getElementById("error"),c=document.getElementById("submit-btn"),S=document.getElementById("phase-unlock"),I=document.getElementById("phase-setup"),b=document.getElementById("phase-waiting"),C=document.getElementById("countdown"),$=document.getElementById("waiting-display-name"),z=document.getElementById("btn-back"),N=document.getElementById("success-flash"),v=e.hardwareKey;document.getElementById("hw-key-display").textContent=v;document.getElementById("hw-key-waiting").textContent=v;const j=e.cmsUrl||"";let y=null,d=null,x=15,r=null;async function k(){if(r)return r;try{const t=new P(e);await t.registerDisplay(),console.log("[Setup] Using REST transport"),r=t}catch(t){console.log("[Setup] REST unavailable, using XMDS/SOAP:",t.message),r=new K(e)}return r}function p(t){S.classList.remove("active"),I.classList.remove("active"),b.classList.remove("active"),t.classList.add("active")}function O(t){h.textContent=t,h.style.display="block"}function _(){h.style.display="none"}function w(){let t=x;C.textContent=t,clearInterval(d),d=setInterval(()=>{t--,C.textContent=Math.max(0,t),t<=0&&clearInterval(d)},1e3)}async function E(){if(document.getElementById("cms-url").value.trim().replace(/\/$/,"")!==j){console.log("[Setup] CMS URL changed — wiping cached content");const n=await caches.keys();await Promise.all(n.map(a=>caches.delete(a)))}N.classList.add("active"),setTimeout(()=>{window.location.href="/player/index.html"+window.location.search},800)}async function M(){try{const n=await(await k()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(y),clearInterval(d),E();return}w()}catch(t){console.warn("[Setup] Poll failed:",t.message),w()}}function A(t){$.textContent=t,p(b),w(),y=setInterval(M,x*1e3)}function D(){clearInterval(y),clearInterval(d),y=null}async function X(t,n){const a=document.getElementById("api-client-id").value.trim(),o=document.getElementById("api-client-secret").value.trim();if(!a||!o)return!1;try{const l=await fetch("/api/authorize/access_token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:a,client_secret:o})});if(!l.ok)throw new Error(`OAuth2 failed: ${l.status}`);const{access_token:s}=await l.json(),i=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${s}`}});if(!i.ok)throw new Error(`Find display failed: ${i.status}`);const g=await i.json();if(!g.length)return console.log("[Setup] Display not found via API (may not be registered yet)"),!1;const m=g[0];if(m.licensed===1)return console.log("[Setup] Display already authorized"),!0;const f=await fetch(`/api/display/authorise/${m.displayId}`,{method:"PUT",headers:{Authorization:`Bearer ${s}`}});if(!f.ok)throw new Error(`Authorize failed: ${f.status}`);return console.log("[Setup] Display auto-authorized via proxy!"),e.apiClientId=a,e.apiClientSecret=o,!0}catch(l){return console.warn("[Setup] Auto-authorize failed:",l.message),!1}}const u=e.isConfigured()&&e.cmsKey,B=new URLSearchParams(window.location.search).has("unlocked"),R=document.getElementById("btn-back-player");u&&!B&&p(S);(u||B)&&(R.style.display="block",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));function U(){D(),window.location.href="/player/index.html"+window.location.search}R.addEventListener("click",U);(u||B)&&document.addEventListener("keydown",t=>{t.key==="Escape"&&(t.preventDefault(),U())});document.getElementById("unlock-form").addEventListener("submit",t=>{t.preventDefault();const n=document.getElementById("unlock-error");document.getElementById("unlock-key").value.trim()===e.cmsKey?(n.style.display="none",document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""),p(I)):(n.textContent="Incorrect CMS key",n.style.display="block")});!u&&e.isConfigured()&&(document.getElementById("cms-url").value=e.cmsUrl,document.getElementById("cms-key").value=e.cmsKey,document.getElementById("display-name").value=e.displayName,e.apiClientId&&(document.getElementById("api-client-id").value=e.apiClientId,document.getElementById("api-client-secret").value=e.apiClientSecret||""));T.addEventListener("submit",async t=>{var l;t.preventDefault(),_();const n=document.getElementById("cms-url").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();try{c.textContent="Saving...",c.disabled=!0;const s=window.electronAPI||((l=window.parent)==null?void 0:l.electronAPI);if(s!=null&&s.setConfig)await s.setConfig({cmsUrl:n,cmsKey:a,displayName:o});else if(!(await fetch("/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cmsUrl:n,cmsKey:a,displayName:o})})).ok)throw new Error("Failed to save config");e.data.cmsUrl=n,e.data.cmsKey=a,e.data.displayName=o,e.save(),Y(e.hardwareKey),c.textContent="Connecting...",r=null;const i=await k();if((await i.registerDisplay()).code==="READY")E();else{if(c.textContent="Authorizing...",await X(n,v)&&(await i.registerDisplay()).code==="READY"){E();return}A(o)}}catch(s){O(`Connection failed: ${s.message}`),c.textContent="Connect",c.disabled=!1}});z.addEventListener("click",()=>{D(),p(I),c.textContent="Connect",c.disabled=!1});async function Y(t){try{const n=indexedDB.open("xibo-hw-backup",1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},n.onsuccess=()=>{const a=n.result,o=a.transaction("keys","readwrite");o.objectStore("keys").put(t,"hardwareKey"),o.oncomplete=()=>a.close()}}catch(n){console.warn("[Setup] IndexedDB backup failed:",n)}}c.disabled=!1;c.textContent="Connect";e.isConfigured()&&!u&&(async()=>{try{(await(await k()).registerDisplay()).code==="READY"?window.location.href="/player/index.html":A(e.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
|
|
2
|
+
//# sourceMappingURL=setup-DcthBcbI.js.map
|