@xiboplayer/pwa 0.5.4 → 0.5.5
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 +42 -0
- package/dist/assets/{cms-api-B3gEu-pj.js → cms-api-Df_4fWKB.js} +2 -2
- package/dist/assets/{cms-api-B3gEu-pj.js.map → cms-api-Df_4fWKB.js.map} +1 -1
- package/dist/assets/{index-BJfE9Kwo.js → index-BI2Wgrnr.js} +2 -2
- package/dist/assets/{index-BJfE9Kwo.js.map → index-BI2Wgrnr.js.map} +1 -1
- package/dist/assets/index-BtefBXN1.js +2 -0
- package/dist/assets/{index-CQyGlAYj.js.map → index-BtefBXN1.js.map} +1 -1
- package/dist/assets/index-C6HTCgOh.js +2 -0
- package/dist/assets/{index-CzDf1qpA.js.map → index-C6HTCgOh.js.map} +1 -1
- package/dist/assets/{index-CXNhzvrm.js → index-CO_3HB3b.js} +2 -2
- package/dist/assets/{index-CXNhzvrm.js.map → index-CO_3HB3b.js.map} +1 -1
- package/dist/assets/{index-DxBxL_GE.js → index-CSP8cHo2.js} +2 -2
- package/dist/assets/{index-DxBxL_GE.js.map → index-CSP8cHo2.js.map} +1 -1
- package/dist/assets/index-CXUhpySp.js +2 -0
- package/dist/assets/{index-B0GfHN6H.js.map → index-CXUhpySp.js.map} +1 -1
- package/dist/assets/index-DjVtpboH.js +2 -0
- package/dist/assets/{index-Y1vt-BGr.js.map → index-DjVtpboH.js.map} +1 -1
- package/dist/assets/{index-CUXQMBpU.js → index-DozRpAD9.js} +2 -2
- package/dist/assets/{index-CUXQMBpU.js.map → index-DozRpAD9.js.map} +1 -1
- package/dist/assets/index-O5-FLIor.js +2 -0
- package/dist/assets/{index-CExOPp2u.js.map → index-O5-FLIor.js.map} +1 -1
- package/dist/assets/main-4E7jVmyh.js +715 -0
- package/dist/assets/main-4E7jVmyh.js.map +1 -0
- package/dist/assets/{setup-DgQcE5P_.js → setup-D2LzAr3z.js} +2 -2
- package/dist/assets/{setup-DgQcE5P_.js.map → setup-D2LzAr3z.js.map} +1 -1
- package/dist/assets/{sync-manager-DBfiw5Ey.js → sync-manager-Cibvio-3.js} +2 -2
- package/dist/assets/{sync-manager-DBfiw5Ey.js.map → sync-manager-Cibvio-3.js.map} +1 -1
- package/dist/assets/widget-html-BzYo0-WO.js +5 -0
- package/dist/assets/widget-html-BzYo0-WO.js.map +1 -0
- package/dist/assets/{xmds-client-CX0t7Oes.js → xmds-client-uoul_PDG.js} +2 -2
- package/dist/assets/{xmds-client-CX0t7Oes.js.map → xmds-client-uoul_PDG.js.map} +1 -1
- package/dist/index.html +3 -3
- package/dist/setup.html +3 -3
- package/dist/sw-pwa.js +1 -1
- package/package.json +1 -1
- package/dist/assets/index-B0GfHN6H.js +0 -2
- package/dist/assets/index-CExOPp2u.js +0 -2
- package/dist/assets/index-CQyGlAYj.js +0 -2
- package/dist/assets/index-CzDf1qpA.js +0 -2
- package/dist/assets/index-Y1vt-BGr.js +0 -2
- package/dist/assets/main-ByDZRbW8.js +0 -715
- package/dist/assets/main-ByDZRbW8.js.map +0 -1
- package/dist/assets/widget-html-B_acad6q.js +0 -2
- package/dist/assets/widget-html-B_acad6q.js.map +0 -1
package/README.md
CHANGED
|
@@ -40,6 +40,48 @@ All overlays and controls are hidden by default for clean kiosk operation.
|
|
|
40
40
|
|
|
41
41
|
Timeline overlay also supports **click-to-skip** — click any layout in the timeline to jump directly to it.
|
|
42
42
|
|
|
43
|
+
## Auto-authorize via CMS API (optional)
|
|
44
|
+
|
|
45
|
+
By default, new displays must be manually authorized by a CMS administrator. To skip this step and have the player authorize itself automatically, provide OAuth2 API credentials — either via the setup page or via `config.json` provisioning in the Electron/Chromium shells.
|
|
46
|
+
|
|
47
|
+
### How it works
|
|
48
|
+
|
|
49
|
+
After the player registers with the CMS (via XMDS `RegisterDisplay`), it uses the CMS REST API with an OAuth2 `client_credentials` flow to:
|
|
50
|
+
|
|
51
|
+
1. Obtain an access token from `/api/authorize/access_token`
|
|
52
|
+
2. Find the display by hardware key via `GET /api/display?hardwareKey=...`
|
|
53
|
+
3. Authorize the display via `PUT /api/display/{id}/authorise`
|
|
54
|
+
|
|
55
|
+
If auto-authorize fails (wrong credentials, missing scope, CMS unreachable), the player silently falls back to manual authorization — the CMS administrator sees the display as "Awaiting approval".
|
|
56
|
+
|
|
57
|
+
### CMS setup
|
|
58
|
+
|
|
59
|
+
1. In the CMS, go to **Administration > Applications**
|
|
60
|
+
2. Click **Add Application**
|
|
61
|
+
3. Set **Grant Type** to `client_credentials`
|
|
62
|
+
4. **Important:** on the **Scopes** tab (2nd tab), enable the **`displays`** scope — this is required for the player to find and authorize itself
|
|
63
|
+
5. Save and copy the **Client ID** and **Client Secret**
|
|
64
|
+
|
|
65
|
+
Without the `displays` scope enabled, the API will return `403 Forbidden` and auto-authorize will not work.
|
|
66
|
+
|
|
67
|
+
### Interactive setup
|
|
68
|
+
|
|
69
|
+
In the setup page, expand "Auto-authorize via API (optional)" and enter the Client ID and Client Secret. These are saved to localStorage alongside the CMS configuration.
|
|
70
|
+
|
|
71
|
+
### Provisioning via config.json
|
|
72
|
+
|
|
73
|
+
When using the Electron or Chromium shells, add the credentials to `config.json`:
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{
|
|
77
|
+
"cmsUrl": "https://your-cms.example.com",
|
|
78
|
+
"cmsKey": "your-cms-key",
|
|
79
|
+
"displayName": "Lobby Display",
|
|
80
|
+
"apiClientId": "your-client-id",
|
|
81
|
+
"apiClientSecret": "your-client-secret"
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
43
85
|
## Debug Overlays
|
|
44
86
|
|
|
45
87
|
Three toggleable overlays provide real-time insight into player operation without leaving the playback screen. All are hidden by default for clean kiosk operation — press the corresponding key to toggle.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const y={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},f=[];class C{constructor(t,e=null){this.name=t,this.useGlobal=e===null,this.useGlobal||this.setLevel(e)}setLevel(t){this.useGlobal=!1,typeof t=="string"?this.level=y[t.toUpperCase()]??y.INFO:this.level=t}getEffectiveLevel(){return this.useGlobal?d.level:this.level}debug(...t){this.getEffectiveLevel()<=y.DEBUG&&console.log(`[${this.name}] DEBUG:`,...t),w("debug",this.name,t)}info(...t){this.getEffectiveLevel()<=y.INFO&&console.log(`[${this.name}]`,...t),w("info",this.name,t)}warn(...t){this.getEffectiveLevel()<=y.WARNING&&console.warn(`[${this.name}]`,...t),w("warning",this.name,t)}error(...t){this.getEffectiveLevel()<=y.ERROR&&console.error(`[${this.name}]`,...t),w("error",this.name,t)}log(t,...e){switch(t.toUpperCase()){case"DEBUG":return this.debug(...e);case"INFO":return this.info(...e);case"WARNING":case"WARN":return this.warn(...e);case"ERROR":return this.error(...e)}}}const d={level:y.WARNING,setGlobalLevel(i){typeof i=="string"?this.level=y[i.toUpperCase()]??y.INFO:this.level=i,console.log(`[Logger] Global log level set to: ${this.getLevelName(this.level)}`)},getLevelName(i){return Object.keys(y).find(t=>y[t]===i)||"UNKNOWN"}};let $=!1;if(typeof window<"u"){const t=new URLSearchParams(window.location.search).get("logLevel"),e=localStorage.getItem("xibo_log_level");t?(d.setGlobalLevel(t),$=!0):e?(d.setGlobalLevel(e),$=!0):d.setGlobalLevel("WARNING")}function L(i,t=null){return new C(i,t)}function G(i){d.setGlobalLevel(i),typeof window<"u"&&localStorage.setItem("xibo_log_level",i.toUpperCase())}function R(){return d.getLevelName(d.level)}function O(){return d.level<=y.DEBUG}function I(i){if($||!i)return!1;const t=K(i);return d.setGlobalLevel(t),!0}function K(i){switch((i||"").toLowerCase()){case"debug":return"DEBUG";case"info":case"notice":case"audit":return"INFO";case"warning":return"WARNING";case"error":case"critical":case"alert":case"emergency":return"ERROR";default:return"INFO"}}function w(i,t,e){if(f.length!==0)for(const a of f)try{a({level:i,name:t,args:e})}catch{}}function _(i){f.push(i)}function q(i){const t=f.indexOf(i);t>=0&&f.splice(t,1)}function T(i,t){const e=new Uint8Array(i);let a="";for(let n=0;n<e.length;n++)a+=String.fromCharCode(e[n]);const s=btoa(a),r=[];for(let n=0;n<s.length;n+=64)r.push(s.substring(n,n+64));return`-----BEGIN ${t}-----
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}
|
|
4
|
-
-----END ${t}-----`}async function v(){const i=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:1024,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),t=await crypto.subtle.exportKey("spki",i.publicKey),e=await crypto.subtle.exportKey("pkcs8",i.privateKey);return{publicKeyPem:T(t,"PUBLIC KEY"),privateKeyPem:T(e,"PRIVATE KEY")}}function D(i){return!i||typeof i!="string"?!1:/^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\n[A-Za-z0-9+/=\n]+\n-----END \1-----$/.test(i.trim())}var b={};const m="xibo_config",x="xibo-hw-backup",A=1;function k(){const i=typeof process<"u"&&b?b:{},t={cmsUrl:i.CMS_URL||"",cmsKey:i.CMS_KEY||"",displayName:i.DISPLAY_NAME||"",hardwareKey:i.HARDWARE_KEY||"",xmrChannel:i.XMR_CHANNEL||"",googleGeoApiKey:i.GOOGLE_GEO_API_KEY||""};return Object.values(t).some(a=>a!=="")?t:null}class N{constructor(){this.data=this.load(),this._fromEnv||this._restoreHardwareKeyFromBackup()}load(){const t=k();if(t)return this._fromEnv=!0,t;if(typeof localStorage>"u")return{cmsUrl:"",cmsKey:"",displayName:"",hardwareKey:"",xmrChannel:""};const e=localStorage.getItem(m);let a={};if(e)try{a=JSON.parse(e)}catch(r){console.error("[Config] Failed to parse localStorage config:",r)}let s=!1;return!a.hardwareKey||a.hardwareKey.length<10?(console.warn("[Config] Missing/invalid hardwareKey — generating"),a.hardwareKey=this.generateStableHardwareKey(),this._backupHardwareKey(a.hardwareKey),s=!0):console.log("[Config] ✓ Loaded existing hardwareKey:",a.hardwareKey),a.xmrChannel||(console.warn("[Config] Missing xmrChannel — generating"),a.xmrChannel=this.generateXmrChannel(),s=!0),a.cmsUrl=a.cmsUrl||"",a.cmsKey=a.cmsKey||"",a.displayName=a.displayName||"",s&&localStorage.setItem(m,JSON.stringify(a)),a}_backupKeys(t){try{const e=indexedDB.open(x,A);e.onupgradeneeded=()=>{const a=e.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},e.onsuccess=()=>{const a=e.result,s=a.transaction("keys","readwrite"),r=s.objectStore("keys");for(const[n,o]of Object.entries(t))r.put(o,n);s.oncomplete=()=>{console.log("[Config] Keys backed up to IndexedDB:",Object.keys(t).join(", ")),a.close()}}}catch{}}_backupHardwareKey(t){this._backupKeys({hardwareKey:t})}async _restoreHardwareKeyFromBackup(){if(!(typeof indexedDB>"u"))try{const t=await new Promise((r,n)=>{const o=indexedDB.open(x,A);o.onupgradeneeded=()=>{const c=o.result;c.objectStoreNames.contains("keys")||c.createObjectStore("keys")},o.onsuccess=()=>r(o.result),o.onerror=()=>n(o.error)}),a=t.transaction("keys","readonly").objectStore("keys"),s=await new Promise(r=>{const n=a.get("hardwareKey");n.onsuccess=()=>r(n.result),n.onerror=()=>r(null)});t.close(),s&&s!==this.data.hardwareKey?(console.log("[Config] Restoring hardware key from IndexedDB backup:",s),console.log("[Config] (was:",this.data.hardwareKey,")"),this.data.hardwareKey=s,this.save()):!s&&this.data.hardwareKey&&this._backupHardwareKey(this.data.hardwareKey)}catch{}}save(){typeof localStorage<"u"&&localStorage.setItem(m,JSON.stringify(this.data))}isConfigured(){return!!(this.data.cmsUrl&&this.data.cmsKey&&this.data.displayName)}generateStableHardwareKey(){if(typeof crypto<"u"&&crypto.randomUUID){const s="pwa-"+crypto.randomUUID().replace(/-/g,"").substring(0,28);return console.log("[Config] Generated new UUID-based hardware key:",s),s}const e="pwa-"+Array.from({length:28},()=>Math.floor(Math.random()*16).toString(16)).join("");return console.log("[Config] Generated new random hardware key:",e),e}getCanvasFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");return e?(e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("Xibo Player",2,15),t.toDataURL()):"no-canvas"}catch{return"canvas-error"}}generateHardwareKey(){return this.generateStableHardwareKey()}generateXmrChannel(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}async ensureXmrKeyPair(){if(this.data.xmrPubKey&&D(this.data.xmrPubKey))return;console.log("[Config] Generating RSA key pair for XMR registration...");const{publicKeyPem:t,privateKeyPem:e}=await v();this.data.xmrPubKey=t,this.data.xmrPrivKey=e,this.save(),typeof indexedDB<"u"&&this._backupKeys({xmrPubKey:t,xmrPrivKey:e}),console.log("[Config] RSA key pair generated and saved")}hash(t){let e=2166136261;for(let s=0;s<t.length;s++)e^=t.charCodeAt(s),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);e=e>>>0;let a="";for(let s=0;s<4;s++){let r=e+s*1234567;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n)+s,r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);r=r>>>0,a+=r.toString(16).padStart(8,"0")}return a.substring(0,32)}get cmsUrl(){return this.data.cmsUrl}set cmsUrl(t){this.data.cmsUrl=t,this.save()}get cmsKey(){return this.data.cmsKey}set cmsKey(t){this.data.cmsKey=t,this.save()}get displayName(){return this.data.displayName}set displayName(t){this.data.displayName=t,this.save()}get hardwareKey(){return this.data.hardwareKey||(console.error("[Config] CRITICAL: hardwareKey missing! Generating emergency key."),this.data.hardwareKey=this.generateStableHardwareKey(),this.save()),this.data.hardwareKey}get xmrChannel(){return this.data.xmrChannel||(console.warn("[Config] xmrChannel missing at access time — generating"),this.data.xmrChannel=this.generateXmrChannel(),this.save()),this.data.xmrChannel}get xmrPubKey(){return this.data.xmrPubKey||""}get xmrPrivKey(){return this.data.xmrPrivKey||""}get googleGeoApiKey(){return this.data.googleGeoApiKey||""}set googleGeoApiKey(t){this.data.googleGeoApiKey=t,this.save()}}const M=new N,E=L("FetchRetry"),S=3e4,P=12e4;function U(i){if(!i)return S;const t=Number(i);if(!isNaN(t)&&t>=0)return Math.min(t*1e3,P);const e=new Date(i);if(!isNaN(e.getTime())){const a=e.getTime()-Date.now();return Math.min(Math.max(a,0),P)}return S}async function j(i,t={},e={}){const{maxRetries:a=3,baseDelayMs:s=1e3,maxDelayMs:r=3e4}=e;let n,o;for(let c=0;c<=a;c++){try{const l=await fetch(i,t);if(l.status===429){const u=U(l.headers.get("Retry-After"));if(E.debug(`429 Rate limited, waiting ${u}ms (Retry-After: ${l.headers.get("Retry-After")})`),o=l,n=new Error("HTTP 429: Too Many Requests"),n.status=429,c<a){await new Promise(p=>setTimeout(p,u));continue}break}if(l.ok||l.status>=400&&l.status<500)return l;o=l,n=new Error(`HTTP ${l.status}: ${l.statusText}`),n.status=l.status}catch(l){n=l,o=null}if(c<a){const u=Math.min(s*Math.pow(2,c),r)*(.5+Math.random()*.5);E.debug(`Retry ${c+1}/${a} in ${Math.round(u)}ms:`,String(i).slice(0,80)),await new Promise(p=>setTimeout(p,u))}}if(o)return o;throw n}const h=L("CmsApi");class B{constructor({baseUrl:t,clientId:e,clientSecret:a,apiToken:s}={}){this.baseUrl=(t||"").replace(/\/+$/,""),this.clientId=e||null,this.clientSecret=a||null,this.accessToken=s||null,this.tokenExpiry=s?1/0:0}async authenticate(){h.info("Authenticating with CMS API...");const t=await fetch(`${this.baseUrl}/api/authorize/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.clientId,client_secret:this.clientSecret})});if(!t.ok){const a=await t.text();throw new Error(`OAuth2 authentication failed (${t.status}): ${a}`)}const e=await t.json();return this.accessToken=e.access_token,this.tokenExpiry=Date.now()+(e.expires_in||3600)*1e3,h.info("Authenticated successfully, token expires in",e.expires_in,"s"),this.accessToken}async ensureToken(){if(!(this.accessToken&&Date.now()<this.tokenExpiry-6e4)){if(!this.clientId||!this.clientSecret){if(this.accessToken)return;throw new g("AUTH","/authorize",0,"No valid token and no OAuth2 credentials")}await this.authenticate()}}async request(t,e,a={}){var c;await this.ensureToken();const s=new URL(`${this.baseUrl}/api${e}`),r={method:t,headers:{Authorization:`Bearer ${this.accessToken}`}};if(t==="GET")for(const[l,u]of Object.entries(a))u!=null&&s.searchParams.set(l,String(u));else r.headers["Content-Type"]="application/x-www-form-urlencoded",r.body=new URLSearchParams(a);const n=await fetch(s,r);if(!n.ok){const l=await n.text();let u;try{const p=JSON.parse(l);u=((c=p.error)==null?void 0:c.message)||p.message||l}catch{u=l}throw new g(t,e,n.status,u)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}get(t,e){return this.request("GET",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}del(t){return this.request("DELETE",t)}async findDisplay(t){h.info("Looking up display by hardwareKey:",t);const e=await this.request("GET","/display",{hardwareKey:t}),a=Array.isArray(e)?e:[];if(a.length===0)return h.info("No display found for hardwareKey:",t),null;const s=a[0];return h.info(`Found display: ${s.display} (ID: ${s.displayId}, licensed: ${s.licensed})`),s}async authorizeDisplay(t){h.info("Authorizing display:",t),await this.request("PUT",`/display/authorise/${t}`),h.info("Display authorized successfully")}async editDisplay(t,e){return h.info("Editing display:",t,e),this.request("PUT",`/display/${t}`,e)}async listDisplays(t={}){const e=await this.request("GET","/display",t);return Array.isArray(e)?e:[]}async requestScreenshot(t){await this.request("PUT",`/display/requestscreenshot/${t}`)}async getDisplayStatus(t){return this.request("GET",`/display/status/${t}`)}async requestMultipart(t,e,a){var o;await this.ensureToken();const s=`${this.baseUrl}/api${e}`,r=await fetch(s,{method:t,headers:{Authorization:`Bearer ${this.accessToken}`},body:a});if(!r.ok){const c=await r.text();let l;try{const u=JSON.parse(c);l=((o=u.error)==null?void 0:o.message)||u.message||c}catch{l=c}throw new Error(`CMS API ${t} ${e} failed (${r.status}): ${l}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async createLayout({name:t,resolutionId:e,description:a}){const s={name:t,resolutionId:e};return a&&(s.description=a),this.request("POST","/layout",s)}async listLayouts(t={}){const e=await this.request("GET","/layout",t);return Array.isArray(e)?e:[]}async getLayout(t){return this.request("GET",`/layout/${t}`)}async deleteLayout(t){await this.request("DELETE",`/layout/${t}`)}async publishLayout(t){await this.request("PUT",`/layout/publish/${t}`,{publishNow:1})}async checkoutLayout(t){return this.request("PUT",`/layout/checkout/${t}`)}async getDraftLayout(t){const e=await this.listLayouts({parentId:t});return e.length>0?e[0]:null}async editLayoutBackground(t,e){return this.request("PUT",`/layout/background/${t}`,e)}async addRegion(t,e){return this.request("POST",`/region/${t}`,e)}async editRegion(t,e){return this.request("PUT",`/region/${t}`,e)}async deleteRegion(t){await this.request("DELETE",`/region/${t}`)}async addWidget(t,e,a={}){const{templateId:s,displayOrder:r,...n}=a,o={};s!==void 0&&(o.templateId=s),r!==void 0&&(o.displayOrder=r);const c=await this.request("POST",`/playlist/widget/${t}/${e}`,o);return Object.keys(n).length>0?(n.duration!==void 0&&n.useDuration===void 0&&(n.useDuration=1),this.request("PUT",`/playlist/widget/${c.widgetId}`,n)):c}async editWidget(t,e){return this.request("PUT",`/playlist/widget/${t}`,e)}async deleteWidget(t){await this.request("DELETE",`/playlist/widget/${t}`)}async uploadMedia(t){return this.requestMultipart("POST","/library",t)}async listMedia(t={}){const e=await this.request("GET","/library",t);return Array.isArray(e)?e:[]}async getMedia(t){return this.request("GET",`/library/${t}`)}async deleteMedia(t){await this.request("DELETE",`/library/${t}`)}async createCampaign(t){return this.request("POST","/campaign",{name:t})}async listCampaigns(t={}){const e=await this.request("GET","/campaign",t);return Array.isArray(e)?e:[]}async deleteCampaign(t){await this.request("DELETE",`/campaign/${t}`)}async assignLayoutToCampaign(t,e,a){const s={layoutId:e};a!==void 0&&(s.displayOrder=a),await this.request("POST",`/campaign/layout/assign/${t}`,s)}async createSchedule(t){const e={...t};Array.isArray(e.displayGroupIds)&&delete e.displayGroupIds,await this.ensureToken();const a=`${this.baseUrl}/api/schedule`,s=new URLSearchParams;for(const[o,c]of Object.entries(e))c!=null&&s.set(o,String(c));if(Array.isArray(t.displayGroupIds))for(const o of t.displayGroupIds)s.append("displayGroupIds[]",String(o));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const o=await r.text();throw new Error(`CMS API POST /schedule failed (${r.status}): ${o}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async deleteSchedule(t){await this.request("DELETE",`/schedule/${t}`)}async listSchedules(t={}){const e=await this.request("GET","/schedule/data/events",t);return Array.isArray(e)?e:(e==null?void 0:e.events)||[]}async listDisplayGroups(t={}){const e=await this.request("GET","/displaygroup",t);return Array.isArray(e)?e:[]}async createDisplayGroup(t,e){const a={displayGroup:t};return e&&(a.description=e),this.request("POST","/displaygroup",a)}async deleteDisplayGroup(t){await this.request("DELETE",`/displaygroup/${t}`)}async assignDisplayToGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/assign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API assign display to group failed (${r.status}): ${n}`)}}async unassignDisplayFromGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/unassign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API unassign display from group failed (${r.status}): ${n}`)}}async listResolutions(){const t=await this.request("GET","/resolution");return Array.isArray(t)?t:[]}async listTemplates(t={}){const e=await this.request("GET","/template",t);return Array.isArray(e)?e:[]}async assignMediaToPlaylist(t,e){const a=Array.isArray(e)?e:[e];await this.ensureToken();const s=`${this.baseUrl}/api/playlist/library/assign/${t}`,r=new URLSearchParams;for(const c of a)r.append("media[]",String(c));const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:r});if(!n.ok){const c=await n.text();throw new g("POST",`/playlist/library/assign/${t}`,n.status,c)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}async editLayout(t,e){return this.request("PUT",`/layout/${t}`,e)}async copyLayout(t,e={}){return this.post(`/layout/copy/${t}`,e)}async discardLayout(t){await this.put(`/layout/discard/${t}`)}async editCampaign(t,e){return this.put(`/campaign/${t}`,e)}async getCampaign(t){return this.get(`/campaign/${t}`)}async unassignLayoutFromCampaign(t,e){await this.post(`/campaign/layout/unassign/${t}`,{layoutId:e})}async editSchedule(t,e){return this.put(`/schedule/${t}`,e)}async retireLayout(t){await this.put(`/layout/retire/${t}`)}async unretireLayout(t){await this.put(`/layout/unretire/${t}`)}async getLayoutStatus(t){return this.get(`/layout/status/${t}`)}async tagLayout(t,e){await this.post(`/layout/${t}/tag`,{tag:e.join(",")})}async untagLayout(t,e){await this.post(`/layout/${t}/untag`,{tag:e.join(",")})}async listCommands(t={}){const e=await this.get("/command",t);return Array.isArray(e)?e:[]}async createCommand(t){return this.post("/command",t)}async editCommand(t,e){return this.put(`/command/${t}`,e)}async deleteCommand(t){await this.del(`/command/${t}`)}async deleteDisplay(t){await this.del(`/display/${t}`)}async wolDisplay(t){await this.post(`/display/wol/${t}`)}async setDefaultLayout(t,e){return this.put(`/display/${t}`,{defaultLayoutId:e})}async purgeDisplay(t){await this.post(`/display/purge/${t}`)}async listDayParts(t={}){const e=await this.get("/daypart",t);return Array.isArray(e)?e:[]}async createDayPart(t){return this.post("/daypart",t)}async editDayPart(t,e){return this.put(`/daypart/${t}`,e)}async deleteDayPart(t){await this.del(`/daypart/${t}`)}async uploadMediaUrl(t,e){return this.post("/library",{url:t,name:e,type:"uri"})}async copyMedia(t){return this.post(`/library/copy/${t}`)}async downloadMedia(t){await this.ensureToken();const e=`${this.baseUrl}/api/library/download/${t}`,a=await fetch(e,{headers:{Authorization:`Bearer ${this.accessToken}`}});if(!a.ok){const s=await a.text();throw new g("GET",`/library/download/${t}`,a.status,s)}return a}async editMedia(t,e){return this.put(`/library/${t}`,e)}async getMediaUsage(t){return this.get(`/library/usage/${t}`)}async tidyLibrary(){await this.post("/library/tidy")}async listPlaylists(t={}){const e=await this.get("/playlist",t);return Array.isArray(e)?e:[]}async createPlaylist(t){return this.post("/playlist",{name:t})}async getPlaylist(t){return this.get(`/playlist/${t}`)}async editPlaylist(t,e){return this.put(`/playlist/${t}`,e)}async deletePlaylist(t){await this.del(`/playlist/${t}`)}async reorderPlaylist(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/playlist/order/${t}`,s=new URLSearchParams;for(const n of e)s.append("widgets[]",String(n));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new g("POST",`/playlist/order/${t}`,r.status,n)}}async copyPlaylist(t){return this.post(`/playlist/copy/${t}`)}async setWidgetTransition(t,e,a={}){return this.put(`/playlist/widget/transition/${t}`,{type:e,...a})}async setWidgetAudio(t,e){return this.put(`/playlist/widget/${t}/audio`,e)}async removeWidgetAudio(t){await this.del(`/playlist/widget/${t}/audio`)}async setWidgetExpiry(t,e){return this.put(`/playlist/widget/${t}/expiry`,e)}async saveAsTemplate(t,e){return this.post(`/template/${t}`,e)}async getTemplate(t){return this.get(`/template/${t}`)}async deleteTemplate(t){await this.del(`/template/${t}`)}async listDatasets(t={}){const e=await this.get("/dataset",t);return Array.isArray(e)?e:[]}async createDataset(t){return this.post("/dataset",t)}async editDataset(t,e){return this.put(`/dataset/${t}`,e)}async deleteDataset(t){await this.del(`/dataset/${t}`)}async listDatasetColumns(t){const e=await this.get(`/dataset/${t}/column`);return Array.isArray(e)?e:[]}async createDatasetColumn(t,e){return this.post(`/dataset/${t}/column`,e)}async editDatasetColumn(t,e,a){return this.put(`/dataset/${t}/column/${e}`,a)}async deleteDatasetColumn(t,e){await this.del(`/dataset/${t}/column/${e}`)}async listDatasetData(t,e={}){const a=await this.get(`/dataset/data/${t}`,e);return Array.isArray(a)?a:[]}async addDatasetRow(t,e){return this.post(`/dataset/data/${t}`,e)}async editDatasetRow(t,e,a){return this.put(`/dataset/data/${t}/${e}`,a)}async deleteDatasetRow(t,e){await this.del(`/dataset/data/${t}/${e}`)}async importDatasetCsv(t,e){return this.requestMultipart("POST",`/dataset/import/${t}`,e)}async clearDataset(t){await this.del(`/dataset/data/${t}`)}async listNotifications(t={}){const e=await this.get("/notification",t);return Array.isArray(e)?e:[]}async createNotification(t){return this.post("/notification",t)}async editNotification(t,e){return this.put(`/notification/${t}`,e)}async deleteNotification(t){await this.del(`/notification/${t}`)}async listFolders(t={}){const e=await this.get("/folder",t);return Array.isArray(e)?e:[]}async createFolder(t){return this.post("/folder",t)}async editFolder(t,e){return this.put(`/folder/${t}`,e)}async deleteFolder(t){await this.del(`/folder/${t}`)}async listTags(t={}){const e=await this.get("/tag",t);return Array.isArray(e)?e:[]}async createTag(t){return this.post("/tag",t)}async editTag(t,e){return this.put(`/tag/${t}`,e)}async deleteTag(t){await this.del(`/tag/${t}`)}async tagEntity(t,e,a){await this.post(`/${t}/${e}/tag`,{tag:a.join(",")})}async untagEntity(t,e,a){await this.post(`/${t}/${e}/untag`,{tag:a.join(",")})}async dgChangeLayout(t,e){await this.post(`/displaygroup/${t}/action/changeLayout`,{layoutId:e})}async dgOverlayLayout(t,e){await this.post(`/displaygroup/${t}/action/overlayLayout`,{layoutId:e})}async dgRevertToSchedule(t){await this.post(`/displaygroup/${t}/action/revertToSchedule`)}async dgCollectNow(t){await this.post(`/displaygroup/${t}/action/collectNow`)}async dgSendCommand(t,e){await this.post(`/displaygroup/${t}/action/command`,{commandId:e})}async editDisplayGroup(t,e){return this.put(`/displaygroup/${t}`,e)}}class g extends Error{constructor(t,e,a,s){super(`CMS API ${t} ${e} → ${a}: ${s}`),this.name="CmsApiError",this.method=t,this.path=e,this.status=a,this.detail=s}}export{B as C,y as L,I as a,M as b,L as c,g as d,j as f,R as g,O as i,K as m,_ as r,G as s,q as u};
|
|
5
|
-
//# sourceMappingURL=cms-api-
|
|
4
|
+
-----END ${t}-----`}async function v(){const i=await crypto.subtle.generateKey({name:"RSA-OAEP",modulusLength:1024,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["encrypt","decrypt"]),t=await crypto.subtle.exportKey("spki",i.publicKey),e=await crypto.subtle.exportKey("pkcs8",i.privateKey);return{publicKeyPem:T(t,"PUBLIC KEY"),privateKeyPem:T(e,"PRIVATE KEY")}}function D(i){return!i||typeof i!="string"?!1:/^-----BEGIN (PUBLIC KEY|PRIVATE KEY)-----\n[A-Za-z0-9+/=\n]+\n-----END \1-----$/.test(i.trim())}var b={};const m="xibo_config",x="xibo-hw-backup",A=1;function k(){const i=typeof process<"u"&&b?b:{},t={cmsUrl:i.CMS_URL||"",cmsKey:i.CMS_KEY||"",displayName:i.DISPLAY_NAME||"",hardwareKey:i.HARDWARE_KEY||"",xmrChannel:i.XMR_CHANNEL||"",googleGeoApiKey:i.GOOGLE_GEO_API_KEY||""};return Object.values(t).some(a=>a!=="")?t:null}class N{constructor(){this.data=this.load(),this._fromEnv||this._restoreHardwareKeyFromBackup()}load(){const t=k();if(t)return this._fromEnv=!0,t;if(typeof localStorage>"u")return{cmsUrl:"",cmsKey:"",displayName:"",hardwareKey:"",xmrChannel:""};const e=localStorage.getItem(m);let a={};if(e)try{a=JSON.parse(e)}catch(r){console.error("[Config] Failed to parse localStorage config:",r)}let s=!1;return!a.hardwareKey||a.hardwareKey.length<10?(console.warn("[Config] Missing/invalid hardwareKey — generating"),a.hardwareKey=this.generateStableHardwareKey(),this._backupHardwareKey(a.hardwareKey),s=!0):console.log("[Config] ✓ Loaded existing hardwareKey:",a.hardwareKey),a.xmrChannel||(console.warn("[Config] Missing xmrChannel — generating"),a.xmrChannel=this.generateXmrChannel(),s=!0),a.cmsUrl=a.cmsUrl||"",a.cmsKey=a.cmsKey||"",a.displayName=a.displayName||"",s&&localStorage.setItem(m,JSON.stringify(a)),a}_backupKeys(t){try{const e=indexedDB.open(x,A);e.onupgradeneeded=()=>{const a=e.result;a.objectStoreNames.contains("keys")||a.createObjectStore("keys")},e.onsuccess=()=>{const a=e.result,s=a.transaction("keys","readwrite"),r=s.objectStore("keys");for(const[n,o]of Object.entries(t))r.put(o,n);s.oncomplete=()=>{console.log("[Config] Keys backed up to IndexedDB:",Object.keys(t).join(", ")),a.close()}}}catch{}}_backupHardwareKey(t){this._backupKeys({hardwareKey:t})}async _restoreHardwareKeyFromBackup(){if(!(typeof indexedDB>"u"))try{const t=await new Promise((r,n)=>{const o=indexedDB.open(x,A);o.onupgradeneeded=()=>{const c=o.result;c.objectStoreNames.contains("keys")||c.createObjectStore("keys")},o.onsuccess=()=>r(o.result),o.onerror=()=>n(o.error)}),a=t.transaction("keys","readonly").objectStore("keys"),s=await new Promise(r=>{const n=a.get("hardwareKey");n.onsuccess=()=>r(n.result),n.onerror=()=>r(null)});t.close(),s&&s!==this.data.hardwareKey?(console.log("[Config] Restoring hardware key from IndexedDB backup:",s),console.log("[Config] (was:",this.data.hardwareKey,")"),this.data.hardwareKey=s,this.save()):!s&&this.data.hardwareKey&&this._backupHardwareKey(this.data.hardwareKey)}catch{}}save(){typeof localStorage<"u"&&localStorage.setItem(m,JSON.stringify(this.data))}isConfigured(){return!!(this.data.cmsUrl&&this.data.cmsKey&&this.data.displayName)}generateStableHardwareKey(){if(typeof crypto<"u"&&crypto.randomUUID){const s="pwa-"+crypto.randomUUID().replace(/-/g,"").substring(0,28);return console.log("[Config] Generated new UUID-based hardware key:",s),s}const e="pwa-"+Array.from({length:28},()=>Math.floor(Math.random()*16).toString(16)).join("");return console.log("[Config] Generated new random hardware key:",e),e}getCanvasFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");return e?(e.textBaseline="top",e.font="14px Arial",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("Xibo Player",2,15),t.toDataURL()):"no-canvas"}catch{return"canvas-error"}}generateHardwareKey(){return this.generateStableHardwareKey()}generateXmrChannel(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}async ensureXmrKeyPair(){if(this.data.xmrPubKey&&D(this.data.xmrPubKey))return;console.log("[Config] Generating RSA key pair for XMR registration...");const{publicKeyPem:t,privateKeyPem:e}=await v();this.data.xmrPubKey=t,this.data.xmrPrivKey=e,this.save(),typeof indexedDB<"u"&&this._backupKeys({xmrPubKey:t,xmrPrivKey:e}),console.log("[Config] RSA key pair generated and saved")}hash(t){let e=2166136261;for(let s=0;s<t.length;s++)e^=t.charCodeAt(s),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24);e=e>>>0;let a="";for(let s=0;s<4;s++){let r=e+s*1234567;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n)+s,r+=(r<<1)+(r<<4)+(r<<7)+(r<<8)+(r<<24);r=r>>>0,a+=r.toString(16).padStart(8,"0")}return a.substring(0,32)}get cmsUrl(){return this.data.cmsUrl}set cmsUrl(t){this.data.cmsUrl=t,this.save()}get cmsKey(){return this.data.cmsKey}set cmsKey(t){this.data.cmsKey=t,this.save()}get displayName(){return this.data.displayName}set displayName(t){this.data.displayName=t,this.save()}get hardwareKey(){return this.data.hardwareKey||(console.error("[Config] CRITICAL: hardwareKey missing! Generating emergency key."),this.data.hardwareKey=this.generateStableHardwareKey(),this.save()),this.data.hardwareKey}get xmrChannel(){return this.data.xmrChannel||(console.warn("[Config] xmrChannel missing at access time — generating"),this.data.xmrChannel=this.generateXmrChannel(),this.save()),this.data.xmrChannel}get xmrPubKey(){return this.data.xmrPubKey||""}get xmrPrivKey(){return this.data.xmrPrivKey||""}get googleGeoApiKey(){return this.data.googleGeoApiKey||""}set googleGeoApiKey(t){this.data.googleGeoApiKey=t,this.save()}}const M=new N,E=L("FetchRetry"),S=3e4,P=12e4;function U(i){if(!i)return S;const t=Number(i);if(!isNaN(t)&&t>=0)return Math.min(t*1e3,P);const e=new Date(i);if(!isNaN(e.getTime())){const a=e.getTime()-Date.now();return Math.min(Math.max(a,0),P)}return S}async function j(i,t={},e={}){const{maxRetries:a=3,baseDelayMs:s=1e3,maxDelayMs:r=3e4}=e;let n,o;for(let c=0;c<=a;c++){try{const l=await fetch(i,t);if(l.status===429){const u=U(l.headers.get("Retry-After"));if(E.debug(`429 Rate limited, waiting ${u}ms (Retry-After: ${l.headers.get("Retry-After")})`),o=l,n=new Error("HTTP 429: Too Many Requests"),n.status=429,c<a){await new Promise(p=>setTimeout(p,u));continue}break}if(l.ok||l.status>=400&&l.status<500)return l;o=l,n=new Error(`HTTP ${l.status}: ${l.statusText}`),n.status=l.status}catch(l){n=l,o=null}if(c<a){const u=Math.min(s*Math.pow(2,c),r)*(.5+Math.random()*.5);E.debug(`Retry ${c+1}/${a} in ${Math.round(u)}ms:`,String(i).slice(0,80)),await new Promise(p=>setTimeout(p,u))}}if(o)return o;throw n}const h=L("CmsApi");class B{constructor({baseUrl:t,clientId:e,clientSecret:a,apiToken:s}={}){this.baseUrl=(t||"").replace(/\/+$/,""),this.clientId=e||null,this.clientSecret=a||null,this.accessToken=s||null,this.tokenExpiry=s?1/0:0}async authenticate(){h.info("Authenticating with CMS API...");const t=await fetch(`${this.baseUrl}/api/authorize/access_token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:this.clientId,client_secret:this.clientSecret})});if(!t.ok){const a=await t.text();throw new Error(`OAuth2 authentication failed (${t.status}): ${a}`)}const e=await t.json();return this.accessToken=e.access_token,this.tokenExpiry=Date.now()+(e.expires_in||3600)*1e3,h.info("Authenticated successfully, token expires in",e.expires_in,"s"),this.accessToken}async ensureToken(){if(!(this.accessToken&&Date.now()<this.tokenExpiry-6e4)){if(!this.clientId||!this.clientSecret){if(this.accessToken)return;throw new g("AUTH","/authorize",0,"No valid token and no OAuth2 credentials")}await this.authenticate()}}async request(t,e,a={}){var c;await this.ensureToken();const s=new URL(`${this.baseUrl}/api${e}`),r={method:t,headers:{Authorization:`Bearer ${this.accessToken}`}};if(t==="GET")for(const[l,u]of Object.entries(a))u!=null&&s.searchParams.set(l,String(u));else r.headers["Content-Type"]="application/x-www-form-urlencoded",r.body=new URLSearchParams(a);const n=await fetch(s,r);if(!n.ok){const l=await n.text();let u;try{const p=JSON.parse(l);u=((c=p.error)==null?void 0:c.message)||p.message||l}catch{u=l}throw new g(t,e,n.status,u)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}get(t,e){return this.request("GET",t,e)}post(t,e){return this.request("POST",t,e)}put(t,e){return this.request("PUT",t,e)}del(t){return this.request("DELETE",t)}async findDisplay(t){h.info("Looking up display by hardwareKey:",t);const e=await this.request("GET","/display",{hardwareKey:t}),a=Array.isArray(e)?e:[];if(a.length===0)return h.info("No display found for hardwareKey:",t),null;const s=a[0];return h.info(`Found display: ${s.display} (ID: ${s.displayId}, licensed: ${s.licensed})`),s}async authorizeDisplay(t){h.info("Authorizing display:",t),await this.request("PUT",`/display/authorise/${t}`),h.info("Display authorized successfully")}async editDisplay(t,e){return h.info("Editing display:",t,e),this.request("PUT",`/display/${t}`,e)}async listDisplays(t={}){const e=await this.request("GET","/display",t);return Array.isArray(e)?e:[]}async requestScreenshot(t){await this.request("PUT",`/display/requestscreenshot/${t}`)}async getDisplayStatus(t){return this.request("GET",`/display/status/${t}`)}async requestMultipart(t,e,a){var o;await this.ensureToken();const s=`${this.baseUrl}/api${e}`,r=await fetch(s,{method:t,headers:{Authorization:`Bearer ${this.accessToken}`},body:a});if(!r.ok){const c=await r.text();let l;try{const u=JSON.parse(c);l=((o=u.error)==null?void 0:o.message)||u.message||c}catch{l=c}throw new Error(`CMS API ${t} ${e} failed (${r.status}): ${l}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async createLayout({name:t,resolutionId:e,description:a}){const s={name:t,resolutionId:e};return a&&(s.description=a),this.request("POST","/layout",s)}async listLayouts(t={}){const e=await this.request("GET","/layout",t);return Array.isArray(e)?e:[]}async getLayout(t){return this.request("GET",`/layout/${t}`)}async deleteLayout(t){await this.request("DELETE",`/layout/${t}`)}async publishLayout(t){await this.request("PUT",`/layout/publish/${t}`,{publishNow:1})}async checkoutLayout(t){return this.request("PUT",`/layout/checkout/${t}`)}async getDraftLayout(t){const e=await this.listLayouts({parentId:t});return e.length>0?e[0]:null}async editLayoutBackground(t,e){return this.request("PUT",`/layout/background/${t}`,e)}async addRegion(t,e){return this.request("POST",`/region/${t}`,e)}async editRegion(t,e){return this.request("PUT",`/region/${t}`,e)}async deleteRegion(t){await this.request("DELETE",`/region/${t}`)}async addWidget(t,e,a={}){const{templateId:s,displayOrder:r,...n}=a,o={};s!==void 0&&(o.templateId=s),r!==void 0&&(o.displayOrder=r);const c=await this.request("POST",`/playlist/widget/${t}/${e}`,o);return Object.keys(n).length>0?(n.duration!==void 0&&n.useDuration===void 0&&(n.useDuration=1),this.request("PUT",`/playlist/widget/${c.widgetId}`,n)):c}async editWidget(t,e){return this.request("PUT",`/playlist/widget/${t}`,e)}async deleteWidget(t){await this.request("DELETE",`/playlist/widget/${t}`)}async uploadMedia(t){return this.requestMultipart("POST","/library",t)}async listMedia(t={}){const e=await this.request("GET","/library",t);return Array.isArray(e)?e:[]}async getMedia(t){return this.request("GET",`/library/${t}`)}async deleteMedia(t){await this.request("DELETE",`/library/${t}`)}async createCampaign(t){return this.request("POST","/campaign",{name:t})}async listCampaigns(t={}){const e=await this.request("GET","/campaign",t);return Array.isArray(e)?e:[]}async deleteCampaign(t){await this.request("DELETE",`/campaign/${t}`)}async assignLayoutToCampaign(t,e,a){const s={layoutId:e};a!==void 0&&(s.displayOrder=a),await this.request("POST",`/campaign/layout/assign/${t}`,s)}async createSchedule(t){const e={...t};Array.isArray(e.displayGroupIds)&&delete e.displayGroupIds,await this.ensureToken();const a=`${this.baseUrl}/api/schedule`,s=new URLSearchParams;for(const[o,c]of Object.entries(e))c!=null&&s.set(o,String(c));if(Array.isArray(t.displayGroupIds))for(const o of t.displayGroupIds)s.append("displayGroupIds[]",String(o));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const o=await r.text();throw new Error(`CMS API POST /schedule failed (${r.status}): ${o}`)}return(r.headers.get("Content-Type")||"").includes("application/json")?r.json():null}async deleteSchedule(t){await this.request("DELETE",`/schedule/${t}`)}async listSchedules(t={}){const e=await this.request("GET","/schedule/data/events",t);return Array.isArray(e)?e:(e==null?void 0:e.events)||[]}async listDisplayGroups(t={}){const e=await this.request("GET","/displaygroup",t);return Array.isArray(e)?e:[]}async createDisplayGroup(t,e){const a={displayGroup:t};return e&&(a.description=e),this.request("POST","/displaygroup",a)}async deleteDisplayGroup(t){await this.request("DELETE",`/displaygroup/${t}`)}async assignDisplayToGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/assign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API assign display to group failed (${r.status}): ${n}`)}}async unassignDisplayFromGroup(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/displaygroup/${t}/display/unassign`,s=new URLSearchParams;s.append("displayId[]",String(e));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new Error(`CMS API unassign display from group failed (${r.status}): ${n}`)}}async listResolutions(){const t=await this.request("GET","/resolution");return Array.isArray(t)?t:[]}async listTemplates(t={}){const e=await this.request("GET","/template",t);return Array.isArray(e)?e:[]}async assignMediaToPlaylist(t,e){const a=Array.isArray(e)?e:[e];await this.ensureToken();const s=`${this.baseUrl}/api/playlist/library/assign/${t}`,r=new URLSearchParams;for(const c of a)r.append("media[]",String(c));const n=await fetch(s,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:r});if(!n.ok){const c=await n.text();throw new g("POST",`/playlist/library/assign/${t}`,n.status,c)}return(n.headers.get("Content-Type")||"").includes("application/json")?n.json():null}async editLayout(t,e){return this.request("PUT",`/layout/${t}`,e)}async copyLayout(t,e={}){return this.post(`/layout/copy/${t}`,e)}async discardLayout(t){await this.put(`/layout/discard/${t}`)}async editCampaign(t,e){return this.put(`/campaign/${t}`,e)}async getCampaign(t){return this.get(`/campaign/${t}`)}async unassignLayoutFromCampaign(t,e){await this.post(`/campaign/layout/unassign/${t}`,{layoutId:e})}async editSchedule(t,e){return this.put(`/schedule/${t}`,e)}async retireLayout(t){await this.put(`/layout/retire/${t}`)}async unretireLayout(t){await this.put(`/layout/unretire/${t}`)}async getLayoutStatus(t){return this.get(`/layout/status/${t}`)}async tagLayout(t,e){await this.post(`/layout/${t}/tag`,{tag:e.join(",")})}async untagLayout(t,e){await this.post(`/layout/${t}/untag`,{tag:e.join(",")})}async listCommands(t={}){const e=await this.get("/command",t);return Array.isArray(e)?e:[]}async createCommand(t){return this.post("/command",t)}async editCommand(t,e){return this.put(`/command/${t}`,e)}async deleteCommand(t){await this.del(`/command/${t}`)}async deleteDisplay(t){await this.del(`/display/${t}`)}async wolDisplay(t){await this.post(`/display/wol/${t}`)}async setDefaultLayout(t,e){return this.put(`/display/${t}`,{defaultLayoutId:e})}async purgeDisplay(t){await this.post(`/display/purge/${t}`)}async listDayParts(t={}){const e=await this.get("/daypart",t);return Array.isArray(e)?e:[]}async createDayPart(t){return this.post("/daypart",t)}async editDayPart(t,e){return this.put(`/daypart/${t}`,e)}async deleteDayPart(t){await this.del(`/daypart/${t}`)}async uploadMediaUrl(t,e){return this.post("/library",{url:t,name:e,type:"uri"})}async copyMedia(t){return this.post(`/library/copy/${t}`)}async downloadMedia(t){await this.ensureToken();const e=`${this.baseUrl}/api/library/download/${t}`,a=await fetch(e,{headers:{Authorization:`Bearer ${this.accessToken}`}});if(!a.ok){const s=await a.text();throw new g("GET",`/library/download/${t}`,a.status,s)}return a}async editMedia(t,e){return this.put(`/library/${t}`,e)}async getMediaUsage(t){return this.get(`/library/usage/${t}`)}async tidyLibrary(){await this.post("/library/tidy")}async listPlaylists(t={}){const e=await this.get("/playlist",t);return Array.isArray(e)?e:[]}async createPlaylist(t){return this.post("/playlist",{name:t})}async getPlaylist(t){return this.get(`/playlist/${t}`)}async editPlaylist(t,e){return this.put(`/playlist/${t}`,e)}async deletePlaylist(t){await this.del(`/playlist/${t}`)}async reorderPlaylist(t,e){await this.ensureToken();const a=`${this.baseUrl}/api/playlist/order/${t}`,s=new URLSearchParams;for(const n of e)s.append("widgets[]",String(n));const r=await fetch(a,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/x-www-form-urlencoded"},body:s});if(!r.ok){const n=await r.text();throw new g("POST",`/playlist/order/${t}`,r.status,n)}}async copyPlaylist(t){return this.post(`/playlist/copy/${t}`)}async setWidgetTransition(t,e,a={}){return this.put(`/playlist/widget/transition/${t}`,{type:e,...a})}async setWidgetAudio(t,e){return this.put(`/playlist/widget/${t}/audio`,e)}async removeWidgetAudio(t){await this.del(`/playlist/widget/${t}/audio`)}async setWidgetExpiry(t,e){return this.put(`/playlist/widget/${t}/expiry`,e)}async saveAsTemplate(t,e){return this.post(`/template/${t}`,e)}async getTemplate(t){return this.get(`/template/${t}`)}async deleteTemplate(t){await this.del(`/template/${t}`)}async listDatasets(t={}){const e=await this.get("/dataset",t);return Array.isArray(e)?e:[]}async createDataset(t){return this.post("/dataset",t)}async editDataset(t,e){return this.put(`/dataset/${t}`,e)}async deleteDataset(t){await this.del(`/dataset/${t}`)}async listDatasetColumns(t){const e=await this.get(`/dataset/${t}/column`);return Array.isArray(e)?e:[]}async createDatasetColumn(t,e){return this.post(`/dataset/${t}/column`,e)}async editDatasetColumn(t,e,a){return this.put(`/dataset/${t}/column/${e}`,a)}async deleteDatasetColumn(t,e){await this.del(`/dataset/${t}/column/${e}`)}async listDatasetData(t,e={}){const a=await this.get(`/dataset/data/${t}`,e);return Array.isArray(a)?a:[]}async addDatasetRow(t,e){return this.post(`/dataset/data/${t}`,e)}async editDatasetRow(t,e,a){return this.put(`/dataset/data/${t}/${e}`,a)}async deleteDatasetRow(t,e){await this.del(`/dataset/data/${t}/${e}`)}async importDatasetCsv(t,e){return this.requestMultipart("POST",`/dataset/import/${t}`,e)}async clearDataset(t){await this.del(`/dataset/data/${t}`)}async listNotifications(t={}){const e=await this.get("/notification",t);return Array.isArray(e)?e:[]}async createNotification(t){return this.post("/notification",t)}async editNotification(t,e){return this.put(`/notification/${t}`,e)}async deleteNotification(t){await this.del(`/notification/${t}`)}async listFolders(t={}){const e=await this.get("/folder",t);return Array.isArray(e)?e:[]}async createFolder(t){return this.post("/folder",t)}async editFolder(t,e){return this.put(`/folder/${t}`,e)}async deleteFolder(t){await this.del(`/folder/${t}`)}async listTags(t={}){const e=await this.get("/tag",t);return Array.isArray(e)?e:[]}async createTag(t){return this.post("/tag",t)}async editTag(t,e){return this.put(`/tag/${t}`,e)}async deleteTag(t){await this.del(`/tag/${t}`)}async tagEntity(t,e,a){await this.post(`/${t}/${e}/tag`,{tag:a.join(",")})}async untagEntity(t,e,a){await this.post(`/${t}/${e}/untag`,{tag:a.join(",")})}async dgChangeLayout(t,e){await this.post(`/displaygroup/${t}/action/changeLayout`,{layoutId:e})}async dgOverlayLayout(t,e){await this.post(`/displaygroup/${t}/action/overlayLayout`,{layoutId:e})}async dgRevertToSchedule(t){await this.post(`/displaygroup/${t}/action/revertToSchedule`)}async dgCollectNow(t){await this.post(`/displaygroup/${t}/action/collectNow`)}async dgSendCommand(t,e){await this.post(`/displaygroup/${t}/action/command`,{commandId:e})}async editDisplayGroup(t,e){return this.put(`/displaygroup/${t}`,e)}}class g extends Error{constructor(t,e,a,s){super(`CMS API ${t} ${e} → ${a}: ${s}`),this.name="CmsApiError",this.method=t,this.path=e,this.status=a,this.detail=s}}export{B as C,y as L,M as a,g as b,L as c,I as d,j as f,R as g,O as i,K as m,_ as r,G as s,q as u};
|
|
5
|
+
//# sourceMappingURL=cms-api-Df_4fWKB.js.map
|