@xiboplayer/pwa 0.5.1 → 0.5.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/README.md +1 -0
- package/dist/assets/cms-api-B3gEu-pj.js +5 -0
- package/dist/assets/cms-api-B3gEu-pj.js.map +1 -0
- package/dist/assets/{index-pcbcUHVR.js → index-BCL7JKFz.js} +2 -2
- package/dist/assets/{index-pcbcUHVR.js.map → index-BCL7JKFz.js.map} +1 -1
- package/dist/assets/{index-CCUivrBn.js → index-CKuRgFp6.js} +2 -2
- package/dist/assets/{index-CCUivrBn.js.map → index-CKuRgFp6.js.map} +1 -1
- package/dist/assets/index-CpeXG_hc.js +2 -0
- package/dist/assets/{index-_Kvq-_Zm.js.map → index-CpeXG_hc.js.map} +1 -1
- package/dist/assets/{index-C7MNhxyH.js → index-CzhSvB4B.js} +2 -2
- package/dist/assets/{index-C7MNhxyH.js.map → index-CzhSvB4B.js.map} +1 -1
- package/dist/assets/{index-Do4yVSNc.js → index-DA3or6a6.js} +2 -2
- package/dist/assets/{index-Do4yVSNc.js.map → index-DA3or6a6.js.map} +1 -1
- package/dist/assets/index-DByQCT0-.js +2 -0
- package/dist/assets/{index-BHmOBAZo.js.map → index-DByQCT0-.js.map} +1 -1
- package/dist/assets/{index-Bk3xGi9A.js → index-DPcIXGuN.js} +2 -2
- package/dist/assets/{index-Bk3xGi9A.js.map → index-DPcIXGuN.js.map} +1 -1
- package/dist/assets/{index-DaTnG3Ri.js → index-DiLroK9-.js} +2 -2
- package/dist/assets/{index-DaTnG3Ri.js.map → index-DiLroK9-.js.map} +1 -1
- package/dist/assets/index-m5gp9Gft.js +2 -0
- package/dist/assets/{index-D1vit3S3.js.map → index-m5gp9Gft.js.map} +1 -1
- package/dist/assets/{main-B65Xrh0d.js → main-DfHNWLGS.js} +4 -4
- package/dist/assets/{main-B65Xrh0d.js.map → main-DfHNWLGS.js.map} +1 -1
- package/dist/assets/{setup-Byd6qu0w.js → setup-D67k289O.js} +2 -2
- package/dist/assets/{setup-Byd6qu0w.js.map → setup-D67k289O.js.map} +1 -1
- package/dist/assets/{sync-manager-Dm6IKYtR.js → sync-manager-DBfiw5Ey.js} +2 -2
- package/dist/assets/{sync-manager-Dm6IKYtR.js.map → sync-manager-DBfiw5Ey.js.map} +1 -1
- package/dist/assets/{widget-html-Cb84FvUB.js → widget-html-B_acad6q.js} +2 -2
- package/dist/assets/{widget-html-Cb84FvUB.js.map → widget-html-B_acad6q.js.map} +1 -1
- package/dist/assets/xmds-client-Ci6s-34Q.js +16 -0
- package/dist/assets/xmds-client-Ci6s-34Q.js.map +1 -0
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/dist/sw-pwa.js.map +1 -1
- package/package.json +13 -13
- package/dist/assets/cms-api-Cqh1b8je.js +0 -5
- package/dist/assets/cms-api-Cqh1b8je.js.map +0 -1
- package/dist/assets/index-BHmOBAZo.js +0 -2
- package/dist/assets/index-D1vit3S3.js +0 -2
- package/dist/assets/index-_Kvq-_Zm.js +0 -2
- package/dist/assets/xmds-client-BPdCcQeh.js +0 -16
- package/dist/assets/xmds-client-BPdCcQeh.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./modulepreload-polyfill-B5Qt9EMX.js";import{b as e,C as D}from"./cms-api-
|
|
2
|
-
//# sourceMappingURL=setup-
|
|
1
|
+
import"./modulepreload-polyfill-B5Qt9EMX.js";import{b as e,C as D}from"./cms-api-B3gEu-pj.js";import{R as A,X as K}from"./xmds-client-Ci6s-34Q.js";const P="0.5.2";document.getElementById("version-footer").textContent=`Xibo Player v${P}`;const L=document.getElementById("setup-form"),y=document.getElementById("error"),c=document.getElementById("submit-btn"),w=document.getElementById("phase-unlock"),f=document.getElementById("phase-setup"),B=document.getElementById("phase-waiting"),v=document.getElementById("countdown"),R=document.getElementById("waiting-display-name"),U=document.getElementById("btn-back"),N=document.getElementById("success-flash"),I=e.hardwareKey;document.getElementById("hw-key-display").textContent=I;document.getElementById("hw-key-waiting").textContent=I;let u=null,s=null,k=15,i=null;async function E(){if(i)return i;try{const t=new A(e);await t.registerDisplay(),console.log("[Setup] Using REST transport"),i=t}catch(t){console.log("[Setup] REST unavailable, using XMDS/SOAP:",t.message),i=new K(e)}return i}function m(t){w.classList.remove("active"),f.classList.remove("active"),B.classList.remove("active"),t.classList.add("active")}function z(t){y.textContent=t,y.style.display="block"}function T(){y.style.display="none"}function p(){let t=k;v.textContent=t,clearInterval(s),s=setInterval(()=>{t--,v.textContent=Math.max(0,t),t<=0&&clearInterval(s)},1e3)}function g(){N.classList.add("active"),setTimeout(()=>{window.location.href="./index.html"},800)}async function X(){try{const n=await(await E()).registerDisplay();if(console.log("[Setup] Poll result:",n.code,n.message),n.code==="READY"){clearInterval(u),clearInterval(s),g();return}p()}catch(t){console.warn("[Setup] Poll failed:",t.message),p()}}function C(t){R.textContent=t,m(B),p(),u=setInterval(X,k*1e3)}function b(){clearInterval(u),clearInterval(s),u=null}async function Y(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=new D({baseUrl:t,clientId:a,clientSecret:o});await l.authenticate();const d=await l.findDisplay(n);return d?d.licensed===1?(console.log("[Setup] Display already authorized"),!0):(await l.authorizeDisplay(d.displayId),console.log("[Setup] Display auto-authorized via API!"),e.apiClientId=a,e.apiClientSecret=o,!0):(console.log("[Setup] Display not found via API (may not be registered yet)"),!1)}catch(l){return console.warn("[Setup] Auto-authorize failed:",l.message),!1}}const r=e.isConfigured()&&e.cmsKey,h=new URLSearchParams(window.location.search).has("unlocked"),S=document.getElementById("btn-back-player");r&&!h&&m(w);(r||h)&&(S.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 x(){b(),window.location.href="./index.html"}S.addEventListener("click",x);(r||h)&&document.addEventListener("keydown",t=>{t.key==="Escape"&&(t.preventDefault(),x())});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||""),m(f)):(n.textContent="Incorrect CMS key",n.style.display="block")});!r&&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||""));L.addEventListener("submit",async t=>{t.preventDefault(),T();const n=document.getElementById("cms-url").value.trim().replace(/\/$/,""),a=document.getElementById("cms-key").value.trim(),o=document.getElementById("display-name").value.trim();e.cmsUrl=n,e.cmsKey=a,e.displayName=o,j(e.hardwareKey);try{c.textContent="Connecting...",c.disabled=!0,i=null;const l=await E();if((await l.registerDisplay()).code==="READY")g();else{if(c.textContent="Authorizing...",await Y(n,I)&&(await l.registerDisplay()).code==="READY"){g();return}C(o)}}catch(l){z(`Connection failed: ${l.message}`),c.textContent="Connect",c.disabled=!1}});U.addEventListener("click",()=>{b(),m(f),c.textContent="Connect",c.disabled=!1});async function j(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()&&!r&&(async()=>{try{(await(await E()).registerDisplay()).code==="READY"?window.location.href="./index.html":C(e.displayName)}catch{console.log("[Setup] Auto-check failed, showing form")}})();
|
|
2
|
+
//# sourceMappingURL=setup-D67k289O.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"setup-Byd6qu0w.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config, CmsApiClient } 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 = `Xibo Player 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 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 function showSuccess() {\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = './index.html';\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 ──\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 const api = new CmsApiClient({ baseUrl: cmsUrl, clientId, clientSecret });\n await api.authenticate();\n\n const display = await api.findDisplay(hardwareKey);\n if (!display) {\n console.log('[Setup] Display not found via API (may not be registered yet)');\n return false;\n }\n\n if (display.licensed === 1) {\n console.log('[Setup] Display already authorized');\n return true;\n }\n\n // Auto-authorize\n await api.authorizeDisplay(display.displayId);\n console.log('[Setup] Display auto-authorized via API!');\n\n // Save API credentials for future use\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n\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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = './index.html';\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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.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 // Save config\n config.cmsUrl = cmsUrl;\n config.cmsKey = cmsKey;\n config.displayName = displayName;\n\n // Also backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n try {\n submitBtn.textContent = 'Connecting...';\n submitBtn.disabled = true;\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 // 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 = './index.html';\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 "],"names":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","api","CmsApiClient","display","isReconfigure","alreadyUnlocked","btnBackPlayer","goBackToPlayer","unlockError","cmsKey","backupHardwareKey","client","key","req","db","tx"],"mappings":"mJAKI,MAAMA,EAAsD,QAC5D,SAAS,eAAe,gBAAgB,EAAE,YAAc,gBAAgBA,CAAU,GAGlF,MAAMC,EAAO,SAAS,eAAe,YAAY,EAC3CC,EAAU,SAAS,eAAe,OAAO,EACzCC,EAAY,SAAS,eAAe,YAAY,EAChDC,EAAc,SAAS,eAAe,cAAc,EACpDC,EAAa,SAAS,eAAe,aAAa,EAClDC,EAAe,SAAS,eAAe,eAAe,EACtDC,EAAc,SAAS,eAAe,WAAW,EACjDC,EAAgB,SAAS,eAAe,sBAAsB,EAC9DC,EAAU,SAAS,eAAe,UAAU,EAC5CC,EAAe,SAAS,eAAe,eAAe,EAGtDC,EAAQC,EAAO,YACrB,SAAS,eAAe,gBAAgB,EAAE,YAAc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Y,MAAM,EAAE,IAAIH,EAAK,aAAa,EAC7CG,EAAG,WAAa,IAAMD,EAAG,MAAA,CAC3B,CACF,OAASlC,EAAG,CACV,QAAQ,KAAK,mCAAoCA,CAAC,CACpD,CACF,CAGAjB,EAAU,SAAW,GACrBA,EAAU,YAAc,UAIpBS,EAAO,gBAAkB,CAACgC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM3B,EAAA,GACO,gBAAA,GACjB,OAAS,QAClB,OAAO,SAAS,KAAO,eAGvBgB,EAAarB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
|
|
1
|
+
{"version":3,"file":"setup-D67k289O.js","sources":["../../setup.html?html-proxy&index=1.js"],"sourcesContent":["\n import { config, CmsApiClient } 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 = `Xibo Player 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 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 function showSuccess() {\n successFlash.classList.add('active');\n setTimeout(() => {\n window.location.href = './index.html';\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 ──\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 const api = new CmsApiClient({ baseUrl: cmsUrl, clientId, clientSecret });\n await api.authenticate();\n\n const display = await api.findDisplay(hardwareKey);\n if (!display) {\n console.log('[Setup] Display not found via API (may not be registered yet)');\n return false;\n }\n\n if (display.licensed === 1) {\n console.log('[Setup] Display already authorized');\n return true;\n }\n\n // Auto-authorize\n await api.authorizeDisplay(display.displayId);\n console.log('[Setup] Display auto-authorized via API!');\n\n // Save API credentials for future use\n config.apiClientId = clientId;\n config.apiClientSecret = clientSecret;\n\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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.apiClientSecret || '';\n }\n }\n\n // ── Back to Player (cancel reconfiguration) ──\n function goBackToPlayer() {\n stopPolling();\n window.location.href = './index.html';\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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.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.apiClientId) {\n document.getElementById('api-client-id').value = config.apiClientId;\n document.getElementById('api-client-secret').value = config.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 // Save config\n config.cmsUrl = cmsUrl;\n config.cmsKey = cmsKey;\n config.displayName = displayName;\n\n // Also backup hardware key to IndexedDB for stability\n backupHardwareKey(config.hardwareKey);\n\n // Test connection\n try {\n submitBtn.textContent = 'Connecting...';\n submitBtn.disabled = true;\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 // 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 = './index.html';\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 "],"names":["appVersion","form","errorEl","submitBtn","phaseUnlock","phaseSetup","phaseWaiting","countdownEl","waitingNameEl","btnBack","successFlash","hwKey","config","pollTimer","countdownTimer","pollSeconds","transport","getTransport","rest","RestClient","e","XmdsClient","showPhase","phase","showError","msg","hideError","startCountdown","remaining","showSuccess","checkAuthorization","result","error","startPolling","displayName","stopPolling","tryAutoAuthorize","cmsUrl","hardwareKey","clientId","clientSecret","api","CmsApiClient","display","isReconfigure","alreadyUnlocked","btnBackPlayer","goBackToPlayer","unlockError","cmsKey","backupHardwareKey","client","key","req","db","tx"],"mappings":"mJAKI,MAAMA,EAAsD,QAC5D,SAAS,eAAe,gBAAgB,EAAE,YAAc,gBAAgBA,CAAU,GAGlF,MAAMC,EAAO,SAAS,eAAe,YAAY,EAC3CC,EAAU,SAAS,eAAe,OAAO,EACzCC,EAAY,SAAS,eAAe,YAAY,EAChDC,EAAc,SAAS,eAAe,cA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AAU,KAAK,iBAAkB,CAAC,EAC9CA,EAAI,gBAAkB,IAAM,CAC1B,MAAMC,EAAKD,EAAI,OACVC,EAAG,iBAAiB,SAAS,MAAM,GACtCA,EAAG,kBAAkB,MAAM,CAE/B,EACAD,EAAI,UAAY,IAAM,CACpB,MAAMC,EAAKD,EAAI,OACTE,EAAKD,EAAG,YAAY,OAAQ,WAAW,EAC7CC,EAAG,YAAY,MAAM,EAAE,IAAIH,EAAK,aAAa,EAC7CG,EAAG,WAAa,IAAMD,EAAG,MAAA,CAC3B,CACF,OAASlC,EAAG,CACV,QAAQ,KAAK,mCAAoCA,CAAC,CACpD,CACF,CAGAjB,EAAU,SAAW,GACrBA,EAAU,YAAc,UAIpBS,EAAO,gBAAkB,CAACgC,IAC3B,SAAY,CACX,GAAI,EAEa,MADA,MAAM3B,EAAA,GACO,gBAAA,GACjB,OAAS,QAClB,OAAO,SAAS,KAAO,eAGvBgB,EAAarB,EAAO,WAAW,CAEnC,MAAY,CAEV,QAAQ,IAAI,yCAAyC,CACvD,CACF,GAAA"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as n}from"./cms-api-
|
|
2
|
-
//# sourceMappingURL=sync-manager-
|
|
1
|
+
import{c as n}from"./cms-api-B3gEu-pj.js";const r="xibo-sync",l=5e3,i=15e3,d=1e4;class f{constructor(t){this.displayId=t.displayId,this.syncConfig=t.syncConfig,this.isLead=t.syncConfig.isLead,this.switchDelay=t.syncConfig.syncSwitchDelay||750,this.videoPauseDelay=t.syncConfig.syncVideoPauseDelay||100,this.onLayoutChange=t.onLayoutChange||(()=>{}),this.onLayoutShow=t.onLayoutShow||(()=>{}),this.onVideoStart=t.onVideoStart||(()=>{}),this.onStatsReport=t.onStatsReport||null,this.onLogsReport=t.onLogsReport||null,this.onStatsAck=t.onStatsAck||null,this.onLogsAck=t.onLogsAck||null,this.channel=null,this.followers=new Map,this._heartbeatTimer=null,this._cleanupTimer=null,this._readyResolve=null,this._pendingLayoutId=null,this._started=!1,this._tag=this.isLead?"[Sync:LEAD]":"[Sync:FOLLOW]",this._log=n(this.isLead?"Sync:LEAD":"Sync:FOLLOW")}start(){if(!this._started){if(this._started=!0,typeof BroadcastChannel>"u"){this._log.warn("BroadcastChannel not available — sync disabled");return}this.channel=new BroadcastChannel(r),this.channel.onmessage=t=>this._handleMessage(t.data),this._heartbeatTimer=setInterval(()=>this._sendHeartbeat(),l),this._sendHeartbeat(),this.isLead&&(this._cleanupTimer=setInterval(()=>this._cleanupStaleFollowers(),l)),this._log.info("Started. DisplayId:",this.displayId)}}stop(){this._started&&(this._started=!1,this._heartbeatTimer&&(clearInterval(this._heartbeatTimer),this._heartbeatTimer=null),this._cleanupTimer&&(clearInterval(this._cleanupTimer),this._cleanupTimer=null),this.channel&&(this.channel.close(),this.channel=null),this.followers.clear(),this._log.info("Stopped"))}async requestLayoutChange(t){if(!this.isLead){this._log.warn("requestLayoutChange called on follower — ignoring");return}t=String(t),this._pendingLayoutId=t;for(const[,a]of this.followers)a.ready=!1,a.readyLayoutId=null;const e=Date.now()+this.switchDelay;this._log.info(`Requesting layout change: ${t} (show at ${new Date(e).toISOString()}, ${this.followers.size} followers)`),this._send({type:"layout-change",layoutId:t,showAt:e,displayId:this.displayId}),this.followers.size>0&&await this._waitForFollowersReady(t);const s=e-Date.now();s>0&&await new Promise(a=>setTimeout(a,s)),this._log.info(`Sending layout-show: ${t}`),this._send({type:"layout-show",layoutId:t,displayId:this.displayId}),this.onLayoutShow(t),this._pendingLayoutId=null}async requestVideoStart(t,e){this.isLead&&(await new Promise(s=>setTimeout(s,this.videoPauseDelay)),this._send({type:"video-start",layoutId:String(t),regionId:e,displayId:this.displayId}),this.onVideoStart(String(t),e))}reportReady(t){t=String(t),this._log.info(`Reporting ready for layout ${t}`),this._send({type:"layout-ready",layoutId:t,displayId:this.displayId})}reportStats(t){this.isLead||(this._log.info("Delegating stats to lead"),this._send({type:"stats-report",displayId:this.displayId,statsXml:t}))}reportLogs(t){this.isLead||(this._log.info("Delegating logs to lead"),this._send({type:"logs-report",displayId:this.displayId,logsXml:t}))}_handleMessage(t){if(t.displayId!==this.displayId)switch(t.type){case"heartbeat":this._handleHeartbeat(t);break;case"layout-change":this.isLead||(this._log.info(`Layout change requested: ${t.layoutId}`),this.onLayoutChange(t.layoutId,t.showAt));break;case"layout-ready":this.isLead&&this._handleFollowerReady(t);break;case"layout-show":this.isLead||(this._log.info(`Layout show signal: ${t.layoutId}`),this.onLayoutShow(t.layoutId));break;case"video-start":this.isLead||(this._log.info(`Video start signal: ${t.layoutId} region ${t.regionId}`),this.onVideoStart(t.layoutId,t.regionId));break;case"stats-report":if(this.isLead&&this.onStatsReport){const e=()=>this._send({type:"stats-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onStatsReport(t.displayId,t.statsXml,e)}break;case"logs-report":if(this.isLead&&this.onLogsReport){const e=()=>this._send({type:"logs-ack",displayId:this.displayId,targetDisplayId:t.displayId});this.onLogsReport(t.displayId,t.logsXml,e)}break;case"stats-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onStatsAck&&(this._log.info("Stats acknowledged by lead"),this.onStatsAck(t.targetDisplayId));break;case"logs-ack":!this.isLead&&t.targetDisplayId===this.displayId&&this.onLogsAck&&(this._log.info("Logs acknowledged by lead"),this.onLogsAck(t.targetDisplayId));break;default:this._log.warn("Unknown message type:",t.type)}}_handleHeartbeat(t){const e=this.followers.get(t.displayId);e?e.lastSeen=Date.now():(this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!1,readyLayoutId:null,role:t.role||"unknown"}),this._log.info(`Follower joined: ${t.displayId} (${this.followers.size} total)`))}_handleFollowerReady(t){const e=this.followers.get(t.displayId);e?(e.ready=!0,e.readyLayoutId=t.layoutId,e.lastSeen=Date.now()):this.followers.set(t.displayId,{lastSeen:Date.now(),ready:!0,readyLayoutId:t.layoutId}),this._log.info(`Follower ${t.displayId} ready for layout ${t.layoutId}`),this._pendingLayoutId===t.layoutId&&this._readyResolve&&this._allFollowersReady(t.layoutId)&&(this._log.info("All followers ready"),this._readyResolve(),this._readyResolve=null)}_allFollowersReady(t){for(const[,e]of this.followers)if(!(Date.now()-e.lastSeen>i)&&(!e.ready||e.readyLayoutId!==t))return!1;return!0}_waitForFollowersReady(t){return new Promise(e=>{if(this._allFollowersReady(t)){e();return}this._readyResolve=e,setTimeout(()=>{if(this._readyResolve===e){const s=[];for(const[a,o]of this.followers)(!o.ready||o.readyLayoutId!==t)&&s.push(a);this._log.warn(`Ready timeout — proceeding without: ${s.join(", ")}`),this._readyResolve=null,e()}},d)})}_sendHeartbeat(){this._send({type:"heartbeat",displayId:this.displayId,role:this.isLead?"lead":"follower",timestamp:Date.now()})}_cleanupStaleFollowers(){const t=Date.now();for(const[e,s]of this.followers)t-s.lastSeen>i&&(this._log.info(`Removing stale follower: ${e} (last seen ${Math.round((t-s.lastSeen)/1e3)}s ago)`),this.followers.delete(e))}_send(t){if(this.channel)try{this.channel.postMessage(t)}catch(e){this._log.error("Failed to send:",e)}}getStatus(){return{started:this._started,isLead:this.isLead,displayId:this.displayId,followers:this.followers.size,pendingLayoutId:this._pendingLayoutId,followerDetails:Array.from(this.followers.entries()).map(([t,e])=>({displayId:t,lastSeen:e.lastSeen,ready:e.ready,readyLayoutId:e.readyLayoutId,stale:Date.now()-e.lastSeen>i}))}}}export{f as SyncManager};
|
|
2
|
+
//# sourceMappingURL=sync-manager-DBfiw5Ey.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-manager-Dm6IKYtR.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.4.9/node_modules/@xiboplayer/sync/src/sync-manager.js"],"sourcesContent":["/**\n * SyncManager - Multi-display synchronization via BroadcastChannel\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * on the same machine (video wall, multi-monitor setups).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (unused in browser, kept for compat)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst CHANNEL_NAME = 'xibo-sync';\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n\n // State\n this.channel = null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager (opens BroadcastChannel, begins heartbeats)\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n if (typeof BroadcastChannel === 'undefined') {\n this._log.warn( 'BroadcastChannel not available — sync disabled');\n return;\n }\n\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n this.channel.onmessage = (event) => this._handleMessage(event.data);\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info( 'Started. DisplayId:', this.displayId);\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n\n this.followers.clear();\n this._log.info( 'Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn( 'requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark all followers as not-ready for this layout\n for (const [, follower] of this.followers) {\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info( `Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info( `Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info( `Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info( `Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( 'Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info( `Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info( `Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info( 'All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn( `Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info( `Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.channel) return;\n try {\n this.channel.postMessage(msg);\n } catch (e) {\n this._log.error( 'Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n"],"names":["CHANNEL_NAME","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","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,4BAA4BmB,CAAE,eAAe,KAAK,OAAOE,EAAMd,EAAS,UAAY,GAAI,CAAC,QAAQ,EACjH,KAAK,UAAU,OAAOY,CAAE,EAG9B,CAGA,MAAML,EAAK,CACT,GAAK,KAAK,QACV,GAAI,CACF,KAAK,QAAQ,YAAYA,CAAG,CAC9B,OAAS,EAAG,CACV,KAAK,KAAK,MAAO,kBAAmB,CAAC,CACvC,CACF,CAQA,WAAY,CACV,MAAO,CACL,QAAS,KAAK,SACd,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,UAAW,KAAK,UAAU,KAC1B,gBAAiB,KAAK,iBACtB,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACK,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWpB,CACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"sync-manager-DBfiw5Ey.js","sources":["../../node_modules/.pnpm/@xiboplayer+sync@0.5.1/node_modules/@xiboplayer/sync/src/sync-manager.js"],"sourcesContent":["/**\n * SyncManager - Multi-display synchronization via BroadcastChannel\n *\n * Coordinates layout transitions across multiple browser tabs/windows\n * on the same machine (video wall, multi-monitor setups).\n *\n * Protocol:\n * Lead Follower(s)\n * ──── ──────────\n * layout-change(layoutId, showAt) → receives, loads layout\n * ← layout-ready(layoutId, displayId)\n * (waits for all followers ready)\n * layout-show(layoutId) → shows layout simultaneously\n *\n * Heartbeat:\n * All nodes broadcast heartbeat every 5s.\n * Lead tracks active followers. If a follower goes silent for 15s,\n * it's considered offline and excluded from ready-wait.\n *\n * @module @xiboplayer/sync\n */\n\n/**\n * @typedef {Object} SyncConfig\n * @property {string} syncGroup - \"lead\" or leader's LAN IP\n * @property {number} syncPublisherPort - TCP port (unused in browser, kept for compat)\n * @property {number} syncSwitchDelay - Delay in ms before showing new content\n * @property {number} syncVideoPauseDelay - Delay in ms before unpausing video\n * @property {boolean} isLead - Whether this display is the leader\n */\n\nimport { createLogger } from '@xiboplayer/utils';\n\nconst CHANNEL_NAME = 'xibo-sync';\nconst HEARTBEAT_INTERVAL = 5000; // Send heartbeat every 5s\nconst FOLLOWER_TIMEOUT = 15000; // Consider follower offline after 15s silence\nconst READY_TIMEOUT = 10000; // Max wait for followers to be ready\n\nexport class SyncManager {\n /**\n * @param {Object} options\n * @param {string} options.displayId - This display's unique hardware key\n * @param {SyncConfig} options.syncConfig - Sync configuration from RegisterDisplay\n * @param {Function} [options.onLayoutChange] - Called when lead requests layout change\n * @param {Function} [options.onLayoutShow] - Called when lead gives show signal\n * @param {Function} [options.onVideoStart] - Called when lead gives video start signal\n * @param {Function} [options.onStatsReport] - (Lead) Called when follower sends stats\n * @param {Function} [options.onLogsReport] - (Lead) Called when follower sends logs\n * @param {Function} [options.onStatsAck] - (Follower) Called when lead confirms stats submission\n * @param {Function} [options.onLogsAck] - (Follower) Called when lead confirms logs submission\n */\n constructor(options) {\n this.displayId = options.displayId;\n this.syncConfig = options.syncConfig;\n this.isLead = options.syncConfig.isLead;\n this.switchDelay = options.syncConfig.syncSwitchDelay || 750;\n this.videoPauseDelay = options.syncConfig.syncVideoPauseDelay || 100;\n\n // Callbacks\n this.onLayoutChange = options.onLayoutChange || (() => {});\n this.onLayoutShow = options.onLayoutShow || (() => {});\n this.onVideoStart = options.onVideoStart || (() => {});\n this.onStatsReport = options.onStatsReport || null;\n this.onLogsReport = options.onLogsReport || null;\n this.onStatsAck = options.onStatsAck || null;\n this.onLogsAck = options.onLogsAck || null;\n\n // State\n this.channel = null;\n this.followers = new Map(); // displayId → { lastSeen, ready }\n this._heartbeatTimer = null;\n this._cleanupTimer = null;\n this._readyResolve = null; // Resolve function for current ready-wait\n this._pendingLayoutId = null; // Layout we're waiting for readiness on\n this._started = false;\n\n // Logger with role prefix for clarity in multi-tab console\n this._tag = this.isLead ? '[Sync:LEAD]' : '[Sync:FOLLOW]';\n this._log = createLogger(this.isLead ? 'Sync:LEAD' : 'Sync:FOLLOW');\n }\n\n /**\n * Start the sync manager (opens BroadcastChannel, begins heartbeats)\n */\n start() {\n if (this._started) return;\n this._started = true;\n\n if (typeof BroadcastChannel === 'undefined') {\n this._log.warn( 'BroadcastChannel not available — sync disabled');\n return;\n }\n\n this.channel = new BroadcastChannel(CHANNEL_NAME);\n this.channel.onmessage = (event) => this._handleMessage(event.data);\n\n // Start heartbeat\n this._heartbeatTimer = setInterval(() => this._sendHeartbeat(), HEARTBEAT_INTERVAL);\n this._sendHeartbeat(); // Send initial heartbeat immediately\n\n // Lead: periodically clean up stale followers\n if (this.isLead) {\n this._cleanupTimer = setInterval(() => this._cleanupStaleFollowers(), HEARTBEAT_INTERVAL);\n }\n\n this._log.info( 'Started. DisplayId:', this.displayId);\n }\n\n /**\n * Stop the sync manager\n */\n stop() {\n if (!this._started) return;\n this._started = false;\n\n if (this._heartbeatTimer) {\n clearInterval(this._heartbeatTimer);\n this._heartbeatTimer = null;\n }\n if (this._cleanupTimer) {\n clearInterval(this._cleanupTimer);\n this._cleanupTimer = null;\n }\n if (this.channel) {\n this.channel.close();\n this.channel = null;\n }\n\n this.followers.clear();\n this._log.info( 'Stopped');\n }\n\n // ── Lead API ──────────────────────────────────────────────────────\n\n /**\n * [Lead only] Request all displays to change to a layout.\n * Waits for followers to report ready, then sends show signal.\n *\n * @param {string|number} layoutId - Layout to change to\n * @returns {Promise<void>} Resolves when show signal is sent\n */\n async requestLayoutChange(layoutId) {\n if (!this.isLead) {\n this._log.warn( 'requestLayoutChange called on follower — ignoring');\n return;\n }\n\n layoutId = String(layoutId);\n this._pendingLayoutId = layoutId;\n\n // Mark all followers as not-ready for this layout\n for (const [, follower] of this.followers) {\n follower.ready = false;\n follower.readyLayoutId = null;\n }\n\n const showAt = Date.now() + this.switchDelay;\n\n this._log.info( `Requesting layout change: ${layoutId} (show at ${new Date(showAt).toISOString()}, ${this.followers.size} followers)`);\n\n // Broadcast layout-change to all followers\n this._send({\n type: 'layout-change',\n layoutId,\n showAt,\n displayId: this.displayId,\n });\n\n // Wait for all active followers to report ready (or timeout)\n if (this.followers.size > 0) {\n await this._waitForFollowersReady(layoutId);\n }\n\n // Apply switch delay (remaining time from showAt)\n const remaining = showAt - Date.now();\n if (remaining > 0) {\n await new Promise(resolve => setTimeout(resolve, remaining));\n }\n\n // Send show signal\n this._log.info( `Sending layout-show: ${layoutId}`);\n this._send({\n type: 'layout-show',\n layoutId,\n displayId: this.displayId,\n });\n\n // Also trigger on self (lead shows too)\n this.onLayoutShow(layoutId);\n\n this._pendingLayoutId = null;\n }\n\n /**\n * [Lead only] Signal followers to start video playback.\n *\n * @param {string|number} layoutId - Layout containing the video\n * @param {string} regionId - Region with the video widget\n */\n async requestVideoStart(layoutId, regionId) {\n if (!this.isLead) return;\n\n // Wait videoPauseDelay before unpausing\n await new Promise(resolve => setTimeout(resolve, this.videoPauseDelay));\n\n this._send({\n type: 'video-start',\n layoutId: String(layoutId),\n regionId,\n displayId: this.displayId,\n });\n\n // Also trigger on self\n this.onVideoStart(String(layoutId), regionId);\n }\n\n // ── Follower API ──────────────────────────────────────────────────\n\n /**\n * [Follower only] Report that layout is loaded and ready to show.\n * Called by platform layer after layout content is prepared.\n *\n * @param {string|number} layoutId - Layout that is ready\n */\n reportReady(layoutId) {\n layoutId = String(layoutId);\n\n this._log.info( `Reporting ready for layout ${layoutId}`);\n\n this._send({\n type: 'layout-ready',\n layoutId,\n displayId: this.displayId,\n });\n }\n\n /**\n * [Follower only] Delegate stats submission to the lead.\n * Lead will submit on our behalf and send a stats-ack when done.\n *\n * @param {string} statsXml - Formatted stats XML to submit\n */\n reportStats(statsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating stats to lead');\n this._send({\n type: 'stats-report',\n displayId: this.displayId,\n statsXml,\n });\n }\n\n /**\n * [Follower only] Delegate logs submission to the lead.\n * Lead will submit on our behalf and send a logs-ack when done.\n *\n * @param {string} logsXml - Formatted logs XML to submit\n */\n reportLogs(logsXml) {\n if (this.isLead) return;\n\n this._log.info('Delegating logs to lead');\n this._send({\n type: 'logs-report',\n displayId: this.displayId,\n logsXml,\n });\n }\n\n // ── Message handling ──────────────────────────────────────────────\n\n /** @private */\n _handleMessage(msg) {\n // Ignore our own messages\n if (msg.displayId === this.displayId) return;\n\n switch (msg.type) {\n case 'heartbeat':\n this._handleHeartbeat(msg);\n break;\n\n case 'layout-change':\n // Follower: lead is requesting a layout change\n if (!this.isLead) {\n this._log.info( `Layout change requested: ${msg.layoutId}`);\n this.onLayoutChange(msg.layoutId, msg.showAt);\n }\n break;\n\n case 'layout-ready':\n // Lead: follower reports ready\n if (this.isLead) {\n this._handleFollowerReady(msg);\n }\n break;\n\n case 'layout-show':\n // Follower: lead says show now\n if (!this.isLead) {\n this._log.info( `Layout show signal: ${msg.layoutId}`);\n this.onLayoutShow(msg.layoutId);\n }\n break;\n\n case 'video-start':\n // Follower: lead says start video\n if (!this.isLead) {\n this._log.info( `Video start signal: ${msg.layoutId} region ${msg.regionId}`);\n this.onVideoStart(msg.layoutId, msg.regionId);\n }\n break;\n\n case 'stats-report':\n // Lead: follower is delegating stats submission\n if (this.isLead && this.onStatsReport) {\n const statsAck = () => this._send({ type: 'stats-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onStatsReport(msg.displayId, msg.statsXml, statsAck);\n }\n break;\n\n case 'logs-report':\n // Lead: follower is delegating logs submission\n if (this.isLead && this.onLogsReport) {\n const logsAck = () => this._send({ type: 'logs-ack', displayId: this.displayId, targetDisplayId: msg.displayId });\n this.onLogsReport(msg.displayId, msg.logsXml, logsAck);\n }\n break;\n\n case 'stats-ack':\n // Follower: lead confirmed stats were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onStatsAck) {\n this._log.info('Stats acknowledged by lead');\n this.onStatsAck(msg.targetDisplayId);\n }\n break;\n\n case 'logs-ack':\n // Follower: lead confirmed logs were submitted for us\n if (!this.isLead && msg.targetDisplayId === this.displayId && this.onLogsAck) {\n this._log.info('Logs acknowledged by lead');\n this.onLogsAck(msg.targetDisplayId);\n }\n break;\n\n default:\n this._log.warn( 'Unknown message type:', msg.type);\n }\n }\n\n /** @private */\n _handleHeartbeat(msg) {\n const existing = this.followers.get(msg.displayId);\n if (existing) {\n existing.lastSeen = Date.now();\n } else {\n // New follower discovered\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: false,\n readyLayoutId: null,\n role: msg.role || 'unknown',\n });\n this._log.info( `Follower joined: ${msg.displayId} (${this.followers.size} total)`);\n }\n }\n\n /** @private */\n _handleFollowerReady(msg) {\n const follower = this.followers.get(msg.displayId);\n if (!follower) {\n // Late joiner — register them\n this.followers.set(msg.displayId, {\n lastSeen: Date.now(),\n ready: true,\n readyLayoutId: msg.layoutId,\n });\n } else {\n follower.ready = true;\n follower.readyLayoutId = msg.layoutId;\n follower.lastSeen = Date.now();\n }\n\n this._log.info( `Follower ${msg.displayId} ready for layout ${msg.layoutId}`);\n\n // Check if all followers are now ready\n if (this._pendingLayoutId === msg.layoutId && this._readyResolve) {\n if (this._allFollowersReady(msg.layoutId)) {\n this._log.info( 'All followers ready');\n this._readyResolve();\n this._readyResolve = null;\n }\n }\n }\n\n /** @private */\n _allFollowersReady(layoutId) {\n for (const [, follower] of this.followers) {\n // Skip stale followers\n if (Date.now() - follower.lastSeen > FOLLOWER_TIMEOUT) continue;\n if (!follower.ready || follower.readyLayoutId !== layoutId) {\n return false;\n }\n }\n return true;\n }\n\n /** @private */\n _waitForFollowersReady(layoutId) {\n return new Promise((resolve) => {\n // Already all ready?\n if (this._allFollowersReady(layoutId)) {\n resolve();\n return;\n }\n\n this._readyResolve = resolve;\n\n // Timeout: don't wait forever for unresponsive followers\n setTimeout(() => {\n if (this._readyResolve === resolve) {\n const notReady = [];\n for (const [id, f] of this.followers) {\n if (!f.ready || f.readyLayoutId !== layoutId) {\n notReady.push(id);\n }\n }\n this._log.warn( `Ready timeout — proceeding without: ${notReady.join(', ')}`);\n this._readyResolve = null;\n resolve();\n }\n }, READY_TIMEOUT);\n });\n }\n\n // ── Heartbeat & cleanup ───────────────────────────────────────────\n\n /** @private */\n _sendHeartbeat() {\n this._send({\n type: 'heartbeat',\n displayId: this.displayId,\n role: this.isLead ? 'lead' : 'follower',\n timestamp: Date.now(),\n });\n }\n\n /** @private */\n _cleanupStaleFollowers() {\n const now = Date.now();\n for (const [id, follower] of this.followers) {\n if (now - follower.lastSeen > FOLLOWER_TIMEOUT) {\n this._log.info( `Removing stale follower: ${id} (last seen ${Math.round((now - follower.lastSeen) / 1000)}s ago)`);\n this.followers.delete(id);\n }\n }\n }\n\n /** @private */\n _send(msg) {\n if (!this.channel) return;\n try {\n this.channel.postMessage(msg);\n } catch (e) {\n this._log.error( 'Failed to send:', e);\n }\n }\n\n // ── Status ────────────────────────────────────────────────────────\n\n /**\n * Get current sync status\n * @returns {Object}\n */\n getStatus() {\n return {\n started: this._started,\n isLead: this.isLead,\n displayId: this.displayId,\n followers: this.followers.size,\n pendingLayoutId: this._pendingLayoutId,\n followerDetails: Array.from(this.followers.entries()).map(([id, f]) => ({\n displayId: id,\n lastSeen: f.lastSeen,\n ready: f.ready,\n readyLayoutId: f.readyLayoutId,\n stale: Date.now() - f.lastSeen > FOLLOWER_TIMEOUT,\n })),\n };\n }\n}\n"],"names":["CHANNEL_NAME","HEARTBEAT_INTERVAL","FOLLOWER_TIMEOUT","READY_TIMEOUT","SyncManager","options","createLogger","event","layoutId","follower","showAt","remaining","resolve","regionId","statsXml","logsXml","msg","statsAck","logsAck","existing","notReady","id","f","now"],"mappings":"0CAiCA,MAAMA,EAAe,YACfC,EAAqB,IACrBC,EAAmB,KACnBC,EAAgB,IAEf,MAAMC,CAAY,CAavB,YAAYC,EAAS,CACnB,KAAK,UAAYA,EAAQ,UACzB,KAAK,WAAaA,EAAQ,WAC1B,KAAK,OAASA,EAAQ,WAAW,OACjC,KAAK,YAA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,MAAO,CACL,QAAS,KAAK,SACd,OAAQ,KAAK,OACb,UAAW,KAAK,UAChB,UAAW,KAAK,UAAU,KAC1B,gBAAiB,KAAK,iBACtB,gBAAiB,MAAM,KAAK,KAAK,UAAU,SAAS,EAAE,IAAI,CAAC,CAACK,EAAIC,CAAC,KAAO,CACtE,UAAWD,EACX,SAAUC,EAAE,SACZ,MAAOA,EAAE,MACT,cAAeA,EAAE,cACjB,MAAO,KAAK,IAAG,EAAKA,EAAE,SAAWpB,CACzC,EAAQ,CACR,CACE,CACF","x_google_ignoreList":[0]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as R}from"./cms-api-Cqh1b8je.js";class H{constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t)}once(e,t){const s=(...i)=>{t(...i),this.off(e,s)};this.on(e,s)}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),i=s.indexOf(t);i!==-1&&s.splice(i,1)}emit(e,...t){if(!this.events.has(e))return;const s=this.events.get(e).slice();for(const i of s)i(...t)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const J=R("Cache"),ee="xibo-media-v1",te=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class se{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${te}/cache/${e}/${s||t}`}addDependant(e,t){const s=String(e);this.dependants.has(s)||this.dependants.set(s,new Set),this.dependants.get(s).add(String(t))}removeLayoutDependants(e){const t=String(e),s=[];for(const[i,n]of this.dependants)n.delete(t),n.size===0&&(this.dependants.delete(i),s.push(i));return s.length>0&&J.info(`${s.length} media files orphaned after layout ${e} removed:`,s),s}isMediaReferenced(e){const t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){await caches.delete(ee),this.dependants.clear()}}const pe=new se,c=R("CacheProxy"),Q=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class O extends H{constructor(){super(),this.controller=null,this.fetchReady=!1,this.fetchReadyPromise=null,this.fetchReadyResolve=null}async init(){if(this.fetchReadyPromise=new Promise(e=>{this.fetchReadyResolve=e}),navigator.serviceWorker.addEventListener("message",e=>{var t;((t=e.data)==null?void 0:t.type)==="SW_READY"&&(c.info("Received SW_READY signal - fetch handler is ready"),this.fetchReady=!0,this.fetchReadyResolve())}),"serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration();if(e&&e.active&&e.active.state==="activated"){c.info("Using active Service Worker (controller not required)"),this.controller=navigator.serviceWorker.controller||e.active,this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...");return}if(await navigator.serviceWorker.ready,this.controller=navigator.serviceWorker.controller,!this.controller)throw new Error("Service Worker not controlling page");this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...")}else throw new Error("Service Worker not supported")}async getFile(e,t){this.fetchReady||(c.debug(`Waiting for SW fetch handler to be ready before fetching ${e}/${t}...`),await this.fetchReadyPromise,c.debug("SW fetch handler ready, proceeding with fetch"));const s=`${Q}/cache/${e}/${t}`;c.debug(`getFile(${e}, ${t}) → fetching ${s}`),c.debug("About to call fetch()...");try{c.debug(`Calling fetch(${s})...`);const i=await fetch(s);if(c.debug("fetch returned, status:",i.status,i.statusText),!i.ok){if(c.debug(`Response not OK (${i.status}), returning null`),i.status===404)return null;throw new Error(`Failed to get file: ${i.status}`)}c.debug("Response OK, getting blob...");const n=await i.blob();return c.debug("Got blob, size:",n.size),n}catch(i){return c.error("getFile EXCEPTION:",i),c.error("Error name:",i.name),c.error("Error message:",i.message),null}}async hasFile(e,t){this.fetchReady||await this.fetchReadyPromise;const s=`${Q}/cache/${e}/${t}`;try{return(await fetch(s,{method:"HEAD"})).ok}catch{return!1}}async requestDownload(e){if(!this.controller)throw new Error("Service Worker not available");const t=Array.isArray(e)?{files:e}:e;return new Promise((s,i)=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,error:h,enqueuedCount:a,activeCount:p,queuedCount:d}=r.data;o?(c.info("Download request acknowledged:",a,"files"),c.info("Queue state:",p,"active,",d,"queued"),s()):i(new Error(h||"Service Worker download failed"))},this.controller.postMessage({type:"DOWNLOAD_FILES",data:t},[n.port2])})}async prioritizeDownload(e,t){if(this.controller)return new Promise(s=>{const i=new MessageChannel;i.port1.onmessage=n=>s(n.data),this.controller.postMessage({type:"PRIORITIZE_DOWNLOAD",data:{fileType:e,fileId:t}},[i.port2])})}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){this.controller&&this.controller.postMessage({type:"PRIORITIZE_LAYOUT_FILES",data:{mediaIds:e}})}}class fe extends H{constructor(){super(),this.backend=null,this.backendType="service-worker"}async init(){var i,n;if(!("serviceWorker"in navigator))throw new Error("Service Worker not supported - PWA requires Service Worker");c.debug("Checking Service Worker state..."),c.debug("controller =",navigator.serviceWorker.controller);const e=await navigator.serviceWorker.getRegistration();if(c.debug("registration =",e),c.debug("active =",e==null?void 0:e.active),c.debug("installing =",e==null?void 0:e.installing),c.debug("waiting =",e==null?void 0:e.waiting),e&&e.active&&!e.installing&&!e.waiting){c.info("Active Service Worker found (no updates pending)"),c.debug("SW state =",e.active.state),navigator.serviceWorker.controller||(c.debug("Not controlling yet, waiting 200ms for claim..."),await new Promise(r=>setTimeout(r,200)),c.debug("After wait, controller =",navigator.serviceWorker.controller)),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (fast path)");return}e&&(e.installing||e.waiting)&&(c.info("New Service Worker detected, waiting for it to activate..."),c.debug("installing =",(i=e.installing)==null?void 0:i.state),c.debug("waiting =",(n=e.waiting)==null?void 0:n.state)),c.info("No active Service Worker, waiting for registration...");const t=navigator.serviceWorker.ready,s=new Promise((r,o)=>setTimeout(()=>o(new Error("Service Worker ready timeout after 10s")),1e4));try{await Promise.race([t,s]),c.debug("Service Worker ready promise resolved")}catch(r){throw c.error("Service Worker wait failed:",r),new Error("Service Worker not ready - please reload page")}await new Promise(r=>setTimeout(r,100)),c.debug("After claim wait, controller =",navigator.serviceWorker.controller),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (slow path)")}async getFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.getFile(e,t)}async hasFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.hasFile(e,t)}async requestDownload(e){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.requestDownload(e)}async prioritizeDownload(e,t){var s;if((s=this.backend)!=null&&s.prioritizeDownload)return await this.backend.prioritizeDownload(e,t)}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){var t;if((t=this.backend)!=null&&t.prioritizeLayoutFiles)return await this.backend.prioritizeLayoutFiles(e)}getBackendType(){return this.backendType}isUsingServiceWorker(){return this.backendType==="service-worker"}async getAllFiles(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,files:n}=s.data;e(i?n:[])},navigator.serviceWorker.controller.postMessage({type:"GET_ALL_FILES"},[t.port2]),setTimeout(()=>e([]),5e3)})}async deleteFiles(e){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise((t,s)=>{const i=new MessageChannel;i.port1.onmessage=n=>{const{success:r,error:o,deleted:h,total:a}=n.data;r?t({deleted:h,total:a}):s(new Error(o||"Delete failed"))},navigator.serviceWorker.controller.postMessage({type:"DELETE_FILES",data:{files:e}},[i.port2]),setTimeout(()=>t({deleted:0,total:e.length}),5e3)})}async prewarmVideoChunks(e){var s;if(!e||e.length===0)return{warmed:0,total:0};const t=(s=navigator.serviceWorker)==null?void 0:s.controller;return t?new Promise(i=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,warmed:h,total:a}=r.data;i(o?{warmed:h,total:a}:{warmed:0,total:e.length})},t.postMessage({type:"PREWARM_VIDEO_CHUNKS",data:{mediaIds:e}},[n.port2]),setTimeout(()=>i({warmed:0,total:e.length}),2e3)}):{warmed:0,total:e.length}}async getDownloadProgress(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,progress:n}=s.data;e(i?n:{})},navigator.serviceWorker.controller.postMessage({type:"GET_DOWNLOAD_PROGRESS"},[t.port2]),setTimeout(()=>e({}),1e3)})}}const l=R("Download"),ie=6,j=50*1024*1024,ne=3,oe=100*1024*1024,L=3,re=500,ae=2,N=6e5,ce=15e3;function he(u){var i,n;const t=(n=(i=(u.path||u.code||"").split(".").pop())==null?void 0:i.split("?")[0])==null?void 0:n.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},$=Symbol("BARRIER");function S(u){try{const e=u.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function K(u,e=30){const t=S(u);return t===1/0?!1:Date.now()/1e3>=t-e}function G(u){if(!u.startsWith("http"))return u;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost"||e.port!=="8765")return u;const t=new URL(u),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}class z{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=L;t++){const s=new AbortController,i=setTimeout(()=>s.abort(),N);try{const n=this.getUrl(),r={signal:s.signal};Object.keys(e).length>0&&(r.headers=e);const o=await fetch(n,r);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(n){const r=s.signal.aborted?`Timeout after ${N/1e3}s`:n.message;if(t<L){const o=re*t,h=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${h} attempt ${t}/${L} failed: ${r}. Retrying in ${o/1e3}s...`),await new Promise(a=>setTimeout(a,o))}else throw this.state="failed",s.signal.aborted?new Error(r):n}finally{clearTimeout(i)}}}}class Y{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,i)=>{this._resolve=s,this._reject=i}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:i}=this.fileInfo;if(l.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=i&&i>0?parseInt(i):0,this._contentType=he(this.fileInfo),this.totalBytes===0){const r=this.getUrl(),o=new AbortController,h=setTimeout(()=>o.abort(),ce);try{const a=await fetch(r,{method:"HEAD",signal:o.signal});a.ok&&(this.totalBytes=parseInt(a.headers.get("Content-Length")||"0"),this._contentType=a.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(h)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const n=this.options.chunkSize||j;if(this.totalBytes>oe){const r=[];for(let d=0;d<this.totalBytes;d+=n)r.push({start:d,end:Math.min(d+n-1,this.totalBytes-1),index:r.length});this.totalChunks=r.length;const o=r.filter(d=>!this.skipChunks.has(d.index)),h=r.length-o.length;for(const d of r)this.skipChunks.has(d.index)&&(this.downloadedBytes+=d.end-d.start+1);if(o.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}h>0&&l.info(`[FileDownload] Resuming: ${h} chunks cached, ${o.length} to download`);const a=h>0;if(a){const d=o.sort((g,y)=>g.index-y.index);for(const g of d){const y=new z(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});y._parentFile=this,y._priority=f.normal,this.tasks.push(y)}}else for(const d of o){const g=new z(this.fileInfo,{chunkIndex:d.index,rangeStart:d.start,rangeEnd:d.end});g._parentFile=this,g._priority=d.index===0||d.index===r.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(d=>d._priority>=f.high).length;l.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(a?" (resume)":""))}else{this.totalChunks=1;const r=new z(this.fileInfo,{});r._parentFile=this,this.tasks.push(r)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){l.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const i=[];for(let r=0;r<this.totalChunks;r++){const o=this._chunkBlobs.get(r);o&&i.push(o)}const n=new Blob(i,{type:this._contentType});l.info("[FileDownload] Complete:",`${t}/${s}`,`(${n.size} bytes, reassembled)`),this._resolve(n)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const i=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${i}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(n=>n!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}l.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class ge{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=q.stableKey(e);if(this.queue.active.has(t)){const i=this.queue.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const i=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const n=this._filesToPrepare[s++];t++,n.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():i()})}};this._filesToPrepare.length===0?e():i()})}_sortWithBarriers(){var r;const e=[],t=[],s=[],i=[];for(const o of this._tasks)if(o.chunkIndex==null)e.push(o);else if(o.chunkIndex===0)t.push(o);else{const h=((r=o._parentFile)==null?void 0:r.totalChunks)||0;h>1&&o.chunkIndex===h-1?s.push(o):i.push(o)}e.sort((o,h)=>{var a,p;return(((a=o._parentFile)==null?void 0:a.totalBytes)||0)-(((p=h._parentFile)==null?void 0:p.totalBytes)||0)}),i.sort((o,h)=>o.chunkIndex-h.chunkIndex);const n=[...e,...t,...s];return i.length>0&&n.push($,...i),n}}class q{constructor(e={}){this.concurrency=e.concurrency||ie,this.chunkSize=e.chunkSize||j,this.maxChunksPerFile=e.chunksPerFile||ne,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=q.stableKey(e);if(this.active.has(t)){const i=this.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(l.info("[DownloadQueue] Refreshing URL for",t),i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),l.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const i of e)i===$?(this.queue.push($),s++):(this.queue.push(i),t++);l.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,i=this.active.get(s);if(!i)return l.info("[DownloadQueue] Not found:",s),!1;let n=0;for(const r of this.queue)r._parentFile===i&&r._priority<f.high&&(r._priority=f.high,n++);return this._sortQueue(),l.info("[DownloadQueue] Prioritized:",s,`(${n} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=f.high){var n,r;const s=new Set(e.map(String));let i=0;for(const o of this.queue)s.has(String((n=o._parentFile)==null?void 0:n.fileInfo.id))&&o._priority<t&&(o._priority=t,i++);for(const o of this._activeTasks)s.has(String((r=o._parentFile)==null?void 0:r.fileInfo.id))&&o._priority<t&&(o._priority=t);this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",i,"tasks boosted to",t)}urgentChunk(e,t,s){const i=`${e}/${t}`,n=this.active.get(i);if(!n)return l.info("[DownloadQueue] urgentChunk: file not active:",i,"chunk",s),!1;if(this._activeTasks.some(a=>a._parentFile===n&&a.chunkIndex===s&&a.state==="downloading")){const a=this._activeTasks.find(p=>p._parentFile===n&&p.chunkIndex===s);return a&&a._priority<f.urgent?(a._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",i,"chunk",s),!1)}const o=this.queue.findIndex(a=>a!==$&&a._parentFile===n&&a.chunkIndex===s);if(o===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",i,"chunk",s),!1;const h=this.queue.splice(o,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var i;if(this.paused)return;const e=this.queue.some(n=>n!==$&&n._priority>=f.urgent)||((i=this._activeTasks)==null?void 0:i.some(n=>n._priority>=f.urgent&&n.state==="downloading")),t=e?ae:this.concurrency,s=e?f.urgent:0;for(;this.running<t&&this.queue.length>0;){const n=this.queue[0];if(n===$){if(this.running>0)break;this.queue.shift();continue}if(n._priority<s||!this._canStartTask(n)){let r=!1;for(let o=1;o<this.queue.length&&this.queue[o]!==$;o++){const h=this.queue[o];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(o,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(n)}this.queue.length===0&&this.running===0&&l.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),l.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(i=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),this.processQueue(),e._parentFile.onTaskFailed(e,i)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===$||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state};return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0}}class we{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}enqueueForLayout(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,s){return this.queue.urgentChunk(e,t,s)}clear(){this.queue.clear()}}const _=R("CacheAnalyzer");function E(u){if(u===0)return"0 B";if(!Number.isFinite(u))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(u)/Math.log(1024));return`${(u/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class ye{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.getAllFiles(),s=await this._getStorageEstimate(),i=new Set(e.map(a=>String(a.id))),n=[],r=[];for(const a of t)if(i.has(String(a.id)))n.push(a);else if(a.type==="widget"){const p=String(a.id).split("/")[0];i.has(p)?n.push(a):r.push(a)}else r.push(a);r.sort((a,p)=>(a.cachedAt||0)-(p.cachedAt||0));const o=r.reduce((a,p)=>a+(p.size||0),0),h={timestamp:Date.now(),storage:{usage:s.usage,quota:s.quota,percent:s.quota>0?Math.round(s.usage/s.quota*100):0},files:{required:n.length,orphaned:r.length,total:t.length},orphaned:r.map(a=>({id:a.id,type:a.type,size:a.size||0,cachedAt:a.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(_.info(`Storage: ${E(s.usage)} / ${E(s.quota)} (${h.storage.percent}%)`),_.info(`Cache: ${n.length} required, ${r.length} orphaned (${E(o)} reclaimable)`),r.length>0)for(const a of r){const p=Date.now()-(a.cachedAt||0),d=Math.floor(p/864e5),g=Math.floor(p%864e5/36e5),y=d>0?`${d}d ago`:`${g}h ago`;_.info(` Orphaned: ${a.type}/${a.id} (${E(a.size||0)}, cached ${y})`)}if(h.storage.percent>this.threshold&&r.length>0){_.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const a=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(r,a)}else _.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:t,quota:s}=await navigator.storage.estimate();return{usage:t||0,quota:s||1/0}}}catch(t){_.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let i=0;for(const n of e){if(i>=t)break;s.push(n),i+=n.size||0}if(s.length===0)return[];try{const n=s.map(r=>({type:r.type,id:r.id}));await this.cache.deleteFiles(n);for(const r of s)_.info(` Evicted: ${r.type}/${r.id} (${E(r.size||0)})`);_.info(`Evicted ${s.length} files, freed ${E(i)}`)}catch(n){return _.warn("Eviction failed:",n.message),[]}return s.map(n=>({id:n.id,type:n.type,size:n.size||0,cachedAt:n.cachedAt||0}))}}const w=R("Cache"),le="xibo-media-v1",v=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function ke(u,e,t,s){const i=`${v}/cache/widget/${u}/${e}/${t}`,n=await caches.open(le),r=`<base href="${v}/cache/media/">`;let o=s;s.includes("<base ")||(s.includes("<head>")?o=s.replace("<head>","<head>"+r):s.includes("<HEAD>")?o=s.replace("<HEAD>","<HEAD>"+r):o=r+s);const h=/https?:\/\/[^"'\s)]+(?:xmds\.php|pwa\/file)\?[^"'\s)]*file=([^&"'\s)]+)[^"'\s)]*/g,a=[];o=o.replace(h,(y,k)=>{const m=`${v}/cache/static/${k}`;return a.push({filename:k,originalUrl:y}),w.info(`Rewrote widget URL: ${k} → ${m}`),m});const p="<style>img,video{object-position:center center}</style>";o.includes("object-position:center center")||(o.includes("</head>")?o=o.replace("</head>",p+"</head>"):o.includes("</HEAD>")&&(o=o.replace("</HEAD>",p+"</HEAD>"))),o=o.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${v}/ic"`),w.info("Injected base tag and rewrote CMS/data URLs in widget HTML");const d=new URL(i,window.location.origin),g=new Response(o,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*"}});if(await n.put(d,g),w.info(`Stored widget HTML at ${i} (${o.length} bytes)`),a.length>0){const k=await caches.open("xibo-static-v1");await Promise.all(a.map(async({filename:m,originalUrl:X})=>{const A=`${v}/cache/static/${m}`;if(!await k.match(A))try{const b=await fetch(X);if(!b.ok){w.warn(`Failed to fetch static resource: ${m} (HTTP ${b.status})`);return}const M=m.split(".").pop().toLowerCase(),W={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[M]||"application/octet-stream";if(M==="css"){let C=await b.text();const I=[],Z=/url\((['"]?)(https?:\/\/[^'")\s]+\?[^'")\s]*file=([^&'")\s]+\.(?:woff2?|ttf|otf|eot|svg))[^'")\s]*)\1\)/gi;C=C.replace(Z,(T,D,F,P)=>(I.push({filename:P,originalUrl:F}),w.info(`Rewrote font URL in CSS: ${P}`),`url(${D}${v}/cache/static/${encodeURIComponent(P)}${D})`)),await k.put(A,new Response(C,{headers:{"Content-Type":"text/css"}})),w.info(`Cached CSS with ${I.length} rewritten font URLs: ${m}`),await Promise.all(I.map(async({filename:T,originalUrl:D})=>{const F=`${v}/cache/static/${encodeURIComponent(T)}`;if(!await k.match(F))try{const x=await fetch(D);if(!x.ok){w.warn(`Failed to fetch font: ${T} (HTTP ${x.status})`);return}const B=await x.blob(),V=T.split(".").pop().toLowerCase(),U={otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[V]||"application/octet-stream";await k.put(F,new Response(B,{headers:{"Content-Type":U}})),w.info(`Cached font: ${T} (${U}, ${B.size} bytes)`)}catch(x){w.warn(`Failed to cache font: ${T}`,x)}}))}else{const C=await b.blob();await k.put(A,new Response(C,{headers:{"Content-Type":W}})),w.info(`Cached static resource: ${m} (${W}, ${C.size} bytes)`)}}catch(b){w.warn(`Failed to cache static resource: ${m}`,b)}}))}return i}export{$ as B,ye as C,we as D,H as E,Y as F,ge as L,fe as a,se as b,ke as c,pe as d,K as i,G as r};
|
|
2
|
-
//# sourceMappingURL=widget-html-
|
|
1
|
+
import{c as R}from"./cms-api-B3gEu-pj.js";class H{constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e).push(t)}once(e,t){const s=(...i)=>{t(...i),this.off(e,s)};this.on(e,s)}off(e,t){if(!this.events.has(e))return;const s=this.events.get(e),i=s.indexOf(t);i!==-1&&s.splice(i,1)}emit(e,...t){if(!this.events.has(e))return;const s=this.events.get(e).slice();for(const i of s)i(...t)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}const J=R("Cache"),ee="xibo-media-v1",te=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class se{constructor(){this.dependants=new Map}getCacheKey(e,t,s=null){return`${te}/cache/${e}/${s||t}`}addDependant(e,t){const s=String(e);this.dependants.has(s)||this.dependants.set(s,new Set),this.dependants.get(s).add(String(t))}removeLayoutDependants(e){const t=String(e),s=[];for(const[i,n]of this.dependants)n.delete(t),n.size===0&&(this.dependants.delete(i),s.push(i));return s.length>0&&J.info(`${s.length} media files orphaned after layout ${e} removed:`,s),s}isMediaReferenced(e){const t=this.dependants.get(String(e));return t?t.size>0:!1}async clearAll(){await caches.delete(ee),this.dependants.clear()}}const pe=new se,c=R("CacheProxy"),Q=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";class O extends H{constructor(){super(),this.controller=null,this.fetchReady=!1,this.fetchReadyPromise=null,this.fetchReadyResolve=null}async init(){if(this.fetchReadyPromise=new Promise(e=>{this.fetchReadyResolve=e}),navigator.serviceWorker.addEventListener("message",e=>{var t;((t=e.data)==null?void 0:t.type)==="SW_READY"&&(c.info("Received SW_READY signal - fetch handler is ready"),this.fetchReady=!0,this.fetchReadyResolve())}),"serviceWorker"in navigator){const e=await navigator.serviceWorker.getRegistration();if(e&&e.active&&e.active.state==="activated"){c.info("Using active Service Worker (controller not required)"),this.controller=navigator.serviceWorker.controller||e.active,this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...");return}if(await navigator.serviceWorker.ready,this.controller=navigator.serviceWorker.controller,!this.controller)throw new Error("Service Worker not controlling page");this.controller.postMessage({type:"PING"}),c.info("Service Worker backend initialized, waiting for fetch readiness...")}else throw new Error("Service Worker not supported")}async getFile(e,t){this.fetchReady||(c.debug(`Waiting for SW fetch handler to be ready before fetching ${e}/${t}...`),await this.fetchReadyPromise,c.debug("SW fetch handler ready, proceeding with fetch"));const s=`${Q}/cache/${e}/${t}`;c.debug(`getFile(${e}, ${t}) → fetching ${s}`),c.debug("About to call fetch()...");try{c.debug(`Calling fetch(${s})...`);const i=await fetch(s);if(c.debug("fetch returned, status:",i.status,i.statusText),!i.ok){if(c.debug(`Response not OK (${i.status}), returning null`),i.status===404)return null;throw new Error(`Failed to get file: ${i.status}`)}c.debug("Response OK, getting blob...");const n=await i.blob();return c.debug("Got blob, size:",n.size),n}catch(i){return c.error("getFile EXCEPTION:",i),c.error("Error name:",i.name),c.error("Error message:",i.message),null}}async hasFile(e,t){this.fetchReady||await this.fetchReadyPromise;const s=`${Q}/cache/${e}/${t}`;try{return(await fetch(s,{method:"HEAD"})).ok}catch{return!1}}async requestDownload(e){if(!this.controller)throw new Error("Service Worker not available");const t=Array.isArray(e)?{files:e}:e;return new Promise((s,i)=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,error:h,enqueuedCount:a,activeCount:p,queuedCount:d}=r.data;o?(c.info("Download request acknowledged:",a,"files"),c.info("Queue state:",p,"active,",d,"queued"),s()):i(new Error(h||"Service Worker download failed"))},this.controller.postMessage({type:"DOWNLOAD_FILES",data:t},[n.port2])})}async prioritizeDownload(e,t){if(this.controller)return new Promise(s=>{const i=new MessageChannel;i.port1.onmessage=n=>s(n.data),this.controller.postMessage({type:"PRIORITIZE_DOWNLOAD",data:{fileType:e,fileId:t}},[i.port2])})}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){this.controller&&this.controller.postMessage({type:"PRIORITIZE_LAYOUT_FILES",data:{mediaIds:e}})}}class fe extends H{constructor(){super(),this.backend=null,this.backendType="service-worker"}async init(){var i,n;if(!("serviceWorker"in navigator))throw new Error("Service Worker not supported - PWA requires Service Worker");c.debug("Checking Service Worker state..."),c.debug("controller =",navigator.serviceWorker.controller);const e=await navigator.serviceWorker.getRegistration();if(c.debug("registration =",e),c.debug("active =",e==null?void 0:e.active),c.debug("installing =",e==null?void 0:e.installing),c.debug("waiting =",e==null?void 0:e.waiting),e&&e.active&&!e.installing&&!e.waiting){c.info("Active Service Worker found (no updates pending)"),c.debug("SW state =",e.active.state),navigator.serviceWorker.controller||(c.debug("Not controlling yet, waiting 200ms for claim..."),await new Promise(r=>setTimeout(r,200)),c.debug("After wait, controller =",navigator.serviceWorker.controller)),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (fast path)");return}e&&(e.installing||e.waiting)&&(c.info("New Service Worker detected, waiting for it to activate..."),c.debug("installing =",(i=e.installing)==null?void 0:i.state),c.debug("waiting =",(n=e.waiting)==null?void 0:n.state)),c.info("No active Service Worker, waiting for registration...");const t=navigator.serviceWorker.ready,s=new Promise((r,o)=>setTimeout(()=>o(new Error("Service Worker ready timeout after 10s")),1e4));try{await Promise.race([t,s]),c.debug("Service Worker ready promise resolved")}catch(r){throw c.error("Service Worker wait failed:",r),new Error("Service Worker not ready - please reload page")}await new Promise(r=>setTimeout(r,100)),c.debug("After claim wait, controller =",navigator.serviceWorker.controller),this.backend=new O,await this.backend.init(),c.info("Service Worker backend ready (slow path)")}async getFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.getFile(e,t)}async hasFile(e,t){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.hasFile(e,t)}async requestDownload(e){if(!this.backend)throw new Error("CacheProxy not initialized");return await this.backend.requestDownload(e)}async prioritizeDownload(e,t){var s;if((s=this.backend)!=null&&s.prioritizeDownload)return await this.backend.prioritizeDownload(e,t)}async isCached(e,t){return this.hasFile(e,t)}async prioritizeLayoutFiles(e){var t;if((t=this.backend)!=null&&t.prioritizeLayoutFiles)return await this.backend.prioritizeLayoutFiles(e)}getBackendType(){return this.backendType}isUsingServiceWorker(){return this.backendType==="service-worker"}async getAllFiles(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,files:n}=s.data;e(i?n:[])},navigator.serviceWorker.controller.postMessage({type:"GET_ALL_FILES"},[t.port2]),setTimeout(()=>e([]),5e3)})}async deleteFiles(e){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise((t,s)=>{const i=new MessageChannel;i.port1.onmessage=n=>{const{success:r,error:o,deleted:h,total:a}=n.data;r?t({deleted:h,total:a}):s(new Error(o||"Delete failed"))},navigator.serviceWorker.controller.postMessage({type:"DELETE_FILES",data:{files:e}},[i.port2]),setTimeout(()=>t({deleted:0,total:e.length}),5e3)})}async prewarmVideoChunks(e){var s;if(!e||e.length===0)return{warmed:0,total:0};const t=(s=navigator.serviceWorker)==null?void 0:s.controller;return t?new Promise(i=>{const n=new MessageChannel;n.port1.onmessage=r=>{const{success:o,warmed:h,total:a}=r.data;i(o?{warmed:h,total:a}:{warmed:0,total:e.length})},t.postMessage({type:"PREWARM_VIDEO_CHUNKS",data:{mediaIds:e}},[n.port2]),setTimeout(()=>i({warmed:0,total:e.length}),2e3)}):{warmed:0,total:e.length}}async getDownloadProgress(){if(!this.backend)throw new Error("CacheProxy not initialized");return new Promise(e=>{const t=new MessageChannel;t.port1.onmessage=s=>{const{success:i,progress:n}=s.data;e(i?n:{})},navigator.serviceWorker.controller.postMessage({type:"GET_DOWNLOAD_PROGRESS"},[t.port2]),setTimeout(()=>e({}),1e3)})}}const l=R("Download"),ie=6,j=50*1024*1024,ne=3,oe=100*1024*1024,L=3,re=500,ae=2,N=6e5,ce=15e3;function he(u){var i,n;const t=(n=(i=(u.path||u.code||"").split(".").pop())==null?void 0:i.split("?")[0])==null?void 0:n.toLowerCase();return{mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",css:"text/css",js:"application/javascript",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",xml:"application/xml",xlf:"application/xml"}[t]||"application/octet-stream"}const f={normal:0,layout:1,high:2,urgent:3},$=Symbol("BARRIER");function S(u){try{const e=u.match(/X-Amz-Expires=(\d+)/);return e?parseInt(e[1],10):1/0}catch{return 1/0}}function K(u,e=30){const t=S(u);return t===1/0?!1:Date.now()/1e3>=t-e}function G(u){if(!u.startsWith("http"))return u;const e=typeof self<"u"?self.location:void 0;if(!e||e.hostname!=="localhost"||e.port!=="8765")return u;const t=new URL(u),s=t.origin;return`/file-proxy?cms=${encodeURIComponent(s)}&url=${encodeURIComponent(t.pathname+t.search)}`}class z{constructor(e,t={}){this.fileInfo=e,this.chunkIndex=t.chunkIndex??null,this.rangeStart=t.rangeStart??null,this.rangeEnd=t.rangeEnd??null,this.state="pending",this.blob=null,this._parentFile=null,this._priority=f.normal}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}async start(){this.state="downloading";const e={};this.rangeStart!=null&&(e.Range=`bytes=${this.rangeStart}-${this.rangeEnd}`);for(let t=1;t<=L;t++){const s=new AbortController,i=setTimeout(()=>s.abort(),N);try{const n=this.getUrl(),r={signal:s.signal};Object.keys(e).length>0&&(r.headers=e);const o=await fetch(n,r);if(!o.ok&&o.status!==206)throw new Error(`Fetch failed: ${o.status}`);return this.blob=await o.blob(),this.state="complete",this.blob}catch(n){const r=s.signal.aborted?`Timeout after ${N/1e3}s`:n.message;if(t<L){const o=re*t,h=this.chunkIndex!=null?` chunk ${this.chunkIndex}`:"";l.warn(`[DownloadTask] ${this.fileInfo.type}/${this.fileInfo.id}${h} attempt ${t}/${L} failed: ${r}. Retrying in ${o/1e3}s...`),await new Promise(a=>setTimeout(a,o))}else throw this.state="failed",s.signal.aborted?new Error(r):n}finally{clearTimeout(i)}}}}class Y{constructor(e,t={}){this.fileInfo=e,this.options=t,this.state="pending",this.tasks=[],this.completedChunks=0,this.totalChunks=0,this.totalBytes=0,this.downloadedBytes=0,this.onChunkDownloaded=null,this.skipChunks=e.skipChunks||new Set,this._contentType="application/octet-stream",this._chunkBlobs=new Map,this._runningCount=0,this._resolve=null,this._reject=null,this._promise=new Promise((s,i)=>{this._resolve=s,this._reject=i}),this._promise.catch(()=>{})}getUrl(){const e=this.fileInfo.path;if(K(e))throw new Error(`URL expired for ${this.fileInfo.type}/${this.fileInfo.id} — waiting for fresh URL from next collection cycle`);return G(e)}wait(){return this._promise}async prepare(e){try{this.state="preparing";const{id:t,type:s,size:i}=this.fileInfo;if(l.info("[FileDownload] Starting:",`${s}/${t}`),this.totalBytes=i&&i>0?parseInt(i):0,this._contentType=he(this.fileInfo),this.totalBytes===0){const r=this.getUrl(),o=new AbortController,h=setTimeout(()=>o.abort(),ce);try{const a=await fetch(r,{method:"HEAD",signal:o.signal});a.ok&&(this.totalBytes=parseInt(a.headers.get("Content-Length")||"0"),this._contentType=a.headers.get("Content-Type")||this._contentType)}finally{clearTimeout(h)}}l.info("[FileDownload] File size:",(this.totalBytes/1024/1024).toFixed(1),"MB");const n=this.options.chunkSize||j;if(this.totalBytes>oe){const r=[];for(let d=0;d<this.totalBytes;d+=n)r.push({start:d,end:Math.min(d+n-1,this.totalBytes-1),index:r.length});this.totalChunks=r.length;const o=r.filter(d=>!this.skipChunks.has(d.index)),h=r.length-o.length;for(const d of r)this.skipChunks.has(d.index)&&(this.downloadedBytes+=d.end-d.start+1);if(o.length===0){l.info("[FileDownload] All chunks already cached, nothing to download"),this.state="complete",this._resolve(new Blob([],{type:this._contentType}));return}h>0&&l.info(`[FileDownload] Resuming: ${h} chunks cached, ${o.length} to download`);const a=h>0;if(a){const d=o.sort((g,y)=>g.index-y.index);for(const g of d){const y=new z(this.fileInfo,{chunkIndex:g.index,rangeStart:g.start,rangeEnd:g.end});y._parentFile=this,y._priority=f.normal,this.tasks.push(y)}}else for(const d of o){const g=new z(this.fileInfo,{chunkIndex:d.index,rangeStart:d.start,rangeEnd:d.end});g._parentFile=this,g._priority=d.index===0||d.index===r.length-1?f.high:f.normal,this.tasks.push(g)}const p=this.tasks.filter(d=>d._priority>=f.high).length;l.info(`[FileDownload] ${s}/${t}: ${this.tasks.length} chunks`+(p>0?` (${p} priority)`:"")+(a?" (resume)":""))}else{this.totalChunks=1;const r=new z(this.fileInfo,{});r._parentFile=this,this.tasks.push(r)}e.enqueueChunkTasks(this.tasks),this.state="downloading"}catch(t){l.error("[FileDownload] Prepare failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}async onTaskComplete(e){if(this.completedChunks++,this.downloadedBytes+=e.blob.size,e.chunkIndex!=null&&this._chunkBlobs.set(e.chunkIndex,e.blob),this.options.onProgress&&this.options.onProgress(this.downloadedBytes,this.totalBytes),this.onChunkDownloaded&&e.chunkIndex!=null)try{await this.onChunkDownloaded(e.chunkIndex,e.blob,this.totalChunks)}catch(t){l.warn("[FileDownload] onChunkDownloaded callback error:",t)}if(this.completedChunks===this.tasks.length&&this.state!=="complete"){this.state="complete";const{type:t,id:s}=this.fileInfo;if(e.chunkIndex==null)l.info("[FileDownload] Complete:",`${t}/${s}`,`(${e.blob.size} bytes)`),this._resolve(e.blob);else if(this.onChunkDownloaded)l.info("[FileDownload] Complete:",`${t}/${s}`,`(progressive, ${this.totalChunks} chunks)`),this._resolve(new Blob([],{type:this._contentType}));else{const i=[];for(let r=0;r<this.totalChunks;r++){const o=this._chunkBlobs.get(r);o&&i.push(o)}const n=new Blob(i,{type:this._contentType});l.info("[FileDownload] Complete:",`${t}/${s}`,`(${n.size} bytes, reassembled)`),this._resolve(n)}this._chunkBlobs.clear()}}onTaskFailed(e,t){var s;if(!(this.state==="complete"||this.state==="failed")){if((s=t.message)!=null&&s.includes("URL expired")){const i=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.warn(`[FileDownload] URL expired, dropping${i}:`,`${this.fileInfo.type}/${this.fileInfo.id}`),this.tasks=this.tasks.filter(n=>n!==e),(this.tasks.length===0||this.completedChunks>=this.tasks.length)&&(this.state="complete",this._urlExpired=!0,this._resolve(new Blob([],{type:this._contentType})));return}l.error("[FileDownload] Failed:",`${this.fileInfo.type}/${this.fileInfo.id}`,t),this.state="failed",this._reject(t)}}}class ge{constructor(e){this.queue=e,this._filesToPrepare=[],this._tasks=[],this._maxPreparing=2}addFile(e){const t=q.stableKey(e);if(this.queue.active.has(t)){const i=this.queue.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.queue.chunkSize,calculateMD5:this.queue.calculateMD5,onProgress:this.queue.onProgress});return this.queue.active.set(t,s),this._filesToPrepare.push(s),s}enqueueChunkTasks(e){this._tasks.push(...e)}async build(){return await this._prepareAll(),this._sortWithBarriers()}async _prepareAll(){await new Promise(e=>{let t=0,s=0;const i=()=>{for(;t<this._maxPreparing&&s<this._filesToPrepare.length;){const n=this._filesToPrepare[s++];t++,n.prepare(this).finally(()=>{t--,s>=this._filesToPrepare.length&&t===0?e():i()})}};this._filesToPrepare.length===0?e():i()})}_sortWithBarriers(){var r;const e=[],t=[],s=[],i=[];for(const o of this._tasks)if(o.chunkIndex==null)e.push(o);else if(o.chunkIndex===0)t.push(o);else{const h=((r=o._parentFile)==null?void 0:r.totalChunks)||0;h>1&&o.chunkIndex===h-1?s.push(o):i.push(o)}e.sort((o,h)=>{var a,p;return(((a=o._parentFile)==null?void 0:a.totalBytes)||0)-(((p=h._parentFile)==null?void 0:p.totalBytes)||0)}),i.sort((o,h)=>o.chunkIndex-h.chunkIndex);const n=[...e,...t,...s];return i.length>0&&n.push($,...i),n}}class q{constructor(e={}){this.concurrency=e.concurrency||ie,this.chunkSize=e.chunkSize||j,this.maxChunksPerFile=e.chunksPerFile||ne,this.calculateMD5=e.calculateMD5,this.onProgress=e.onProgress,this.queue=[],this.active=new Map,this._activeTasks=[],this.running=0,this._prepareQueue=[],this._preparingCount=0,this._maxPreparing=2,this.paused=!1}static stableKey(e){return`${e.type}/${e.id}`}enqueue(e){const t=q.stableKey(e);if(this.active.has(t)){const i=this.active.get(t);if(e.path&&e.path!==i.fileInfo.path){const n=S(i.fileInfo.path);S(e.path)>n&&(l.info("[DownloadQueue] Refreshing URL for",t),i.fileInfo.path=e.path)}return i}const s=new Y(e,{chunkSize:this.chunkSize,calculateMD5:this.calculateMD5,onProgress:this.onProgress});return this.active.set(t,s),l.info("[DownloadQueue] Enqueued:",t),this._schedulePrepare(s),s}_schedulePrepare(e){this._prepareQueue.push(e),this._processPrepareQueue()}_processPrepareQueue(){for(;this._preparingCount<this._maxPreparing&&this._prepareQueue.length>0;){const e=this._prepareQueue.shift();this._preparingCount++,e.prepare(this).finally(()=>{this._preparingCount--,this._processPrepareQueue()})}}enqueueChunkTasks(e){for(const t of e)this.queue.push(t);this._sortQueue(),l.info(`[DownloadQueue] ${e.length} tasks added (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}enqueueOrderedTasks(e){let t=0,s=0;for(const i of e)i===$?(this.queue.push($),s++):(this.queue.push(i),t++);l.info(`[DownloadQueue] Ordered queue: ${t} tasks, ${s} barriers (${this.queue.length} pending, ${this.running} active)`),this.processQueue()}_sortQueue(){this.queue.sort((e,t)=>t._priority-e._priority)}prioritize(e,t){const s=`${e}/${t}`,i=this.active.get(s);if(!i)return l.info("[DownloadQueue] Not found:",s),!1;let n=0;for(const r of this.queue)r._parentFile===i&&r._priority<f.high&&(r._priority=f.high,n++);return this._sortQueue(),l.info("[DownloadQueue] Prioritized:",s,`(${n} tasks boosted)`),!0}prioritizeLayoutFiles(e,t=f.high){var n,r;const s=new Set(e.map(String));let i=0;for(const o of this.queue)s.has(String((n=o._parentFile)==null?void 0:n.fileInfo.id))&&o._priority<t&&(o._priority=t,i++);for(const o of this._activeTasks)s.has(String((r=o._parentFile)==null?void 0:r.fileInfo.id))&&o._priority<t&&(o._priority=t);this._sortQueue(),l.info("[DownloadQueue] Layout files prioritized:",s.size,"files,",i,"tasks boosted to",t)}urgentChunk(e,t,s){const i=`${e}/${t}`,n=this.active.get(i);if(!n)return l.info("[DownloadQueue] urgentChunk: file not active:",i,"chunk",s),!1;if(this._activeTasks.some(a=>a._parentFile===n&&a.chunkIndex===s&&a.state==="downloading")){const a=this._activeTasks.find(p=>p._parentFile===n&&p.chunkIndex===s);return a&&a._priority<f.urgent?(a._priority=f.urgent,l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (already in-flight, limiting slots)`),!0):(l.info("[DownloadQueue] urgentChunk: already urgent:",i,"chunk",s),!1)}const o=this.queue.findIndex(a=>a!==$&&a._parentFile===n&&a.chunkIndex===s);if(o===-1)return l.info("[DownloadQueue] urgentChunk: chunk not in queue:",i,"chunk",s),!1;const h=this.queue.splice(o,1)[0];return h._priority=f.urgent,this.queue.unshift(h),l.info(`[DownloadQueue] URGENT: ${i} chunk ${s} (moved to front)`),this.processQueue(),!0}processQueue(){var i;if(this.paused)return;const e=this.queue.some(n=>n!==$&&n._priority>=f.urgent)||((i=this._activeTasks)==null?void 0:i.some(n=>n._priority>=f.urgent&&n.state==="downloading")),t=e?ae:this.concurrency,s=e?f.urgent:0;for(;this.running<t&&this.queue.length>0;){const n=this.queue[0];if(n===$){if(this.running>0)break;this.queue.shift();continue}if(n._priority<s||!this._canStartTask(n)){let r=!1;for(let o=1;o<this.queue.length&&this.queue[o]!==$;o++){const h=this.queue[o];if(h._priority>=s&&this._canStartTask(h)){this.queue.splice(o,1),this._startTask(h),r=!0;break}}if(!r)break;continue}this.queue.shift(),this._startTask(n)}this.queue.length===0&&this.running===0&&l.info("[DownloadQueue] All downloads complete")}_canStartTask(e){return e._parentFile._runningCount<this.maxChunksPerFile}_startTask(e){this.running++,e._parentFile._runningCount++,this._activeTasks.push(e);const t=`${e.fileInfo.type}/${e.fileInfo.id}`,s=e.chunkIndex!=null?` chunk ${e.chunkIndex}`:"";l.info(`[DownloadQueue] Starting: ${t}${s} (${this.running}/${this.concurrency} active)`),e.start().then(()=>(this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(i=>i!==e),l.info(`[DownloadQueue] Fetched: ${t}${s} (${this.running} active, ${this.queue.length} pending)`),this.processQueue(),e._parentFile.onTaskComplete(e))).catch(i=>{this.running--,e._parentFile._runningCount--,this._activeTasks=this._activeTasks.filter(n=>n!==e),this.processQueue(),e._parentFile.onTaskFailed(e,i)})}awaitAllPrepared(){return new Promise(e=>{const t=()=>{this._preparingCount===0&&this._prepareQueue.length===0?e():setTimeout(t,50)};t()})}removeCompleted(e){const t=this.active.get(e);t&&(t.state==="complete"||t.state==="failed")&&(this.queue=this.queue.filter(s=>s===$||s._parentFile!==t),this.active.delete(e))}getTask(e){return this.active.get(e)||null}getProgress(){const e={};for(const[t,s]of this.active.entries())e[t]={downloaded:s.downloadedBytes,total:s.totalBytes,percent:s.totalBytes>0?(s.downloadedBytes/s.totalBytes*100).toFixed(1):0,state:s.state};return e}clear(){this.queue=[],this.active.clear(),this.running=0,this._prepareQueue=[],this._preparingCount=0}}class we{constructor(e={}){this.queue=new q(e)}enqueue(e){return this.queue.enqueue(e)}enqueueForLayout(e){return this.queue.enqueue(e)}getTask(e){return this.queue.getTask(e)}getProgress(){return this.queue.getProgress()}prioritizeLayoutFiles(e,t){this.queue.prioritizeLayoutFiles(e,t),this.queue.processQueue()}urgentChunk(e,t,s){return this.queue.urgentChunk(e,t,s)}clear(){this.queue.clear()}}const _=R("CacheAnalyzer");function E(u){if(u===0)return"0 B";if(!Number.isFinite(u))return"∞";const e=["B","KB","MB","GB","TB"],t=Math.floor(Math.log(u)/Math.log(1024));return`${(u/Math.pow(1024,t)).toFixed(t>0?1:0)} ${e[t]}`}class ye{constructor(e,{threshold:t=80}={}){this.cache=e,this.threshold=t}async analyze(e){const t=await this.cache.getAllFiles(),s=await this._getStorageEstimate(),i=new Set(e.map(a=>String(a.id))),n=[],r=[];for(const a of t)if(i.has(String(a.id)))n.push(a);else if(a.type==="widget"){const p=String(a.id).split("/")[0];i.has(p)?n.push(a):r.push(a)}else r.push(a);r.sort((a,p)=>(a.cachedAt||0)-(p.cachedAt||0));const o=r.reduce((a,p)=>a+(p.size||0),0),h={timestamp:Date.now(),storage:{usage:s.usage,quota:s.quota,percent:s.quota>0?Math.round(s.usage/s.quota*100):0},files:{required:n.length,orphaned:r.length,total:t.length},orphaned:r.map(a=>({id:a.id,type:a.type,size:a.size||0,cachedAt:a.cachedAt||0})),orphanedSize:o,evicted:[],threshold:this.threshold};if(_.info(`Storage: ${E(s.usage)} / ${E(s.quota)} (${h.storage.percent}%)`),_.info(`Cache: ${n.length} required, ${r.length} orphaned (${E(o)} reclaimable)`),r.length>0)for(const a of r){const p=Date.now()-(a.cachedAt||0),d=Math.floor(p/864e5),g=Math.floor(p%864e5/36e5),y=d>0?`${d}d ago`:`${g}h ago`;_.info(` Orphaned: ${a.type}/${a.id} (${E(a.size||0)}, cached ${y})`)}if(h.storage.percent>this.threshold&&r.length>0){_.warn(`Storage exceeds ${this.threshold}% threshold — evicting orphaned files`);const a=s.usage-s.quota*this.threshold/100;h.evicted=await this._evict(r,a)}else _.info(`No eviction needed (threshold: ${this.threshold}%)`);return h}async _getStorageEstimate(){var e;try{if(typeof navigator<"u"&&((e=navigator.storage)!=null&&e.estimate)){const{usage:t,quota:s}=await navigator.storage.estimate();return{usage:t||0,quota:s||1/0}}}catch(t){_.warn("Storage estimate unavailable:",t.message)}return{usage:0,quota:1/0}}async _evict(e,t){const s=[];let i=0;for(const n of e){if(i>=t)break;s.push(n),i+=n.size||0}if(s.length===0)return[];try{const n=s.map(r=>({type:r.type,id:r.id}));await this.cache.deleteFiles(n);for(const r of s)_.info(` Evicted: ${r.type}/${r.id} (${E(r.size||0)})`);_.info(`Evicted ${s.length} files, freed ${E(i)}`)}catch(n){return _.warn("Eviction failed:",n.message),[]}return s.map(n=>({id:n.id,type:n.type,size:n.size||0,cachedAt:n.cachedAt||0}))}}const w=R("Cache"),le="xibo-media-v1",v=typeof window<"u"&&window.location.pathname.replace(/\/[^/]*$/,"").replace(/\/$/,"")||"/player/pwa";async function ke(u,e,t,s){const i=`${v}/cache/widget/${u}/${e}/${t}`,n=await caches.open(le),r=`<base href="${v}/cache/media/">`;let o=s;s.includes("<base ")||(s.includes("<head>")?o=s.replace("<head>","<head>"+r):s.includes("<HEAD>")?o=s.replace("<HEAD>","<HEAD>"+r):o=r+s);const h=/https?:\/\/[^"'\s)]+(?:xmds\.php|pwa\/file)\?[^"'\s)]*file=([^&"'\s)]+)[^"'\s)]*/g,a=[];o=o.replace(h,(y,k)=>{const m=`${v}/cache/static/${k}`;return a.push({filename:k,originalUrl:y}),w.info(`Rewrote widget URL: ${k} → ${m}`),m});const p="<style>img,video{object-position:center center}</style>";o.includes("object-position:center center")||(o.includes("</head>")?o=o.replace("</head>",p+"</head>"):o.includes("</HEAD>")&&(o=o.replace("</HEAD>",p+"</HEAD>"))),o=o.replace(/hostAddress\s*:\s*["']https?:\/\/[^"']+["']/g,`hostAddress: "${v}/ic"`),w.info("Injected base tag and rewrote CMS/data URLs in widget HTML");const d=new URL(i,window.location.origin),g=new Response(o,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*"}});if(await n.put(d,g),w.info(`Stored widget HTML at ${i} (${o.length} bytes)`),a.length>0){const k=await caches.open("xibo-static-v1");await Promise.all(a.map(async({filename:m,originalUrl:X})=>{const A=`${v}/cache/static/${m}`;if(!await k.match(A))try{const b=await fetch(X);if(!b.ok){w.warn(`Failed to fetch static resource: ${m} (HTTP ${b.status})`);return}const M=m.split(".").pop().toLowerCase(),W={js:"application/javascript",css:"text/css",otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[M]||"application/octet-stream";if(M==="css"){let C=await b.text();const I=[],Z=/url\((['"]?)(https?:\/\/[^'")\s]+\?[^'")\s]*file=([^&'")\s]+\.(?:woff2?|ttf|otf|eot|svg))[^'")\s]*)\1\)/gi;C=C.replace(Z,(T,D,F,P)=>(I.push({filename:P,originalUrl:F}),w.info(`Rewrote font URL in CSS: ${P}`),`url(${D}${v}/cache/static/${encodeURIComponent(P)}${D})`)),await k.put(A,new Response(C,{headers:{"Content-Type":"text/css"}})),w.info(`Cached CSS with ${I.length} rewritten font URLs: ${m}`),await Promise.all(I.map(async({filename:T,originalUrl:D})=>{const F=`${v}/cache/static/${encodeURIComponent(T)}`;if(!await k.match(F))try{const x=await fetch(D);if(!x.ok){w.warn(`Failed to fetch font: ${T} (HTTP ${x.status})`);return}const B=await x.blob(),V=T.split(".").pop().toLowerCase(),U={otf:"font/otf",ttf:"font/ttf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",svg:"image/svg+xml"}[V]||"application/octet-stream";await k.put(F,new Response(B,{headers:{"Content-Type":U}})),w.info(`Cached font: ${T} (${U}, ${B.size} bytes)`)}catch(x){w.warn(`Failed to cache font: ${T}`,x)}}))}else{const C=await b.blob();await k.put(A,new Response(C,{headers:{"Content-Type":W}})),w.info(`Cached static resource: ${m} (${W}, ${C.size} bytes)`)}}catch(b){w.warn(`Failed to cache static resource: ${m}`,b)}}))}return i}export{$ as B,ye as C,we as D,H as E,Y as F,ge as L,fe as a,se as b,ke as c,pe as d,K as i,G as r};
|
|
2
|
+
//# sourceMappingURL=widget-html-B_acad6q.js.map
|