@xiboplayer/pwa 0.5.0 → 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-66_11hkr.js → index-CzhSvB4B.js} +2 -2
- package/dist/assets/{index-66_11hkr.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-CN4YZpqx.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-B2e9LkNw.js.map → index-m5gp9Gft.js.map} +1 -1
- package/dist/assets/main-DfHNWLGS.js +715 -0
- package/dist/assets/main-DfHNWLGS.js.map +1 -0
- package/dist/assets/setup-D67k289O.js +2 -0
- package/dist/assets/setup-D67k289O.js.map +1 -0
- 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 +5 -5
- package/dist/setup.html +8 -7
- 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-B2e9LkNw.js +0 -2
- package/dist/assets/index-CN4YZpqx.js +0 -2
- package/dist/assets/index-_Kvq-_Zm.js +0 -2
- package/dist/assets/main-93Kmpgur.js +0 -649
- package/dist/assets/main-93Kmpgur.js.map +0 -1
- package/dist/assets/setup-C_0dET1G.js +0 -2
- package/dist/assets/setup-C_0dET1G.js.map +0 -1
- package/dist/assets/xmds-client-BPdCcQeh.js +0 -16
- package/dist/assets/xmds-client-BPdCcQeh.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xmds-client-Ci6s-34Q.js","sources":["../../node_modules/.pnpm/@xiboplayer+xmds@0.5.1/node_modules/@xiboplayer/xmds/src/schedule-parser.js","../../node_modules/.pnpm/@xiboplayer+xmds@0.5.1/node_modules/@xiboplayer/xmds/src/rest-client.js","../../node_modules/.pnpm/@xiboplayer+xmds@0.5.1/node_modules/@xiboplayer/xmds/src/xmds-client.js"],"sourcesContent":["/**\n * Shared schedule XML parser used by both RestClient and XmdsClient.\n *\n * Both transports return the same XML structure for the Schedule endpoint,\n * so the parsing logic lives here to avoid duplication.\n */\n\n/**\n * Parse criteria child elements from a layout/overlay element.\n * Criteria are conditions that must be met for the item to display.\n *\n * XML format: <criteria metric=\"dayOfWeek\" condition=\"equals\" type=\"string\">Monday</criteria>\n *\n * @param {Element} parentEl - Parent XML element containing <criteria> children\n * @returns {Array<{metric: string, condition: string, type: string, value: string}>}\n */\nfunction parseCriteria(parentEl) {\n const criteria = [];\n for (const child of parentEl.children) {\n if (child.tagName !== 'criteria') continue;\n criteria.push({\n metric: child.getAttribute('metric') || '',\n condition: child.getAttribute('condition') || '',\n type: child.getAttribute('type') || 'string',\n value: child.textContent || ''\n });\n }\n return criteria;\n}\n\n/**\n * Parse Schedule XML response into a normalized schedule object.\n *\n * @param {string} xml - Raw XML string from CMS schedule endpoint\n * @returns {Object} Parsed schedule with default, layouts, campaigns, overlays, actions, commands, dataConnectors\n */\nexport function parseScheduleResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const schedule = {\n default: null,\n defaultDependants: [],\n dependants: [], // Global dependants that gate ALL layouts\n layouts: [],\n campaigns: [],\n overlays: [],\n actions: [],\n commands: [],\n dataConnectors: []\n };\n\n // Parse global dependants (root-level <dependants> — must be cached before any layout plays)\n const scheduleEl = doc.querySelector('schedule');\n if (scheduleEl) {\n const globalDeps = Array.from(scheduleEl.children).filter(\n el => el.tagName === 'dependants'\n );\n for (const depContainer of globalDeps) {\n // Skip if this is nested inside <default>, <layout>, etc.\n if (depContainer.parentElement !== scheduleEl) continue;\n for (const fileEl of depContainer.querySelectorAll('file')) {\n if (fileEl.textContent) schedule.dependants.push(fileEl.textContent);\n }\n }\n }\n\n const defaultEl = doc.querySelector('default');\n if (defaultEl) {\n schedule.default = defaultEl.getAttribute('file');\n // Parse dependants — files that must be cached before this layout plays\n const defaultDeps = defaultEl.querySelectorAll('dependants > file');\n if (defaultDeps.length > 0) {\n schedule.defaultDependants = [...defaultDeps].map(el => el.textContent);\n }\n }\n\n // Parse campaigns (groups of layouts with shared priority)\n for (const campaignEl of doc.querySelectorAll('campaign')) {\n const campaign = {\n id: campaignEl.getAttribute('id'),\n priority: parseInt(campaignEl.getAttribute('priority') || '0'),\n fromdt: campaignEl.getAttribute('fromdt'),\n todt: campaignEl.getAttribute('todt'),\n scheduleid: campaignEl.getAttribute('scheduleid'),\n maxPlaysPerHour: parseInt(campaignEl.getAttribute('maxPlaysPerHour') || '0'),\n shareOfVoice: parseInt(campaignEl.getAttribute('shareOfVoice') || '0'),\n isGeoAware: campaignEl.getAttribute('isGeoAware') === '1',\n geoLocation: campaignEl.getAttribute('geoLocation') || '',\n syncEvent: campaignEl.getAttribute('syncEvent') === '1',\n recurrenceType: campaignEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(campaignEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: campaignEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: campaignEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(campaignEl),\n layouts: []\n };\n\n // Parse layouts within this campaign\n for (const layoutEl of campaignEl.querySelectorAll('layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n campaign.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n // Layouts in campaigns inherit timing from campaign level\n fromdt: layoutEl.getAttribute('fromdt') || campaign.fromdt,\n todt: layoutEl.getAttribute('todt') || campaign.todt,\n scheduleid: campaign.scheduleid,\n priority: campaign.priority, // Priority at campaign level\n campaignId: campaign.id,\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n schedule.campaigns.push(campaign);\n }\n\n // Parse standalone layouts (not in campaigns)\n for (const layoutEl of doc.querySelectorAll('schedule > layout')) {\n const fileId = layoutEl.getAttribute('file');\n const depEls = layoutEl.querySelectorAll('dependants > file');\n schedule.layouts.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n file: fileId,\n fromdt: layoutEl.getAttribute('fromdt'),\n todt: layoutEl.getAttribute('todt'),\n scheduleid: layoutEl.getAttribute('scheduleid'),\n priority: parseInt(layoutEl.getAttribute('priority') || '0'),\n campaignId: null, // Standalone layout\n maxPlaysPerHour: parseInt(layoutEl.getAttribute('maxPlaysPerHour') || '0'),\n isGeoAware: layoutEl.getAttribute('isGeoAware') === '1',\n geoLocation: layoutEl.getAttribute('geoLocation') || '',\n syncEvent: layoutEl.getAttribute('syncEvent') === '1',\n shareOfVoice: parseInt(layoutEl.getAttribute('shareOfVoice') || '0'),\n duration: parseInt(layoutEl.getAttribute('duration') || '0'),\n cyclePlayback: layoutEl.getAttribute('cyclePlayback') === '1',\n groupKey: layoutEl.getAttribute('groupKey') || null,\n playCount: parseInt(layoutEl.getAttribute('playCount') || '0'),\n recurrenceType: layoutEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(layoutEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: layoutEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: layoutEl.getAttribute('recurrenceRange') || null,\n dependants: depEls.length > 0 ? [...depEls].map(el => el.textContent) : [],\n criteria: parseCriteria(layoutEl)\n });\n }\n\n // Parse overlay layouts (appear on top of main layouts)\n const overlaysContainer = doc.querySelector('overlays');\n if (overlaysContainer) {\n for (const overlayEl of overlaysContainer.querySelectorAll('overlay')) {\n const fileId = overlayEl.getAttribute('file');\n schedule.overlays.push({\n id: String(fileId), // Normalized string ID for consistent type usage\n duration: parseInt(overlayEl.getAttribute('duration') || '60'),\n file: fileId,\n fromdt: overlayEl.getAttribute('fromdt'),\n todt: overlayEl.getAttribute('todt'),\n priority: parseInt(overlayEl.getAttribute('priority') || '0'),\n scheduleid: overlayEl.getAttribute('scheduleid'),\n isGeoAware: overlayEl.getAttribute('isGeoAware') === '1',\n geoLocation: overlayEl.getAttribute('geoLocation') || '',\n syncEvent: overlayEl.getAttribute('syncEvent') === '1',\n maxPlaysPerHour: parseInt(overlayEl.getAttribute('maxPlaysPerHour') || '0'),\n recurrenceType: overlayEl.getAttribute('recurrenceType') || null,\n recurrenceDetail: parseInt(overlayEl.getAttribute('recurrenceDetail') || '0') || null,\n recurrenceRepeatsOn: overlayEl.getAttribute('recurrenceRepeatsOn') || null,\n recurrenceRange: overlayEl.getAttribute('recurrenceRange') || null,\n criteria: parseCriteria(overlayEl)\n });\n }\n }\n\n // Parse action events (scheduled triggers)\n const actionsContainer = doc.querySelector('actions');\n if (actionsContainer) {\n for (const actionEl of actionsContainer.querySelectorAll('action')) {\n schedule.actions.push({\n actionType: actionEl.getAttribute('actionType') || '',\n triggerCode: actionEl.getAttribute('triggerCode') || '',\n layoutCode: actionEl.getAttribute('layoutCode') || '',\n commandCode: actionEl.getAttribute('commandCode') || '',\n duration: parseInt(actionEl.getAttribute('duration') || '0'),\n fromdt: actionEl.getAttribute('fromdt'),\n todt: actionEl.getAttribute('todt'),\n priority: parseInt(actionEl.getAttribute('priority') || '0'),\n scheduleid: actionEl.getAttribute('scheduleid'),\n isGeoAware: actionEl.getAttribute('isGeoAware') === '1',\n geoLocation: actionEl.getAttribute('geoLocation') || ''\n });\n }\n }\n\n // Parse server commands (remote control)\n for (const cmdEl of doc.querySelectorAll('schedule > command')) {\n schedule.commands.push({\n code: cmdEl.getAttribute('code') || '',\n date: cmdEl.getAttribute('date') || ''\n });\n }\n\n // Parse data connectors (real-time data sources for widgets)\n // Spec: <dataConnectors><connector dataSetId=\"\" dataParams=\"\" js=\"\"/></dataConnectors>\n const dataConnectorsContainer = doc.querySelector('dataConnectors');\n if (dataConnectorsContainer) {\n for (const dcEl of dataConnectorsContainer.querySelectorAll('connector')) {\n schedule.dataConnectors.push({\n id: dcEl.getAttribute('id') || '',\n dataConnectorId: dcEl.getAttribute('dataConnectorId') || '',\n dataSetId: dcEl.getAttribute('dataSetId') || '',\n dataKey: dcEl.getAttribute('dataKey') || '',\n dataParams: dcEl.getAttribute('dataParams') || '',\n js: dcEl.getAttribute('js') || '',\n url: dcEl.getAttribute('url') || '',\n updateInterval: parseInt(dcEl.getAttribute('updateInterval') || '300', 10)\n });\n }\n }\n\n return schedule;\n}\n","/**\n * REST transport client for Xibo CMS.\n *\n * Uses the /pwa REST API endpoints with JSON payloads and ETag caching.\n * Lighter than SOAP — ~30% smaller payloads, standard HTTP semantics.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry } from '@xiboplayer/utils';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('REST');\n\nexport class RestClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 7;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n\n // ETag-based HTTP caching\n this._etags = new Map(); // endpoint → ETag string\n this._responseCache = new Map(); // endpoint → cached parsed response\n\n log.info('Using REST transport');\n }\n\n // ─── Transport helpers ──────────────────────────────────────────\n\n /**\n * Get the REST API base URL.\n * Falls back to /pwa path relative to the CMS address.\n */\n getRestBaseUrl() {\n const base = this.config.restApiUrl || `${this.config.cmsUrl}/pwa`;\n return base.replace(/\\/+$/, '');\n }\n\n /**\n * Check if running behind the local proxy (Electron or Chromium kiosk).\n */\n _isProxyMode() {\n return typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n (window.location.hostname === 'localhost' && window.location.port === '8765'));\n }\n\n /**\n * Rewrite an absolute REST URL to go through /rest-proxy.\n * Preserves all query params from the original URL.\n */\n _rewriteForProxy(urlString) {\n if (!this._isProxyMode() || !urlString.startsWith('http')) return urlString;\n const parsed = new URL(urlString);\n const proxyUrl = new URL('/rest-proxy', window.location.origin);\n proxyUrl.searchParams.set('cms', parsed.origin);\n proxyUrl.searchParams.set('path', parsed.pathname);\n // Forward all original query params\n for (const [key, value] of parsed.searchParams) {\n proxyUrl.searchParams.set(key, value);\n }\n return proxyUrl.toString();\n }\n\n /**\n * Make a REST GET request with optional ETag caching.\n * Returns the parsed JSON body, or cached data on 304.\n */\n async restGet(path, queryParams = {}) {\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n url.searchParams.set('serverKey', this.config.cmsKey);\n url.searchParams.set('hardwareKey', this.config.hardwareKey);\n url.searchParams.set('v', String(this.schemaVersion));\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, String(value));\n }\n\n const cacheKey = path;\n const headers = {};\n const cachedEtag = this._etags.get(cacheKey);\n if (cachedEtag) {\n headers['If-None-Match'] = cachedEtag;\n }\n\n log.debug(`GET ${path}`, queryParams);\n\n const response = await fetchWithRetry(this._rewriteForProxy(url.toString()), {\n method: 'GET',\n headers,\n }, this.retryOptions);\n\n // 304 Not Modified — return cached response\n if (response.status === 304) {\n const cached = this._responseCache.get(cacheKey);\n if (cached) {\n log.debug(`${path} → 304 (using cache)`);\n return cached;\n }\n // Cache miss despite 304 — fall through to fetch fresh\n }\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST GET ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n // Store ETag for future requests\n const etag = response.headers.get('ETag');\n if (etag) {\n this._etags.set(cacheKey, etag);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n let data;\n if (contentType.includes('application/json')) {\n data = await response.json();\n } else {\n // XML or HTML — return raw text\n data = await response.text();\n }\n\n // Cache parsed response for 304 reuse\n this._responseCache.set(cacheKey, data);\n return data;\n }\n\n /**\n * Make a REST POST/PUT request with JSON body.\n * Returns the parsed JSON response.\n */\n async restSend(method, path, body = {}) {\n const url = new URL(`${this.getRestBaseUrl()}${path}`);\n url.searchParams.set('v', String(this.schemaVersion));\n\n log.debug(`${method} ${path}`);\n\n const response = await fetchWithRetry(this._rewriteForProxy(url.toString()), {\n method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n ...body,\n }),\n }, this.retryOptions);\n\n if (!response.ok) {\n const errorBody = await response.text().catch(() => '');\n throw new Error(`REST ${method} ${path} failed: ${response.status} ${response.statusText} ${errorBody}`);\n }\n\n const contentType = response.headers.get('Content-Type') || '';\n if (contentType.includes('application/json')) {\n return await response.json();\n }\n return await response.text();\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n * POST /register → JSON with display settings\n */\n async registerDisplay() {\n const os = typeof navigator !== 'undefined'\n ? `${navigator.platform} ${navigator.userAgent}`\n : 'unknown';\n\n const json = await this.restSend('POST', '/register', {\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'chromeOS',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || 1,\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel,\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed',\n });\n\n return this._parseRegisterDisplayJson(json);\n }\n\n /**\n * Parse REST JSON RegisterDisplay response into the same format as SOAP.\n */\n _parseRegisterDisplayJson(json) {\n // Handle both direct object and wrapped {display: ...} forms\n const display = json.display || json;\n const attrs = display['@attributes'] || {};\n const code = attrs.code || display.code;\n const message = attrs.message || display.message || '';\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n let tags = [];\n let commands = [];\n for (const [key, value] of Object.entries(display)) {\n if (key === '@attributes' || key === 'file') continue;\n if (key === 'commands') {\n // Parse commands: array of {code/commandCode, commandString} objects\n if (Array.isArray(value)) {\n commands = value.map(c => ({\n commandCode: c.code || c.commandCode || '',\n commandString: c.commandString || ''\n }));\n }\n continue;\n }\n if (key === 'tags') {\n // Parse tags from CMS JSON (SimpleXMLElement serialization varies):\n // Array of strings: [\"geoApiKey|AIzaSy...\"]\n // Array of objects: [{tag: \"geoApiKey|AIzaSy...\"}]\n // Single-tag object: {tag: \"geoApiKey|AIzaSy...\"} (SimpleXMLElement collapses single-element arrays)\n // String: \"geoApiKey|AIzaSy...\"\n const extractTag = (t) => typeof t === 'object' ? (t.tag || t.value || '') : String(t);\n if (Array.isArray(value)) {\n tags = value.map(extractTag).filter(Boolean);\n } else if (value && typeof value === 'object') {\n // Single tag: {tag: \"value\"} — wrap in array\n const t = extractTag(value);\n if (t) tags = [t];\n } else if (typeof value === 'string' && value) {\n tags = [value];\n }\n continue;\n }\n settings[key] = typeof value === 'object' ? JSON.stringify(value) : String(value);\n }\n\n const checkRf = attrs.checkRf || '';\n const checkSchedule = attrs.checkSchedule || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: attrs.date || display.date || null,\n timezone: attrs.timezone || display.timezone || null,\n status: attrs.status || display.status || null,\n localDate: attrs.localDate || display.localDate || null,\n version_instructions: attrs.version_instructions || display.version_instructions || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n // syncGroup: \"lead\" if this display is leader, or leader's LAN IP if follower\n const syncConfig = display.syncGroup ? {\n syncGroup: String(display.syncGroup),\n syncPublisherPort: parseInt(display.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(display.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(display.syncVideoPauseDelay || '100', 10),\n isLead: String(display.syncGroup) === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n * GET /requiredFiles → JSON file manifest (with ETag caching)\n */\n async requiredFiles() {\n const json = await this.restGet('/requiredFiles');\n return this._parseRequiredFilesJson(json);\n }\n\n /**\n * Parse REST JSON RequiredFiles into the same array format as SOAP.\n */\n _parseRequiredFilesJson(json) {\n const files = [];\n let fileList = json.file || [];\n\n // Normalize single item to array\n if (!Array.isArray(fileList)) {\n fileList = [fileList];\n }\n\n for (const f of fileList) {\n const attrs = f['@attributes'] || f;\n const path = attrs.path || null;\n files.push({\n type: attrs.type || null,\n id: attrs.id || null,\n size: parseInt(attrs.size || '0'),\n md5: attrs.md5 || null,\n download: attrs.download || null,\n path,\n saveAs: attrs.saveAs || null,\n fileType: attrs.fileType || null,\n code: attrs.code || null,\n layoutid: attrs.layoutid || null,\n regionid: attrs.regionid || null,\n mediaid: attrs.mediaid || null,\n });\n }\n\n // Parse purge items — files CMS wants the player to delete\n const purgeItems = [];\n let purgeList = json.purge?.item || [];\n if (!Array.isArray(purgeList)) purgeList = [purgeList];\n for (const p of purgeList) {\n const pAttrs = p['@attributes'] || p;\n purgeItems.push({\n id: pAttrs.id || null,\n storedAs: pAttrs.storedAs || null,\n });\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n * GET /schedule → XML (preserved for layout parser compatibility, with ETag caching)\n */\n async schedule() {\n const xml = await this.restGet('/schedule');\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n * GET /getResource → HTML string\n */\n async getResource(layoutId, regionId, mediaId) {\n return this.restGet('/getResource', {\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId),\n });\n }\n\n /**\n * NotifyStatus - report current status\n * PUT /status → JSON acknowledgement\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n // Enrich with storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return this.restSend('PUT', '/status', {\n statusData: status,\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n * POST /mediaInventory → JSON acknowledgement\n */\n async mediaInventory(inventoryXml) {\n // Accept array (JSON-native) or string (XML) — send under the right key\n const body = Array.isArray(inventoryXml)\n ? { inventoryItems: inventoryXml }\n : { inventory: inventoryXml };\n return this.restSend('POST', '/mediaInventory', body);\n }\n\n /**\n * BlackList - report broken media to CMS\n * POST /blacklist → JSON acknowledgement\n * @param {string|number} mediaId - The media ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const result = await this.restSend('POST', '/blacklist', {\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render',\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return result?.success === true;\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS\n * POST /log → JSON acknowledgement\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n // Accept array (JSON-native) or string (XML) — send under the right key\n const body = Array.isArray(logXml) ? { logs: logXml } : { logXml };\n if (hardwareKeyOverride) body.hardwareKey = hardwareKeyOverride;\n const result = await this.restSend('POST', '/log', body);\n return result?.success === true;\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS\n * POST /screenshot → JSON acknowledgement\n */\n async submitScreenShot(base64Image) {\n const result = await this.restSend('POST', '/screenshot', {\n screenshot: base64Image,\n });\n return result?.success === true;\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * POST /stats → JSON acknowledgement\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * POST /fault → JSON acknowledgement\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n const result = await this.restSend('POST', '/fault', { fault: faultJson });\n return result?.success === true;\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * GET /weather → JSON weather data\n * @returns {Promise<Object>} Weather data from CMS\n */\n async getWeather() {\n return this.restGet('/weather');\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n // Accept array (JSON-native) or string (XML) — send under the right key\n const body = Array.isArray(statsXml) ? { stats: statsXml } : { statXml: statsXml };\n if (hardwareKeyOverride) body.hardwareKey = hardwareKeyOverride;\n const result = await this.restSend('POST', '/stats', body);\n const success = result?.success === true;\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n","/**\n * XMDS SOAP transport client for Xibo CMS.\n *\n * Uses the traditional SOAP/XML endpoint (xmds.php) for full protocol\n * compatibility with all Xibo CMS versions.\n *\n * Protocol: https://github.com/linuxnow/xibo_players_docs\n */\nimport { createLogger, fetchWithRetry } from '@xiboplayer/utils';\nimport { parseScheduleResponse } from './schedule-parser.js';\n\nconst log = createLogger('XMDS');\n\nexport class XmdsClient {\n constructor(config) {\n this.config = config;\n this.schemaVersion = 5;\n this.retryOptions = config.retryOptions || { maxRetries: 2, baseDelayMs: 2000 };\n }\n\n // ─── SOAP transport helpers ─────────────────────────────────────\n\n /**\n * Build SOAP envelope for a given method and parameters\n */\n buildEnvelope(method, params) {\n const paramElements = Object.entries(params)\n .map(([key, value]) => {\n const escaped = String(value)\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n return `<${key} xsi:type=\"xsd:string\">${escaped}</${key}>`;\n })\n .join('\\n ');\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soap:Envelope\n xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"\n xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:tns=\"urn:xmds\"\n xmlns:types=\"urn:xmds/encodedTypes\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <soap:Body soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n <tns:${method}>\n ${paramElements}\n </tns:${method}>\n </soap:Body>\n</soap:Envelope>`;\n }\n\n /**\n * Rewrite XMDS URL for Electron proxy.\n * If running inside the Electron shell, use the local proxy to avoid CORS.\n * Detection: preload.js exposes window.electronAPI.isElectron = true,\n * or fallback to checking localhost:8765 (default Electron server port).\n */\n rewriteXmdsUrl(cmsUrl) {\n if (typeof window !== 'undefined' &&\n (window.electronAPI?.isElectron ||\n (window.location.hostname === 'localhost' && window.location.port === '8765'))) {\n const encodedCmsUrl = encodeURIComponent(cmsUrl);\n return `/xmds-proxy?cms=${encodedCmsUrl}`;\n }\n\n return `${cmsUrl}/xmds.php`;\n }\n\n /**\n * Call XMDS SOAP method\n */\n async call(method, params = {}) {\n const xmdsUrl = this.rewriteXmdsUrl(this.config.cmsUrl);\n const url = `${xmdsUrl}${xmdsUrl.includes('?') ? '&' : '?'}v=${this.schemaVersion}&method=${method}`;\n const body = this.buildEnvelope(method, params);\n\n log.debug(`${method}`, params);\n log.debug(`URL: ${url}`);\n\n const response = await fetchWithRetry(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'text/xml; charset=utf-8'\n },\n body\n }, this.retryOptions);\n\n if (!response.ok) {\n throw new Error(`XMDS ${method} failed: ${response.status} ${response.statusText}`);\n }\n\n const xml = await response.text();\n return this.parseResponse(xml, method);\n }\n\n /**\n * Parse SOAP response\n */\n parseResponse(xml, method) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n // Check for SOAP fault (handle namespace prefix like soap:Fault)\n let fault = doc.querySelector('Fault');\n if (!fault) {\n fault = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === 'Fault' || el.tagName.endsWith(':Fault')\n );\n }\n if (fault) {\n const faultString = fault.querySelector('faultstring')?.textContent\n || Array.from(fault.querySelectorAll('*')).find(el => el.localName === 'faultstring')?.textContent\n || 'Unknown SOAP fault';\n throw new Error(`SOAP Fault: ${faultString}`);\n }\n\n // Extract response element (handle namespace prefixes like ns1:MethodResponse)\n const responseTag = `${method}Response`;\n let responseEl = doc.querySelector(responseTag);\n if (!responseEl) {\n responseEl = Array.from(doc.querySelectorAll('*')).find(\n el => el.localName === responseTag || el.tagName.endsWith(':' + responseTag)\n );\n }\n\n if (!responseEl) {\n throw new Error(`No ${responseTag} element in SOAP response`);\n }\n\n const returnEl = responseEl.firstElementChild;\n if (!returnEl) {\n return null;\n }\n\n return returnEl.textContent;\n }\n\n // ─── Public API ─────────────────────────────────────────────────\n\n /**\n * RegisterDisplay - authenticate and get settings\n */\n async registerDisplay() {\n const os = `${navigator.platform} ${navigator.userAgent}`;\n\n const xml = await this.call('RegisterDisplay', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n displayName: this.config.displayName,\n clientType: this.config.clientType || 'chromeOS',\n clientVersion: this.config.clientVersion || '0.1.0',\n clientCode: this.config.clientCode || '1',\n operatingSystem: os,\n macAddress: this.config.macAddress || 'n/a',\n xmrChannel: this.config.xmrChannel || '',\n xmrPubKey: this.config.xmrPubKey || '',\n licenceResult: 'licensed'\n });\n\n return this.parseRegisterDisplayResponse(xml);\n }\n\n /**\n * Parse RegisterDisplay XML response\n */\n parseRegisterDisplayResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const display = doc.querySelector('display');\n if (!display) {\n throw new Error('Invalid RegisterDisplay response: no <display> element');\n }\n\n const code = display.getAttribute('code');\n const message = display.getAttribute('message');\n\n if (code !== 'READY') {\n return { code, message, settings: null };\n }\n\n const settings = {};\n const tags = [];\n const commands = [];\n for (const child of display.children) {\n const name = child.tagName.toLowerCase();\n if (name === 'file') continue;\n if (name === 'commands') {\n // Parse <commands><command code=\"xyz\" commandString=\"args\"/></commands>\n for (const cmdEl of child.querySelectorAll('command')) {\n commands.push({\n commandCode: cmdEl.getAttribute('code') || cmdEl.getAttribute('commandCode') || '',\n commandString: cmdEl.getAttribute('commandString') || ''\n });\n }\n continue;\n }\n if (name === 'tags') {\n // Parse <tags><tag>value</tag>...</tags> into array\n for (const tagEl of child.querySelectorAll('tag')) {\n if (tagEl.textContent) tags.push(tagEl.textContent);\n }\n continue;\n }\n settings[child.tagName] = child.textContent;\n }\n\n const checkRf = display.getAttribute('checkRf') || '';\n const checkSchedule = display.getAttribute('checkSchedule') || '';\n\n // Extract display-level attributes from CMS (server time, status, version info)\n const displayAttrs = {\n date: display.getAttribute('date') || null,\n timezone: display.getAttribute('timezone') || null,\n status: display.getAttribute('status') || null,\n localDate: display.getAttribute('localDate') || null,\n version_instructions: display.getAttribute('version_instructions') || null,\n };\n\n // Extract sync group config if present (multi-display sync coordination)\n const syncGroupVal = settings.syncGroup || null;\n const syncConfig = syncGroupVal ? {\n syncGroup: syncGroupVal,\n syncPublisherPort: parseInt(settings.syncPublisherPort || '9590', 10),\n syncSwitchDelay: parseInt(settings.syncSwitchDelay || '750', 10),\n syncVideoPauseDelay: parseInt(settings.syncVideoPauseDelay || '100', 10),\n isLead: syncGroupVal === 'lead',\n } : null;\n\n return { code, message, settings, tags, commands, displayAttrs, checkRf, checkSchedule, syncConfig };\n }\n\n /**\n * RequiredFiles - get list of files to download\n */\n async requiredFiles() {\n const xml = await this.call('RequiredFiles', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return this.parseRequiredFilesResponse(xml);\n }\n\n /**\n * Parse RequiredFiles XML response\n */\n parseRequiredFilesResponse(xml) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(xml, 'text/xml');\n\n const files = [];\n for (const fileEl of doc.querySelectorAll('file')) {\n files.push({\n type: fileEl.getAttribute('type'),\n id: fileEl.getAttribute('id'),\n size: parseInt(fileEl.getAttribute('size') || '0'),\n md5: fileEl.getAttribute('md5'),\n download: fileEl.getAttribute('download'),\n path: fileEl.getAttribute('path'),\n saveAs: fileEl.getAttribute('saveAs') || null,\n fileType: fileEl.getAttribute('fileType') || null,\n code: fileEl.getAttribute('code'),\n layoutid: fileEl.getAttribute('layoutid'),\n regionid: fileEl.getAttribute('regionid'),\n mediaid: fileEl.getAttribute('mediaid')\n });\n }\n\n // Parse purge block — files CMS wants the player to delete\n const purgeItems = [];\n const purgeEl = doc.querySelector('purge');\n if (purgeEl) {\n for (const itemEl of purgeEl.querySelectorAll('item')) {\n purgeItems.push({\n id: itemEl.getAttribute('id'),\n storedAs: itemEl.getAttribute('storedAs')\n });\n }\n }\n\n return { files, purge: purgeItems };\n }\n\n /**\n * Schedule - get layout schedule\n */\n async schedule() {\n const xml = await this.call('Schedule', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n\n return parseScheduleResponse(xml);\n }\n\n /**\n * GetResource - get rendered widget HTML\n */\n async getResource(layoutId, regionId, mediaId) {\n const xml = await this.call('GetResource', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n layoutId: String(layoutId),\n regionId: String(regionId),\n mediaId: String(mediaId)\n });\n\n return xml;\n }\n\n /**\n * NotifyStatus - report current status\n * @param {Object} status - Status object with currentLayoutId, deviceName, etc.\n */\n async notifyStatus(status) {\n // Enrich with storage estimate if available\n if (typeof navigator !== 'undefined' && navigator.storage?.estimate) {\n try {\n const estimate = await navigator.storage.estimate();\n status.availableSpace = estimate.quota - estimate.usage;\n status.totalSpace = estimate.quota;\n } catch (_) { /* storage estimate not supported */ }\n }\n\n // Add timezone if not already provided\n if (!status.timeZone && typeof Intl !== 'undefined') {\n status.timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;\n }\n\n // Add statusDialog (summary for CMS display status page) if not provided\n if (!status.statusDialog) {\n status.statusDialog = `Current Layout: ${status.currentLayoutId || 'None'}`;\n }\n\n return await this.call('NotifyStatus', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n status: JSON.stringify(status)\n });\n }\n\n /**\n * MediaInventory - report downloaded files\n */\n async mediaInventory(inventoryXml) {\n return await this.call('MediaInventory', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaInventory: inventoryXml\n });\n }\n\n /**\n * BlackList - report broken media to CMS\n * @param {string} mediaId - The media file ID\n * @param {string} type - File type ('media' or 'layout')\n * @param {string} reason - Reason for blacklisting\n * @returns {Promise<boolean>}\n */\n async blackList(mediaId, type, reason) {\n try {\n const xml = await this.call('BlackList', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n mediaId: String(mediaId),\n type: type || 'media',\n reason: reason || 'Failed to render'\n });\n log.info(`BlackListed ${type}/${mediaId}: ${reason}`);\n return xml === 'true';\n } catch (error) {\n log.warn('BlackList failed:', error);\n return false;\n }\n }\n\n /**\n * SubmitLog - submit player logs to CMS for remote debugging\n * @param {string} logXml - XML string containing log entries\n * @returns {Promise<boolean>} - true if logs were successfully submitted\n */\n async submitLog(logXml, hardwareKeyOverride = null) {\n const xml = await this.call('SubmitLog', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n logXml: logXml\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitScreenShot - submit screenshot to CMS for display verification\n * @param {string} base64Image - Base64-encoded PNG image data\n * @returns {Promise<boolean>} - true if screenshot was successfully submitted\n */\n async submitScreenShot(base64Image) {\n const xml = await this.call('SubmitScreenShot', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n screenShot: base64Image\n });\n\n return xml === 'true';\n }\n\n /**\n * SubmitStats - submit proof of play statistics\n * @param {string} statsXml - XML-encoded stats string\n * @returns {Promise<boolean>} - true if stats were successfully submitted\n */\n /**\n * ReportFaults - submit fault data to CMS for dashboard alerts\n * @param {string} faultJson - JSON-encoded fault data\n * @returns {Promise<boolean>}\n */\n async reportFaults(faultJson) {\n return this.call('ReportFaults', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey,\n fault: faultJson\n });\n }\n\n /**\n * GetWeather - get current weather data for schedule criteria\n * @returns {Promise<string>} Weather data XML from CMS\n */\n async getWeather() {\n return this.call('GetWeather', {\n serverKey: this.config.cmsKey,\n hardwareKey: this.config.hardwareKey\n });\n }\n\n async submitStats(statsXml, hardwareKeyOverride = null) {\n try {\n const xml = await this.call('SubmitStats', {\n serverKey: this.config.cmsKey,\n hardwareKey: hardwareKeyOverride || this.config.hardwareKey,\n statXml: statsXml\n });\n\n const success = xml === 'true';\n log.info(`SubmitStats result: ${success}`);\n return success;\n } catch (error) {\n log.error('SubmitStats failed:', error);\n throw error;\n }\n }\n}\n"],"names":["parseCriteria","parentEl","criteria","child","parseScheduleResponse","xml","doc","schedule","scheduleEl","globalDeps","el","depContainer","fileEl","defaultEl","defaultDeps","campaignEl","campaign","layoutEl","fileId","depEls","overlaysContainer","overlayEl","actionsContainer","actionEl","cmdEl","dataConnectorsContainer","dcEl","log","createLogger","RestClient","config","_a","urlString","parsed","proxyUrl","key","value","path","queryParams","url","cacheKey","headers","cachedEtag","response","fetchWithRetry","cached","errorBody","etag","contentType","data","method","body","os","json","display","attrs","code","message","settings","tags","commands","c","extractTag","t","checkRf","checkSchedule","displayAttrs","syncConfig","files","fileList","f","purgeItems","purgeList","p","pAttrs","layoutId","regionId","mediaId","status","estimate","inventoryXml","type","reason","result","error","logXml","hardwareKeyOverride","base64Image","faultJson","statsXml","success","XmdsClient","params","paramElements","escaped","cmsUrl","xmdsUrl","fault","faultString","_b","responseTag","responseEl","returnEl","name","tagEl","syncGroupVal","purgeEl","itemEl"],"mappings":"iDAgBA,SAASA,EAAcC,EAAU,CAC/B,MAAMC,EAAW,CAAA,EACjB,UAAWC,KAASF,EAAS,SACvBE,EAAM,UAAY,YACtBD,EAAS,KAAK,CACZ,OAA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E,EAAO,CACd,OAAAzD,EAAI,KAAK,oBAAqByD,CAAK,EAC5B,EACT,CACF,CAOA,MAAM,UAAUC,EAAQC,EAAsB,KAAM,CAOlD,OANY,MAAM,KAAK,KAAK,YAAa,CACvC,UAAW,KAAK,OAAO,OACvB,YAAaA,GAAuB,KAAK,OAAO,YAChD,OAAQD,CACd,CAAK,IAEc,MACjB,CAOA,MAAM,iBAAiBE,EAAa,CAOlC,OANY,MAAM,KAAK,KAAK,mBAAoB,CAC9C,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,YACzB,WAAYA,CAClB,CAAK,IAEc,MACjB,CAYA,MAAM,aAAaC,EAAW,CAC5B,OAAO,KAAK,KAAK,eAAgB,CAC/B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,YACzB,MAAOA,CACb,CAAK,CACH,CAMA,MAAM,YAAa,CACjB,OAAO,KAAK,KAAK,aAAc,CAC7B,UAAW,KAAK,OAAO,OACvB,YAAa,KAAK,OAAO,WAC/B,CAAK,CACH,CAEA,MAAM,YAAYC,EAAUH,EAAsB,KAAM,CACtD,GAAI,CAOF,MAAMI,EANM,MAAM,KAAK,KAAK,cAAe,CACzC,UAAW,KAAK,OAAO,OACvB,YAAaJ,GAAuB,KAAK,OAAO,YAChD,QAASG,CACjB,CAAO,IAEuB,OACxB,OAAA9D,EAAI,KAAK,uBAAuB+D,CAAO,EAAE,EAClCA,CACT,OAASN,EAAO,CACd,MAAAzD,EAAI,MAAM,sBAAuByD,CAAK,EAChCA,CACR,CACF,CACF","x_google_ignoreList":[0,1,2]}
|
package/dist/index.html
CHANGED
|
@@ -88,10 +88,10 @@
|
|
|
88
88
|
height: 100%;
|
|
89
89
|
}
|
|
90
90
|
</style>
|
|
91
|
-
<script type="module" crossorigin src="./assets/main-
|
|
91
|
+
<script type="module" crossorigin src="./assets/main-DfHNWLGS.js"></script>
|
|
92
92
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
93
|
-
<link rel="modulepreload" crossorigin href="./assets/cms-api-
|
|
94
|
-
<link rel="modulepreload" crossorigin href="./assets/widget-html-
|
|
93
|
+
<link rel="modulepreload" crossorigin href="./assets/cms-api-B3gEu-pj.js">
|
|
94
|
+
<link rel="modulepreload" crossorigin href="./assets/widget-html-B_acad6q.js">
|
|
95
95
|
</head>
|
|
96
96
|
<body>
|
|
97
97
|
<!-- Status overlay -->
|
|
@@ -111,14 +111,14 @@
|
|
|
111
111
|
|
|
112
112
|
// Check if player is configured with valid CMS connection params
|
|
113
113
|
const params = new URLSearchParams(window.location.search);
|
|
114
|
-
const hasUrlConfig = params.has('
|
|
114
|
+
const hasUrlConfig = params.has('cmsUrl') && params.has('cmsKey');
|
|
115
115
|
|
|
116
116
|
let hasStoredConfig = false;
|
|
117
117
|
try {
|
|
118
118
|
const raw = localStorage.getItem('xibo_config');
|
|
119
119
|
if (raw) {
|
|
120
120
|
const cfg = JSON.parse(raw);
|
|
121
|
-
hasStoredConfig = !!(cfg.
|
|
121
|
+
hasStoredConfig = !!(cfg.cmsUrl && cfg.cmsKey);
|
|
122
122
|
}
|
|
123
123
|
} catch (e) { /* corrupt config — treat as missing */ }
|
|
124
124
|
|
package/dist/setup.html
CHANGED
|
@@ -287,10 +287,10 @@
|
|
|
287
287
|
color: #444;
|
|
288
288
|
}
|
|
289
289
|
</style>
|
|
290
|
-
<script type="module" crossorigin src="./assets/setup-
|
|
290
|
+
<script type="module" crossorigin src="./assets/setup-D67k289O.js"></script>
|
|
291
291
|
<link rel="modulepreload" crossorigin href="./assets/modulepreload-polyfill-B5Qt9EMX.js">
|
|
292
|
-
<link rel="modulepreload" crossorigin href="./assets/cms-api-
|
|
293
|
-
<link rel="modulepreload" crossorigin href="./assets/xmds-client-
|
|
292
|
+
<link rel="modulepreload" crossorigin href="./assets/cms-api-B3gEu-pj.js">
|
|
293
|
+
<link rel="modulepreload" crossorigin href="./assets/xmds-client-Ci6s-34Q.js">
|
|
294
294
|
</head>
|
|
295
295
|
<body>
|
|
296
296
|
<div class="container">
|
|
@@ -317,8 +317,8 @@
|
|
|
317
317
|
<div id="phase-setup" class="phase active">
|
|
318
318
|
<form id="setup-form">
|
|
319
319
|
<div class="form-group">
|
|
320
|
-
<label for="cms-
|
|
321
|
-
<input type="url" id="cms-
|
|
320
|
+
<label for="cms-url">CMS URL</label>
|
|
321
|
+
<input type="url" id="cms-url" placeholder="https://cms.example.com" required>
|
|
322
322
|
</div>
|
|
323
323
|
|
|
324
324
|
<div class="form-group">
|
|
@@ -351,6 +351,7 @@
|
|
|
351
351
|
</details>
|
|
352
352
|
|
|
353
353
|
<button type="submit" id="submit-btn" disabled>Loading...</button>
|
|
354
|
+
<button type="button" id="btn-back-player" class="btn-secondary" style="display: none;">Back to Player</button>
|
|
354
355
|
</form>
|
|
355
356
|
|
|
356
357
|
<div id="error" class="error-msg"></div>
|
|
@@ -389,8 +390,8 @@
|
|
|
389
390
|
</div>
|
|
390
391
|
</div>
|
|
391
392
|
|
|
392
|
-
<div class="footer">
|
|
393
|
-
Xibo Player
|
|
393
|
+
<div class="footer" id="version-footer">
|
|
394
|
+
Xibo Player
|
|
394
395
|
</div>
|
|
395
396
|
</div>
|
|
396
397
|
|
package/dist/sw-pwa.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-Cb84FvUB.js";import{VERSION as Q}from"./assets/index-pcbcUHVR.js";import"./assets/cms-api-Cqh1b8je.js";const y=(()=>{var h;return typeof self<"u"&&((h=self.registration)!=null&&h.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function x(h,t=1){if(h===0)return"0 Bytes";if(h<1024)return`${h} Bytes`;const e=h/1024;if(e<1024)return`${e.toFixed(t)} KB`;const a=e/1024;return a<1024?`${a.toFixed(t)} MB`:`${(a/1024).toFixed(t)} GB`}function G(h,t){const e=h.replace(/bytes=/,"").split("-"),a=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):t-1;return{start:a,end:s}}function K(h,t,e){const a=Math.floor(h/e),s=Math.floor(t/e);return{startChunk:a,endChunk:s,count:s-a+1}}function j(h,t,e,a,s){if(h.length===1){const o=t%a,d=e-t+1;return h[0].slice(o,o+d)}const i=[],n=t%a,l=e%a;i.push(h[0].slice(n));for(let o=1;o<h.length-1;o++)i.push(h[o]);return h.length>1&&i.push(h[h.length-1].slice(0,l+1)),new Blob(i,{type:s})}class D{constructor(t){this.name=t,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...t){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...t)}info(...t){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...t)}warn(...t){console.warn(`[${this.name}]`,...t)}error(...t){console.error(`[${this.name}]`,...t)}}function ee(h){h||(h=new D("ChunkConfig"));const t=typeof navigator<"u"&&navigator.deviceMemory||null;let e=4;if(t)e=t,h.info("Detected device memory:",t,"GB");else if(typeof navigator<"u"){const l=navigator.userAgent.toLowerCase();l.includes("raspberry pi")||l.includes("armv6")?(e=.5,h.info("Detected Pi Zero (512 MB RAM estimated)")):l.includes("armv7")?(e=1,h.info("Detected ARM device (1 GB RAM estimated)")):h.info("Using default RAM estimate:",e,"GB")}let a,s,i,n;return e<=.5?(a=10*1024*1024,s=25,i=25*1024*1024,n=1,h.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):e<=1?(a=20*1024*1024,s=50,i=50*1024*1024,n=2,h.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):e<=2?(a=30*1024*1024,s=100,i=75*1024*1024,n=2,h.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):e<=4?(a=50*1024*1024,s=200,i=100*1024*1024,n=4,h.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(a=100*1024*1024,s=500,i=200*1024*1024,n=6,h.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:a,blobCacheSize:s,threshold:i,concurrency:n}}class te{constructor({cacheName:t="xibo-media-v1",chunkSize:e}={}){this.cache=null,this.cacheName=t,this.chunkSize=e,this.log=new D("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(t){return this.cache||await this.init(),await this.cache.match(t,{ignoreSearch:!0,ignoreVary:!0})}async put(t,e,a){this.cache||await this.init();const s=new Response(e,{headers:{"Content-Type":a,"Content-Length":e.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(t,s)}async delete(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(this.metadataCache.delete(t),e){const a=[this.cache.delete(`${t}/metadata`)];for(let s=0;s<e.numChunks;s++)a.push(this.cache.delete(`${t}/chunk-${s}`));return await Promise.all(a),!0}return await this.cache.delete(t)}async clear(){this.cache||await this.init();const t=await this.cache.keys();await Promise.all(t.map(e=>this.cache.delete(e))),this.metadataCache.clear(),this.log.info("Cleared",t.length,"cached files")}async fileExists(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(e)return{exists:!0,chunked:!0,metadata:e};if(await this.get(t))return{exists:!0,chunked:!1,metadata:null};const s=await this.getMetadata(t);return s&&s.chunked?(this.metadataCache.set(t,s),{exists:!0,chunked:!0,metadata:s}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(t){const e=await this.fileExists(t);if(!e.exists)return null;if(e.chunked)return e.metadata.totalSize;const a=await this.get(t),s=a==null?void 0:a.headers.get("Content-Length");return s?parseInt(s):null}async putChunked(t,e,a){this.cache||await this.init();const s=this.chunkSize,i=e.size,n=Math.ceil(i/s);this.log.info(`Storing as ${n} chunks: ${t} (${x(i)})`);const l={totalSize:i,chunkSize:s,numChunks:n,contentType:a,chunked:!0,complete:!1,createdAt:Date.now()},o=new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${t}/metadata`,o),this.metadataCache.set(t,l);for(let d=0;d<n;d++){const u=d*s,f=Math.min(u+s,i),c=e.slice(u,f),$=new Response(c,{headers:{"Content-Type":a,"Content-Length":c.size,"X-Chunk-Index":d,"X-Total-Chunks":n}});await this.cache.put(`${t}/chunk-${d}`,$),((d+1)%5===0||d===n-1)&&this.log.info(`Stored chunk ${d+1}/${n} (${x(c.size)})`)}l.complete=!0,await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,l),this.log.info(`Chunked storage complete: ${t}`)}async getMetadata(t){const e=this.metadataCache.get(t);if(e)return e;this.cache||await this.init();const a=await this.cache.match(`${t}/metadata`);if(!a)return null;const s=await a.text(),i=JSON.parse(s);return this.metadataCache.set(t,i),i}async updateMetadata(t,e){this.cache||await this.init(),await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,e)}async getAllFiles(){this.cache||await this.init();const t=await this.cache.keys(),e=[],a=new Set;for(const s of t){const n=new URL(s.url).pathname;if(n.includes("/chunk-")||n.endsWith("/metadata")){const o=n.replace(/\/(chunk-\d+|metadata)$/,"");if(a.has(o))continue;a.add(o);const d=await this.getMetadata(o),u=o.match(/\/cache\/(media|layout|widget)\/(.+)/);u&&e.push({id:u[2],type:u[1],size:(d==null?void 0:d.totalSize)||0,cachedAt:(d==null?void 0:d.createdAt)||0});continue}if(n.includes("/cache/static/")||a.has(n))continue;a.add(n);const l=n.match(/\/cache\/(media|layout|widget)\/(.+)/);if(l){const o=await this.cache.match(s);e.push({id:l[2],type:l[1],size:parseInt((o==null?void 0:o.headers.get("Content-Length"))||"0"),cachedAt:0})}}return e}async isChunked(t){const e=await this.getMetadata(t);return(e==null?void 0:e.chunked)===!0}async getChunk(t,e){return this.cache||await this.init(),await this.cache.match(`${t}/chunk-${e}`)}}class ae{constructor(t=200){this.cache=new Map,this.maxBytes=t*1024*1024,this.currentBytes=0,this.log=new D("BlobCache")}has(t){return this.cache.has(t)}async get(t,e){if(this.cache.has(t)){const s=this.cache.get(t);return s.lastAccess=Date.now(),this.log.debug(`HIT: ${t} (${x(s.size)})`),s.blob}this.log.debug(`MISS: ${t} - loading from Cache API`);const a=await e();for(;this.currentBytes+a.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+a.size<=this.maxBytes){this.cache.set(t,{blob:a,lastAccess:Date.now(),size:a.size}),this.currentBytes+=a.size;const s=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${t} (${x(a.size)}) - utilization: ${s}%`)}else this.log.debug(`Skipping memory cache (too large): ${t} (${x(a.size)} > ${x(this.maxBytes)})`);return a}evictLRU(){let t=null,e=null;for(const[a,s]of this.cache)(!t||s.lastAccess<t.lastAccess)&&(t=s,e=a);e&&(this.currentBytes-=t.size,this.cache.delete(e),this.log.debug(`EVICTED LRU: ${e} (${x(t.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class se{constructor(t,e,a,{staticCache:s="xibo-static-v1"}={}){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.staticCache=s,this.pendingFetches=new Map,this.log=new D("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(t,e,a){const s=await this.cacheManager.fileExists(t);if(!s.exists)return{found:!1,handler:null,data:null};if(s.chunked){const i={metadata:s.metadata,cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-chunked",data:i}:a?{found:!0,handler:"range-chunked",data:{...i,rangeHeader:a}}:{found:!0,handler:"full-chunked",data:i}}else{const n={cached:await this.cacheManager.get(t),cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-whole",data:n}:a?{found:!0,handler:"range-whole",data:{...n,rangeHeader:a}}:{found:!0,handler:"full-whole",data:n}}}async handleRequest(t){var f;const e=new URL(t.request.url);if(this.log.info("handleRequest called for:",e.href),this.log.info("pathname:",e.pathname),e.pathname===y+"/"||e.pathname===y+"/index.html"||e.pathname===y+"/setup.html"){const $=await(await caches.open(this.staticCache)).match(t.request);return $?(this.log.info("Serving static file from cache:",e.pathname),$):(this.log.info("Fetching static file from network:",e.pathname),fetch(t.request))}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&(e.searchParams.get("fileType")==="bundle"||e.searchParams.get("fileType")==="fontCss"||e.searchParams.get("fileType")==="font")){const c=e.searchParams.get("file"),$=`${y}/cache/static/${c}`,M=await caches.open(this.staticCache),C=await M.match($);if(C)return this.log.info("Serving widget resource from cache:",c),C.clone();if(this.pendingFetches.has(c))return this.log.info("Deduplicating widget resource fetch:",c),(await this.pendingFetches.get(c)).clone();this.log.info("Fetching widget resource from CMS:",c);const T=(async()=>{try{const g=await fetch(t.request);if(g.ok){this.log.info("Caching widget resource:",c,`(${g.headers.get("Content-Type")})`);const v=g.clone();return await M.put($,v),g}else return this.log.warn("Widget resource not available (",g.status,"):",c,"- NOT caching"),g}catch(g){return this.log.error("Failed to fetch widget resource:",c,g),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(c,T);try{return(await T).clone()}finally{this.pendingFetches.delete(c)}}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&e.searchParams.has("file")){const c=e.searchParams.get("file"),$=c.split(".")[0],M=e.searchParams.get("type"),C=M==="L"?"layout":"media";this.log.info("XMDS request:",c,"type:",M,"→",y+"/cache/"+C+"/"+$);const T=`${y}/cache/${C}/${$}`,g=await this.cacheManager.get(T);return g?new Response(g.clone().body,{headers:{"Content-Type":g.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",c),fetch(t.request))}if(e.pathname.startsWith(y+"/cache/static/")){const c=e.pathname.split("/").pop();this.log.info("Static resource request:",c);const M=await(await caches.open(this.staticCache)).match(`${y}/cache/static/${c}`);if(M)return this.log.info("Serving static resource from static cache:",c),M.clone();const C=await this.cacheManager.get(e.pathname);return C?(this.log.info("Serving static resource from media cache:",c),new Response(C.clone().body,{headers:{"Content-Type":C.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",c),new Response("Resource not cached",{status:404}))}if(!e.pathname.startsWith(y+"/cache/"))return this.log.info("NOT a cache request, returning null:",e.pathname),null;if(this.log.info("IS a cache request, proceeding...",e.pathname),e.pathname.startsWith(y+"/cache/widget/")){this.log.info("Widget HTML request:",e.pathname);const c=await this.cacheManager.get(e.pathname);return c?new Response(c.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const a=e.pathname.replace(/\.json$/,""),s=t.request.method,i=t.request.headers.get("Range");this.log.debug("Request URL:",e.pathname),this.log.debug("Cache key:",a),i?this.log.info(s,a,`Range: ${i}`):this.log.info(s,a);const n=await this.routeFileRequest(a,s,i);if(n.found)switch(n.handler){case"head-whole":return this.handleHeadWhole((f=n.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(n.data.metadata,n.data.cacheKey);case"range-whole":return this.handleRangeRequest(n.data.cached,n.data.rangeHeader,n.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(n.data.cacheKey,n.data.rangeHeader,n.data.metadata);case"full-whole":return this.handleFullWhole(n.data.cached,n.data.cacheKey);case"full-chunked":return this.handleFullChunked(n.data.cacheKey,n.data.metadata);default:return this.log.error("Unknown handler:",n.handler),new Response("Internal error: unknown handler",{status:500})}const l=a.split("/"),o=l[l.length-2],d=l[l.length-1];let u=null;for(const[,c]of this.downloadManager.queue.active.entries())if(c.fileInfo.type===o&&String(c.fileInfo.id)===d){u=c;break}if(u){this.log.info("Download in progress, waiting:",a);try{await u.wait();const c=await this.routeFileRequest(a,s,i);if(c.found)switch(this.log.info("Download complete, serving via",c.handler),c.handler){case"full-whole":return this.handleFullWhole(c.data.cached,c.data.cacheKey);case"full-chunked":return this.handleFullChunked(c.data.cacheKey,c.data.metadata);default:return this.handleRequest(t)}}catch(c){return this.log.error("Download failed:",a,c),new Response("Download failed: "+c.message,{status:500})}}return this.log.info("Not found:",a),new Response("Not found",{status:404})}handleHeadWhole(t){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":t?t.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(t,e){return await this.cacheManager.getChunk(e,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":t.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",e),new Response(null,{status:404}))}handleFullWhole(t,e){const a=t.headers.get("Content-Length"),s=a?x(parseInt(a)):"unknown size";return this.log.info("Serving from cache:",e,`(${s})`),new Response(t.body,{headers:{"Content-Type":t.headers.get("Content-Type")||"application/octet-stream","Content-Length":a||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(t,e){this.log.info("Chunked file GET without Range:",t,`- serving full file from ${e.numChunks} chunks`);const a=`bytes=0-${e.totalSize-1}`;return this.handleChunkedRangeRequest(t,a,e)}async handleRangeRequest(t,e,a){const s=await this.blobCache.get(a,async()=>await t.clone().blob()),i=s.size,{start:n,end:l}=G(e,i),o=s.slice(n,l+1);return this.log.debug(`Range: bytes ${n}-${l}/${i} (${x(o.size)} of ${x(i)})`),new Response(o,{status:206,statusText:"Partial Content",headers:{"Content-Type":t.headers.get("Content-Type")||"video/mp4","Content-Length":o.size.toString(),"Content-Range":`bytes ${n}-${l}/${i}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(t,e,a){const{totalSize:s,chunkSize:i,numChunks:n,contentType:l}=a,{start:o,end:d}=G(e,s);let u=d;const f=e.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const p=Math.floor(o/i),r=n-1;let w=!0;for(let m=p;m<=r;m++){const k=`${t}/chunk-${m}`;if(this.blobCache.has(k))continue;if(!await this.cacheManager.getChunk(t,m)){w=!1;break}}if(w)this.log.info(`All chunks cached from ${p} to ${r}, serving full range (bytes ${o}-${u}/${s})`);else{const m=Math.min((p+1)*i-1,s-1);m<u&&(u=m,this.log.info(`Progressive streaming: capping bytes=${o}- to chunk ${p} (bytes ${o}-${u}/${s})`))}}const{startChunk:$,endChunk:M,count:C}=K(o,u,i);this.log.debug(`Chunked range: bytes ${o}-${u}/${s} (chunks ${$}-${M}, ${C} chunks)`);const T=p=>{const r=`${t}/chunk-${p}`;return this.blobCache.get(r,()=>{if(this.pendingChunkLoads.has(r))return this.pendingChunkLoads.get(r);const w=(async()=>{let m=await this.cacheManager.getChunk(t,p);if(m)return await m.blob();this.log.info(`Chunk ${p}/${n} not yet available for ${t}, signalling urgent...`);{const k=t.split("/"),b=k[k.length-1],E=k[k.length-2];this.downloadManager.queue.urgentChunk(E,b,p)}for(let k=0;k<60;k++)if(await new Promise(b=>setTimeout(b,1e3)),m=await this.cacheManager.getChunk(t,p),m)return this.log.info(`Chunk ${p}/${n} arrived for ${t} after ${k+1}s`),await m.blob();throw new Error(`Chunk ${p} not available for ${t} after 60s`)})();return this.pendingChunkLoads.set(r,w),w.finally(()=>this.pendingChunkLoads.delete(r)),w})},g=[];let v=!0;for(let p=$;p<=M;p++){const r=await this.cacheManager.getChunk(t,p);if(r){const w=`${t}/chunk-${p}`,m=await this.blobCache.get(w,async()=>await r.blob());g.push(m)}else{v=!1;break}}if(v&&g.length===C){const p=j(g,o,u,i);return this.log.debug(`Serving chunked range: ${x(p.size)} from ${C} chunk(s)`),new Response(p,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":p.size.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${t} bytes ${o}-${u} (waiting for chunks)`);const L=u-o+1,z=new ReadableStream({async start(p){try{const r=[];for(let k=$;k<=M;k++){const b=await T(k);r.push(b)}const m=await j(r,o,u,i).arrayBuffer();p.enqueue(new Uint8Array(m)),p.close()}catch(r){this.log.error(`Stream error for ${t}: ${r.message}`),p.error(r)}}});return new Response(z,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":L.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}function I(h,t){const e=new Set,a=h.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const n of a)e.add(n[1]);const s=h.matchAll(/<media\s+([^>]+)>/g);for(const n of s){const l=n[1];if(!l.includes("fileId=")){const o=l.match(/\bid="(\d+)"/);o&&e.add(o[1])}}const i=h.matchAll(/<layout[^>]+background="(\d+)"/g);for(const n of i)e.add(n[1]);return t&&t.debug(`extractMediaIdsFromXlf: found ${e.size} IDs: ${[...e].join(", ")} (XLF ${h.length} bytes)`),e}const X={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"};class ne{constructor(t,e,a,s){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...s},this.log=new D("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(t){const{type:e,data:a}=t.data;switch(e==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",e):this.log.info("Received:",e),e){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(i=>{i.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(a);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(a.fileType,a.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(a.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(a.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(a.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(a.fileType,a.fileId,a.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",e),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(t){if(!t||!Array.isArray(t))return{success:!1,error:"No files provided"};let e=0;for(const a of t){const s=`${y}/cache/${a.type}/${a.id}`;await this.cacheManager.delete(s)?(this.log.info("Purged:",s),e++):this.log.debug("Not cached (skip purge):",s)}return this.log.info(`Purge complete: ${e}/${t.length} files deleted`),{success:!0,deleted:e,total:t.length}}async handlePrewarmVideoChunks(t){if(!t||!Array.isArray(t)||t.length===0)return{success:!1,error:"No mediaIds provided"};let e=0;for(const a of t){const s=`${y}/cache/media/${a}`,i=await this.cacheManager.getMetadata(s);if(i!=null&&i.chunked){const n=i.numChunks-1,l=[0];n>0&&l.push(n);for(const o of l){const d=`${s}/chunk-${o}`;await this.blobCache.get(d,async()=>{const u=await this.cacheManager.getChunk(s,o);return u?await u.blob():new Blob})}this.log.info(`Pre-warmed ${l.length} chunks for media ${a} (${i.numChunks} total)`),e++}else{const n=await this.cacheManager.get(s);n&&(await this.blobCache.get(s,async()=>await n.clone().blob()),this.log.info(`Pre-warmed whole file for media ${a}`),e++)}}return{success:!0,warmed:e,total:t.length}}handlePrioritizeDownload(t,e){this.log.info("Prioritize request:",`${t}/${e}`);const a=this.downloadManager.queue.prioritize(t,e);return this.downloadManager.queue.processQueue(),{success:!0,found:a}}handleUrgentChunk(t,e,a){return this.log.info("Urgent chunk request:",`${t}/${e}`,"chunk",a),{success:!0,acted:this.downloadManager.queue.urgentChunk(t,e,a)}}async handleDownloadFiles({layoutOrder:t,files:e,layoutDependants:a}){const s=this.downloadManager,i=s.queue;let n=0;const l=[],o=new Map,d=[],u=new Map;for(const r of e)r.type==="layout"?o.set(parseInt(r.id),r):r.type==="resource"||r.code==="fonts.css"||r.path&&(r.path.includes("bundle.min")||r.path.includes("fonts"))?d.push(r):u.set(String(r.id),r);this.log.info(`Download: ${t.length} layouts, ${u.size} media, ${d.length} resources`);const f=new Map,c=[];for(const r of t){const w=o.get(r);w!=null&&w.path&&c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);let b;if(k)b=await k.clone().text();else{const E=await fetch(U(w.path));if(!E.ok){this.log.warn(`XLF fetch failed: ${r} (${E.status})`);return}const F=await E.blob();await this.cacheManager.put(m,F,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (${F.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:F.size})),b=await F.text()}f.set(r,I(b,this.log))})())}for(const[r,w]of o)t.includes(r)||c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);if(!k&&w.path){const b=await fetch(U(w.path));if(b.ok){const E=await b.blob();await this.cacheManager.put(m,E,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (non-scheduled, ${E.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:E.size}));const S=await E.text();f.set(r,I(S,this.log))}}else if(k){const b=await k.clone().text();f.set(r,I(b,this.log))}})());await Promise.allSettled(c),this.log.info(`Parsed ${f.size} XLFs`);const $=new O(i);for(const r of d)await this._enqueueFile(s,$,r,l)&&n++;const M=await $.build();M.length>0&&(M.push(H),i.enqueueOrderedTasks(M));const C=new Set,T=[...f.keys()].filter(r=>!t.includes(r)),g=new Map;for(const[r,w]of u)w.saveAs&&g.set(w.saveAs,r);const v=new Map;if(a)for(const[r,w]of Object.entries(a))v.set(parseInt(r,10),w);for(const r of t){const w=f.get(r);if(!w)continue;const m=new Set(w);for(const S of T){const R=f.get(S);if(R)for(const Y of R)m.add(Y)}const k=v.get(r)||[];for(const S of k){const R=g.get(S);R&&m.add(R)}const b=[];for(const S of m){if(C.has(S))continue;const R=u.get(S);R&&(b.push(R),C.add(S))}if(b.length===0)continue;this.log.info(`Layout ${r}: ${b.length} media`),b.sort((S,R)=>(S.size||0)-(R.size||0));const E=new O(i);for(const S of b)await this._enqueueFile(s,E,S,l)&&n++;const F=await E.build();F.length>0&&(F.push(H),i.enqueueOrderedTasks(F))}const L=[...u.keys()].filter(r=>!C.has(r));if(L.length>0){this.log.info(`${L.length} media not in any XLF: ${L.join(", ")}`);const r=new O(i);for(const m of L){const k=u.get(m);k&&await this._enqueueFile(s,r,k,l)&&n++}const w=await r.build();w.length>0&&i.enqueueOrderedTasks(w)}const z=i.running,p=i.queue.length;return this.log.info("Downloads active:",z,", queued:",p),{success:!0,enqueuedCount:n,activeCount:z,queuedCount:p}}async _enqueueFile(t,e,a,s){if(!a.path||a.path==="null"||a.path==="undefined")return this.log.debug("Skipping file with no path:",a.id),!1;const i=`${y}/cache/${a.type}/${a.id}`,n=await this.cacheManager.fileExists(i);if(n.exists)if(n.chunked&&n.metadata&&!n.metadata.complete){const{numChunks:u}=n.metadata,f=new Set;for(let c=0;c<u;c++)await this.cacheManager.getChunk(i,c)&&f.add(c);if(f.size===u)return this.log.info("All chunks present but metadata incomplete, marking complete:",i),n.metadata.complete=!0,await this.cacheManager.updateMetadata(i,n.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${u} chunks cached, resuming:`,i),a.skipChunks=f}else return this.log.debug("File already cached:",i,n.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(a),!1;const l=`${a.type}/${a.id}`;if(t.getTask(l))return this.log.debug("File already downloading:",l,"- skipping duplicate"),!1;const d=e.addFile(a);if(d.state==="pending"){const u=this.cacheFileAfterDownload(d,a);return s.push(u),!0}return!1}async cacheFileAfterDownload(t,e){try{const a=`${y}/cache/${e.type}/${e.id}`,s=e.type==="layout"?"text/xml":e.type==="widget"?"text/html":"application/octet-stream",i=parseInt(e.size)||0;if(i>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(t,e,a,s,i);const n=await t.wait();return await this.cacheManager.put(a,n,s),this.log.info("Cached after download:",a,`(${n.size} bytes)`),(await self.clients.matchAll()).forEach(o=>{o.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:n.size})}),this._cacheStaticResource(e,n),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),n}catch(a){throw this.log.error("Failed to cache after download:",e.id,a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),a}}async _progressiveCacheFile(t,e,a,s,i){const{chunkSize:n,cacheName:l}=this.config,o=await caches.open(l);let d=0,u=!1;const f=Math.ceil(i/n);this.log.info(`Progressive download: ${a} (${x(i)}, ~${f} chunks)`);const c={totalSize:i,chunkSize:n,numChunks:f,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()};await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(a,c),this.log.info("Metadata stored, ready for progressive streaming:",a),t.onChunkDownloaded=async(C,T,g)=>{const v=new Response(T,{headers:{"Content-Type":s,"Content-Length":T.size,"X-Chunk-Index":C,"X-Total-Chunks":g}});if(await o.put(`${a}/chunk-${C}`,v),d++,(d%2===0||d===g)&&this.log.info(`Progressive: chunk ${d}/${g} cached for ${e.id}`),!u&&(C===0||C===g-1)){const L=C===0||await this.cacheManager.getChunk(a,0),z=C===g-1||await this.cacheManager.getChunk(a,g-1);L&&z&&(u=!0,(await self.clients.matchAll()).forEach(r=>{r.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,progressive:!0,chunksReady:d,totalChunks:g})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",a))}g!==f&&(c.numChunks=g,await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})))};const $=await t.wait();return d===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",a),$.size>0?await this.cacheManager.putChunked(a,$,s):await this.cacheManager.put(a,$,s),(await self.clients.matchAll()).forEach(T=>{T.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:$.size||i})}),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),$):t._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${a} (${d}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s})):(this.log.info(`Progressive download complete: ${a} (${d} chunks stored)`),c.complete=!0,await this.cacheManager.updateMetadata(a,c),(await self.clients.matchAll()).forEach(C=>{C.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,complete:!0})}),this.pendingChunkStorage.delete(a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s}))}_cacheStaticResource(t,e){const a=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;a&&(a.endsWith(".js")||a.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(a))&&(async()=>{try{const s=await caches.open(this.config.staticCache),i=`${y}/cache/static/${a}`,n=a.split(".").pop().toLowerCase(),l=X[n]||"application/octet-stream";await Promise.all([s.put(i,new Response(e.slice(0,e.size,e.type),{headers:{"Content-Type":l}})),this.cacheManager.put(i,e.slice(0,e.size,e.type),l)]),this.log.info("Also cached as static resource:",a,`(${l})`)}catch(s){this.log.warn("Failed to cache static resource:",a,s)}})()}async ensureStaticCacheEntry(t){const e=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;if(!e||!(e.endsWith(".js")||e.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(e)))return;const a=await caches.open(this.config.staticCache),s=`${y}/cache/static/${e}`;if(await a.match(s))return;const n=`${y}/cache/${t.type}/${t.id}`,l=await this.cacheManager.get(n);if(!l)return;const o=await l.blob(),d=e.split(".").pop().toLowerCase(),u=X[d]||"application/octet-stream",f=`${y}/cache/static/${e}`;await Promise.all([a.put(s,new Response(o.slice(0,o.size,o.type),{headers:{"Content-Type":u}})),this.cacheManager.put(f,o.slice(0,o.size,o.type),u)]),this.log.info("Backfilled static cache for:",e,`(${u}, ${o.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const q="2026-02-24T14:19:08.357Z",N="xibo-media-v1",P="xibo-static-v1",ie=[y+"/",y+"/index.html",y+"/setup.html"],A=new D("SW"),B=ee(A),_=B.chunkSize,oe=B.threshold,ce=B.blobCacheSize,re=B.concurrency;A.info("Loading modular Service Worker:",q);const V=new Z({concurrency:re,chunkSize:_,chunksPerFile:2}),W=new te({cacheName:N,chunkSize:_}),J=new ae(ce),he=new se(V,W,J,{staticCache:P}),le=new ne(V,W,J,{cacheName:N,staticCache:P,chunkSize:_,chunkStorageThreshold:oe});async function ue(h){const t=new URL(h.request.url),e=t.pathname.replace(y+"/ic",""),a=h.request.method;A.info("Interactive Control request:",a,e);let s=null;if(a==="POST"||a==="PUT")try{s=await h.request.text()}catch{}const i=await self.clients.matchAll({type:"window"});if(i.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const n=i[0];try{const l=await new Promise((o,d)=>{const u=new MessageChannel,f=setTimeout(()=>d(new Error("IC timeout")),5e3);u.port1.onmessage=c=>{clearTimeout(f),o(c.data)},n.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:e,search:t.search,body:s},[u.port2])});return new Response(l.body||"",{status:l.status||200,headers:{"Content-Type":l.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(l){return A.error("IC handler error:",l),new Response(JSON.stringify({error:l.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",h=>{A.info("Installing... Version:",q),h.waitUntil(Promise.all([W.init(),caches.open(P).then(t=>(A.info("Caching static files"),t.addAll(ie)))]).then(async()=>{if(A.info("Cache initialized"),self.registration.active)try{const e=await(await caches.open("xibo-sw-version")).match("version");if(e){const a=await e.text();if(a===q){A.info("Same version already active, skipping activation to preserve streams");return}A.info("Version changed:",a,"→",q)}}catch{}return A.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",h=>{A.info("Activating... Version:",q,"| @xiboplayer/cache:",Q),h.waitUntil(caches.keys().then(t=>Promise.all(t.filter(e=>e.startsWith("xibo-")&&e!==N&&e!==P&&e!=="xibo-sw-version").map(e=>(A.info("Deleting old cache:",e),caches.delete(e))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(q)),A.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{A.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(e=>{e.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",h=>{const t=new URL(h.request.url);if(t.pathname.startsWith(y+"/cache/")||t.pathname.startsWith(y+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&h.request.method==="GET"){if(t.pathname.startsWith(y+"/ic/")){h.respondWith(ue(h));return}h.respondWith(he.handleRequest(h))}});self.addEventListener("message",h=>{h.waitUntil(le.handleMessage(h).then(t=>{var e;(e=h.ports[0])==null||e.postMessage(t)}))});A.info("Modular Service Worker ready");
|
|
1
|
+
import{r as U,L as O,B as H,D as Z}from"./assets/widget-html-B_acad6q.js";import{VERSION as Q}from"./assets/index-BCL7JKFz.js";import"./assets/cms-api-B3gEu-pj.js";const y=(()=>{var h;return typeof self<"u"&&((h=self.registration)!=null&&h.scope)?new URL(self.registration.scope).pathname.replace(/\/$/,""):"/player/pwa"})();function x(h,t=1){if(h===0)return"0 Bytes";if(h<1024)return`${h} Bytes`;const e=h/1024;if(e<1024)return`${e.toFixed(t)} KB`;const a=e/1024;return a<1024?`${a.toFixed(t)} MB`:`${(a/1024).toFixed(t)} GB`}function G(h,t){const e=h.replace(/bytes=/,"").split("-"),a=parseInt(e[0],10),s=e[1]?parseInt(e[1],10):t-1;return{start:a,end:s}}function K(h,t,e){const a=Math.floor(h/e),s=Math.floor(t/e);return{startChunk:a,endChunk:s,count:s-a+1}}function j(h,t,e,a,s){if(h.length===1){const o=t%a,d=e-t+1;return h[0].slice(o,o+d)}const i=[],n=t%a,l=e%a;i.push(h[0].slice(n));for(let o=1;o<h.length-1;o++)i.push(h[o]);return h.length>1&&i.push(h[h.length-1].slice(0,l+1)),new Blob(i,{type:s})}class D{constructor(t){this.name=t,this.level=typeof self<"u"&&self.swLogLevel||"INFO"}debug(...t){this.level==="DEBUG"&&console.log(`[${this.name}] DEBUG:`,...t)}info(...t){(this.level==="DEBUG"||this.level==="INFO")&&console.log(`[${this.name}]`,...t)}warn(...t){console.warn(`[${this.name}]`,...t)}error(...t){console.error(`[${this.name}]`,...t)}}function ee(h){h||(h=new D("ChunkConfig"));const t=typeof navigator<"u"&&navigator.deviceMemory||null;let e=4;if(t)e=t,h.info("Detected device memory:",t,"GB");else if(typeof navigator<"u"){const l=navigator.userAgent.toLowerCase();l.includes("raspberry pi")||l.includes("armv6")?(e=.5,h.info("Detected Pi Zero (512 MB RAM estimated)")):l.includes("armv7")?(e=1,h.info("Detected ARM device (1 GB RAM estimated)")):h.info("Using default RAM estimate:",e,"GB")}let a,s,i,n;return e<=.5?(a=10*1024*1024,s=25,i=25*1024*1024,n=1,h.info("Low-memory config: 10 MB chunks, 25 MB cache, 1 concurrent download")):e<=1?(a=20*1024*1024,s=50,i=50*1024*1024,n=2,h.info("1GB-RAM config: 20 MB chunks, 50 MB cache, 2 concurrent downloads")):e<=2?(a=30*1024*1024,s=100,i=75*1024*1024,n=2,h.info("2GB-RAM config: 30 MB chunks, 100 MB cache, 2 concurrent downloads")):e<=4?(a=50*1024*1024,s=200,i=100*1024*1024,n=4,h.info("4GB-RAM config: 50 MB chunks, 200 MB cache, 4 concurrent downloads")):(a=100*1024*1024,s=500,i=200*1024*1024,n=6,h.info("High-RAM config: 100 MB chunks, 500 MB cache, 6 concurrent downloads")),{chunkSize:a,blobCacheSize:s,threshold:i,concurrency:n}}class te{constructor({cacheName:t="xibo-media-v1",chunkSize:e}={}){this.cache=null,this.cacheName=t,this.chunkSize=e,this.log=new D("Cache"),this.metadataCache=new Map}async init(){this.cache=await caches.open(this.cacheName)}async get(t){return this.cache||await this.init(),await this.cache.match(t,{ignoreSearch:!0,ignoreVary:!0})}async put(t,e,a){this.cache||await this.init();const s=new Response(e,{headers:{"Content-Type":a,"Content-Length":e.size,"Access-Control-Allow-Origin":"*","Accept-Ranges":"bytes"}});await this.cache.put(t,s)}async delete(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(this.metadataCache.delete(t),e){const a=[this.cache.delete(`${t}/metadata`)];for(let s=0;s<e.numChunks;s++)a.push(this.cache.delete(`${t}/chunk-${s}`));return await Promise.all(a),!0}return await this.cache.delete(t)}async clear(){this.cache||await this.init();const t=await this.cache.keys();await Promise.all(t.map(e=>this.cache.delete(e))),this.metadataCache.clear(),this.log.info("Cleared",t.length,"cached files")}async fileExists(t){this.cache||await this.init();const e=this.metadataCache.get(t);if(e)return{exists:!0,chunked:!0,metadata:e};if(await this.get(t))return{exists:!0,chunked:!1,metadata:null};const s=await this.getMetadata(t);return s&&s.chunked?(this.metadataCache.set(t,s),{exists:!0,chunked:!0,metadata:s}):{exists:!1,chunked:!1,metadata:null}}async getFileSize(t){const e=await this.fileExists(t);if(!e.exists)return null;if(e.chunked)return e.metadata.totalSize;const a=await this.get(t),s=a==null?void 0:a.headers.get("Content-Length");return s?parseInt(s):null}async putChunked(t,e,a){this.cache||await this.init();const s=this.chunkSize,i=e.size,n=Math.ceil(i/s);this.log.info(`Storing as ${n} chunks: ${t} (${x(i)})`);const l={totalSize:i,chunkSize:s,numChunks:n,contentType:a,chunked:!0,complete:!1,createdAt:Date.now()},o=new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}});await this.cache.put(`${t}/metadata`,o),this.metadataCache.set(t,l);for(let d=0;d<n;d++){const u=d*s,f=Math.min(u+s,i),c=e.slice(u,f),$=new Response(c,{headers:{"Content-Type":a,"Content-Length":c.size,"X-Chunk-Index":d,"X-Total-Chunks":n}});await this.cache.put(`${t}/chunk-${d}`,$),((d+1)%5===0||d===n-1)&&this.log.info(`Stored chunk ${d+1}/${n} (${x(c.size)})`)}l.complete=!0,await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(l),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,l),this.log.info(`Chunked storage complete: ${t}`)}async getMetadata(t){const e=this.metadataCache.get(t);if(e)return e;this.cache||await this.init();const a=await this.cache.match(`${t}/metadata`);if(!a)return null;const s=await a.text(),i=JSON.parse(s);return this.metadataCache.set(t,i),i}async updateMetadata(t,e){this.cache||await this.init(),await this.cache.put(`${t}/metadata`,new Response(JSON.stringify(e),{headers:{"Content-Type":"application/json"}})),this.metadataCache.set(t,e)}async getAllFiles(){this.cache||await this.init();const t=await this.cache.keys(),e=[],a=new Set;for(const s of t){const n=new URL(s.url).pathname;if(n.includes("/chunk-")||n.endsWith("/metadata")){const o=n.replace(/\/(chunk-\d+|metadata)$/,"");if(a.has(o))continue;a.add(o);const d=await this.getMetadata(o),u=o.match(/\/cache\/(media|layout|widget)\/(.+)/);u&&e.push({id:u[2],type:u[1],size:(d==null?void 0:d.totalSize)||0,cachedAt:(d==null?void 0:d.createdAt)||0});continue}if(n.includes("/cache/static/")||a.has(n))continue;a.add(n);const l=n.match(/\/cache\/(media|layout|widget)\/(.+)/);if(l){const o=await this.cache.match(s);e.push({id:l[2],type:l[1],size:parseInt((o==null?void 0:o.headers.get("Content-Length"))||"0"),cachedAt:0})}}return e}async isChunked(t){const e=await this.getMetadata(t);return(e==null?void 0:e.chunked)===!0}async getChunk(t,e){return this.cache||await this.init(),await this.cache.match(`${t}/chunk-${e}`)}}class ae{constructor(t=200){this.cache=new Map,this.maxBytes=t*1024*1024,this.currentBytes=0,this.log=new D("BlobCache")}has(t){return this.cache.has(t)}async get(t,e){if(this.cache.has(t)){const s=this.cache.get(t);return s.lastAccess=Date.now(),this.log.debug(`HIT: ${t} (${x(s.size)})`),s.blob}this.log.debug(`MISS: ${t} - loading from Cache API`);const a=await e();for(;this.currentBytes+a.size>this.maxBytes&&this.cache.size>0;)this.evictLRU();if(this.currentBytes+a.size<=this.maxBytes){this.cache.set(t,{blob:a,lastAccess:Date.now(),size:a.size}),this.currentBytes+=a.size;const s=(this.currentBytes/this.maxBytes*100).toFixed(1);this.log.debug(`CACHED: ${t} (${x(a.size)}) - utilization: ${s}%`)}else this.log.debug(`Skipping memory cache (too large): ${t} (${x(a.size)} > ${x(this.maxBytes)})`);return a}evictLRU(){let t=null,e=null;for(const[a,s]of this.cache)(!t||s.lastAccess<t.lastAccess)&&(t=s,e=a);e&&(this.currentBytes-=t.size,this.cache.delete(e),this.log.debug(`EVICTED LRU: ${e} (${x(t.size)})`))}clear(){this.cache.clear(),this.currentBytes=0,this.log.info("Cleared all cached blobs")}getStats(){return{entries:this.cache.size,bytes:this.currentBytes,maxBytes:this.maxBytes,utilization:(this.currentBytes/this.maxBytes*100).toFixed(1)+"%"}}}class se{constructor(t,e,a,{staticCache:s="xibo-static-v1"}={}){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.staticCache=s,this.pendingFetches=new Map,this.log=new D("SW"),this.pendingChunkLoads=new Map}async routeFileRequest(t,e,a){const s=await this.cacheManager.fileExists(t);if(!s.exists)return{found:!1,handler:null,data:null};if(s.chunked){const i={metadata:s.metadata,cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-chunked",data:i}:a?{found:!0,handler:"range-chunked",data:{...i,rangeHeader:a}}:{found:!0,handler:"full-chunked",data:i}}else{const n={cached:await this.cacheManager.get(t),cacheKey:t};return e==="HEAD"?{found:!0,handler:"head-whole",data:n}:a?{found:!0,handler:"range-whole",data:{...n,rangeHeader:a}}:{found:!0,handler:"full-whole",data:n}}}async handleRequest(t){var f;const e=new URL(t.request.url);if(this.log.info("handleRequest called for:",e.href),this.log.info("pathname:",e.pathname),e.pathname===y+"/"||e.pathname===y+"/index.html"||e.pathname===y+"/setup.html"){const $=await(await caches.open(this.staticCache)).match(t.request);return $?(this.log.info("Serving static file from cache:",e.pathname),$):(this.log.info("Fetching static file from network:",e.pathname),fetch(t.request))}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&(e.searchParams.get("fileType")==="bundle"||e.searchParams.get("fileType")==="fontCss"||e.searchParams.get("fileType")==="font")){const c=e.searchParams.get("file"),$=`${y}/cache/static/${c}`,M=await caches.open(this.staticCache),C=await M.match($);if(C)return this.log.info("Serving widget resource from cache:",c),C.clone();if(this.pendingFetches.has(c))return this.log.info("Deduplicating widget resource fetch:",c),(await this.pendingFetches.get(c)).clone();this.log.info("Fetching widget resource from CMS:",c);const T=(async()=>{try{const g=await fetch(t.request);if(g.ok){this.log.info("Caching widget resource:",c,`(${g.headers.get("Content-Type")})`);const v=g.clone();return await M.put($,v),g}else return this.log.warn("Widget resource not available (",g.status,"):",c,"- NOT caching"),g}catch(g){return this.log.error("Failed to fetch widget resource:",c,g),new Response("Failed to fetch widget resource",{status:502,statusText:"Bad Gateway",headers:{"Content-Type":"text/plain"}})}})();this.pendingFetches.set(c,T);try{return(await T).clone()}finally{this.pendingFetches.delete(c)}}if((e.pathname.includes("xmds.php")||e.pathname.includes("pwa/file"))&&e.searchParams.has("file")){const c=e.searchParams.get("file"),$=c.split(".")[0],M=e.searchParams.get("type"),C=M==="L"?"layout":"media";this.log.info("XMDS request:",c,"type:",M,"→",y+"/cache/"+C+"/"+$);const T=`${y}/cache/${C}/${$}`,g=await this.cacheManager.get(T);return g?new Response(g.clone().body,{headers:{"Content-Type":g.headers.get("Content-Type")||"video/mp4","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000","Accept-Ranges":"bytes"}}):(this.log.info("XMDS file not cached, passing through:",c),fetch(t.request))}if(e.pathname.startsWith(y+"/cache/static/")){const c=e.pathname.split("/").pop();this.log.info("Static resource request:",c);const M=await(await caches.open(this.staticCache)).match(`${y}/cache/static/${c}`);if(M)return this.log.info("Serving static resource from static cache:",c),M.clone();const C=await this.cacheManager.get(e.pathname);return C?(this.log.info("Serving static resource from media cache:",c),new Response(C.clone().body,{headers:{"Content-Type":C.headers.get("Content-Type")||"application/octet-stream","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})):(this.log.warn("Static resource not cached:",c),new Response("Resource not cached",{status:404}))}if(!e.pathname.startsWith(y+"/cache/"))return this.log.info("NOT a cache request, returning null:",e.pathname),null;if(this.log.info("IS a cache request, proceeding...",e.pathname),e.pathname.startsWith(y+"/cache/widget/")){this.log.info("Widget HTML request:",e.pathname);const c=await this.cacheManager.get(e.pathname);return c?new Response(c.clone().body,{headers:{"Content-Type":"text/html; charset=utf-8","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}}):new Response("<!DOCTYPE html><html><body>Widget not found</body></html>",{status:404,headers:{"Content-Type":"text/html"}})}const a=e.pathname.replace(/\.json$/,""),s=t.request.method,i=t.request.headers.get("Range");this.log.debug("Request URL:",e.pathname),this.log.debug("Cache key:",a),i?this.log.info(s,a,`Range: ${i}`):this.log.info(s,a);const n=await this.routeFileRequest(a,s,i);if(n.found)switch(n.handler){case"head-whole":return this.handleHeadWhole((f=n.data.cached)==null?void 0:f.headers.get("Content-Length"));case"head-chunked":return this.handleHeadChunked(n.data.metadata,n.data.cacheKey);case"range-whole":return this.handleRangeRequest(n.data.cached,n.data.rangeHeader,n.data.cacheKey);case"range-chunked":return this.handleChunkedRangeRequest(n.data.cacheKey,n.data.rangeHeader,n.data.metadata);case"full-whole":return this.handleFullWhole(n.data.cached,n.data.cacheKey);case"full-chunked":return this.handleFullChunked(n.data.cacheKey,n.data.metadata);default:return this.log.error("Unknown handler:",n.handler),new Response("Internal error: unknown handler",{status:500})}const l=a.split("/"),o=l[l.length-2],d=l[l.length-1];let u=null;for(const[,c]of this.downloadManager.queue.active.entries())if(c.fileInfo.type===o&&String(c.fileInfo.id)===d){u=c;break}if(u){this.log.info("Download in progress, waiting:",a);try{await u.wait();const c=await this.routeFileRequest(a,s,i);if(c.found)switch(this.log.info("Download complete, serving via",c.handler),c.handler){case"full-whole":return this.handleFullWhole(c.data.cached,c.data.cacheKey);case"full-chunked":return this.handleFullChunked(c.data.cacheKey,c.data.metadata);default:return this.handleRequest(t)}}catch(c){return this.log.error("Download failed:",a,c),new Response("Download failed: "+c.message,{status:500})}}return this.log.info("Not found:",a),new Response("Not found",{status:404})}handleHeadWhole(t){return this.log.info("HEAD response: File exists (whole file)"),new Response(null,{status:200,headers:{"Content-Length":t?t.toString():"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleHeadChunked(t,e){return await this.cacheManager.getChunk(e,0)?(this.log.info("HEAD response: File exists (chunked)"),new Response(null,{status:200,headers:{"Content-Length":t.totalSize.toString(),"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})):(this.log.info("HEAD response: Chunked file not yet playable (chunk 0 missing):",e),new Response(null,{status:404}))}handleFullWhole(t,e){const a=t.headers.get("Content-Length"),s=a?x(parseInt(a)):"unknown size";return this.log.info("Serving from cache:",e,`(${s})`),new Response(t.body,{headers:{"Content-Type":t.headers.get("Content-Type")||"application/octet-stream","Content-Length":a||"","Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*","Cache-Control":"public, max-age=31536000"}})}async handleFullChunked(t,e){this.log.info("Chunked file GET without Range:",t,`- serving full file from ${e.numChunks} chunks`);const a=`bytes=0-${e.totalSize-1}`;return this.handleChunkedRangeRequest(t,a,e)}async handleRangeRequest(t,e,a){const s=await this.blobCache.get(a,async()=>await t.clone().blob()),i=s.size,{start:n,end:l}=G(e,i),o=s.slice(n,l+1);return this.log.debug(`Range: bytes ${n}-${l}/${i} (${x(o.size)} of ${x(i)})`),new Response(o,{status:206,statusText:"Partial Content",headers:{"Content-Type":t.headers.get("Content-Type")||"video/mp4","Content-Length":o.size.toString(),"Content-Range":`bytes ${n}-${l}/${i}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}async handleChunkedRangeRequest(t,e,a){const{totalSize:s,chunkSize:i,numChunks:n,contentType:l}=a,{start:o,end:d}=G(e,s);let u=d;const f=e.replace(/bytes=/,"");if(f.indexOf("-")===f.length-1){const p=Math.floor(o/i),r=n-1;let w=!0;for(let m=p;m<=r;m++){const k=`${t}/chunk-${m}`;if(this.blobCache.has(k))continue;if(!await this.cacheManager.getChunk(t,m)){w=!1;break}}if(w)this.log.info(`All chunks cached from ${p} to ${r}, serving full range (bytes ${o}-${u}/${s})`);else{const m=Math.min((p+1)*i-1,s-1);m<u&&(u=m,this.log.info(`Progressive streaming: capping bytes=${o}- to chunk ${p} (bytes ${o}-${u}/${s})`))}}const{startChunk:$,endChunk:M,count:C}=K(o,u,i);this.log.debug(`Chunked range: bytes ${o}-${u}/${s} (chunks ${$}-${M}, ${C} chunks)`);const T=p=>{const r=`${t}/chunk-${p}`;return this.blobCache.get(r,()=>{if(this.pendingChunkLoads.has(r))return this.pendingChunkLoads.get(r);const w=(async()=>{let m=await this.cacheManager.getChunk(t,p);if(m)return await m.blob();this.log.info(`Chunk ${p}/${n} not yet available for ${t}, signalling urgent...`);{const k=t.split("/"),b=k[k.length-1],E=k[k.length-2];this.downloadManager.queue.urgentChunk(E,b,p)}for(let k=0;k<60;k++)if(await new Promise(b=>setTimeout(b,1e3)),m=await this.cacheManager.getChunk(t,p),m)return this.log.info(`Chunk ${p}/${n} arrived for ${t} after ${k+1}s`),await m.blob();throw new Error(`Chunk ${p} not available for ${t} after 60s`)})();return this.pendingChunkLoads.set(r,w),w.finally(()=>this.pendingChunkLoads.delete(r)),w})},g=[];let v=!0;for(let p=$;p<=M;p++){const r=await this.cacheManager.getChunk(t,p);if(r){const w=`${t}/chunk-${p}`,m=await this.blobCache.get(w,async()=>await r.blob());g.push(m)}else{v=!1;break}}if(v&&g.length===C){const p=j(g,o,u,i);return this.log.debug(`Serving chunked range: ${x(p.size)} from ${C} chunk(s)`),new Response(p,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":p.size.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}this.log.info(`Streaming response for ${t} bytes ${o}-${u} (waiting for chunks)`);const L=u-o+1,z=new ReadableStream({async start(p){try{const r=[];for(let k=$;k<=M;k++){const b=await T(k);r.push(b)}const m=await j(r,o,u,i).arrayBuffer();p.enqueue(new Uint8Array(m)),p.close()}catch(r){this.log.error(`Stream error for ${t}: ${r.message}`),p.error(r)}}});return new Response(z,{status:206,statusText:"Partial Content",headers:{"Content-Type":l,"Content-Length":L.toString(),"Content-Range":`bytes ${o}-${u}/${s}`,"Accept-Ranges":"bytes","Access-Control-Allow-Origin":"*"}})}}function I(h,t){const e=new Set,a=h.matchAll(/<media[^>]+fileId="(\d+)"/g);for(const n of a)e.add(n[1]);const s=h.matchAll(/<media\s+([^>]+)>/g);for(const n of s){const l=n[1];if(!l.includes("fileId=")){const o=l.match(/\bid="(\d+)"/);o&&e.add(o[1])}}const i=h.matchAll(/<layout[^>]+background="(\d+)"/g);for(const n of i)e.add(n[1]);return t&&t.debug(`extractMediaIdsFromXlf: found ${e.size} IDs: ${[...e].join(", ")} (XLF ${h.length} bytes)`),e}const X={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"};class ne{constructor(t,e,a,s){this.downloadManager=t,this.cacheManager=e,this.blobCache=a,this.config={cacheName:"xibo-media-v1",staticCache:"xibo-static-v1",...s},this.log=new D("SW Message"),this.pendingChunkStorage=new Map}async handleMessage(t){const{type:e,data:a}=t.data;switch(e==="GET_DOWNLOAD_PROGRESS"?this.log.debug("Received:",e):this.log.info("Received:",e),e){case"PING":return this.log.info("PING received, broadcasting SW_READY"),(await self.clients.matchAll()).forEach(i=>{i.postMessage({type:"SW_READY"})}),{success:!0};case"DOWNLOAD_FILES":return await this.handleDownloadFiles(a);case"PRIORITIZE_DOWNLOAD":return this.handlePrioritizeDownload(a.fileType,a.fileId);case"CLEAR_CACHE":return await this.handleClearCache();case"GET_DOWNLOAD_PROGRESS":return await this.handleGetProgress();case"DELETE_FILES":return await this.handleDeleteFiles(a.files);case"PREWARM_VIDEO_CHUNKS":return await this.handlePrewarmVideoChunks(a.mediaIds);case"PRIORITIZE_LAYOUT_FILES":return this.downloadManager.prioritizeLayoutFiles(a.mediaIds),{success:!0};case"URGENT_CHUNK":return this.handleUrgentChunk(a.fileType,a.fileId,a.chunkIndex);case"GET_ALL_FILES":return await this.handleGetAllFiles();default:return this.log.warn("Unknown message type:",e),{success:!1,error:"Unknown message type"}}}async handleDeleteFiles(t){if(!t||!Array.isArray(t))return{success:!1,error:"No files provided"};let e=0;for(const a of t){const s=`${y}/cache/${a.type}/${a.id}`;await this.cacheManager.delete(s)?(this.log.info("Purged:",s),e++):this.log.debug("Not cached (skip purge):",s)}return this.log.info(`Purge complete: ${e}/${t.length} files deleted`),{success:!0,deleted:e,total:t.length}}async handlePrewarmVideoChunks(t){if(!t||!Array.isArray(t)||t.length===0)return{success:!1,error:"No mediaIds provided"};let e=0;for(const a of t){const s=`${y}/cache/media/${a}`,i=await this.cacheManager.getMetadata(s);if(i!=null&&i.chunked){const n=i.numChunks-1,l=[0];n>0&&l.push(n);for(const o of l){const d=`${s}/chunk-${o}`;await this.blobCache.get(d,async()=>{const u=await this.cacheManager.getChunk(s,o);return u?await u.blob():new Blob})}this.log.info(`Pre-warmed ${l.length} chunks for media ${a} (${i.numChunks} total)`),e++}else{const n=await this.cacheManager.get(s);n&&(await this.blobCache.get(s,async()=>await n.clone().blob()),this.log.info(`Pre-warmed whole file for media ${a}`),e++)}}return{success:!0,warmed:e,total:t.length}}handlePrioritizeDownload(t,e){this.log.info("Prioritize request:",`${t}/${e}`);const a=this.downloadManager.queue.prioritize(t,e);return this.downloadManager.queue.processQueue(),{success:!0,found:a}}handleUrgentChunk(t,e,a){return this.log.info("Urgent chunk request:",`${t}/${e}`,"chunk",a),{success:!0,acted:this.downloadManager.queue.urgentChunk(t,e,a)}}async handleDownloadFiles({layoutOrder:t,files:e,layoutDependants:a}){const s=this.downloadManager,i=s.queue;let n=0;const l=[],o=new Map,d=[],u=new Map;for(const r of e)r.type==="layout"?o.set(parseInt(r.id),r):r.type==="resource"||r.code==="fonts.css"||r.path&&(r.path.includes("bundle.min")||r.path.includes("fonts"))?d.push(r):u.set(String(r.id),r);this.log.info(`Download: ${t.length} layouts, ${u.size} media, ${d.length} resources`);const f=new Map,c=[];for(const r of t){const w=o.get(r);w!=null&&w.path&&c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);let b;if(k)b=await k.clone().text();else{const E=await fetch(U(w.path));if(!E.ok){this.log.warn(`XLF fetch failed: ${r} (${E.status})`);return}const F=await E.blob();await this.cacheManager.put(m,F,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (${F.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:F.size})),b=await F.text()}f.set(r,I(b,this.log))})())}for(const[r,w]of o)t.includes(r)||c.push((async()=>{const m=`${y}/cache/layout/${r}`,k=await this.cacheManager.get(m);if(!k&&w.path){const b=await fetch(U(w.path));if(b.ok){const E=await b.blob();await this.cacheManager.put(m,E,"text/xml"),this.log.info(`Fetched + cached XLF ${r} (non-scheduled, ${E.size} bytes)`),(await self.clients.matchAll()).forEach(R=>R.postMessage({type:"FILE_CACHED",fileId:String(r),fileType:"layout",size:E.size}));const S=await E.text();f.set(r,I(S,this.log))}}else if(k){const b=await k.clone().text();f.set(r,I(b,this.log))}})());await Promise.allSettled(c),this.log.info(`Parsed ${f.size} XLFs`);const $=new O(i);for(const r of d)await this._enqueueFile(s,$,r,l)&&n++;const M=await $.build();M.length>0&&(M.push(H),i.enqueueOrderedTasks(M));const C=new Set,T=[...f.keys()].filter(r=>!t.includes(r)),g=new Map;for(const[r,w]of u)w.saveAs&&g.set(w.saveAs,r);const v=new Map;if(a)for(const[r,w]of Object.entries(a))v.set(parseInt(r,10),w);for(const r of t){const w=f.get(r);if(!w)continue;const m=new Set(w);for(const S of T){const R=f.get(S);if(R)for(const Y of R)m.add(Y)}const k=v.get(r)||[];for(const S of k){const R=g.get(S);R&&m.add(R)}const b=[];for(const S of m){if(C.has(S))continue;const R=u.get(S);R&&(b.push(R),C.add(S))}if(b.length===0)continue;this.log.info(`Layout ${r}: ${b.length} media`),b.sort((S,R)=>(S.size||0)-(R.size||0));const E=new O(i);for(const S of b)await this._enqueueFile(s,E,S,l)&&n++;const F=await E.build();F.length>0&&(F.push(H),i.enqueueOrderedTasks(F))}const L=[...u.keys()].filter(r=>!C.has(r));if(L.length>0){this.log.info(`${L.length} media not in any XLF: ${L.join(", ")}`);const r=new O(i);for(const m of L){const k=u.get(m);k&&await this._enqueueFile(s,r,k,l)&&n++}const w=await r.build();w.length>0&&i.enqueueOrderedTasks(w)}const z=i.running,p=i.queue.length;return this.log.info("Downloads active:",z,", queued:",p),{success:!0,enqueuedCount:n,activeCount:z,queuedCount:p}}async _enqueueFile(t,e,a,s){if(!a.path||a.path==="null"||a.path==="undefined")return this.log.debug("Skipping file with no path:",a.id),!1;const i=`${y}/cache/${a.type}/${a.id}`,n=await this.cacheManager.fileExists(i);if(n.exists)if(n.chunked&&n.metadata&&!n.metadata.complete){const{numChunks:u}=n.metadata,f=new Set;for(let c=0;c<u;c++)await this.cacheManager.getChunk(i,c)&&f.add(c);if(f.size===u)return this.log.info("All chunks present but metadata incomplete, marking complete:",i),n.metadata.complete=!0,await this.cacheManager.updateMetadata(i,n.metadata),!1;this.log.info(`Incomplete chunked download: ${f.size}/${u} chunks cached, resuming:`,i),a.skipChunks=f}else return this.log.debug("File already cached:",i,n.chunked?"(chunked)":"(whole file)"),await this.ensureStaticCacheEntry(a),!1;const l=`${a.type}/${a.id}`;if(t.getTask(l))return this.log.debug("File already downloading:",l,"- skipping duplicate"),!1;const d=e.addFile(a);if(d.state==="pending"){const u=this.cacheFileAfterDownload(d,a);return s.push(u),!0}return!1}async cacheFileAfterDownload(t,e){try{const a=`${y}/cache/${e.type}/${e.id}`,s=e.type==="layout"?"text/xml":e.type==="widget"?"text/html":"application/octet-stream",i=parseInt(e.size)||0;if(i>this.config.chunkStorageThreshold)return await this._progressiveCacheFile(t,e,a,s,i);const n=await t.wait();return await this.cacheManager.put(a,n,s),this.log.info("Cached after download:",a,`(${n.size} bytes)`),(await self.clients.matchAll()).forEach(o=>{o.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:n.size})}),this._cacheStaticResource(e,n),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),n}catch(a){throw this.log.error("Failed to cache after download:",e.id,a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),a}}async _progressiveCacheFile(t,e,a,s,i){const{chunkSize:n,cacheName:l}=this.config,o=await caches.open(l);let d=0,u=!1;const f=Math.ceil(i/n);this.log.info(`Progressive download: ${a} (${x(i)}, ~${f} chunks)`);const c={totalSize:i,chunkSize:n,numChunks:f,contentType:s,chunked:!0,complete:!1,createdAt:Date.now()};await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})),this.cacheManager.metadataCache.set(a,c),this.log.info("Metadata stored, ready for progressive streaming:",a),t.onChunkDownloaded=async(C,T,g)=>{const v=new Response(T,{headers:{"Content-Type":s,"Content-Length":T.size,"X-Chunk-Index":C,"X-Total-Chunks":g}});if(await o.put(`${a}/chunk-${C}`,v),d++,(d%2===0||d===g)&&this.log.info(`Progressive: chunk ${d}/${g} cached for ${e.id}`),!u&&(C===0||C===g-1)){const L=C===0||await this.cacheManager.getChunk(a,0),z=C===g-1||await this.cacheManager.getChunk(a,g-1);L&&z&&(u=!0,(await self.clients.matchAll()).forEach(r=>{r.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,progressive:!0,chunksReady:d,totalChunks:g})}),this.log.info("Chunk 0 + last chunk cached — client notified, early playback ready:",a))}g!==f&&(c.numChunks=g,await o.put(`${a}/metadata`,new Response(JSON.stringify(c),{headers:{"Content-Type":"application/json"}})))};const $=await t.wait();return d===0?(this.log.warn("Progressive callback never fired, falling back to putChunked:",a),$.size>0?await this.cacheManager.putChunked(a,$,s):await this.cacheManager.put(a,$,s),(await self.clients.matchAll()).forEach(T=>{T.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:$.size||i})}),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),$):t._urlExpired?(this.log.warn(`URL expired mid-download, partial cache: ${a} (${d}/${f} chunks stored)`),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s})):(this.log.info(`Progressive download complete: ${a} (${d} chunks stored)`),c.complete=!0,await this.cacheManager.updateMetadata(a,c),(await self.clients.matchAll()).forEach(C=>{C.postMessage({type:"FILE_CACHED",fileId:e.id,fileType:e.type,size:i,complete:!0})}),this.pendingChunkStorage.delete(a),this.downloadManager.queue.removeCompleted(`${e.type}/${e.id}`),new Blob([],{type:s}))}_cacheStaticResource(t,e){const a=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;a&&(a.endsWith(".js")||a.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(a))&&(async()=>{try{const s=await caches.open(this.config.staticCache),i=`${y}/cache/static/${a}`,n=a.split(".").pop().toLowerCase(),l=X[n]||"application/octet-stream";await Promise.all([s.put(i,new Response(e.slice(0,e.size,e.type),{headers:{"Content-Type":l}})),this.cacheManager.put(i,e.slice(0,e.size,e.type),l)]),this.log.info("Also cached as static resource:",a,`(${l})`)}catch(s){this.log.warn("Failed to cache static resource:",a,s)}})()}async ensureStaticCacheEntry(t){const e=t.path?(()=>{try{return new URL(t.path).searchParams.get("file")}catch{return null}})():null;if(!e||!(e.endsWith(".js")||e.endsWith(".css")||/\.(otf|ttf|woff2?|eot|svg)$/i.test(e)))return;const a=await caches.open(this.config.staticCache),s=`${y}/cache/static/${e}`;if(await a.match(s))return;const n=`${y}/cache/${t.type}/${t.id}`,l=await this.cacheManager.get(n);if(!l)return;const o=await l.blob(),d=e.split(".").pop().toLowerCase(),u=X[d]||"application/octet-stream",f=`${y}/cache/static/${e}`;await Promise.all([a.put(s,new Response(o.slice(0,o.size,o.type),{headers:{"Content-Type":u}})),this.cacheManager.put(f,o.slice(0,o.size,o.type),u)]),this.log.info("Backfilled static cache for:",e,`(${u}, ${o.size} bytes)`)}async handleGetAllFiles(){return{success:!0,files:await this.cacheManager.getAllFiles()}}async handleClearCache(){return this.log.info("Clearing cache"),await this.cacheManager.clear(),{success:!0}}async handleGetProgress(){return{success:!0,progress:this.downloadManager.getProgress()}}}const q="2026-02-24T20:46:52.689Z",N="xibo-media-v1",P="xibo-static-v1",ie=[y+"/",y+"/index.html",y+"/setup.html"],A=new D("SW"),B=ee(A),_=B.chunkSize,oe=B.threshold,ce=B.blobCacheSize,re=B.concurrency;A.info("Loading modular Service Worker:",q);const V=new Z({concurrency:re,chunkSize:_,chunksPerFile:2}),W=new te({cacheName:N,chunkSize:_}),J=new ae(ce),he=new se(V,W,J,{staticCache:P}),le=new ne(V,W,J,{cacheName:N,staticCache:P,chunkSize:_,chunkStorageThreshold:oe});async function ue(h){const t=new URL(h.request.url),e=t.pathname.replace(y+"/ic",""),a=h.request.method;A.info("Interactive Control request:",a,e);let s=null;if(a==="POST"||a==="PUT")try{s=await h.request.text()}catch{}const i=await self.clients.matchAll({type:"window"});if(i.length===0)return new Response(JSON.stringify({error:"No active player"}),{status:503,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}});const n=i[0];try{const l=await new Promise((o,d)=>{const u=new MessageChannel,f=setTimeout(()=>d(new Error("IC timeout")),5e3);u.port1.onmessage=c=>{clearTimeout(f),o(c.data)},n.postMessage({type:"INTERACTIVE_CONTROL",method:a,path:e,search:t.search,body:s},[u.port2])});return new Response(l.body||"",{status:l.status||200,headers:{"Content-Type":l.contentType||"application/json","Access-Control-Allow-Origin":"*"}})}catch(l){return A.error("IC handler error:",l),new Response(JSON.stringify({error:l.message}),{status:500,headers:{"Content-Type":"application/json","Access-Control-Allow-Origin":"*"}})}}self.addEventListener("install",h=>{A.info("Installing... Version:",q),h.waitUntil(Promise.all([W.init(),caches.open(P).then(t=>(A.info("Caching static files"),t.addAll(ie)))]).then(async()=>{if(A.info("Cache initialized"),self.registration.active)try{const e=await(await caches.open("xibo-sw-version")).match("version");if(e){const a=await e.text();if(a===q){A.info("Same version already active, skipping activation to preserve streams");return}A.info("Version changed:",a,"→",q)}}catch{}return A.info("New version, activating immediately"),self.skipWaiting()}))});self.addEventListener("activate",h=>{A.info("Activating... Version:",q,"| @xiboplayer/cache:",Q),h.waitUntil(caches.keys().then(t=>Promise.all(t.filter(e=>e.startsWith("xibo-")&&e!==N&&e!==P&&e!=="xibo-sw-version").map(e=>(A.info("Deleting old cache:",e),caches.delete(e))))).then(async()=>(await(await caches.open("xibo-sw-version")).put("version",new Response(q)),A.info("Taking control of all clients immediately"),self.clients.claim())).then(async()=>{A.info("Notifying all clients that fetch handler is ready"),(await self.clients.matchAll()).forEach(e=>{e.postMessage({type:"SW_READY"})})}))});self.addEventListener("fetch",h=>{const t=new URL(h.request.url);if(t.pathname.startsWith(y+"/cache/")||t.pathname.startsWith(y+"/ic/")||t.pathname.startsWith("/player/")&&(t.pathname.endsWith(".html")||t.pathname==="/player/")||t.pathname.includes("xmds.php")&&t.searchParams.has("file")&&h.request.method==="GET"){if(t.pathname.startsWith(y+"/ic/")){h.respondWith(ue(h));return}h.respondWith(he.handleRequest(h))}});self.addEventListener("message",h=>{h.waitUntil(le.handleMessage(h).then(t=>{var e;(e=h.ports[0])==null||e.postMessage(t)}))});A.info("Modular Service Worker ready");
|
|
2
2
|
//# sourceMappingURL=sw-pwa.js.map
|