@xiboplayer/pwa 0.7.18 → 0.7.19
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/{main-BG2cZsg-.js → main-BmtbYkOU.js} +4 -4
- package/dist/assets/{main-BG2cZsg-.js.map → main-BmtbYkOU.js.map} +1 -1
- package/dist/assets/main-ByurY8zd.js +3 -0
- package/dist/assets/{main-CkREX2X6.js.map → main-ByurY8zd.js.map} +1 -1
- package/dist/assets/{setup-COzyFqMn.js → setup-TzYPvQkI.js} +2 -2
- package/dist/assets/{setup-COzyFqMn.js.map → setup-TzYPvQkI.js.map} +1 -1
- package/dist/assets/{src-CfCGHb7u.js → src-BbJ9IAbR.js} +2 -2
- package/dist/assets/{src-CfCGHb7u.js.map → src-BbJ9IAbR.js.map} +1 -1
- package/dist/assets/{src-IJdgG16K.js → src-BhNSI3YP.js} +2 -2
- package/dist/assets/{src-IJdgG16K.js.map → src-BhNSI3YP.js.map} +1 -1
- package/dist/assets/{src-BdgQ2CiL.js → src-CR4vHRyW.js} +2 -2
- package/dist/assets/{src-BdgQ2CiL.js.map → src-CR4vHRyW.js.map} +1 -1
- package/dist/assets/{src-C3Sg89t9.js → src-CRWze-JF.js} +2 -2
- package/dist/assets/{src-C3Sg89t9.js.map → src-CRWze-JF.js.map} +1 -1
- package/dist/assets/{src-BF_sMbmn.js → src-CSIdq4vk.js} +2 -2
- package/dist/assets/{src-BF_sMbmn.js.map → src-CSIdq4vk.js.map} +1 -1
- package/dist/assets/{src-BV-4JdnK.js → src-DAFtXxFV.js} +2 -2
- package/dist/assets/{src-BV-4JdnK.js.map → src-DAFtXxFV.js.map} +1 -1
- package/dist/assets/{src-M1enQEwh.js → src-DLAmD0IH.js} +2 -2
- package/dist/assets/{src-M1enQEwh.js.map → src-DLAmD0IH.js.map} +1 -1
- package/dist/assets/{src-DnPIj2iO.js → src-Jz8Hu7ah.js} +2 -2
- package/dist/assets/{src-DnPIj2iO.js.map → src-Jz8Hu7ah.js.map} +1 -1
- package/dist/assets/{src-BYVnjdc0.js → src-S093VuQs.js} +2 -2
- package/dist/assets/{src-BYVnjdc0.js.map → src-S093VuQs.js.map} +1 -1
- package/dist/assets/{src-BA9Y85MN.js → src-cynIeb-W.js} +2 -2
- package/dist/assets/{src-BA9Y85MN.js.map → src-cynIeb-W.js.map} +1 -1
- package/dist/assets/{sync-manager-C68deMxf.js → sync-manager-CJQQp9_5.js} +2 -2
- package/dist/assets/{sync-manager-C68deMxf.js.map → sync-manager-CJQQp9_5.js.map} +1 -1
- package/dist/index.html +1 -1
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +2 -2
- package/dist/sw-pwa.js.map +1 -1
- package/package.json +13 -13
- package/dist/assets/main-CkREX2X6.js +0 -3
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./main-BmtbYkOU.js","./chunk-7ZXdHUL4.js","./preload-helper-Chd9yIcd.js","./src-S093VuQs.js","./src-CRWze-JF.js","./src-DLAmD0IH.js","./src-CR4vHRyW.js","./src-CSIdq4vk.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import"./modulepreload-polyfill-Cf3xff8G.js";import{t as e}from"./preload-helper-Chd9yIcd.js";window.__XIBO_REDIRECTING||e(()=>import(`./main-BmtbYkOU.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url);
|
|
3
|
+
//# sourceMappingURL=main-ByurY8zd.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";8FACS,OAAO,oBACV,aAAO","names":[],"ignoreList":[],"sources":["../../index.html?html-proxy&index=1.js"],"sourcesContent":["\n if (!window.__XIBO_REDIRECTING) {\n import('/src/main.ts');\n }\n "],"file":"main-
|
|
1
|
+
{"version":3,"mappings":";8FACS,OAAO,oBACV,aAAO","names":[],"ignoreList":[],"sources":["../../index.html?html-proxy&index=1.js"],"sourcesContent":["\n if (!window.__XIBO_REDIRECTING) {\n import('/src/main.ts');\n }\n "],"file":"main-ByurY8zd.js"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./modulepreload-polyfill-Cf3xff8G.js";import{i as e}from"./src-
|
|
2
|
-
//# sourceMappingURL=setup-
|
|
1
|
+
import"./modulepreload-polyfill-Cf3xff8G.js";import{i as e}from"./src-CRWze-JF.js";import{n as t,r as n}from"./src-BbJ9IAbR.js";var r=`0.7.19`;document.getElementById(`version-footer`).textContent=`xiboplayer v${r}`;var i=document.getElementById(`setup-form`),a=document.getElementById(`error`),o=document.getElementById(`submit-btn`),s=document.getElementById(`phase-unlock`),c=document.getElementById(`phase-setup`),l=document.getElementById(`phase-waiting`),u=document.getElementById(`countdown`),d=document.getElementById(`waiting-display-name`),f=document.getElementById(`btn-back`),p=document.getElementById(`success-flash`),m=e.hardwareKey;document.getElementById(`hw-key-display`).textContent=m,document.getElementById(`hw-key-waiting`).textContent=m;var h=e.cmsUrl||``,g=null,_=null,v=15,y=null;async function b(){if(y)return y;try{let t=new n(e);await t.registerDisplay(),console.log(`[Setup] Using REST transport`),y=t}catch(n){console.log(`[Setup] REST unavailable, using XMDS/SOAP:`,n.message),y=new t(e)}return y}function x(e){s.classList.remove(`active`),c.classList.remove(`active`),l.classList.remove(`active`),e.classList.add(`active`)}function S(e){a.textContent=e,a.style.display=`block`}function C(){a.style.display=`none`}function w(){let e=v;u.textContent=e,clearInterval(_),_=setInterval(()=>{e--,u.textContent=Math.max(0,e),e<=0&&clearInterval(_)},1e3)}async function T(){if(document.getElementById(`cms-url`).value.trim().replace(/\/$/,``)!==h){console.log(`[Setup] CMS URL changed — wiping cached content`);let e=await caches.keys();await Promise.all(e.map(e=>caches.delete(e)))}p.classList.add(`active`),setTimeout(()=>{window.location.href=`/player/index.html`+window.location.search},800)}async function E(){try{let e=await(await b()).registerDisplay();if(console.log(`[Setup] Poll result:`,e.code,e.message),e.code===`READY`){clearInterval(g),clearInterval(_),T();return}w()}catch(e){console.warn(`[Setup] Poll failed:`,e.message),w()}}function D(e){d.textContent=e,x(l),w(),g=setInterval(E,v*1e3)}function O(){clearInterval(g),clearInterval(_),g=null}async function k(t,n){let r=document.getElementById(`api-client-id`).value.trim(),i=document.getElementById(`api-client-secret`).value.trim();if(!r||!i)return!1;try{let t=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:r,client_secret:i})});if(!t.ok)throw Error(`OAuth2 failed: ${t.status}`);let{access_token:a}=await t.json(),o=await fetch(`/api/display?hardwareKey=${encodeURIComponent(n)}`,{headers:{Authorization:`Bearer ${a}`}});if(!o.ok)throw Error(`Find display failed: ${o.status}`);let s=await o.json();if(!s.length)return console.log(`[Setup] Display not found via API (may not be registered yet)`),!1;let c=s[0];if(c.licensed===1)return console.log(`[Setup] Display already authorized`),!0;let l=await fetch(`/api/display/authorise/${c.displayId}`,{method:`PUT`,headers:{Authorization:`Bearer ${a}`}});if(!l.ok)throw Error(`Authorize failed: ${l.status}`);return console.log(`[Setup] Display auto-authorized via proxy!`),e.data.apiClientId=r,e.data.apiClientSecret=i,!0}catch(e){return console.warn(`[Setup] Auto-authorize failed:`,e.message),!1}}var A=e.isConfigured()&&e.cmsKey,j=new URLSearchParams(window.location.search).has(`unlocked`),M=document.getElementById(`btn-back-player`);A&&!j&&x(s),(A||j)&&(M.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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``));function N(){O(),window.location.href=`/player/index.html`+window.location.search}M.addEventListener(`click`,N),(A||j)&&document.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),N())}),document.getElementById(`unlock-form`).addEventListener(`submit`,t=>{t.preventDefault();let 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.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``),x(c)):(n.textContent=`Incorrect CMS key`,n.style.display=`block`)}),!A&&e.isConfigured()&&(document.getElementById(`cms-url`).value=e.cmsUrl,document.getElementById(`cms-key`).value=e.cmsKey,document.getElementById(`display-name`).value=e.displayName,e.data.apiClientId&&(document.getElementById(`api-client-id`).value=e.data.apiClientId,document.getElementById(`api-client-secret`).value=e.data.apiClientSecret||``)),i.addEventListener(`submit`,async t=>{t.preventDefault(),C();let n=document.getElementById(`cms-url`).value.trim().replace(/\/$/,``),r=document.getElementById(`cms-key`).value.trim(),i=document.getElementById(`display-name`).value.trim();try{if(o.textContent=`Saving...`,o.disabled=!0,!(await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({cmsUrl:n,cmsKey:r,displayName:i})})).ok)throw Error(`Failed to save config`);let t=window.electronAPI||window.parent?.electronAPI;t?.setConfig&&await t.setConfig({cmsUrl:n,cmsKey:r,displayName:i}),e.data.cmsUrl=n,e.data.cmsKey=r,e.data.displayName=i,e.save(),P(e.hardwareKey),o.textContent=`Connecting...`,y=null;let a=await b();if((await a.registerDisplay()).code===`READY`)T();else{if(o.textContent=`Authorizing...`,await k(n,m)&&(e.save(),await fetch(`/config`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret})}),t?.setConfig&&await t.setConfig({apiClientId:e.data.apiClientId,apiClientSecret:e.data.apiClientSecret}),(await a.registerDisplay()).code===`READY`)){T();return}D(i)}}catch(e){S(`Connection failed: ${e.message}`),o.textContent=`Connect`,o.disabled=!1}}),f.addEventListener(`click`,()=>{O(),x(c),o.textContent=`Connect`,o.disabled=!1});async function P(e){try{let t=indexedDB.open(`xibo-hw-backup`,1);t.onupgradeneeded=()=>{let e=t.result;e.objectStoreNames.contains(`keys`)||e.createObjectStore(`keys`)},t.onsuccess=()=>{let n=t.result,r=n.transaction(`keys`,`readwrite`);r.objectStore(`keys`).put(e,`hardwareKey`),r.oncomplete=()=>n.close()}}catch(e){console.warn(`[Setup] IndexedDB backup failed:`,e)}}o.disabled=!1,o.textContent=`Connect`,e.isConfigured()&&!A&&(async()=>{try{(await(await b()).registerDisplay()).code===`READY`?window.location.href=`/player/index.html`+window.location.search:D(e.displayName)}catch{console.log(`[Setup] Auto-check failed, showing form`)}})();
|
|
2
|
+
//# sourceMappingURL=setup-TzYPvQkI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup-COzyFqMn.js","names":[],"sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // Inject version from Vite build\n const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '?';\n document.getElementById('version-footer').textContent = `xiboplayer v${appVersion}`;\n\n // ── Elements ──\n const form = document.getElementById('setup-form');\n const errorEl = document.getElementById('error');\n const submitBtn = document.getElementById('submit-btn');\n const phaseUnlock = document.getElementById('phase-unlock');\n const phaseSetup = document.getElementById('phase-setup');\n const phaseWaiting = document.getElementById('phase-waiting');\n const countdownEl = document.getElementById('countdown');\n const waitingNameEl = document.getElementById('waiting-display-name');\n const btnBack = document.getElementById('btn-back');\n const successFlash = document.getElementById('success-flash');\n\n // Show hardware key\n const hwKey = config.hardwareKey;\n document.getElementById('hw-key-display').textContent = hwKey;\n document.getElementById('hw-key-waiting').textContent = hwKey;\n\n // ── State ──\n const previousCmsUrl = config.cmsUrl || '';\n let pollTimer = null;\n let countdownTimer = null;\n let pollSeconds = 15;\n\n // ── Transport: try REST first, fall back to SOAP ──\n let transport = null;\n async function getTransport() {\n if (transport) return transport;\n try {\n const rest = new RestClient(config);\n await rest.registerDisplay();\n console.log('[Setup] Using REST transport');\n transport = rest;\n } catch (e) {\n console.log('[Setup] REST unavailable, using XMDS/SOAP:', e.message);\n transport = new XmdsClient(config);\n }\n return transport;\n }\n\n // ── Helpers ──\n function showPhase(phase) {\n phaseUnlock.classList.remove('active');\n phaseSetup.classList.remove('active');\n phaseWaiting.classList.remove('active');\n phase.classList.add('active');\n }\n\n function showError(msg) {\n errorEl.textContent = msg;\n errorEl.style.display = 'block';\n }\n\n function hideError() {\n errorEl.style.display = 'none';\n }\n\n function startCountdown() {\n let remaining = pollSeconds;\n countdownEl.textContent = remaining;\n clearInterval(countdownTimer);\n countdownTimer = setInterval(() => {\n remaining--;\n countdownEl.textContent = Math.max(0, remaining);\n if (remaining <= 0) clearInterval(countdownTimer);\n }, 1000);\n }\n\n async function showSuccess() {\n // If CMS URL changed, wipe all cached content (media, layouts, widgets\n // from the old CMS are useless) and the SW's cached index.html (which\n // may have a stale config injection script).\n const newUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n if (newUrl !== previousCmsUrl) {\n console.log('[Setup] CMS URL changed — wiping cached content');\n const cacheNames = await caches.keys();\n await Promise.all(cacheNames.map(name => caches.delete(name)));\n }\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = '/player/index.html' + window.location.search;\n }, 800);\n }\n\n // ── Authorization Polling ──\n async function checkAuthorization() {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n console.log('[Setup] Poll result:', result.code, result.message);\n\n if (result.code === 'READY') {\n // Authorized!\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n showSuccess();\n return;\n }\n\n // Still waiting — restart countdown\n startCountdown();\n } catch (error) {\n console.warn('[Setup] Poll failed:', error.message);\n startCountdown();\n }\n }\n\n function startPolling(displayName) {\n waitingNameEl.textContent = displayName;\n showPhase(phaseWaiting);\n startCountdown();\n pollTimer = setInterval(checkAuthorization, pollSeconds * 1000);\n }\n\n function stopPolling() {\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n pollTimer = null;\n }\n\n // ── Auto-authorize via CMS API (through /api/* forward proxy) ──\n async function tryAutoAuthorize(cmsUrl, hardwareKey) {\n const clientId = document.getElementById('api-client-id').value.trim();\n const clientSecret = document.getElementById('api-client-secret').value.trim();\n if (!clientId || !clientSecret) return false;\n\n try {\n // Step 1: OAuth2 token via proxy\n const tokenResp = await fetch('/api/authorize/access_token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),\n });\n if (!tokenResp.ok) throw new Error(`OAuth2 failed: ${tokenResp.status}`);\n const { access_token } = await tokenResp.json();\n\n // Step 2: Find display by hardwareKey via proxy\n const displayResp = await fetch(\n `/api/display?hardwareKey=${encodeURIComponent(hardwareKey)}`,\n { headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!displayResp.ok) throw new Error(`Find display failed: ${displayResp.status}`);\n const displays = await displayResp.json();\n if (!displays.length) { console.log('[Setup] Display not found via API (may not be registered yet)'); return false; }\n\n const display = displays[0];\n if (display.licensed === 1) { console.log('[Setup] Display already authorized'); return true; }\n\n // Step 3: Authorize display via proxy\n const authResp = await fetch(\n `/api/display/authorise/${display.displayId}`,\n { method: 'PUT', headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!authResp.ok) throw new Error(`Authorize failed: ${authResp.status}`);\n\n console.log('[Setup] Display auto-authorized via proxy!');\n config.data.apiClientId = clientId;\n config.data.apiClientSecret = clientSecret;\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Write config.json via proxy (master config file)\n // The boot path (proxy injection → Config.load()) handles the rest.\n try {\n submitBtn.textContent = 'Saving...';\n submitBtn.disabled = true;\n\n // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\n const saveResp = await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cmsUrl, cmsKey, displayName }),\n });\n if (!saveResp.ok) throw new Error('Failed to save config');\n\n // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\n\n // Also update in-memory config for the test connection below\n config.data.cmsUrl = cmsUrl;\n config.data.cmsKey = cmsKey;\n config.data.displayName = displayName;\n config.save();\n\n // Backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n submitBtn.textContent = 'Connecting...';\n\n // Try REST first, fall back to SOAP\n transport = null; // reset transport for fresh detection\n const client = await getTransport();\n const result = await client.registerDisplay();\n\n if (result.code === 'READY') {\n showSuccess();\n } else {\n // Try auto-authorize via CMS API if credentials provided\n submitBtn.textContent = 'Authorizing...';\n const autoAuthed = await tryAutoAuthorize(cmsUrl, hwKey);\n\n if (autoAuthed) {\n // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\n // Verify registration\n const recheck = await client.registerDisplay();\n if (recheck.code === 'READY') {\n showSuccess();\n return;\n }\n }\n\n // Not authorized yet — switch to polling phase\n startPolling(displayName);\n }\n } catch (error) {\n showError(`Connection failed: ${error.message}`);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n }\n });\n\n // ── Back button ──\n btnBack.addEventListener('click', () => {\n stopPolling();\n showPhase(phaseSetup);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n });\n\n // ── IndexedDB hardware key backup ──\n async function backupHardwareKey(key) {\n try {\n const req = indexedDB.open('xibo-hw-backup', 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n tx.objectStore('keys').put(key, 'hardwareKey');\n tx.oncomplete = () => db.close();\n };\n } catch (e) {\n console.warn('[Setup] IndexedDB backup failed:', e);\n }\n }\n\n // ── Enable submit ──\n submitBtn.disabled = false;\n submitBtn.textContent = 'Connect';\n\n // ── Auto-resume polling if already registered but not authorized ──\n // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = '/player/index.html' + window.location.search;\n } else {\n // Not authorized — go straight to polling\n startPolling(config.displayName);\n }\n } catch (e) {\n // Connection failed, show form\n console.log('[Setup] Auto-check failed, showing form');\n }\n })();\n }\n "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB,CAAC,YAAc,eAAe,IAGvE,IAAM,EAAO,SAAS,eAAe,aAAa,CAC5C,EAAU,SAAS,eAAe,QAAQ,CAC1C,EAAY,SAAS,eAAe,aAAa,CACjD,EAAc,SAAS,eAAe,eAAe,CACrD,EAAa,SAAS,eAAe,cAAc,CACnD,EAAe,SAAS,eAAe,gBAAgB,CACvD,EAAc,SAAS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M,EAAK,EAAI,OACT,EAAK,EAAG,YAAY,OAAQ,YAAY,CAC9C,EAAG,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
|
|
1
|
+
{"version":3,"file":"setup-TzYPvQkI.js","names":[],"sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config } from '@xiboplayer/utils';\n import { RestClient, XmdsClient } from '@xiboplayer/xmds';\n\n // Inject version from Vite build\n const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '?';\n document.getElementById('version-footer').textContent = `xiboplayer v${appVersion}`;\n\n // ── Elements ──\n const form = document.getElementById('setup-form');\n const errorEl = document.getElementById('error');\n const submitBtn = document.getElementById('submit-btn');\n const phaseUnlock = document.getElementById('phase-unlock');\n const phaseSetup = document.getElementById('phase-setup');\n const phaseWaiting = document.getElementById('phase-waiting');\n const countdownEl = document.getElementById('countdown');\n const waitingNameEl = document.getElementById('waiting-display-name');\n const btnBack = document.getElementById('btn-back');\n const successFlash = document.getElementById('success-flash');\n\n // Show hardware key\n const hwKey = config.hardwareKey;\n document.getElementById('hw-key-display').textContent = hwKey;\n document.getElementById('hw-key-waiting').textContent = hwKey;\n\n // ── State ──\n const previousCmsUrl = config.cmsUrl || '';\n let pollTimer = null;\n let countdownTimer = null;\n let pollSeconds = 15;\n\n // ── Transport: try REST first, fall back to SOAP ──\n let transport = null;\n async function getTransport() {\n if (transport) return transport;\n try {\n const rest = new RestClient(config);\n await rest.registerDisplay();\n console.log('[Setup] Using REST transport');\n transport = rest;\n } catch (e) {\n console.log('[Setup] REST unavailable, using XMDS/SOAP:', e.message);\n transport = new XmdsClient(config);\n }\n return transport;\n }\n\n // ── Helpers ──\n function showPhase(phase) {\n phaseUnlock.classList.remove('active');\n phaseSetup.classList.remove('active');\n phaseWaiting.classList.remove('active');\n phase.classList.add('active');\n }\n\n function showError(msg) {\n errorEl.textContent = msg;\n errorEl.style.display = 'block';\n }\n\n function hideError() {\n errorEl.style.display = 'none';\n }\n\n function startCountdown() {\n let remaining = pollSeconds;\n countdownEl.textContent = remaining;\n clearInterval(countdownTimer);\n countdownTimer = setInterval(() => {\n remaining--;\n countdownEl.textContent = Math.max(0, remaining);\n if (remaining <= 0) clearInterval(countdownTimer);\n }, 1000);\n }\n\n async function showSuccess() {\n // If CMS URL changed, wipe all cached content (media, layouts, widgets\n // from the old CMS are useless) and the SW's cached index.html (which\n // may have a stale config injection script).\n const newUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n if (newUrl !== previousCmsUrl) {\n console.log('[Setup] CMS URL changed — wiping cached content');\n const cacheNames = await caches.keys();\n await Promise.all(cacheNames.map(name => caches.delete(name)));\n }\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = '/player/index.html' + window.location.search;\n }, 800);\n }\n\n // ── Authorization Polling ──\n async function checkAuthorization() {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n console.log('[Setup] Poll result:', result.code, result.message);\n\n if (result.code === 'READY') {\n // Authorized!\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n showSuccess();\n return;\n }\n\n // Still waiting — restart countdown\n startCountdown();\n } catch (error) {\n console.warn('[Setup] Poll failed:', error.message);\n startCountdown();\n }\n }\n\n function startPolling(displayName) {\n waitingNameEl.textContent = displayName;\n showPhase(phaseWaiting);\n startCountdown();\n pollTimer = setInterval(checkAuthorization, pollSeconds * 1000);\n }\n\n function stopPolling() {\n clearInterval(pollTimer);\n clearInterval(countdownTimer);\n pollTimer = null;\n }\n\n // ── Auto-authorize via CMS API (through /api/* forward proxy) ──\n async function tryAutoAuthorize(cmsUrl, hardwareKey) {\n const clientId = document.getElementById('api-client-id').value.trim();\n const clientSecret = document.getElementById('api-client-secret').value.trim();\n if (!clientId || !clientSecret) return false;\n\n try {\n // Step 1: OAuth2 token via proxy\n const tokenResp = await fetch('/api/authorize/access_token', {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret }),\n });\n if (!tokenResp.ok) throw new Error(`OAuth2 failed: ${tokenResp.status}`);\n const { access_token } = await tokenResp.json();\n\n // Step 2: Find display by hardwareKey via proxy\n const displayResp = await fetch(\n `/api/display?hardwareKey=${encodeURIComponent(hardwareKey)}`,\n { headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!displayResp.ok) throw new Error(`Find display failed: ${displayResp.status}`);\n const displays = await displayResp.json();\n if (!displays.length) { console.log('[Setup] Display not found via API (may not be registered yet)'); return false; }\n\n const display = displays[0];\n if (display.licensed === 1) { console.log('[Setup] Display already authorized'); return true; }\n\n // Step 3: Authorize display via proxy\n const authResp = await fetch(\n `/api/display/authorise/${display.displayId}`,\n { method: 'PUT', headers: { Authorization: `Bearer ${access_token}` } }\n );\n if (!authResp.ok) throw new Error(`Authorize failed: ${authResp.status}`);\n\n console.log('[Setup] Display auto-authorized via proxy!');\n config.data.apiClientId = clientId;\n config.data.apiClientSecret = clientSecret;\n return true;\n } catch (error) {\n console.warn('[Setup] Auto-authorize failed:', error.message);\n return false;\n }\n }\n\n // ── Unlock gate for reconfiguration ──\n const isReconfigure = config.isConfigured() && config.cmsKey;\n const alreadyUnlocked = new URLSearchParams(window.location.search).has('unlocked');\n const btnBackPlayer = document.getElementById('btn-back-player');\n if (isReconfigure && !alreadyUnlocked) {\n // Show unlock phase instead of setup form\n showPhase(phaseUnlock);\n }\n if (isReconfigure || alreadyUnlocked) {\n // Show \"Back to Player\" on the setup form\n btnBackPlayer.style.display = 'block';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = '/player/index.html' + window.location.search;\n }\n btnBackPlayer.addEventListener('click', goBackToPlayer);\n\n // Esc also goes back to player when reconfiguring\n if (isReconfigure || alreadyUnlocked) {\n document.addEventListener('keydown', (e) => {\n if (e.key === 'Escape') {\n e.preventDefault();\n goBackToPlayer();\n }\n });\n }\n\n // ── Unlock form handler ──\n document.getElementById('unlock-form').addEventListener('submit', (e) => {\n e.preventDefault();\n const unlockError = document.getElementById('unlock-error');\n const enteredKey = document.getElementById('unlock-key').value.trim();\n\n if (enteredKey === config.cmsKey) {\n unlockError.style.display = 'none';\n // Pre-fill form with existing config\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n showPhase(phaseSetup);\n } else {\n unlockError.textContent = 'Incorrect CMS key';\n unlockError.style.display = 'block';\n }\n });\n\n // ── Pre-fill if first-time setup (no unlock gate) ──\n if (!isReconfigure && config.isConfigured()) {\n document.getElementById('cms-url').value = config.cmsUrl;\n document.getElementById('cms-key').value = config.cmsKey;\n document.getElementById('display-name').value = config.displayName;\n if (config.data.apiClientId) {\n document.getElementById('api-client-id').value = config.data.apiClientId;\n document.getElementById('api-client-secret').value = config.data.apiClientSecret || '';\n }\n }\n\n // ── Form Submit ──\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n hideError();\n\n const cmsUrl = document.getElementById('cms-url').value.trim().replace(/\\/$/, '');\n const cmsKey = document.getElementById('cms-key').value.trim();\n const displayName = document.getElementById('display-name').value.trim();\n\n // Write config.json via proxy (master config file)\n // The boot path (proxy injection → Config.load()) handles the rest.\n try {\n submitBtn.textContent = 'Saving...';\n submitBtn.disabled = true;\n\n // Always POST to proxy — updates in-memory config for REST auth,\n // cache-through, and API forwarding. Works on all players.\n const saveResp = await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ cmsUrl, cmsKey, displayName }),\n });\n if (!saveResp.ok) throw new Error('Failed to save config');\n\n // Shell persistence (Electron config.json) — optional, on top of proxy\n const electronAPI = window.electronAPI || window.parent?.electronAPI;\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ cmsUrl, cmsKey, displayName });\n }\n\n // Also update in-memory config for the test connection below\n config.data.cmsUrl = cmsUrl;\n config.data.cmsKey = cmsKey;\n config.data.displayName = displayName;\n config.save();\n\n // Backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n submitBtn.textContent = 'Connecting...';\n\n // Try REST first, fall back to SOAP\n transport = null; // reset transport for fresh detection\n const client = await getTransport();\n const result = await client.registerDisplay();\n\n if (result.code === 'READY') {\n showSuccess();\n } else {\n // Try auto-authorize via CMS API if credentials provided\n submitBtn.textContent = 'Authorizing...';\n const autoAuthed = await tryAutoAuthorize(cmsUrl, hwKey);\n\n if (autoAuthed) {\n // Persist API client credentials so they survive restarts\n config.save();\n await fetch('/config', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret }),\n });\n if (electronAPI?.setConfig) {\n await electronAPI.setConfig({ apiClientId: config.data.apiClientId, apiClientSecret: config.data.apiClientSecret });\n }\n\n // Verify registration\n const recheck = await client.registerDisplay();\n if (recheck.code === 'READY') {\n showSuccess();\n return;\n }\n }\n\n // Not authorized yet — switch to polling phase\n startPolling(displayName);\n }\n } catch (error) {\n showError(`Connection failed: ${error.message}`);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n }\n });\n\n // ── Back button ──\n btnBack.addEventListener('click', () => {\n stopPolling();\n showPhase(phaseSetup);\n submitBtn.textContent = 'Connect';\n submitBtn.disabled = false;\n });\n\n // ── IndexedDB hardware key backup ──\n async function backupHardwareKey(key) {\n try {\n const req = indexedDB.open('xibo-hw-backup', 1);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains('keys')) {\n db.createObjectStore('keys');\n }\n };\n req.onsuccess = () => {\n const db = req.result;\n const tx = db.transaction('keys', 'readwrite');\n tx.objectStore('keys').put(key, 'hardwareKey');\n tx.oncomplete = () => db.close();\n };\n } catch (e) {\n console.warn('[Setup] IndexedDB backup failed:', e);\n }\n }\n\n // ── Enable submit ──\n submitBtn.disabled = false;\n submitBtn.textContent = 'Connect';\n\n // ── Auto-resume polling if already registered but not authorized ──\n // Skip auto-resume when reconfiguring (user explicitly opened setup)\n if (config.isConfigured() && !isReconfigure) {\n (async () => {\n try {\n const client = await getTransport();\n const result = await client.registerDisplay();\n if (result.code === 'READY') {\n window.location.href = '/player/index.html' + window.location.search;\n } else {\n // Not authorized — go straight to polling\n startPolling(config.displayName);\n }\n } catch (e) {\n // Connection failed, show form\n console.log('[Setup] Auto-check failed, showing form');\n }\n })();\n }\n "],"mappings":"gIAKI,IAAM,EAAA,SACN,SAAS,eAAe,iBAAiB,CAAC,YAAc,eAAe,IAGvE,IAAM,EAAO,SAAS,eAAe,aAAa,CAC5C,EAAU,SAAS,eAAe,QAAQ,CAC1C,EAAY,SAAS,eAAe,aAAa,CACjD,EAAc,SAAS,eAAe,eAAe,CACrD,EAAa,SAAS,eAAe,cAAc,CACnD,EAAe,SAAS,eAAe,gBAAgB,CACvD,EAAc,SAAS,eAAe,YAAY,CAClD,EAAgB,SAAS,eAAe,uBAAuB,CAC/D,EAAU,S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G,YAAY,OAAO,CAAC,IAAI,EAAK,cAAc,CAC9C,EAAG,eAAmB,EAAG,OAAO,QAE3B,EAAG,CACV,QAAQ,KAAK,mCAAoC,EAAE,EAKvD,EAAU,SAAW,GACrB,EAAU,YAAc,UAIpB,EAAO,cAAc,EAAI,CAAC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM,GAAc,EACP,iBAAiB,EAClC,OAAS,QAClB,OAAO,SAAS,KAAO,qBAAuB,OAAO,SAAS,OAG9D,EAAa,EAAO,YAAY,MAExB,CAEV,QAAQ,IAAI,0CAA0C,KAEtD"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{n as e}from"./chunk-7ZXdHUL4.js";import{r as t,t as n,u as r}from"./src-C3Sg89t9.js";var i={name:`@xiboplayer/xmds`,version:`0.7.18`,description:`XMDS SOAP client for Xibo CMS communication`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./xmds-client":`./src/xmds-client.js`,"./rest-client":`./src/rest-client.js`,"./schedule-parser":`./src/schedule-parser.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`xmds`,`soap`,`cms`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/xmds`},homepage:`https://xiboplayer.org`};async function a(e){if(typeof navigator<`u`&&navigator.storage?.estimate)try{let t=await navigator.storage.estimate();e.availableSpace=t.quota-t.usage,e.totalSpace=t.quota}catch{}!e.timeZone&&typeof Intl<`u`&&(e.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),e.statusDialog||=`Current Layout: ${e.currentLayoutId||`None`}`}var o=r(`REST`),s=class{constructor(e){this.config=e,this.schemaVersion=7,this.retryOptions=e.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,o.info(`Using REST transport`)}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${n}`:(this.config.restApiUrl||`${this.config.cmsUrl}${n}`).replace(/\/+$/,``)}_isProxyMode(){return typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)}_cacheSet(e,t,n){if(this._etags.size>=this._maxCacheSize){let e=this._etags.keys().next().value;this._etags.delete(e),this._responseCache.delete(e)}this._etags.set(e,t),this._responseCache.set(e,n)}async _authenticate(){let e=`${this.getRestBaseUrl()}/auth`;o.debug(`Authenticating...`);let n=await t(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Auth failed: ${n.status} ${n.statusText} ${e}`)}let r=await n.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,o.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(e,n={},r=!1){let i=await this._getToken(),a=new URL(`${this.getRestBaseUrl()}${e}`);for(let[e,t]of Object.entries(n))a.searchParams.set(e,String(t));let s=e,c={Authorization:`Bearer ${i}`},l=this._etags.get(s);l&&(c[`If-None-Match`]=l),o.debug(`GET ${e}`,n);let u=await t(a.toString(),{method:`GET`,headers:c},this.retryOptions);if(u.status===401){if(r)throw Error(`REST GET ${e} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restGet(e,n,!0)}if(u.status===304){let t=this._responseCache.get(s);if(t)return o.debug(`${e} → 304 (using cache)`),t}if(!u.ok){let t=await u.text().catch(()=>``);throw Error(`REST GET ${e} failed: ${u.status} ${u.statusText} ${t}`)}let d=u.headers.get(`Content-Type`)||``,f;f=d.includes(`application/json`)?await u.json():await u.text();let p=u.headers.get(`ETag`);return p&&this._cacheSet(s,p,f),f}async restSend(e,n,r={},i=!1){let a=await this._getToken(),s=new URL(`${this.getRestBaseUrl()}${n}`);o.debug(`${e} ${n}`);let c=await t(s.toString(),{method:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${a}`},body:JSON.stringify(r)},this.retryOptions);if(c.status===401){if(i)throw Error(`REST ${e} ${n} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restSend(e,n,r,!0)}if(!c.ok){let t=await c.text().catch(()=>``);throw Error(`REST ${e} ${n} failed: ${c.status} ${c.statusText} ${t}`)}return(c.headers.get(`Content-Type`)||``).includes(`application/json`)?await c.json():await c.text()}async registerDisplay(){await this._getToken();let e=typeof navigator<`u`?`${navigator.platform} ${navigator.userAgent}`:`unknown`,t=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:e,macAddress:this.config.macAddress||`n/a`,xmrChannel:this.config.xmrChannel||``,xmrPubKey:this.config.xmrPubKey||``});return this._parseRegisterDisplayJson(t)}_parseRegisterDisplayJson(e){let t=e.display||e,n=t[`@attributes`]||{},r=n.code||t.code,i=n.message||t.message||``;if(r!==`READY`)return{code:r,message:i,settings:null};let a={},o=[],s=[];for(let[e,n]of Object.entries(t))if(!(e===`@attributes`||e===`file`)){if(e===`commands`){Array.isArray(n)&&(s=n.map(e=>({commandCode:e.code||e.commandCode||``,commandString:e.commandString||``})));continue}if(e===`tags`){let e=e=>typeof e==`object`?e.tag||e.value||``:String(e);if(Array.isArray(n))o=n.map(e).filter(Boolean);else if(n&&typeof n==`object`){let t=e(n);t&&(o=[t])}else typeof n==`string`&&n&&(o=[n]);continue}a[e]=typeof n==`object`?JSON.stringify(n):String(n)}let c=n.checkRf||``,l=n.checkSchedule||``,u={date:n.date||t.date||null,timezone:n.timezone||t.timezone||null,status:n.status||t.status||null,localDate:n.localDate||t.localDate||null,version_instructions:n.version_instructions||t.version_instructions||null},d=t.syncConfig||(t.syncGroup?{syncGroup:String(t.syncGroup),syncPublisherPort:parseInt(t.syncPublisherPort||`9590`,10),syncSwitchDelay:parseInt(t.syncSwitchDelay||`750`,10),syncVideoPauseDelay:parseInt(t.syncVideoPauseDelay||`100`,10),isLead:String(t.syncGroup)===`lead`}:null);return{code:r,message:i,settings:a,tags:o,commands:s,displayAttrs:u,checkRf:c,checkSchedule:l,syncConfig:d}}async requiredFiles(){let e=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(e)}_parseRequiredFilesV2(e){let t=[];for(let n of e.media||[])t.push({type:n.type||`media`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:n.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.layouts||[])t.push({type:`layout`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.widgets||[])t.push({type:`dataset`,id:n.id==null?null:String(n.id),size:0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:n.updateInterval||0});for(let n of e.dependencies||[])t.push({type:`static`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:n.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:t,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(e,t,n){return this.restGet(`/widgets/${e}/${t}/${n}`)}async notifyStatus(e){return await a(e),this.restSend(`PUT`,`/displays/${this._displayId}/status`,{statusData:e})}async mediaInventory(e){let t=Array.isArray(e)?{inventoryItems:e}:{inventory:e};return this.restSend(`PUT`,`/displays/${this._displayId}/inventory`,t)}async blackList(e,t,n){return o.warn(`BlackList not available in v2 API (${t}/${e}: ${n})`),!1}async submitLog(e,t=null){let n=Array.isArray(e)?{logs:e}:{logXml:e};return(await this.restSend(`POST`,`/displays/${this._displayId}/logs`,n))?.success===!0}async submitScreenShot(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/screenshot`,{screenshot:e}))?.success===!0}async submitStats(e,t=null){try{let t=Array.isArray(e)?{stats:e}:{statXml:e},n=(await this.restSend(`POST`,`/displays/${this._displayId}/stats`,t))?.success===!0;return o.info(`SubmitStats result: ${n}`),n}catch(e){throw o.error(`SubmitStats failed:`,e),e}}async reportFaults(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/faults`,{fault:e}))?.success===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(e,r){try{let i=`${typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)?``:e.replace(/\/+$/,``)}${n}/health`,a=r?.timeoutMs||8e3,o={method:`GET`};typeof AbortSignal<`u`&&AbortSignal.timeout&&(o.signal=AbortSignal.timeout(a));let s=await t(i,o,r||{maxRetries:0});if(!s.ok)return!1;let c=await s.json();return c.version===2&&c.status===`ok`}catch{return!1}}};function c(e){let t=[];for(let n of e.children)n.tagName===`criteria`&&t.push({metric:n.getAttribute(`metric`)||``,condition:n.getAttribute(`condition`)||``,type:n.getAttribute(`type`)||`string`,value:n.textContent||``});return t}function l(e){let t=new DOMParser().parseFromString(e,`text/xml`),n={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},r=t.querySelector(`schedule`);if(r){let e=Array.from(r.children).filter(e=>e.tagName===`dependants`);for(let t of e)if(t.parentElement===r)for(let e of t.querySelectorAll(`file`))e.textContent&&n.dependants.push(e.textContent)}let i=t.querySelector(`default`);if(i){n.default=i.getAttribute(`file`);let e=i.querySelectorAll(`dependants > file`);e.length>0&&(n.defaultDependants=[...e].map(e=>e.textContent))}for(let e of t.querySelectorAll(`campaign`)){let t={id:e.getAttribute(`id`),priority:parseInt(e.getAttribute(`priority`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:c(e),layouts:[]};for(let n of e.querySelectorAll(`layout`)){let e=n.getAttribute(`file`),r=n.querySelectorAll(`dependants > file`);t.layouts.push({id:String(e),file:e,fromdt:n.getAttribute(`fromdt`)||t.fromdt,todt:n.getAttribute(`todt`)||t.todt,scheduleid:t.scheduleid,priority:t.priority,campaignId:t.id,maxPlaysPerHour:parseInt(n.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:n.getAttribute(`isGeoAware`)===`1`,geoLocation:n.getAttribute(`geoLocation`)||``,syncEvent:n.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(n.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(n.getAttribute(`duration`)||`0`),cyclePlayback:n.getAttribute(`cyclePlayback`)===`1`,groupKey:n.getAttribute(`groupKey`)||null,playCount:parseInt(n.getAttribute(`playCount`)||`0`),dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:c(n)})}n.campaigns.push(t)}for(let e of t.querySelectorAll(`schedule > layout`)){let t=e.getAttribute(`file`),r=e.querySelectorAll(`dependants > file`);n.layouts.push({id:String(t),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),priority:parseInt(e.getAttribute(`priority`)||`0`),campaignId:null,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(e.getAttribute(`duration`)||`0`),cyclePlayback:e.getAttribute(`cyclePlayback`)===`1`,groupKey:e.getAttribute(`groupKey`)||null,playCount:parseInt(e.getAttribute(`playCount`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:c(e)})}let a=t.querySelector(`overlays`);if(a)for(let e of a.querySelectorAll(`overlay`)){let t=e.getAttribute(`file`);n.overlays.push({id:String(t),duration:parseInt(e.getAttribute(`duration`)||`60`),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:c(e)})}let o=t.querySelector(`actions`);if(o)for(let e of o.querySelectorAll(`action`))n.actions.push({actionType:e.getAttribute(`actionType`)||``,triggerCode:e.getAttribute(`triggerCode`)||``,layoutCode:e.getAttribute(`layoutCode`)||``,commandCode:e.getAttribute(`commandCode`)||``,duration:parseInt(e.getAttribute(`duration`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``});for(let e of t.querySelectorAll(`schedule > command`))n.commands.push({code:e.getAttribute(`code`)||``,date:e.getAttribute(`date`)||``});let s=t.querySelector(`dataConnectors`);if(s)for(let e of s.querySelectorAll(`connector`))n.dataConnectors.push({id:e.getAttribute(`id`)||``,dataConnectorId:e.getAttribute(`dataConnectorId`)||``,dataSetId:e.getAttribute(`dataSetId`)||``,dataKey:e.getAttribute(`dataKey`)||``,dataParams:e.getAttribute(`dataParams`)||``,js:e.getAttribute(`js`)||``,url:e.getAttribute(`url`)||``,updateInterval:parseInt(e.getAttribute(`updateInterval`)||`300`,10)});return n}var u=r(`XMDS`),d=class{constructor(e){this.config=e,this.schemaVersion=5,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(e,t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
1
|
+
import{n as e}from"./chunk-7ZXdHUL4.js";import{r as t,t as n,u as r}from"./src-CRWze-JF.js";var i={name:`@xiboplayer/xmds`,version:`0.7.19`,description:`XMDS SOAP client for Xibo CMS communication`,type:`module`,main:`./src/index.js`,types:`./src/index.d.ts`,exports:{".":`./src/index.js`,"./xmds-client":`./src/xmds-client.js`,"./rest-client":`./src/rest-client.js`,"./schedule-parser":`./src/schedule-parser.js`},scripts:{test:`vitest run`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`},dependencies:{"@xiboplayer/utils":`workspace:*`},devDependencies:{vitest:`^4.1.2`},keywords:[`xibo`,`digital-signage`,`xmds`,`soap`,`cms`],author:`Pau Aliagas <linuxnow@gmail.com>`,license:`AGPL-3.0-or-later`,repository:{type:`git`,url:`git+https://github.com/xibo-players/xiboplayer.git`,directory:`packages/xmds`},homepage:`https://xiboplayer.org`};async function a(e){if(typeof navigator<`u`&&navigator.storage?.estimate)try{let t=await navigator.storage.estimate();e.availableSpace=t.quota-t.usage,e.totalSpace=t.quota}catch{}!e.timeZone&&typeof Intl<`u`&&(e.timeZone=Intl.DateTimeFormat().resolvedOptions().timeZone),e.statusDialog||=`Current Layout: ${e.currentLayoutId||`None`}`}var o=r(`REST`),s=class{constructor(e){this.config=e,this.schemaVersion=7,this.retryOptions=e.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,o.info(`Using REST transport`)}getRestBaseUrl(){return this._isProxyMode()?`${window.location.origin}${n}`:(this.config.restApiUrl||`${this.config.cmsUrl}${n}`).replace(/\/+$/,``)}_isProxyMode(){return typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)}_cacheSet(e,t,n){if(this._etags.size>=this._maxCacheSize){let e=this._etags.keys().next().value;this._etags.delete(e),this._responseCache.delete(e)}this._etags.set(e,t),this._responseCache.set(e,n)}async _authenticate(){let e=`${this.getRestBaseUrl()}/auth`;o.debug(`Authenticating...`);let n=await t(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})},this.retryOptions);if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`Auth failed: ${n.status} ${n.statusText} ${e}`)}let r=await n.json();this._token=r.token,this._displayId=r.displayId,this._tokenExpiresAt=Date.now()+(r.expiresIn-60)*1e3,o.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(e,n={},r=!1){let i=await this._getToken(),a=new URL(`${this.getRestBaseUrl()}${e}`);for(let[e,t]of Object.entries(n))a.searchParams.set(e,String(t));let s=e,c={Authorization:`Bearer ${i}`},l=this._etags.get(s);l&&(c[`If-None-Match`]=l),o.debug(`GET ${e}`,n);let u=await t(a.toString(),{method:`GET`,headers:c},this.retryOptions);if(u.status===401){if(r)throw Error(`REST GET ${e} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restGet(e,n,!0)}if(u.status===304){let t=this._responseCache.get(s);if(t)return o.debug(`${e} → 304 (using cache)`),t}if(!u.ok){let t=await u.text().catch(()=>``);throw Error(`REST GET ${e} failed: ${u.status} ${u.statusText} ${t}`)}let d=u.headers.get(`Content-Type`)||``,f;f=d.includes(`application/json`)?await u.json():await u.text();let p=u.headers.get(`ETag`);return p&&this._cacheSet(s,p,f),f}async restSend(e,n,r={},i=!1){let a=await this._getToken(),s=new URL(`${this.getRestBaseUrl()}${n}`);o.debug(`${e} ${n}`);let c=await t(s.toString(),{method:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${a}`},body:JSON.stringify(r)},this.retryOptions);if(c.status===401){if(i)throw Error(`REST ${e} ${n} failed: 401 Unauthorized (after re-auth)`);return this._token=null,this.restSend(e,n,r,!0)}if(!c.ok){let t=await c.text().catch(()=>``);throw Error(`REST ${e} ${n} failed: ${c.status} ${c.statusText} ${t}`)}return(c.headers.get(`Content-Type`)||``).includes(`application/json`)?await c.json():await c.text()}async registerDisplay(){await this._getToken();let e=typeof navigator<`u`?`${navigator.platform} ${navigator.userAgent}`:`unknown`,t=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:e,macAddress:this.config.macAddress||`n/a`,xmrChannel:this.config.xmrChannel||``,xmrPubKey:this.config.xmrPubKey||``});return this._parseRegisterDisplayJson(t)}_parseRegisterDisplayJson(e){let t=e.display||e,n=t[`@attributes`]||{},r=n.code||t.code,i=n.message||t.message||``;if(r!==`READY`)return{code:r,message:i,settings:null};let a={},o=[],s=[];for(let[e,n]of Object.entries(t))if(!(e===`@attributes`||e===`file`)){if(e===`commands`){Array.isArray(n)&&(s=n.map(e=>({commandCode:e.code||e.commandCode||``,commandString:e.commandString||``})));continue}if(e===`tags`){let e=e=>typeof e==`object`?e.tag||e.value||``:String(e);if(Array.isArray(n))o=n.map(e).filter(Boolean);else if(n&&typeof n==`object`){let t=e(n);t&&(o=[t])}else typeof n==`string`&&n&&(o=[n]);continue}a[e]=typeof n==`object`?JSON.stringify(n):String(n)}let c=n.checkRf||``,l=n.checkSchedule||``,u={date:n.date||t.date||null,timezone:n.timezone||t.timezone||null,status:n.status||t.status||null,localDate:n.localDate||t.localDate||null,version_instructions:n.version_instructions||t.version_instructions||null},d=t.syncConfig||(t.syncGroup?{syncGroup:String(t.syncGroup),syncPublisherPort:parseInt(t.syncPublisherPort||`9590`,10),syncSwitchDelay:parseInt(t.syncSwitchDelay||`750`,10),syncVideoPauseDelay:parseInt(t.syncVideoPauseDelay||`100`,10),isLead:String(t.syncGroup)===`lead`}:null);return{code:r,message:i,settings:a,tags:o,commands:s,displayAttrs:u,checkRf:c,checkSchedule:l,syncConfig:d}}async requiredFiles(){let e=await this.restGet(`/displays/${this._displayId}/media`);return this._parseRequiredFilesV2(e)}_parseRequiredFilesV2(e){let t=[];for(let n of e.media||[])t.push({type:n.type||`media`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:n.saveAs||null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.layouts||[])t.push({type:`layout`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null});for(let n of e.widgets||[])t.push({type:`dataset`,id:n.id==null?null:String(n.id),size:0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:null,code:null,layoutid:null,regionid:null,mediaid:null,updateInterval:n.updateInterval||0});for(let n of e.dependencies||[])t.push({type:`static`,id:n.id==null?null:String(n.id),size:n.fileSize||0,md5:n.md5||null,download:`http`,path:n.url||null,saveAs:null,fileType:n.type||null,code:null,layoutid:null,regionid:null,mediaid:null});return{files:t,purge:[]}}async schedule(){return this.restGet(`/displays/${this._displayId}/schedule`)}async getResource(e,t,n){return this.restGet(`/widgets/${e}/${t}/${n}`)}async notifyStatus(e){return await a(e),this.restSend(`PUT`,`/displays/${this._displayId}/status`,{statusData:e})}async mediaInventory(e){let t=Array.isArray(e)?{inventoryItems:e}:{inventory:e};return this.restSend(`PUT`,`/displays/${this._displayId}/inventory`,t)}async blackList(e,t,n){return o.warn(`BlackList not available in v2 API (${t}/${e}: ${n})`),!1}async submitLog(e,t=null){let n=Array.isArray(e)?{logs:e}:{logXml:e};return(await this.restSend(`POST`,`/displays/${this._displayId}/logs`,n))?.success===!0}async submitScreenShot(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/screenshot`,{screenshot:e}))?.success===!0}async submitStats(e,t=null){try{let t=Array.isArray(e)?{stats:e}:{statXml:e},n=(await this.restSend(`POST`,`/displays/${this._displayId}/stats`,t))?.success===!0;return o.info(`SubmitStats result: ${n}`),n}catch(e){throw o.error(`SubmitStats failed:`,e),e}}async reportFaults(e){return(await this.restSend(`POST`,`/displays/${this._displayId}/faults`,{fault:e}))?.success===!0}async getWeather(){return this.restGet(`/displays/${this._displayId}/weather`)}static async isAvailable(e,r){try{let i=`${typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)?``:e.replace(/\/+$/,``)}${n}/health`,a=r?.timeoutMs||8e3,o={method:`GET`};typeof AbortSignal<`u`&&AbortSignal.timeout&&(o.signal=AbortSignal.timeout(a));let s=await t(i,o,r||{maxRetries:0});if(!s.ok)return!1;let c=await s.json();return c.version===2&&c.status===`ok`}catch{return!1}}};function c(e){let t=[];for(let n of e.children)n.tagName===`criteria`&&t.push({metric:n.getAttribute(`metric`)||``,condition:n.getAttribute(`condition`)||``,type:n.getAttribute(`type`)||`string`,value:n.textContent||``});return t}function l(e){let t=new DOMParser().parseFromString(e,`text/xml`),n={default:null,defaultDependants:[],dependants:[],layouts:[],campaigns:[],overlays:[],actions:[],commands:[],dataConnectors:[]},r=t.querySelector(`schedule`);if(r){let e=Array.from(r.children).filter(e=>e.tagName===`dependants`);for(let t of e)if(t.parentElement===r)for(let e of t.querySelectorAll(`file`))e.textContent&&n.dependants.push(e.textContent)}let i=t.querySelector(`default`);if(i){n.default=i.getAttribute(`file`);let e=i.querySelectorAll(`dependants > file`);e.length>0&&(n.defaultDependants=[...e].map(e=>e.textContent))}for(let e of t.querySelectorAll(`campaign`)){let t={id:e.getAttribute(`id`),priority:parseInt(e.getAttribute(`priority`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:c(e),layouts:[]};for(let n of e.querySelectorAll(`layout`)){let e=n.getAttribute(`file`),r=n.querySelectorAll(`dependants > file`);t.layouts.push({id:String(e),file:e,fromdt:n.getAttribute(`fromdt`)||t.fromdt,todt:n.getAttribute(`todt`)||t.todt,scheduleid:t.scheduleid,priority:t.priority,campaignId:t.id,maxPlaysPerHour:parseInt(n.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:n.getAttribute(`isGeoAware`)===`1`,geoLocation:n.getAttribute(`geoLocation`)||``,syncEvent:n.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(n.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(n.getAttribute(`duration`)||`0`),cyclePlayback:n.getAttribute(`cyclePlayback`)===`1`,groupKey:n.getAttribute(`groupKey`)||null,playCount:parseInt(n.getAttribute(`playCount`)||`0`),dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:c(n)})}n.campaigns.push(t)}for(let e of t.querySelectorAll(`schedule > layout`)){let t=e.getAttribute(`file`),r=e.querySelectorAll(`dependants > file`);n.layouts.push({id:String(t),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),scheduleid:e.getAttribute(`scheduleid`),priority:parseInt(e.getAttribute(`priority`)||`0`),campaignId:null,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,shareOfVoice:parseInt(e.getAttribute(`shareOfVoice`)||`0`),duration:parseInt(e.getAttribute(`duration`)||`0`),cyclePlayback:e.getAttribute(`cyclePlayback`)===`1`,groupKey:e.getAttribute(`groupKey`)||null,playCount:parseInt(e.getAttribute(`playCount`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,dependants:r.length>0?[...r].map(e=>e.textContent):[],criteria:c(e)})}let a=t.querySelector(`overlays`);if(a)for(let e of a.querySelectorAll(`overlay`)){let t=e.getAttribute(`file`);n.overlays.push({id:String(t),duration:parseInt(e.getAttribute(`duration`)||`60`),file:t,fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``,syncEvent:e.getAttribute(`syncEvent`)===`1`,maxPlaysPerHour:parseInt(e.getAttribute(`maxPlaysPerHour`)||`0`),recurrenceType:e.getAttribute(`recurrenceType`)||null,recurrenceDetail:parseInt(e.getAttribute(`recurrenceDetail`)||`0`)||null,recurrenceRepeatsOn:e.getAttribute(`recurrenceRepeatsOn`)||null,recurrenceRange:e.getAttribute(`recurrenceRange`)||null,criteria:c(e)})}let o=t.querySelector(`actions`);if(o)for(let e of o.querySelectorAll(`action`))n.actions.push({actionType:e.getAttribute(`actionType`)||``,triggerCode:e.getAttribute(`triggerCode`)||``,layoutCode:e.getAttribute(`layoutCode`)||``,commandCode:e.getAttribute(`commandCode`)||``,duration:parseInt(e.getAttribute(`duration`)||`0`),fromdt:e.getAttribute(`fromdt`),todt:e.getAttribute(`todt`),priority:parseInt(e.getAttribute(`priority`)||`0`),scheduleid:e.getAttribute(`scheduleid`),isGeoAware:e.getAttribute(`isGeoAware`)===`1`,geoLocation:e.getAttribute(`geoLocation`)||``});for(let e of t.querySelectorAll(`schedule > command`))n.commands.push({code:e.getAttribute(`code`)||``,date:e.getAttribute(`date`)||``});let s=t.querySelector(`dataConnectors`);if(s)for(let e of s.querySelectorAll(`connector`))n.dataConnectors.push({id:e.getAttribute(`id`)||``,dataConnectorId:e.getAttribute(`dataConnectorId`)||``,dataSetId:e.getAttribute(`dataSetId`)||``,dataKey:e.getAttribute(`dataKey`)||``,dataParams:e.getAttribute(`dataParams`)||``,js:e.getAttribute(`js`)||``,url:e.getAttribute(`url`)||``,updateInterval:parseInt(e.getAttribute(`updateInterval`)||`300`,10)});return n}var u=r(`XMDS`),d=class{constructor(e){this.config=e,this.schemaVersion=5,this.retryOptions=e.retryOptions||{maxRetries:2,baseDelayMs:2e3}}buildEnvelope(e,t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
2
2
|
<soap:Envelope
|
|
3
3
|
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
|
|
4
4
|
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
|
|
@@ -13,4 +13,4 @@ import{n as e}from"./chunk-7ZXdHUL4.js";import{r as t,t as n,u as r}from"./src-C
|
|
|
13
13
|
</tns:${e}>
|
|
14
14
|
</soap:Body>
|
|
15
15
|
</soap:Envelope>`}rewriteXmdsUrl(e){return typeof window<`u`&&(window.electronAPI?.isElectron||window.location.hostname===`localhost`)?`/xmds-proxy?cms=${encodeURIComponent(e)}`:`${e}/xmds.php`}async call(e,n={}){let r=this.rewriteXmdsUrl(this.config.cmsUrl),i=`${r}${r.includes(`?`)?`&`:`?`}v=${this.schemaVersion}&method=${e}`,a=this.buildEnvelope(e,n);u.debug(`${e}`,n),u.debug(`URL: ${i}`);let o=await t(i,{method:`POST`,headers:{"Content-Type":`text/xml; charset=utf-8`},body:a},this.retryOptions);if(!o.ok)throw Error(`XMDS ${e} failed: ${o.status} ${o.statusText}`);let s=await o.text();return this.parseResponse(s,e)}parseResponse(e,t){let n=new DOMParser().parseFromString(e,`text/xml`),r=n.querySelector(`Fault`);if(r||=Array.from(n.querySelectorAll(`*`)).find(e=>e.localName===`Fault`||e.tagName.endsWith(`:Fault`)),r){let e=r.querySelector(`faultstring`)?.textContent||Array.from(r.querySelectorAll(`*`)).find(e=>e.localName===`faultstring`)?.textContent||`Unknown SOAP fault`;throw Error(`SOAP Fault: ${e}`)}let i=`${t}Response`,a=n.querySelector(i);if(a||=Array.from(n.querySelectorAll(`*`)).find(e=>e.localName===i||e.tagName.endsWith(`:`+i)),!a)throw Error(`No ${i} element in SOAP response`);let o=a.firstElementChild;return o?o.textContent:null}async registerDisplay(){let e=`${navigator.platform} ${navigator.userAgent}`,t=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:e,macAddress:this.config.macAddress||`n/a`,xmrChannel:this.config.xmrChannel||``,xmrPubKey:this.config.xmrPubKey||``,licenceResult:`licensed`});return this.parseRegisterDisplayResponse(t)}parseRegisterDisplayResponse(e){let t=new DOMParser().parseFromString(e,`text/xml`).querySelector(`display`);if(!t)throw Error(`Invalid RegisterDisplay response: no <display> element`);let n=t.getAttribute(`code`),r=t.getAttribute(`message`);if(n!==`READY`)return{code:n,message:r,settings:null};let i={},a=[],o=[];for(let e of t.children){let t=e.tagName.toLowerCase();if(t!==`file`){if(t===`commands`){for(let t of e.querySelectorAll(`command`))o.push({commandCode:t.getAttribute(`code`)||t.getAttribute(`commandCode`)||``,commandString:t.getAttribute(`commandString`)||``});continue}if(t===`tags`){for(let t of e.querySelectorAll(`tag`))t.textContent&&a.push(t.textContent);continue}i[e.tagName]=e.textContent}}let s=t.getAttribute(`checkRf`)||``,c=t.getAttribute(`checkSchedule`)||``,l={date:t.getAttribute(`date`)||null,timezone:t.getAttribute(`timezone`)||null,status:t.getAttribute(`status`)||null,localDate:t.getAttribute(`localDate`)||null,version_instructions:t.getAttribute(`version_instructions`)||null},u=i.syncGroup||null;return{code:n,message:r,settings:i,tags:a,commands:o,displayAttrs:l,checkRf:s,checkSchedule:c,syncConfig:u?{syncGroup:u,syncPublisherPort:parseInt(i.syncPublisherPort||`9590`,10),syncSwitchDelay:parseInt(i.syncSwitchDelay||`750`,10),syncVideoPauseDelay:parseInt(i.syncVideoPauseDelay||`100`,10),isLead:u===`lead`}:null}}async requiredFiles(){let e=await this.call(`RequiredFiles`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey});return this.parseRequiredFilesResponse(e)}parseRequiredFilesResponse(e){let t=new DOMParser().parseFromString(e,`text/xml`),r=[];for(let e of t.querySelectorAll(`file`)){let t={type:e.getAttribute(`type`),id:e.getAttribute(`id`),size:parseInt(e.getAttribute(`size`)||`0`),md5:e.getAttribute(`md5`),download:e.getAttribute(`download`),path:e.getAttribute(`path`),saveAs:e.getAttribute(`saveAs`)||null,fileType:e.getAttribute(`fileType`)||null,code:e.getAttribute(`code`),layoutid:e.getAttribute(`layoutid`),regionid:e.getAttribute(`regionid`),mediaid:e.getAttribute(`mediaid`)};if(t.path&&t.path.includes(`xmds.php`)){t.cmsDownloadUrl=t.path;let e=t.fileType;e===`L`||t.type===`layout`?t.path=`${n}/layouts/${t.id}`:e===`P`?t.path=`${n}/dependencies/${t.saveAs||t.id}`:t.path=`${n}/media/file/${t.saveAs||t.id}`}r.push(t)}let i=[],a=t.querySelector(`purge`);if(a)for(let e of a.querySelectorAll(`item`))i.push({id:e.getAttribute(`id`),storedAs:e.getAttribute(`storedAs`)});return{files:r,purge:i}}async schedule(){return l(await this.call(`Schedule`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey}))}async getResource(e,t,n){return await this.call(`GetResource`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,layoutId:String(e),regionId:String(t),mediaId:String(n)})}async notifyStatus(e){return await a(e),await this.call(`NotifyStatus`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,status:JSON.stringify(e)})}async mediaInventory(e){return await this.call(`MediaInventory`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaInventory:e})}async blackList(e,t,n){try{let r=await this.call(`BlackList`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,mediaId:String(e),type:t||`media`,reason:n||`Failed to render`});return u.info(`BlackListed ${t}/${e}: ${n}`),r===`true`}catch(e){return u.warn(`BlackList failed:`,e),!1}}async submitLog(e,t=null){return await this.call(`SubmitLog`,{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,logXml:e})===`true`}async submitScreenShot(e){return await this.call(`SubmitScreenShot`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,screenShot:e})===`true`}async reportFaults(e){return this.call(`ReportFaults`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey,fault:e})}async getWeather(){return this.call(`GetWeather`,{serverKey:this.config.cmsKey,hardwareKey:this.config.hardwareKey})}async submitStats(e,t=null){try{let n=await this.call(`SubmitStats`,{serverKey:this.config.cmsKey,hardwareKey:t||this.config.hardwareKey,statXml:e})===`true`;return u.info(`SubmitStats result: ${n}`),n}catch(e){throw u.error(`SubmitStats failed:`,e),e}}},f=[`registerDisplay`,`requiredFiles`,`schedule`,`getResource`,`notifyStatus`,`mediaInventory`,`blackList`,`submitLog`,`submitScreenShot`,`submitStats`,`reportFaults`,`getWeather`];function p(e,t=`client`){for(let n of f)if(typeof e[n]!=`function`)throw Error(`${t} missing CmsClient method: ${n}()`)}var m=r(`Protocol`),h=1e4,g=5e3,_=5e3,v=12e4,y=2,b=class{constructor(e,t,n,r={}){this.cmsUrl=e,this.RestClient=t,this.XmdsClient=n;let i=r.probeTimeoutMs;this.firstProbeTimeoutMs=r.firstProbeTimeoutMs??i??h,this.reprobeTimeoutMs=r.reprobeTimeoutMs??i??g,this.reprobeMinDelayMs=r.reprobeMinDelayMs??_,this.reprobeMaxDelayMs=r.reprobeMaxDelayMs??v,this.protocol=null,this.lastProbeTime=0,this._reprobeTimer=null,this._reprobeDelay=this.reprobeMinDelayMs}async probe(e={}){let t=e.first?this.firstProbeTimeoutMs:this.reprobeTimeoutMs,n=await this.RestClient.isAvailable(this.cmsUrl,{maxRetries:0,timeoutMs:t});return this.lastProbeTime=Date.now(),n}async detect(e,t){if(t===`rest`){this.protocol=`rest`,m.info(`Using REST transport (forced)`);let t=new this.RestClient(e);return p(t,`RestClient`),{client:t,protocol:`rest`}}if(t===`xmds`){this.protocol=`xmds`,m.info(`Using XMDS/SOAP transport (forced)`);let t=new this.XmdsClient(e);return p(t,`XmdsClient`),{client:t,protocol:`xmds`}}m.info(`Probing CMS for REST API availability (timeout ${this.firstProbeTimeoutMs}ms)...`);let n=!1;try{n=await this.probe({first:!0})}catch(e){m.warn(`REST probe failed:`,e?.message||e)}if(n){this.protocol=`rest`,m.info(`REST transport detected — using PlayerRestApi`);let t=new this.RestClient(e);return p(t,`RestClient`),{client:t,protocol:`rest`}}this.protocol=`xmds`,m.warn(`REST unavailable — falling back to XMDS/SOAP transport`);let r=new this.XmdsClient(e);return p(r,`XmdsClient`),{client:r,protocol:`xmds`}}async reprobe(e){let t=this.protocol,n=!1;try{n=await this.probe({first:!1})}catch(e){m.warn(`Re-probe failed:`,e?.message||e)}let r=n?`rest`:`xmds`;if(r!==t){m.info(`Protocol changed: ${t} → ${r}`),this.protocol=r;let i=n?new this.RestClient(e):new this.XmdsClient(e);return p(i,n?`RestClient`:`XmdsClient`),{client:i,protocol:r,changed:!0}}return{client:null,protocol:r,changed:!1}}startAutoReprobe(e,t){if(this.protocol!==`xmds`)return;this.stopAutoReprobe(),this._reprobeDelay=this.reprobeMinDelayMs;let n=()=>{let r=this._reprobeDelay;this._reprobeTimer=setTimeout(async()=>{this._reprobeTimer=null;let r;try{r=await this.reprobe(e)}catch(e){m.warn(`Auto-reprobe error:`,e?.message||e),r={changed:!1,protocol:`xmds`,client:null}}if(r.changed&&r.protocol===`rest`){m.info(`REST recovered — promoting back from XMDS fallback`),this._reprobeDelay=this.reprobeMinDelayMs;try{t(r.client)}catch(e){m.warn(`onRestPromoted callback threw:`,e?.message||e)}return}let i=Math.min(this._reprobeDelay*y,this.reprobeMaxDelayMs);m.warn(`Still on XMDS fallback — REST probe failed, next attempt in ${Math.round(i/1e3)}s`),this._reprobeDelay=i,n()},r)};m.info(`Auto-reprobe scheduled — first attempt in ${Math.round(this._reprobeDelay/1e3)}s (backoff up to ${Math.round(this.reprobeMaxDelayMs/1e3)}s)`),n()}stopAutoReprobe(){this._reprobeTimer&&=(clearTimeout(this._reprobeTimer),null),this._reprobeDelay=this.reprobeMinDelayMs}getProtocol(){return this.protocol}},x=e({CMS_CLIENT_METHODS:()=>f,ProtocolDetector:()=>b,RestClient:()=>s,VERSION:()=>S,XmdsClient:()=>d,assertCmsClient:()=>p,parseScheduleResponse:()=>l}),S=i.version;export{d as n,s as r,x as t};
|
|
16
|
-
//# sourceMappingURL=src-
|
|
16
|
+
//# sourceMappingURL=src-BbJ9IAbR.js.map
|