nixamp 0.28.36 → 0.28.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels.js +7 -2
- package/package.json +1 -1
- package/src/channels.ts +7 -2
- package/web/dist/assets/{ar-CRLmcpxV.js → ar-DhdXPO3p.js} +1 -1
- package/web/dist/assets/{cs-C7lpT9_7.js → cs-CoTzYnZt.js} +1 -1
- package/web/dist/assets/{da-C6icvAjb.js → da-M4GDhrcC.js} +1 -1
- package/web/dist/assets/{de-B6Viw_1k.js → de-D7yI8cd_.js} +1 -1
- package/web/dist/assets/{es-h3YK7MBo.js → es-BMGb7XlT.js} +1 -1
- package/web/dist/assets/{fi-tF8W-0sw.js → fi-CXNsmIrh.js} +1 -1
- package/web/dist/assets/{fr-CPVGzn8e.js → fr-BpvyrESQ.js} +1 -1
- package/web/dist/assets/{hi-DiPAdtgw.js → hi-DO7CO-fI.js} +1 -1
- package/web/dist/assets/{hls-3VKVEQE3-C_fSzE0p.js → hls-3VKVEQE3-BCxdTCEU.js} +1 -1
- package/web/dist/assets/{hu-BWP27GQV.js → hu-CosB3vlS.js} +1 -1
- package/web/dist/assets/{id-C9v9_aJK.js → id-DNumDlwq.js} +1 -1
- package/web/dist/assets/{index-_aGaTsm2.js → index-CY3lAwM2.js} +2 -2
- package/web/dist/assets/{it-DtOTP5Bt.js → it-IJKhyCGw.js} +1 -1
- package/web/dist/assets/{mpegts-DBK5aOjj.js → mpegts-DsEoUEPH.js} +1 -1
- package/web/dist/assets/{mpegts-LO6RVLD6-0zaiW5HW.js → mpegts-LO6RVLD6-CC8jMmPy.js} +1 -1
- package/web/dist/assets/{nl-CAX3A01l.js → nl-BU0Mn-e-.js} +1 -1
- package/web/dist/assets/{ru-DuLcjNsF.js → ru-ClqNCOTW.js} +1 -1
- package/web/dist/assets/{sv-C3ZewPxY.js → sv-Df_aXTD6.js} +1 -1
- package/web/dist/assets/{uk-D7PUipxA.js → uk-K5yQBF0h.js} +1 -1
- package/web/dist/assets/{vi-wUJlLppj.js → vi-CYfcOUeA.js} +1 -1
- package/web/dist/assets/{zh-Bd_9PHqO.js → zh-a2v2x-3e.js} +1 -1
- package/web/dist/index.html +1 -1
- package/web/dist/sw.js +22 -22
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={"Supported platforms":`Supported platforms`,"In review":`In review`,"Not available":`Not available`,"Install PWA":`Install PWA`,"PWA installed":`PWA installed`,"Web app":`Web app`,"Install the web app":`Install the web app`,"Keep BackToSchool on your home screen or desktop. No app store needed.":`Keep BackToSchool on your home screen or desktop. No app store needed.`,"iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.":`iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.`,"Android: open your browser menu and choose Install app or Add to Home screen.":`Android: open your browser menu and choose Install app or Add to Home screen.`,"Desktop: look for Install in the address bar or browser menu. The option depends on your browser.":`Desktop: look for Install in the address bar or browser menu. The option depends on your browser.`,"You can also keep using BackToSchool in this browser.":`You can also keep using BackToSchool in this browser.`,"The web app is installed. You can keep learning here.":`The web app is installed. You can keep learning here.`,"Continue learning":`Continue learning`,"The install prompt could not open. Select Web app again for installation instructions.":`The install prompt could not open. Select Web app again for installation instructions.`,"Follow host":`Follow host`,Following:`Following`,"You’ll get email and web notifications for this host.":`You’ll get email and web notifications for this host.`,"Notifications turned off for this host.":`Notifications turned off for this host.`,"Could not update notifications.":`Could not update notifications.`},t={...e,"No parties live right now.":`No parties live right now.`,"Could not refresh parties.":`Could not refresh parties.`,"Pick a server in the directory, or paste its link here.":`Pick a server in the directory, or paste its link here.`,"Interface language":`Interface language`,Language:`Language`,"Translation language":`Translation language`,"Original (auto-detect)":`Original (auto-detect)`,Play:`Play`,Pause:`Pause`,Stop:`Stop`,Next:`Next`,Previous:`Previous`,Select:`Select`,"Next/Prev":`Next/Prev`,Quit:`Quit`,"Now Playing":`Now Playing`,"Spectrum Analyser":`Spectrum Analyser`,Playlist:`Playlist`,Files:`Files`,"Open files":`Open files`,"Open folder":`Open folder`,"Add to library":`Add to library`,"Replace playlist":`Replace playlist`,Filter:`Filter`,Search:`Search`,"Nothing loaded.":`Nothing loaded.`,"Empty.":`Empty.`,"Loading…":`Loading…`,"Connecting…":`Connecting…`,Connected:`Connected`,"Not connected":`Not connected`,"No source":`No source`,Playing:`Playing`,Stopped:`Stopped`,Volume:`Volume`,Seek:`Seek`,"Full screen":`Full screen`,Download:`Download`,Share:`Share`,Copy:`Copy`,"Copy link":`Copy link`,Copied:`Copied`,Save:`Save`,Cancel:`Cancel`,Close:`Close`,Remove:`Remove`,Delete:`Delete`,Edit:`Edit`,Add:`Add`,Send:`Send`,Retry:`Retry`,Back:`Back`,"Next page":`Next page`,"Previous page":`Previous page`,"Show more":`Show more`,Panels:`Panels`,"Reset layout":`Reset layout`,Show:`Show`,Hide:`Hide`,Collapse:`Collapse`,Expand:`Expand`,"Move up":`Move up`,"Move down":`Move down`,Install:`Install`,"TV mode":`TV mode`,On:`On`,Off:`Off`,Account:`Account`,"Sign in":`Sign in`,"Sign out":`Sign out`,"Create account":`Create account`,Email:`Email`,Password:`Password`,"Forgot password?":`Forgot password?`,"Welcome back":`Welcome back`,Profile:`Profile`,Handle:`Handle`,"Your servers":`Your servers`,Server:`Server`,Connect:`Connect`,Disconnect:`Disconnect`,Directory:`Directory`,Favourites:`Favourites`,Follow:`Follow`,Unfollow:`Unfollow`,Notifications:`Notifications`,"Phone number":`Phone number`,"Save number":`Save number`,Transcript:`Transcript`,Captions:`Captions`,"Translate audio":`Translate audio`,"Audio language":`Audio language`,"Audio options":`Audio options`,"Keep background sound":`Keep background sound`,"Background level":`Background level`,"Speaker voices":`Speaker voices`,"Any voice":`Any voice`,"Male voice":`Male voice`,"Female voice":`Female voice`,"Original audio.":`Original audio.`,"Buy translated audio":`Buy translated audio`,"Audio credit":`Audio credit`,"Buy pass":`Buy pass`,Pass:`Pass`,"Pay with":`Pay with`,"Check payment":`Check payment`,"Open checkout":`Open checkout`,"Free sessions":`Free sessions`,"Usage rates and expiry":`Usage rates and expiry`,Catalogs:`Catalogs`,"Add catalog":`Add catalog`,"Catalog name":`Catalog name`,Link:`Link`,"Play link":`Play link`,"Go live":`Go live`,Publish:`Publish`,Listen:`Listen`,"Live now":`Live now`,Upcoming:`Upcoming`,Parties:`Parties`,"Join party":`Join party`,"Invite code":`Invite code`,Invite:`Invite`,Chat:`Chat`,"Chat message":`Chat message`,People:`People`,Speaker:`Speaker`,Speakers:`Speakers`,Listener:`Listener`,Moderator:`Moderator`,"Raise hand":`Raise hand`,"Hand raises":`Hand raises`,Questions:`Questions`,Resources:`Resources`,Replay:`Replay`,Schedule:`Schedule`,Event:`Event`,Host:`Host`,About:`About`,Stage:`Stage`,Title:`Title`,Description:`Description`,Topic:`Topic`,Public:`Public`,"Anyone with the link":`Anyone with the link`,"Invited people":`Invited people`,"Who can join":`Who can join`,"Date and time":`Date and time`,"Expected length":`Expected length`,Repeat:`Repeat`,"Does not repeat":`Does not repeat`,"Every day":`Every day`,"Every week":`Every week`,Homepage:`Homepage`,"Host name":`Host name`,"Profile photo URL":`Profile photo URL`,"Broadcast link":`Broadcast link`,"Edit event":`Edit event`,"Save changes":`Save changes`,"Create live":`Create live`,"Schedule class":`Schedule class`,"Start class":`Start class`,"End event":`End event`,"End session":`End session`,"Session ended":`Session ended`,"Event ended":`Event ended`,Cancelled:`Cancelled`,"Replay available":`Replay available`,Join:`Join`,"Create invite":`Create invite`,"Invite as":`Invite as`,"Watch now":`Watch now`,"Start a room":`Start a room`,"Recent replays":`Recent replays`,"Your account":`Your account`,"Write with AI":`Write with AI`,"Suggested title":`Suggested title`,"Suggested description":`Suggested description`,"Suggested topic":`Suggested topic`,"Use these details":`Use these details`,"Learn something live.":`Learn something live.`,"Screen share":`Screen share`,"Upload and broadcast":`Upload and broadcast`,Help:`Help`,"Reload Player":`Reload Player`,"Copy Bundled CLI Path":`Copy Bundled CLI Path`,"Developer tools":`Developer tools`,Undo:`Undo`,Redo:`Redo`,Cut:`Cut`,Paste:`Paste`,"Select all":`Select all`,Status:`Status`,"Activity log":`Activity log`,Admin:`Admin`,"Playback controls":`Playback controls`,"Tracks and folders":`Tracks and folders`,"Original-language captions.":`Original-language captions.`,"Skip to playback controls":`Skip to playback controls`,"Skip to playlist":`Skip to playlist`,"Skip to transcript and translated audio":`Skip to transcript and translated audio`},n={"■ STOPPED":`Stopped`,"▶ PLAYING":`Playing`,LOADING:`Loading…`,"no source":`No source`,"not connected":`Not connected`,"Now playing":`Now Playing`,"● GO LIVE":`Go live`,"● Go live":`Go live`,"⤓ Download":`Download`,"A man's voice":`Male voice`,"A woman's voice":`Female voice`,"Catalogs on this server":`Catalogs`,"Catalog folders":`Catalogs`,"Parties on this server":`Parties`,"Servers streaming now":`Directory`,"Playlist (0)":`Playlist`,"Playlist folders":`Playlist`,"Playlist pages":`Playlist`,"Filter these files":`Filter`,"Filter these entries":`Filter`,"Filter the entries":`Filter`,"Filter the playlist":`Filter`,"Create a free account":`Create account`,"Create one":`Create account`,"Create your account":`Create account`,"New here? Create an account":`Create account`,"Already have an account? Sign in":`Sign in`,"Your NixAmp account":`Your account`,"Your public handle":`Handle`,handle:`Handle`,password:`Password`,"Phone number for texts":`Phone number`,"Back to the player":`Back`,"Share what is playing":`Share`,"Share this stream":`Share`,"Link to this stream":`Link`,"Copy this stream's URL":`Copy link`,"A link to play":`Link`,"A server's link":`Server`,"Close translated audio purchase":`Close`,"Open secure checkout ↗ (new tab)":`Open checkout`,"Checking…":`Loading…`,"Browse the directory":`Directory`,"See what is live":`Live now`,"Join live":`Join`,"Raise Hand":`Raise hand`,"Hand Raises":`Hand raises`,"Hide this":`Hide`,Log:`Activity log`,"Status:":`Status`,"Nixamp player":`Playback controls`,"Nixamp audio and video player":`Playback controls`,"What is being said":`Transcript`,"The room's chat":`Chat`,Trollbox:`Chat`,"A line for the trollbox":`Chat message`,"Say something to the room…":`Chat message`,"Send it":`Send`,"Something to add":`Chat message`,"What to call it":`Catalog name`,"call it something":`Catalog name`,"An m3u catalog to add":`Catalogs`,"On this device":`Play`,"Play on this device":`Play`,"What this is":`About`,"Looking for servers…":`Loading…`,"Finding today’s conversations…":`Loading…`,"Coming up":`Upcoming`,"Listen after class":`Replay`,"Schedule live":`Schedule class`,"Schedule a class":`Schedule class`,"Plan a conversation":`Schedule class`,"Your classroom":`Event`,"Join in":`Join`,"Open a room →":`Start a room`,"Chat message":`Chat message`,"Add to the conversation":`Chat message`,"Create live":`Create live`,"Host stage":`Stage`,"Your host":`Host`,"Class host":`Host`,"Hand raised ✓":`Raise hand`,"Copied ✓":`Copied`,"Screen share with Pairux ↗":`Screen share`,"Upload & broadcast in Nixamp ↗":`Upload and broadcast`,"Open Music Folder…":`Open folder`,"Choose a music folder":`Open folder`,"Main navigation":`Panels`,"Skip to a section":`Panels`},r=[{code:`en`,label:`English`},{code:`de`,label:`Deutsch`},{code:`sv`,label:`Svenska`},{code:`es`,label:`Español`},{code:`fr`,label:`Français`},{code:`it`,label:`Italiano`},{code:`nl`,label:`Nederlands`},{code:`da`,label:`Dansk`},{code:`fi`,label:`Suomi`},{code:`ru`,label:`Русский`},{code:`uk`,label:`Українська`},{code:`cs`,label:`Čeština`},{code:`hu`,label:`Magyar`},{code:`zh`,label:`中文`},{code:`ar`,label:`العربية`},{code:`hi`,label:`हिन्दी`},{code:`vi`,label:`Tiếng Việt`},{code:`id`,label:`Bahasa Indonesia`}],i=`nixamp.ui.language`;function a(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code??`en`}function o(e,t=[]){let n=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code};return n(e)??t.map(n).find(Boolean)??`en`}var s=`modulepreload`,c=function(e){return`/`+e},l={},u=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=c(t,n),t=u(t),t in l)return;l[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:s,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},d={en:async()=>({default:t}),de:()=>u(()=>import(`./de-B6Viw_1k.js`),[]),sv:()=>u(()=>import(`./sv-C3ZewPxY.js`),[]),es:()=>u(()=>import(`./es-h3YK7MBo.js`),[]),fr:()=>u(()=>import(`./fr-CPVGzn8e.js`),[]),it:()=>u(()=>import(`./it-DtOTP5Bt.js`),[]),nl:()=>u(()=>import(`./nl-CAX3A01l.js`),[]),da:()=>u(()=>import(`./da-C6icvAjb.js`),[]),fi:()=>u(()=>import(`./fi-tF8W-0sw.js`),[]),ru:()=>u(()=>import(`./ru-DuLcjNsF.js`),[]),uk:()=>u(()=>import(`./uk-D7PUipxA.js`),[]),cs:()=>u(()=>import(`./cs-C7lpT9_7.js`),[]),hu:()=>u(()=>import(`./hu-BWP27GQV.js`),[]),zh:()=>u(()=>import(`./zh-Bd_9PHqO.js`),[]),ar:()=>u(()=>import(`./ar-CRLmcpxV.js`),[]),hi:()=>u(()=>import(`./hi-DiPAdtgw.js`),[]),vi:()=>u(()=>import(`./vi-wUJlLppj.js`),[]),id:()=>u(()=>import(`./id-C9v9_aJK.js`),[])},f=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await d[e]()).default){this.load=e}messages=t;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=a(e),r=await this.load(n);if(t!==this.revision)return!1;this.code=n,this.messages=r,this.numberFormats.clear(),this.dateFormats.clear();for(let e of this.listeners)e();return!0}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}text(e,t={}){let r=this.language!==`en`&&Object.hasOwn(n,e)?n[e]:e,i=Object.hasOwn(this.messages,r)?this.messages[r]:e;return this.language!==`en`&&Object.hasOwn(n,e)&&(i=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+i+(e.endsWith(` ✓`)?` ✓`:``)),i.replace(/\{([\w]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}number(e,t){let n=JSON.stringify(t??{}),r=this.numberFormats.get(n);return r||(this.numberFormats.size>=64&&this.numberFormats.clear(),r=new Intl.NumberFormat(this.language,t),this.numberFormats.set(n,r)),r.format(e)}date(e,t){let n=JSON.stringify(t??{}),r=this.dateFormats.get(n);return r||(this.dateFormats.size>=64&&this.dateFormats.clear(),r=new Intl.DateTimeFormat(this.language,t),this.dateFormats.set(n,r)),r.format(e)}get direction(){return this.language===`ar`?`rtl`:`ltr`}},p=(e,t)=>f.text(e,t),m=new Map;function h(e,t,n){let r=m.get(e);r||(r=new Map,m.set(e,r)),r.set(t,n),n()}function g(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return h(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){m.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function _(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return h(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){m.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var v=[`aria-label`,`title`,`placeholder`,`data-title`],y=[`[data-i18n]`,...v.map(e=>`[data-i18n-${e}]`)].join(`,`);function b(e){let t=[...e.querySelectorAll(y)];e instanceof HTMLElement&&e.matches(y)&&t.unshift(e);for(let e of t){if(e.closest(`[translate="no"], [contenteditable="true"]`))continue;let t=e.getAttribute(`data-i18n`);if(t){let n=e.textContent;h(e,`text`,()=>{if(e.textContent!==n){m.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of v){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);h(e,t,()=>{if(e.getAttribute(t)!==r){m.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function ee(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of m){if(!e.isConnected){m.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var te=0;async function ne(e){let t=++te;try{if(!await f.setLanguage(e)||t!==te)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{ee()}}async function re(){let e=o(null,navigator.languages);try{e=o(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...r.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{ne(e.value)});b(document),ee(),f.onChange(ee),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&b(e);for(let e of m.keys())e.isConnected||m.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&f.setLanguage(o(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==f.language&&f.setLanguage(e).catch(()=>{})});try{await f.setLanguage(e)}catch{}}var ie={play:`<span aria-hidden="true">▶</span>`,party:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 21 4-12 8 8Z"/><path d="m7 9 8 8M12 7l1-3M16 10l4-1M16 5l2-2M20 14l1 1M8 4l-1-1"/><circle cx="21" cy="4" r=".5" fill="currentColor"/></svg>`,rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`};function ae(e,t){e.innerHTML=ie[t]}function oe(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function se(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function x(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var ce=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function S(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&ce.has(e.slice(n+1).toLowerCase())}function le(){let e=document.getElementById(`sr-status`);if(!e)return;let t=[`note`,`account-note`,`remote-state`,`transcript-audio-note`,`notify-note`,`notify-phone-note`,`persona-note`],n=new Map,r,i=``;for(let a of t){let t=document.getElementById(a);t&&(n.set(a,t.textContent?.trim()??``),new MutationObserver(()=>{let o=t.textContent?.trim()??``;n.get(a)!==o&&(n.set(a,o),o&&!t.closest(`[hidden], [data-closed], [data-collapsed]`)&&(i=o,clearTimeout(r),r=setTimeout(()=>{e.textContent!==i&&(e.textContent=i)},200)))}).observe(t,{childList:!0,characterData:!0,subtree:!0}))}}var C=new WeakMap;function ue(e,t=!0){let n=e.contains(document.activeElement);C.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function w(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){C.delete(e),e.replaceChildren(...t);return}let n=C.has(e);if(C.set(e,t),n)return;let r=()=>{let t=C.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}C.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var T=new WeakMap,de=new WeakSet;function fe(e,t){let n=new Map([...e.children].map(e=>[e.dataset.liveKey,e])),r=new Set(t.map(e=>e.dataset.liveKey)),i=!1;for(let r of t){let t=n.get(r.dataset.liveKey);t?t!==r&&!t.isEqualNode(r)&&(t.contains(document.activeElement)||t.querySelector(`details[open]`)?i=!0:t.replaceWith(r)):e.append(r)}for(let[e,t]of n)r.has(e)||(t.contains(document.activeElement)?i=!0:t.remove());if(i?T.set(e,t):T.delete(e),de.has(e))return;de.add(e);let a=()=>{let t=T.get(e);t&&fe(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function pe(e){if(!/\.(?:mp4|m4v|mkv|webm|mov|avi|mp3|m4a|flac|ogg|opus|wav|aac)$/i.test(e))return e;let t=(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,``);return t.replace(/^0\d+[_ .-]+(?:\d+[_ .-]+)?/,``).replace(/_+/g,` `).trim()||t}function E(e){if(/^(?:[\\/]|[A-Za-z]:)/.test(e))return[];let t=e.split(/[\\/]/).filter(Boolean);return t.some(e=>e===`..`)?[]:t.filter(e=>e!==`.`).map(e=>e.replace(/_+/g,` `))}function me(e,t,n=`Live`){let r=e[t];if(!r){let e=pe(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${pe(r.title)}`:pe(r.title),a=E(r.folder??``),o=E(r.group??``).join(` › `),s=[...o?[o]:[],...a],c=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,l=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(s.length>0||e.album===r.album));return{title:i,context:c,position:`Playlist · ${l.findIndex(({at:e})=>e===t)+1} of ${l.length}`,fullTitle:c?`${c} › ${i}`:i}}var he=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],ge=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function D(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of ge)if(t.test(e.mimeType))return n}let t=_e(e.src);for(let[e,n]of he)if(e.test(t))return n;return`unknown`}function _e(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ve(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function ye(e,t){let n=D(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function be(e,t){let n=t.capabilities??ve(),r=ye({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await u(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-C_fSzE0p.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await u(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-0zaiW5HW.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await u(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var xe=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),Se=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function O(e){let t=e.lastIndexOf(`.`);return t>0&&Se.has(e.slice(t+1).toLowerCase())}function k(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&xe.has(e.slice(n+1).toLowerCase())}function Ce(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function we(e){return e.filter(e=>k(e.name,e.type)).sort((e,t)=>Ce(Te(e),Te(t))).map(e=>({title:x(e.name),artist:``,album:Ee(Te(e)),duration:0,url:URL.createObjectURL(e),video:S(e.name,e.type),objectUrl:!0,...O(e.name)?{kind:`mpegts`}:{}}))}function Te(e){return e.webkitRelativePath||e.name}function Ee(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function De(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var A=2048;function j(e){if(e.startsWith(`blob:`)||e.startsWith(`data:`))return!0;try{let t=globalThis.location?.origin;return t?new URL(e,t).origin===t:!1}catch{return!1}}function Oe(e,t){return e||t===`hls`||t===`mpegts`}var ke=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(Ae(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get jinglePlaying(){return!!this.jingle&&!this.jingle.paused&&!this.jingle.ended}async playJingle(e){this.jingle!==e&&this.stopJingle(),this.jingle=e,this.ensureGraph(e);try{if(await e.play(),this.context?.state===`suspended`)throw new DOMException(`Audio needs an interaction`,`NotAllowedError`)}catch(t){throw e.pause(),e.currentTime=0,t}}stopJingle(){this.jingle?.pause(),this.jingle=null}get needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(!this.context)try{this.context=new t({sampleRate:48e3})}catch{this.context=new t}if(this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=A,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.output.gain.value=+!this.translated,this.analyser.connect(this.output),this.output.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}audioInput(){if(!this.analysable)throw Error(`This source blocks audio access, so its audio cannot be translated here.`);if(this.ensureGraph(this.active),!this.context||!this.analyser)throw Error(`This browser cannot capture player audio.`);return{context:this.context,node:this.analyser}}translatedAudio(e){this.translated=e,this.output&&(this.output.gain.value=+!e)}get mediaKey(){return this.active.currentSrc||this.active.src}get loaded(){return!!(this.active.currentSrc||this.active.src)}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:D({src:e.url})),r=Oe(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||j(e.url)||(this.handlers.readable?.(e.url)??!1);r.crossOrigin=i?`anonymous`:null,r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await be(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}let a=this.active.currentSrc||this.active.src||e.url;this.analysable=i||a.startsWith(`blob:`)||j(a),t&&await this.play()}async play(){this.stopJingle(),this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.stopJingle(),this.playBlocked=!1,this.active.pause()}async resumeAfterInteraction(){this.playBlocked?await this.play():this.playing&&this.context?.state===`suspended`&&await this.context.resume()}stop(){this.stopJingle(),this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function Ae(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function je(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function Me(e,t){return{...t,tracks:t.tracks??e.tracks}}function Ne(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function Pe(e,t,n=``){let r=`${e===``?``:Ne(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function Fe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=/^\/api\/channels\/([^/]+)\/?$/.exec(t.pathname),r=/^\/api\/media\/(\d+)\/?$/.exec(t.pathname),i=/^\/api\/live\/?$/.test(t.pathname);if(!n&&!r&&!i)return null;let a=t.searchParams.get(`k`)??``,o=a?`${t.origin}/view/${a}`:t.origin,s=`live`;if(r&&(s=`track:${r[1]}`),n)try{s=`channel:${decodeURIComponent(n[1]??``)}`}catch{s=`channel:${n[1]??``}`}return{view:o,what:s}}function Ie(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:Ne(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var Le=null;function Re(e){if(!e&&Le!==null)return Le;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(Le=n),n}catch{return!1}}function ze(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return Pe(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function Be(e){if(typeof e!=`object`||!e)return null;let t=e,n=je(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}function Ve(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var He=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return Ve(this.base,e)}url(e){let t=Pe(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=Ie(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(Pe(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=Be(Ue(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(Pe(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=Be(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=Re()){return ze(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ue(e){try{return JSON.parse(e)}catch{return null}}async function We(e,t,n=``){try{let r=await fetch(Pe(e,`/api/state`,n),{signal:t});return r.ok?Be(await r.json()):null}catch{return null}}function Ge(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function Ke(e,t=``,n){let r;try{r=await fetch(Pe(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function qe(e,t,n=``){try{let r=await fetch(Pe(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function Je(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var Ye=.14,Xe=.02;function Ze(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function Qe(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function $e(e,t,n=Ye){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function et(e,t,n=Xe){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function tt(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function nt(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function rt(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function it(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale??f.language,i)===r.toLocaleDateString(t.locale??f.language,i);return n.toLocaleString(t.locale??f.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function at(e,t={}){let n=e.data,r=nt(n.away,n.awayScore),i=nt(n.home,n.homeScore),a=rt(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=it(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var ot=`nixamp.tv`,M=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function st(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?ct(r):/\bSilk\b/.test(e)&&n===0?!0:M.test(e):ct(i)}function ct(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function lt(e){return e?12:100}function ut(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var dt=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,N=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,ft=/\.m3u8(\?.*)?$/i,pt=/\.(m3u|pls)(\?.*)?$/i;function mt(e){try{let t=new URL(e);return N.test(t.pathname+t.search)}catch{return!1}}function ht(e){try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}}),r=(n.pop()??``).replace(/\.(m3u|pls)$/i,``);return(/^(playlist|index|list|all|episodes|feed)?$/i.test(r)?n.pop()??``:r).replace(/[-_]+/g,` `).trim()||t.hostname}catch{return`Playlist`}}function gt(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||ht(t),r=[],i=(e,n)=>{if(r.length>=1e3)return;let i;try{i=new URL(e.trim(),t)}catch{return}if(i.protocol!==`https:`&&i.protocol!==`http:`)return;let a=i.pathname+i.search;if(!dt.test(a)&&!N.test(a))return;let o=decodeURIComponent(i.pathname.split(`/`).filter(Boolean).pop()??i.hostname);r.push({url:i.toString(),title:n||o})},a=!1;try{a=/\.pls$/i.test(new URL(t).pathname)}catch{a=!1}if(a){let t=new Map,a=new Map;for(let n of e.split(/\r?\n/)){let e=/^(File|Title)(\d+)\s*=\s*(.*)$/i.exec(n.trim());e&&(/^file$/i.test(e[1]??``)?t:a).set(e[2]??``,e[3]??``)}for(let[e,n]of[...t.entries()].sort((e,t)=>Number(e[0])-Number(t[0])))i(n,(a.get(e)??``).trim());return{title:n,entries:r}}let o=``;for(let t of e.split(/\r?\n/)){let e=t.trim();if(e!==``){if(e.startsWith(`#`)){let t=/^#EXTINF:\s*-?[\d.]+\s*(?:,(.*))?$/i.exec(e);t&&(o=(t[1]??``).trim());continue}i(e,o),o=``}}return{title:n,entries:r}}function _t(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function vt(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=_t(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return pt.test(o)?{kind:`list`,url:n.toString(),label:ht(n.toString())}:dt.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:N.test(o)||ft.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var yt=`nixamp.panels`;function bt(){return{order:[],placement:{},collapsed:[],closed:[]}}var xt=/^[a-z][a-z0-9-]{0,63}$/,St=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function Ct(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&xt.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function wt(e){if(!e)return bt();let t;try{t=JSON.parse(e)}catch{return bt()}if(!t||typeof t!=`object`||Array.isArray(t))return bt();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))xt.test(e)&&typeof t==`string`&&St.test(t)&&(r[e]=t);let i=e=>{let t=Ct(e),n=t.includes(`parties-panel`)?t.filter(e=>e!==`onair-panel`):t;return[...new Set(n.map(e=>e===`onair-panel`?`parties-panel`:e))]};return!r[`parties-panel`]&&r[`onair-panel`]&&(r[`parties-panel`]=r[`onair-panel`]),delete r[`onair-panel`],{order:i(n.order),placement:r,collapsed:i(n.collapsed),closed:i(n.closed)}}function Tt(e){return JSON.stringify(e)}function Et(e,t){let n=new Set(e),r=t.filter(e=>n.has(e)),i=new Set(r);return e.forEach((t,n)=>{if(i.has(t))return;let a=0;for(let t=n-1;t>=0;t--){let n=r.indexOf(e[t]);if(n>=0){a=n+1;break}}r.splice(a,0,t),i.add(t)}),r}function Dt(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function Ot(e,t=16e3){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}var kt=16e3,At=3e4;function jt(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function Mt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Nt=`nixamp.captions`,Pt=`nixamp.captions.native-v2.language`,Ft=[{code:``,label:`Original (auto-detect)`},...r];function It(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Ft.some(e=>e.code===t)?t:``}catch{return``}}function Lt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Rt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function zt(e,t,n){let r=[],i=[];for(let a of e)(a.at<=t-n?r:i).push(a);return r.sort((e,t)=>e.at-t.at),{ready:r,still:i}}function Bt(e,t,n,r=1500){let i=t-n;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.at<=i&&i<=n.until+r)return n;if(n.until+r<i)break}return null}function Vt(e){try{return e(Nt)!==`off`}catch{return!0}}function Ht(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Ut(e){let t=e?.status;return typeof t==`number`?[408,502,503,504].includes(t):e instanceof TypeError||e instanceof Error&&[`AbortError`,`TimeoutError`].includes(e.name)}function P(e,t){return Object.assign(Error(e),{status:t})}var Wt=12e3,Gt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;failures=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0,this.options.active(!0);try{this.context??=this.options.audioContext?.()??new AudioContext,this.gain||(this.gain=this.context.createGain(),this.gain.connect(this.context.destination)),await this.context.resume(),this.enabled&&this.options.status(`Waiting for the next translated line…`)}catch{this.fail(`Audio could not start. Enable translated audio again to retry.`)}}disable(){this.enabled=!1,this.reset()}reset(){this.generation++,this.controller?.abort(),this.controller=null,this.next=[],this.running=null,this.seen.clear(),this.failures=0;for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(this.enabled)}setVolume(){this.gain&&(this.gain.gain.value=Math.max(0,Math.min(1,this.options.volume())))}push(e,t,n){this.pushBatch([{line:e,url:t,lag:n}])}pushBatch(e){if(!this.enabled||!this.options.playing())return;let t=e.slice(0,12).filter(({line:e,lag:t})=>{let n=`${e.channel}|${e.at}|${e.language}|${e.speaker??``}`;return this.seen.has(n)||this.stale(e,t)?!1:(this.seen.add(n),this.seen.size>200&&this.seen.delete(this.seen.values().next().value),!0)});t.length&&(this.next=[...this.next.filter(e=>!this.stale(e.line,e.lag)),...t].slice(-24),this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>Wt}fail(e){this.disable(),this.options.status(`${e} Original audio restored.`),this.options.failed()}async run(e){this.running=e;try{for(;this.next.length&&this.enabled&&e===this.generation;){if(await this.waitForRoom(e,3),e!==this.generation)return;let t=this.next.shift();if(this.stale(t.line,t.lag)||!this.options.playing())continue;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),12e3);try{let i=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>i.set(t,e)),e!==this.generation)return;let a=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:i});if(clearTimeout(r),e!==this.generation){await a.body?.cancel();return}if(!a.ok)throw P((await a.json().catch(()=>({}))).error||`Translated audio is unavailable.`,a.status);if(!a.body||!a.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let o=a.body.getReader(),s=new Uint8Array,c=0;try{for(;;){let t,{done:r,value:i}=await Promise.race([o.read(),new Promise((e,r)=>{t=setTimeout(()=>{n.abort(),o.cancel().catch(()=>{}),r(new DOMException(`Voice connection timed out`,`TimeoutError`))},12e3)})]).finally(()=>clearTimeout(t));if(e!==this.generation){await o.cancel();return}if(r)break;let a=new Uint8Array(s.length+i.length);a.set(s),a.set(i,s.length);let l=a.length-a.length%2;s=a.slice(l);for(let t=0;t<l;t+=6400){if(await this.waitForRoom(e,8),e!==this.generation){await o.cancel();return}let n=a.subarray(t,Math.min(l,t+6400));this.schedule(n),c+=n.length}}}finally{o.releaseLock()}if(!c||s.length)throw P(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.failures>=3)throw t;this.options.status(`Voice interrupted · waiting for the next translated phrase…`)}finally{clearTimeout(r)}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}async waitForRoom(e,t){for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>t;)if(await new Promise(e=>setTimeout(e,25)),!this.options.playing()){this.reset();return}}schedule(e){let t=this.context;if(!t||!this.gain||!this.enabled)return;if(t.state!==`running`)throw Error(`Audio playback was suspended.`);let n=e.length/2,r=Math.max(t.currentTime+.03,this.scheduledUntil);if(r-t.currentTime+n/16e3>10)throw Error(`Translated audio fell too far behind.`);let i=t.createBuffer(1,n,16e3),a=i.getChannelData(0),o=new DataView(e.buffer,e.byteOffset,e.length);for(let e=0;e<n;e++)a[e]=o.getInt16(e*2,!0)/32768;let s=t.createBufferSource();s.buffer=i,s.connect(this.gain),this.setVolume(),this.sources.add(s),s.onended=()=>{this.sources.delete(s),s.disconnect()},s.start(r),this.scheduledUntil=r+i.duration,this.options.status(`Playing translated audio · a few seconds behind the video`)}},F=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,I=new WeakMap,Kt=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t,n=5){this.stop();let r=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(I.has(e)||I.set(e,e.audioWorklet.addModule(F).catch(t=>{throw I.delete(e),t})),await I.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=i;let a=e.createGain();a.gain.value=0,t.connect(i),i.connect(a),a.connect(e.destination);let o=new Float32Array(e.sampleRate*n),s=0,c=new Float32Array,l=Date.now();i.port.onmessage=t=>{if(r!==this.generation)return;let i=0,a=t.data;for(;i<a.length;){let t=Math.min(o.length-s,a.length-i);if(o.set(a.subarray(i,i+t),s),s+=t,i+=t,s!==o.length)continue;let r=new Float32Array(16e3*n),u=e.sampleRate/16e3;for(let e=0;e<r.length;e++){let t=Math.floor(e*u),n=Math.max(t+1,Math.floor((e+1)*u)),i=0;for(let e=t;e<n;e++)i+=o[e]??0;r[e]=i/(n-t)}l+=n*1e3,Math.abs(Date.now()-l)>1500&&(l=Date.now(),c=new Float32Array);let d=new Float32Array(c.length+r.length);d.set(c),d.set(r,c.length),this.take({samples:d,at:l-d.length/16,until:l,freshAt:l-n*1e3}),c=d.slice(-32e3*n),s=0}},this.disconnect=()=>{i.port.onmessage=null,i.port.close(),t.disconnect(i),i.disconnect(),a.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},L=3,qt=1,Jt=class e{failed;options;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;level=1;static loaded=new WeakMap;constructor(e,t={}){this.failed=e,this.options=t}async start(t,n){this.stop();let r=this.generation;try{if(this.options.process===!1){if(r!==this.generation)return!1;let e=t.createGain();return this.gain=e,e.gain.value=this.on?this.level*qt:0,this.input=n,n.connect(e),e.connect(t.destination),!0}if(t.sampleRate!==48e3)throw Error(`Unsupported background sample rate`);let i=e.loaded.get(t);if(i||(i=t.audioWorklet.addModule(new URL(`data:text/javascript;base64,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIEEgYnJpZWYKICogc3RhbGwgZHJvcHMgc3RhbGUgZnJhbWVzIGFuZCByZWNvdmVyczsgaXQgbXVzdCBub3QgcGVybWFuZW50bHkgbXV0ZSBhbWJpZW5jZS4KICogTmV2ZXIgYnlwYXNzIHRvIHJhdyBpbnB1dCwgd2hpY2ggd291bGQgcmVzdG9yZSB0aGUgb3JpZ2luYWwgZGlhbG9ndWUuICovCmNvbnN0IEhPUCA9IDUxMjsKY29uc3QgTUFYX1BFTkRJTkcgPSAzMjsgLy8gQm91bmQgd29yayB0byBhYm91dCAzNDAgbXMgYXQgNDgga0h6Lgpjb25zdCBNQVhfQUdFID0gMTI7IC8vIEtlZXAgYXVkaWJsZSBhbWJpZW5jZSB3aXRoaW4gYWJvdXQgMTMwIG1zIG9mIHRoZSBzb3VyY2UuCmNvbnN0IFBSRUJVRkZFUiA9IDQ7CmNsYXNzIEJhY2tncm91bmRUcmFuc3BvcnQgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogIGNvbnN0cnVjdG9yKCkgewogICAgc3VwZXIoKTsKICAgIHRoaXMuY2hhbm5lbCA9IG51bGw7IHRoaXMuYWxpdmUgPSB0cnVlOyB0aGlzLnJlYWR5ID0gZmFsc2U7CiAgICB0aGlzLmlucHV0cyA9IFtdOwogICAgdGhpcy53cml0dGVuID0gMDsgdGhpcy5pZCA9IDA7IHRoaXMuaW5mbGlnaHQgPSAwOwogICAgdGhpcy5xdWV1ZSA9IFtdOyB0aGlzLm91dHB1dCA9IG51bGw7IHRoaXMucmVhZCA9IDA7CiAgICB0aGlzLnBvcnQub25tZXNzYWdlID0gZXZlbnQgPT4gewogICAgICBpZiAoZXZlbnQuZGF0YS5zdG9wKSB7IHRoaXMuYWxpdmUgPSBmYWxzZTsgdGhpcy5jaGFubmVsPy5jbG9zZSgpOyByZXR1cm47IH0KICAgICAgdGhpcy5jaGFubmVsID0gZXZlbnQuZGF0YS5wb3J0OwogICAgICB0aGlzLmNoYW5uZWwub25tZXNzYWdlID0gcmVzdWx0ID0+IHsKICAgICAgICBpZiAoIXRoaXMuYWxpdmUpIHJldHVybjsKICAgICAgICB0aGlzLmluZmxpZ2h0LS07CiAgICAgICAgY29uc3QgZnJhbWUgPSByZXN1bHQuZGF0YTsKICAgICAgICBpZiAoIU51bWJlci5pc1NhZmVJbnRlZ2VyKGZyYW1lLmlkKSB8fCAhQXJyYXkuaXNBcnJheShmcmFtZS5jaGFubmVscykgfHwgZnJhbWUuY2hhbm5lbHMubGVuZ3RoICE9PSAyCiAgICAgICAgICAgIHx8IGZyYW1lLmNoYW5uZWxzLnNvbWUoY2hhbm5lbCA9PiAhKGNoYW5uZWwgaW5zdGFuY2VvZiBGbG9hdDMyQXJyYXkpIHx8IGNoYW5uZWwubGVuZ3RoICE9PSBIT1ApKSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICAvLyBMYXRlIGJhY2tncm91bmQgaXMgYXMgZGlzdHJhY3RpbmcgYXMgbWlzc2luZyBiYWNrZ3JvdW5kLiBEaXNjYXJkIGl0CiAgICAgICAgLy8gd2hpbGUga2VlcGluZyB0aGUgd29ya2VyIGFsaXZlIHRvIGhhbmRsZSB0aGUgbmV4dCBjdXJyZW50IGZyYW1lLgogICAgICAgIGlmIChmcmFtZS5pZCA8IHRoaXMuaWQgLSBNQVhfQUdFKSByZXR1cm47CiAgICAgICAgaWYgKHRoaXMucXVldWUubGVuZ3RoID49IE1BWF9QRU5ESU5HKSB0aGlzLnF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgdGhpcy5xdWV1ZS5wdXNoKGZyYW1lKTsKICAgICAgICBpZiAodGhpcy5xdWV1ZS5sZW5ndGggPj0gUFJFQlVGRkVSKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGlmICghWzEsIDIsIDQsIDYsIDhdLmluY2x1ZGVzKGlucHV0Lmxlbmd0aCkpIHsgdGhpcy5mYWlsKCk7IHJldHVybiBmYWxzZTsgfQogICAgaWYgKHRoaXMuaW5wdXRzLmxlbmd0aCAhPT0gaW5wdXQubGVuZ3RoKSB7CiAgICAgIGlmICh0aGlzLmlucHV0cy5sZW5ndGgpIHRoaXMuaWQrKzsgLy8gRGlzY2FyZCBhIHBhcnRpYWwgZnJhbWUgb24gYSBsYXlvdXQgY2hhbmdlLgogICAgICB0aGlzLmlucHV0cyA9IGlucHV0Lm1hcCgoKSA9PiBuZXcgRmxvYXQzMkFycmF5KEhPUCkpOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgY29uc3QgY291bnQgPSBpbnB1dFswXS5sZW5ndGg7CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IGlucHV0Lmxlbmd0aDsgY2hhbm5lbCsrKSB0aGlzLmlucHV0c1tjaGFubmVsXS5zZXQoaW5wdXRbY2hhbm5lbF0sIHRoaXMud3JpdHRlbik7CiAgICB0aGlzLndyaXR0ZW4gKz0gY291bnQ7CiAgICBpZiAodGhpcy53cml0dGVuID09PSBIT1ApIHsKICAgICAgaWYgKHRoaXMuaW5mbGlnaHQgPCBNQVhfUEVORElORykgewogICAgICAgIGNvbnN0IGNoYW5uZWxzID0gdGhpcy5pbnB1dHM7IHRoaXMuaW5mbGlnaHQrKzsKICAgICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCwgY2hhbm5lbHMgfSwgY2hhbm5lbHMubWFwKG9uZSA9PiBvbmUuYnVmZmVyKSk7CiAgICAgICAgdGhpcy5pbnB1dHMgPSBpbnB1dC5tYXAoKCkgPT4gbmV3IEZsb2F0MzJBcnJheShIT1ApKTsKICAgICAgfQogICAgICAvLyBTa2lwIGV4Y2VzcyB3b3JrIGluc3RlYWQgb2YgYnVpbGRpbmcgYSBiYWNrbG9nIG9yIGtpbGxpbmcgdGhlIGJyYW5jaC4KICAgICAgdGhpcy5pZCsrOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSBIT1ApIHsKICAgICAgd2hpbGUgKHRoaXMucXVldWUubGVuZ3RoICYmIHRoaXMucXVldWVbMF0uaWQgPCB0aGlzLmlkIC0gTUFYX0FHRSkgdGhpcy5xdWV1ZS5zaGlmdCgpOwogICAgICB0aGlzLm91dHB1dCA9IHRoaXMucXVldWUuc2hpZnQoKT8uY2hhbm5lbHMgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsKICAgIH0KICAgIGlmICghdGhpcy5vdXRwdXQpIHsgdGhpcy5yZWFkeSA9IGZhbHNlOyByZXR1cm4gdHJ1ZTsgfQogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCBvdXQubGVuZ3RoOyBjaGFubmVsKyspIG91dFtjaGFubmVsXS5zZXQodGhpcy5vdXRwdXRbY2hhbm5lbF0uc3ViYXJyYXkodGhpcy5yZWFkLCB0aGlzLnJlYWQgKyBjb3VudCkpOwogICAgdGhpcy5yZWFkICs9IGNvdW50OwogICAgcmV0dXJuIHRydWU7CiAgfQp9CnJlZ2lzdGVyUHJvY2Vzc29yKCJuaXhhbXAtYmFja2dyb3VuZCIsIEJhY2tncm91bmRUcmFuc3BvcnQpOwo=`,``+import.meta.url)),e.loaded.set(t,i),i.catch(()=>e.loaded.delete(t))),await i,r!==this.generation)return!1;let a=new Worker(new URL(`/assets/background.worker-Hz7oaQ8X.js`,``+import.meta.url),{type:`module`});this.worker=a;let o=new MessageChannel;if(this.pendingPort=o.port1,await new Promise((e,t)=>{let n=!1,r=r=>{n||(n=!0,clearTimeout(i),this.cancelStart=null,r?t(r):e())},i=setTimeout(()=>r(Error(`Background model did not load`)),8e3);this.cancelStart=()=>r(Error(`Background loading cancelled`)),a.onerror=()=>r(Error(`Background worker failed`)),a.onmessage=e=>r(e.data.ready?void 0:Error(`Background model unavailable`)),a.postMessage({port:o.port2},[o.port2])}),r!==this.generation)return!1;let s=()=>{r===this.generation&&(this.stop(),this.failed())};a.onerror=s,a.onmessage=e=>{e.data.error&&s()};let c=new AudioWorkletNode(t,`nixamp-background`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],channelCount:8,channelCountMode:`clamped-max`,channelInterpretation:`speakers`});this.node=c,c.onprocessorerror=s,c.port.onmessage=e=>{e.data.error&&s()},c.port.postMessage({port:o.port1},[o.port1]),this.pendingPort=null;let l=t.createGain();return this.gain=l,l.gain.value=this.on?this.level*L:0,this.input=n,c.connect(l),l.connect(t.destination),n.connect(c),!0}catch{r===this.generation&&(this.stop(),this.failed())}return!1}active(e){this.on=e,this.gain&&(this.gain.gain.value=e?this.level*(this.options.process===!1?qt:L):0)}setLevel(e){Number.isFinite(e)&&(this.level=Math.max(0,Math.min(2,e)),this.gain&&(this.gain.gain.value=this.on?this.level*(this.options.process===!1?qt:L):0))}stop(){if(this.generation++,this.on=!1,this.cancelStart?.(),this.cancelStart=null,this.pendingPort?.close(),this.pendingPort=null,this.node){this.node.port.postMessage({stop:!0});try{this.input?.disconnect(this.node)}catch{}this.node.disconnect(),this.node.port.close()}if(!this.node&&this.input&&this.gain)try{this.input.disconnect(this.gain)}catch{}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Yt=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t){this.stop();let n=new AbortController;this.controller=n;let r=async()=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e3),a=await(this.options.fetcher??fetch)(`/api/v1/speech/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,language:t}),signal:AbortSignal.any([n.signal,r.signal])}).finally(()=>clearTimeout(i));if(!a.ok||!a.body)throw P((await a.json().catch(()=>({}))).error||`Live translation is unavailable.`,a.status);return a.body},i=await r();if(this.controller!==n){await i.cancel();return}this.consume(i,n,r)}clearClips(){for(let e of this.clips.values())if(!e.ended)try{e.controller.error(new DOMException(`Playback stopped`,`AbortError`))}catch{}this.clips.clear()}stop(){this.controller?.abort(),this.controller=null,this.clearClips()}audio(e){let t=this.clips.get(e);if(!t||t.taken)throw P(`The live audio segment expired. Catching up…`,503);return t.taken=!0,new Response(t.stream,{headers:{"content-type":`audio/pcm`}})}async consume(e,t,n){let r=0;for(;!t.signal.aborted;){let i=Date.now();try{await this.read(e,t);return}catch(a){if(t.signal.aborted||this.controller!==t)return;Date.now()-i>6e4&&(r=0),this.options.reconnecting?.(),this.clearClips();let o=a;for(;!t.signal.aborted;){if(!Ut(o)||r>=5){this.stop(),this.options.failed(o instanceof Error?o.message:`Live audio was interrupted.`);return}if(this.options.status(`Live audio disconnected · reconnecting…`),await new Promise(e=>{let n=()=>{clearTimeout(i),t.signal.removeEventListener(`abort`,n),e()},i=setTimeout(n,500*2**r++);t.signal.addEventListener(`abort`,n,{once:!0})}),t.signal.aborted)return;try{e=await n();break}catch(e){o=e}}}}}async read(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.signal.addEventListener(`abort`,a,{once:!0});try{for(;!t.signal.aborted;){let e,{done:o,value:s}=await Promise.race([n.read(),new Promise((t,n)=>{e=setTimeout(()=>{n(P(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw P(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
1
|
+
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={"Supported platforms":`Supported platforms`,"In review":`In review`,"Not available":`Not available`,"Install PWA":`Install PWA`,"PWA installed":`PWA installed`,"Web app":`Web app`,"Install the web app":`Install the web app`,"Keep BackToSchool on your home screen or desktop. No app store needed.":`Keep BackToSchool on your home screen or desktop. No app store needed.`,"iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.":`iPhone or iPad: open this site in Safari, tap Share, then Add to Home Screen.`,"Android: open your browser menu and choose Install app or Add to Home screen.":`Android: open your browser menu and choose Install app or Add to Home screen.`,"Desktop: look for Install in the address bar or browser menu. The option depends on your browser.":`Desktop: look for Install in the address bar or browser menu. The option depends on your browser.`,"You can also keep using BackToSchool in this browser.":`You can also keep using BackToSchool in this browser.`,"The web app is installed. You can keep learning here.":`The web app is installed. You can keep learning here.`,"Continue learning":`Continue learning`,"The install prompt could not open. Select Web app again for installation instructions.":`The install prompt could not open. Select Web app again for installation instructions.`,"Follow host":`Follow host`,Following:`Following`,"You’ll get email and web notifications for this host.":`You’ll get email and web notifications for this host.`,"Notifications turned off for this host.":`Notifications turned off for this host.`,"Could not update notifications.":`Could not update notifications.`},t={...e,"No parties live right now.":`No parties live right now.`,"Could not refresh parties.":`Could not refresh parties.`,"Pick a server in the directory, or paste its link here.":`Pick a server in the directory, or paste its link here.`,"Interface language":`Interface language`,Language:`Language`,"Translation language":`Translation language`,"Original (auto-detect)":`Original (auto-detect)`,Play:`Play`,Pause:`Pause`,Stop:`Stop`,Next:`Next`,Previous:`Previous`,Select:`Select`,"Next/Prev":`Next/Prev`,Quit:`Quit`,"Now Playing":`Now Playing`,"Spectrum Analyser":`Spectrum Analyser`,Playlist:`Playlist`,Files:`Files`,"Open files":`Open files`,"Open folder":`Open folder`,"Add to library":`Add to library`,"Replace playlist":`Replace playlist`,Filter:`Filter`,Search:`Search`,"Nothing loaded.":`Nothing loaded.`,"Empty.":`Empty.`,"Loading…":`Loading…`,"Connecting…":`Connecting…`,Connected:`Connected`,"Not connected":`Not connected`,"No source":`No source`,Playing:`Playing`,Stopped:`Stopped`,Volume:`Volume`,Seek:`Seek`,"Full screen":`Full screen`,Download:`Download`,Share:`Share`,Copy:`Copy`,"Copy link":`Copy link`,Copied:`Copied`,Save:`Save`,Cancel:`Cancel`,Close:`Close`,Remove:`Remove`,Delete:`Delete`,Edit:`Edit`,Add:`Add`,Send:`Send`,Retry:`Retry`,Back:`Back`,"Next page":`Next page`,"Previous page":`Previous page`,"Show more":`Show more`,Panels:`Panels`,"Reset layout":`Reset layout`,Show:`Show`,Hide:`Hide`,Collapse:`Collapse`,Expand:`Expand`,"Move up":`Move up`,"Move down":`Move down`,Install:`Install`,"TV mode":`TV mode`,On:`On`,Off:`Off`,Account:`Account`,"Sign in":`Sign in`,"Sign out":`Sign out`,"Create account":`Create account`,Email:`Email`,Password:`Password`,"Forgot password?":`Forgot password?`,"Welcome back":`Welcome back`,Profile:`Profile`,Handle:`Handle`,"Your servers":`Your servers`,Server:`Server`,Connect:`Connect`,Disconnect:`Disconnect`,Directory:`Directory`,Favourites:`Favourites`,Follow:`Follow`,Unfollow:`Unfollow`,Notifications:`Notifications`,"Phone number":`Phone number`,"Save number":`Save number`,Transcript:`Transcript`,Captions:`Captions`,"Translate audio":`Translate audio`,"Audio language":`Audio language`,"Audio options":`Audio options`,"Keep background sound":`Keep background sound`,"Background level":`Background level`,"Speaker voices":`Speaker voices`,"Any voice":`Any voice`,"Male voice":`Male voice`,"Female voice":`Female voice`,"Original audio.":`Original audio.`,"Buy translated audio":`Buy translated audio`,"Audio credit":`Audio credit`,"Buy pass":`Buy pass`,Pass:`Pass`,"Pay with":`Pay with`,"Check payment":`Check payment`,"Open checkout":`Open checkout`,"Free sessions":`Free sessions`,"Usage rates and expiry":`Usage rates and expiry`,Catalogs:`Catalogs`,"Add catalog":`Add catalog`,"Catalog name":`Catalog name`,Link:`Link`,"Play link":`Play link`,"Go live":`Go live`,Publish:`Publish`,Listen:`Listen`,"Live now":`Live now`,Upcoming:`Upcoming`,Parties:`Parties`,"Join party":`Join party`,"Invite code":`Invite code`,Invite:`Invite`,Chat:`Chat`,"Chat message":`Chat message`,People:`People`,Speaker:`Speaker`,Speakers:`Speakers`,Listener:`Listener`,Moderator:`Moderator`,"Raise hand":`Raise hand`,"Hand raises":`Hand raises`,Questions:`Questions`,Resources:`Resources`,Replay:`Replay`,Schedule:`Schedule`,Event:`Event`,Host:`Host`,About:`About`,Stage:`Stage`,Title:`Title`,Description:`Description`,Topic:`Topic`,Public:`Public`,"Anyone with the link":`Anyone with the link`,"Invited people":`Invited people`,"Who can join":`Who can join`,"Date and time":`Date and time`,"Expected length":`Expected length`,Repeat:`Repeat`,"Does not repeat":`Does not repeat`,"Every day":`Every day`,"Every week":`Every week`,Homepage:`Homepage`,"Host name":`Host name`,"Profile photo URL":`Profile photo URL`,"Broadcast link":`Broadcast link`,"Edit event":`Edit event`,"Save changes":`Save changes`,"Create live":`Create live`,"Schedule class":`Schedule class`,"Start class":`Start class`,"End event":`End event`,"End session":`End session`,"Session ended":`Session ended`,"Event ended":`Event ended`,Cancelled:`Cancelled`,"Replay available":`Replay available`,Join:`Join`,"Create invite":`Create invite`,"Invite as":`Invite as`,"Watch now":`Watch now`,"Start a room":`Start a room`,"Recent replays":`Recent replays`,"Your account":`Your account`,"Write with AI":`Write with AI`,"Suggested title":`Suggested title`,"Suggested description":`Suggested description`,"Suggested topic":`Suggested topic`,"Use these details":`Use these details`,"Learn something live.":`Learn something live.`,"Screen share":`Screen share`,"Upload and broadcast":`Upload and broadcast`,Help:`Help`,"Reload Player":`Reload Player`,"Copy Bundled CLI Path":`Copy Bundled CLI Path`,"Developer tools":`Developer tools`,Undo:`Undo`,Redo:`Redo`,Cut:`Cut`,Paste:`Paste`,"Select all":`Select all`,Status:`Status`,"Activity log":`Activity log`,Admin:`Admin`,"Playback controls":`Playback controls`,"Tracks and folders":`Tracks and folders`,"Original-language captions.":`Original-language captions.`,"Skip to playback controls":`Skip to playback controls`,"Skip to playlist":`Skip to playlist`,"Skip to transcript and translated audio":`Skip to transcript and translated audio`},n={"■ STOPPED":`Stopped`,"▶ PLAYING":`Playing`,LOADING:`Loading…`,"no source":`No source`,"not connected":`Not connected`,"Now playing":`Now Playing`,"● GO LIVE":`Go live`,"● Go live":`Go live`,"⤓ Download":`Download`,"A man's voice":`Male voice`,"A woman's voice":`Female voice`,"Catalogs on this server":`Catalogs`,"Catalog folders":`Catalogs`,"Parties on this server":`Parties`,"Servers streaming now":`Directory`,"Playlist (0)":`Playlist`,"Playlist folders":`Playlist`,"Playlist pages":`Playlist`,"Filter these files":`Filter`,"Filter these entries":`Filter`,"Filter the entries":`Filter`,"Filter the playlist":`Filter`,"Create a free account":`Create account`,"Create one":`Create account`,"Create your account":`Create account`,"New here? Create an account":`Create account`,"Already have an account? Sign in":`Sign in`,"Your NixAmp account":`Your account`,"Your public handle":`Handle`,handle:`Handle`,password:`Password`,"Phone number for texts":`Phone number`,"Back to the player":`Back`,"Share what is playing":`Share`,"Share this stream":`Share`,"Link to this stream":`Link`,"Copy this stream's URL":`Copy link`,"A link to play":`Link`,"A server's link":`Server`,"Close translated audio purchase":`Close`,"Open secure checkout ↗ (new tab)":`Open checkout`,"Checking…":`Loading…`,"Browse the directory":`Directory`,"See what is live":`Live now`,"Join live":`Join`,"Raise Hand":`Raise hand`,"Hand Raises":`Hand raises`,"Hide this":`Hide`,Log:`Activity log`,"Status:":`Status`,"Nixamp player":`Playback controls`,"Nixamp audio and video player":`Playback controls`,"What is being said":`Transcript`,"The room's chat":`Chat`,Trollbox:`Chat`,"A line for the trollbox":`Chat message`,"Say something to the room…":`Chat message`,"Send it":`Send`,"Something to add":`Chat message`,"What to call it":`Catalog name`,"call it something":`Catalog name`,"An m3u catalog to add":`Catalogs`,"On this device":`Play`,"Play on this device":`Play`,"What this is":`About`,"Looking for servers…":`Loading…`,"Finding today’s conversations…":`Loading…`,"Coming up":`Upcoming`,"Listen after class":`Replay`,"Schedule live":`Schedule class`,"Schedule a class":`Schedule class`,"Plan a conversation":`Schedule class`,"Your classroom":`Event`,"Join in":`Join`,"Open a room →":`Start a room`,"Chat message":`Chat message`,"Add to the conversation":`Chat message`,"Create live":`Create live`,"Host stage":`Stage`,"Your host":`Host`,"Class host":`Host`,"Hand raised ✓":`Raise hand`,"Copied ✓":`Copied`,"Screen share with Pairux ↗":`Screen share`,"Upload & broadcast in Nixamp ↗":`Upload and broadcast`,"Open Music Folder…":`Open folder`,"Choose a music folder":`Open folder`,"Main navigation":`Panels`,"Skip to a section":`Panels`},r=[{code:`en`,label:`English`},{code:`de`,label:`Deutsch`},{code:`sv`,label:`Svenska`},{code:`es`,label:`Español`},{code:`fr`,label:`Français`},{code:`it`,label:`Italiano`},{code:`nl`,label:`Nederlands`},{code:`da`,label:`Dansk`},{code:`fi`,label:`Suomi`},{code:`ru`,label:`Русский`},{code:`uk`,label:`Українська`},{code:`cs`,label:`Čeština`},{code:`hu`,label:`Magyar`},{code:`zh`,label:`中文`},{code:`ar`,label:`العربية`},{code:`hi`,label:`हिन्दी`},{code:`vi`,label:`Tiếng Việt`},{code:`id`,label:`Bahasa Indonesia`}],i=`nixamp.ui.language`;function a(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code??`en`}function o(e,t=[]){let n=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return r.find(e=>e.code===t)?.code};return n(e)??t.map(n).find(Boolean)??`en`}var s=`modulepreload`,c=function(e){return`/`+e},l={},u=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=c(t,n),t=u(t),t in l)return;l[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:s,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},d={en:async()=>({default:t}),de:()=>u(()=>import(`./de-D7yI8cd_.js`),[]),sv:()=>u(()=>import(`./sv-Df_aXTD6.js`),[]),es:()=>u(()=>import(`./es-BMGb7XlT.js`),[]),fr:()=>u(()=>import(`./fr-BpvyrESQ.js`),[]),it:()=>u(()=>import(`./it-IJKhyCGw.js`),[]),nl:()=>u(()=>import(`./nl-BU0Mn-e-.js`),[]),da:()=>u(()=>import(`./da-M4GDhrcC.js`),[]),fi:()=>u(()=>import(`./fi-CXNsmIrh.js`),[]),ru:()=>u(()=>import(`./ru-ClqNCOTW.js`),[]),uk:()=>u(()=>import(`./uk-K5yQBF0h.js`),[]),cs:()=>u(()=>import(`./cs-CoTzYnZt.js`),[]),hu:()=>u(()=>import(`./hu-CosB3vlS.js`),[]),zh:()=>u(()=>import(`./zh-a2v2x-3e.js`),[]),ar:()=>u(()=>import(`./ar-DhdXPO3p.js`),[]),hi:()=>u(()=>import(`./hi-DO7CO-fI.js`),[]),vi:()=>u(()=>import(`./vi-CYfcOUeA.js`),[]),id:()=>u(()=>import(`./id-DNumDlwq.js`),[])},f=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await d[e]()).default){this.load=e}messages=t;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=a(e),r=await this.load(n);if(t!==this.revision)return!1;this.code=n,this.messages=r,this.numberFormats.clear(),this.dateFormats.clear();for(let e of this.listeners)e();return!0}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}text(e,t={}){let r=this.language!==`en`&&Object.hasOwn(n,e)?n[e]:e,i=Object.hasOwn(this.messages,r)?this.messages[r]:e;return this.language!==`en`&&Object.hasOwn(n,e)&&(i=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+i+(e.endsWith(` ✓`)?` ✓`:``)),i.replace(/\{([\w]+)\}/g,(e,n)=>Object.hasOwn(t,n)?String(t[n]):e)}number(e,t){let n=JSON.stringify(t??{}),r=this.numberFormats.get(n);return r||(this.numberFormats.size>=64&&this.numberFormats.clear(),r=new Intl.NumberFormat(this.language,t),this.numberFormats.set(n,r)),r.format(e)}date(e,t){let n=JSON.stringify(t??{}),r=this.dateFormats.get(n);return r||(this.dateFormats.size>=64&&this.dateFormats.clear(),r=new Intl.DateTimeFormat(this.language,t),this.dateFormats.set(n,r)),r.format(e)}get direction(){return this.language===`ar`?`rtl`:`ltr`}},p=(e,t)=>f.text(e,t),m=new Map;function h(e,t,n){let r=m.get(e);r||(r=new Map,m.set(e,r)),r.set(t,n),n()}function g(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return h(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){m.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function _(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return h(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){m.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var v=[`aria-label`,`title`,`placeholder`,`data-title`],y=[`[data-i18n]`,...v.map(e=>`[data-i18n-${e}]`)].join(`,`);function b(e){let t=[...e.querySelectorAll(y)];e instanceof HTMLElement&&e.matches(y)&&t.unshift(e);for(let e of t){if(e.closest(`[translate="no"], [contenteditable="true"]`))continue;let t=e.getAttribute(`data-i18n`);if(t){let n=e.textContent;h(e,`text`,()=>{if(e.textContent!==n){m.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=p(t),e.textContent!==n&&(e.textContent=n)})}for(let t of v){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);h(e,t,()=>{if(e.getAttribute(t)!==r){m.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=p(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function ee(){document.documentElement.lang=f.language,document.documentElement.dir=f.direction;for(let[e,t]of m){if(!e.isConnected){m.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=f.language}var te=0;async function ne(e){let t=++te;try{if(!await f.setLanguage(e)||t!==te)return;try{localStorage.setItem(i,f.language)}catch{}window.nixampLanguage?.set(f.language).catch(()=>{})}catch{ee()}}async function re(){let e=o(null,navigator.languages);try{e=o(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...r.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{ne(e.value)});b(document),ee(),f.onChange(ee),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&b(e);for(let e of m.keys())e.isConnected||m.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&f.setLanguage(o(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==f.language&&f.setLanguage(e).catch(()=>{})});try{await f.setLanguage(e)}catch{}}var ie={play:`<span aria-hidden="true">▶</span>`,party:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 21 4-12 8 8Z"/><path d="m7 9 8 8M12 7l1-3M16 10l4-1M16 5l2-2M20 14l1 1M8 4l-1-1"/><circle cx="21" cy="4" r=".5" fill="currentColor"/></svg>`,rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`};function ae(e,t){e.innerHTML=ie[t]}function oe(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function se(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function x(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var ce=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function S(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&ce.has(e.slice(n+1).toLowerCase())}function le(){let e=document.getElementById(`sr-status`);if(!e)return;let t=[`note`,`account-note`,`remote-state`,`transcript-audio-note`,`notify-note`,`notify-phone-note`,`persona-note`],n=new Map,r,i=``;for(let a of t){let t=document.getElementById(a);t&&(n.set(a,t.textContent?.trim()??``),new MutationObserver(()=>{let o=t.textContent?.trim()??``;n.get(a)!==o&&(n.set(a,o),o&&!t.closest(`[hidden], [data-closed], [data-collapsed]`)&&(i=o,clearTimeout(r),r=setTimeout(()=>{e.textContent!==i&&(e.textContent=i)},200)))}).observe(t,{childList:!0,characterData:!0,subtree:!0}))}}var C=new WeakMap;function ue(e,t=!0){let n=e.contains(document.activeElement);C.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function w(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){C.delete(e),e.replaceChildren(...t);return}let n=C.has(e);if(C.set(e,t),n)return;let r=()=>{let t=C.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}C.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var T=new WeakMap,de=new WeakSet;function fe(e,t){let n=new Map([...e.children].map(e=>[e.dataset.liveKey,e])),r=new Set(t.map(e=>e.dataset.liveKey)),i=!1;for(let r of t){let t=n.get(r.dataset.liveKey);t?t!==r&&!t.isEqualNode(r)&&(t.contains(document.activeElement)||t.querySelector(`details[open]`)?i=!0:t.replaceWith(r)):e.append(r)}for(let[e,t]of n)r.has(e)||(t.contains(document.activeElement)?i=!0:t.remove());if(i?T.set(e,t):T.delete(e),de.has(e))return;de.add(e);let a=()=>{let t=T.get(e);t&&fe(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function pe(e){if(!/\.(?:mp4|m4v|mkv|webm|mov|avi|mp3|m4a|flac|ogg|opus|wav|aac)$/i.test(e))return e;let t=(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,``);return t.replace(/^0\d+[_ .-]+(?:\d+[_ .-]+)?/,``).replace(/_+/g,` `).trim()||t}function E(e){if(/^(?:[\\/]|[A-Za-z]:)/.test(e))return[];let t=e.split(/[\\/]/).filter(Boolean);return t.some(e=>e===`..`)?[]:t.filter(e=>e!==`.`).map(e=>e.replace(/_+/g,` `))}function me(e,t,n=`Live`){let r=e[t];if(!r){let e=pe(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${pe(r.title)}`:pe(r.title),a=E(r.folder??``),o=E(r.group??``).join(` › `),s=[...o?[o]:[],...a],c=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,l=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(s.length>0||e.album===r.album));return{title:i,context:c,position:`Playlist · ${l.findIndex(({at:e})=>e===t)+1} of ${l.length}`,fullTitle:c?`${c} › ${i}`:i}}var he=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],ge=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function D(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of ge)if(t.test(e.mimeType))return n}let t=_e(e.src);for(let[e,n]of he)if(e.test(t))return n;return`unknown`}function _e(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ve(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function ye(e,t){let n=D(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function be(e,t){let n=t.capabilities??ve(),r=ye({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await u(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-BCxdTCEU.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await u(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-CC8jMmPy.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await u(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var xe=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),Se=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function O(e){let t=e.lastIndexOf(`.`);return t>0&&Se.has(e.slice(t+1).toLowerCase())}function k(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&xe.has(e.slice(n+1).toLowerCase())}function Ce(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function we(e){return e.filter(e=>k(e.name,e.type)).sort((e,t)=>Ce(Te(e),Te(t))).map(e=>({title:x(e.name),artist:``,album:Ee(Te(e)),duration:0,url:URL.createObjectURL(e),video:S(e.name,e.type),objectUrl:!0,...O(e.name)?{kind:`mpegts`}:{}}))}function Te(e){return e.webkitRelativePath||e.name}function Ee(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function De(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var A=2048;function j(e){if(e.startsWith(`blob:`)||e.startsWith(`data:`))return!0;try{let t=globalThis.location?.origin;return t?new URL(e,t).origin===t:!1}catch{return!1}}function Oe(e,t){return e||t===`hls`||t===`mpegts`}var ke=class{elements;handlers;attach;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t,n=be){this.elements=e,this.handlers=t,this.attach=n,this.active=e.audio;for(let t of[e.audio,e.video]){t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&(!this.attached||this.attached.engine===`native`)&&this.handlers.onError(Ae(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get jinglePlaying(){return!!this.jingle&&!this.jingle.paused&&!this.jingle.ended}async playJingle(e){this.jingle!==e&&this.stopJingle(),this.jingle=e,this.ensureGraph(e);try{if(await e.play(),this.context?.state===`suspended`)throw new DOMException(`Audio needs an interaction`,`NotAllowedError`)}catch(t){throw e.pause(),e.currentTime=0,t}}stopJingle(){this.jingle?.pause(),this.jingle=null}get needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(!this.context)try{this.context=new t({sampleRate:48e3})}catch{this.context=new t}if(this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=A,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.output.gain.value=+!this.translated,this.analyser.connect(this.output),this.output.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}audioInput(){if(!this.analysable)throw Error(`This source blocks audio access, so its audio cannot be translated here.`);if(this.ensureGraph(this.active),!this.context||!this.analyser)throw Error(`This browser cannot capture player audio.`);return{context:this.context,node:this.analyser}}translatedAudio(e){this.translated=e,this.output&&(this.output.gain.value=+!e)}get mediaKey(){return this.active.currentSrc||this.active.src}get loaded(){return!!(this.active.currentSrc||this.active.src)}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:D({src:e.url})),r=Oe(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||j(e.url)||(this.handlers.readable?.(e.url)??!1);r.crossOrigin=i?`anonymous`:null,r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await this.attach(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onBusy?.(!0)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}let a=this.active.currentSrc||this.active.src||e.url;this.analysable=i||a.startsWith(`blob:`)||j(a),t&&await this.play()}async play(){this.stopJingle(),this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}if(e instanceof Error&&e.name===`AbortError`&&this.attached?.engine!==`native`)return;this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.stopJingle(),this.playBlocked=!1,this.active.pause()}async resumeAfterInteraction(){this.playBlocked?await this.play():this.playing&&this.context?.state===`suspended`&&await this.context.resume()}stop(){this.stopJingle(),this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function Ae(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function je(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function Me(e,t){return{...t,tracks:t.tracks??e.tracks}}function Ne(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function Pe(e,t,n=``){let r=`${e===``?``:Ne(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function Fe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=/^\/api\/channels\/([^/]+)\/?$/.exec(t.pathname),r=/^\/api\/media\/(\d+)\/?$/.exec(t.pathname),i=/^\/api\/live\/?$/.test(t.pathname);if(!n&&!r&&!i)return null;let a=t.searchParams.get(`k`)??``,o=a?`${t.origin}/view/${a}`:t.origin,s=`live`;if(r&&(s=`track:${r[1]}`),n)try{s=`channel:${decodeURIComponent(n[1]??``)}`}catch{s=`channel:${n[1]??``}`}return{view:o,what:s}}function Ie(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:Ne(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var Le=null;function Re(e){if(!e&&Le!==null)return Le;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(Le=n),n}catch{return!1}}function ze(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return Pe(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function Be(e){if(typeof e!=`object`||!e)return null;let t=e,n=je(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}function Ve(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var He=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return Ve(this.base,e)}url(e){let t=Pe(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=Ie(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(Pe(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=Be(Ue(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(Pe(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=Be(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=Re()){return ze(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function Ue(e){try{return JSON.parse(e)}catch{return null}}async function We(e,t,n=``){try{let r=await fetch(Pe(e,`/api/state`,n),{signal:t});return r.ok?Be(await r.json()):null}catch{return null}}function Ge(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function Ke(e,t=``,n){let r;try{r=await fetch(Pe(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function qe(e,t,n=``){try{let r=await fetch(Pe(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function Je(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var Ye=.14,Xe=.02;function Ze(e,t){let n=[];for(let r=0;r<=e;r++){let i=r/e,a=Math.round(1*(t/1)**i),o=n[n.length-1];n.push(o===void 0?a:Math.max(a,o+1))}return n}function Qe(e,t){let n=[];for(let r=0;r+1<t.length;r++){let i=Math.min(t[r],e.length),a=Math.min(Math.max(t[r+1],i+1),e.length),o=0,s=0;for(let t=i;t<a;t++)o+=e[t],s++;n.push(s===0?0:o/s/255)}return n}function $e(e,t,n=Ye){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function et(e,t,n=Xe){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function tt(e,t,n,r,i){let{width:a,height:o}=t;if(a<=0||o<=0||n.length===0)return;e.clearRect(0,0,a,o);let s=a/n.length,c=Math.max(1,s*.72),l=Math.max(2,o*.012);e.fillStyle=i.bar,n.forEach((t,n)=>{let r=Math.max(1,t*(o-l*2));e.fillRect(n*s+(s-c)/2,o-r,c,r)}),e.fillStyle=i.peak,r.forEach((t,n)=>{let r=o-Math.max(1,t*(o-l*2))-l*2;e.fillRect(n*s+(s-c)/2,Math.max(0,r),c,l)})}function nt(e,t){return{name:String(e?.name??e?.displayName??e?.abbreviation??``),score:typeof e?.score==`number`?e.score:typeof t==`number`?t:null,logo:typeof e?.logoUrl==`string`&&/^https?:\/\//.test(e.logoUrl)?e.logoUrl:``}}function rt(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function it(e,t={}){if(!e)return``;let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t.now??new Date,i=t.timeZone?{timeZone:t.timeZone}:{},a=n.toLocaleDateString(t.locale??f.language,i)===r.toLocaleDateString(t.locale??f.language,i);return n.toLocaleString(t.locale??f.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function at(e,t={}){let n=e.data,r=nt(n.away,n.awayScore),i=nt(n.home,n.homeScore),a=rt(e),o=typeof n.statusDetail==`string`?n.statusDetail.trim():``,s;if(a===`in`)s=o?`LIVE · ${o}`:`LIVE`;else if(a===`post`)s=`FINAL`;else{let n=it(e.published_at,t);s=n?`Kicks off ${n}`:o||`Upcoming`}let c=[],l=n.league,u=String(l?.abbreviation??l?.name??``);u&&c.push(u),typeof n.broadcast==`string`&&n.broadcast.trim()&&c.push(n.broadcast.trim());let d=a!==`pre`,f=e=>d&&e.score!==null?` ${e.score}`:``;return{away:r,home:i,state:a,status:s,chips:c,text:`${r.name}${f(r)} – ${i.name}${f(i)}`}}var ot=`nixamp.tv`,M=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function st(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?ct(r):/\bSilk\b/.test(e)&&n===0?!0:M.test(e):ct(i)}function ct(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function lt(e){return e?12:100}function ut(e,t,n){let r=Math.max(1,Math.ceil(e/n)),i=Math.min(Math.max(0,t),r-1),a=i*n;return{page:i,from:a,to:Math.min(e,a+n),pages:r}}var dt=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,N=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,ft=/\.m3u8(\?.*)?$/i,pt=/\.(m3u|pls)(\?.*)?$/i;function mt(e){try{let t=new URL(e);return N.test(t.pathname+t.search)}catch{return!1}}function ht(e){try{let t=new URL(e),n=t.pathname.split(`/`).filter(Boolean).map(e=>{try{return decodeURIComponent(e)}catch{return e}}),r=(n.pop()??``).replace(/\.(m3u|pls)$/i,``);return(/^(playlist|index|list|all|episodes|feed)?$/i.test(r)?n.pop()??``:r).replace(/[-_]+/g,` `).trim()||t.hostname}catch{return`Playlist`}}function gt(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||ht(t),r=[],i=(e,n)=>{if(r.length>=1e3)return;let i;try{i=new URL(e.trim(),t)}catch{return}if(i.protocol!==`https:`&&i.protocol!==`http:`)return;let a=i.pathname+i.search;if(!dt.test(a)&&!N.test(a))return;let o=decodeURIComponent(i.pathname.split(`/`).filter(Boolean).pop()??i.hostname);r.push({url:i.toString(),title:n||o})},a=!1;try{a=/\.pls$/i.test(new URL(t).pathname)}catch{a=!1}if(a){let t=new Map,a=new Map;for(let n of e.split(/\r?\n/)){let e=/^(File|Title)(\d+)\s*=\s*(.*)$/i.exec(n.trim());e&&(/^file$/i.test(e[1]??``)?t:a).set(e[2]??``,e[3]??``)}for(let[e,n]of[...t.entries()].sort((e,t)=>Number(e[0])-Number(t[0])))i(n,(a.get(e)??``).trim());return{title:n,entries:r}}let o=``;for(let t of e.split(/\r?\n/)){let e=t.trim();if(e!==``){if(e.startsWith(`#`)){let t=/^#EXTINF:\s*-?[\d.]+\s*(?:,(.*))?$/i.exec(e);t&&(o=(t[1]??``).trim());continue}i(e,o),o=``}}return{title:n,entries:r}}function _t(e){let t=e.hostname.replace(/^www\.|^m\.|^music\./,``),n=e=>e&&/^[A-Za-z0-9_-]{11}$/.test(e)?e:``;if(t===`youtu.be`)return n(e.pathname.slice(1).split(`/`)[0]??null);if(t!==`youtube.com`&&t!==`youtube-nocookie.com`)return``;if(e.pathname===`/watch`)return n(e.searchParams.get(`v`));let r=/^\/(?:shorts|live|embed|v)\/([^/?]+)/.exec(e.pathname);return r?n(r[1]??null):``}function vt(e,t=!1){let n;try{n=new URL(e.trim())}catch{return null}if(n.protocol!==`https:`&&n.protocol!==`http:`)return null;let r=_t(n);if(r){let e=n.searchParams.get(`t`);return{kind:`embed`,site:`youtube`,src:`https://www.youtube-nocookie.com/embed/${r}?autoplay=1&playsinline=1&rel=0${e&&/^\d+$/.test(e)?`&start=${e}`:``}`,label:`YouTube · ${r}`}}let i=n.hostname.replace(/^www\.|^player\./,``),a=i===`vimeo.com`?/^\/(?:video\/)?(\d+)/.exec(n.pathname)?.[1]:void 0;if(a)return{kind:`embed`,site:`vimeo`,src:`https://player.vimeo.com/video/${a}?autoplay=1&playsinline=1`,label:`Vimeo · ${a}`};if(i===`soundcloud.com`&&n.pathname.split(`/`).filter(Boolean).length>=2)return{kind:`embed`,site:`soundcloud`,src:`https://w.soundcloud.com/player/?url=${encodeURIComponent(n.toString())}&auto_play=true&visual=false`,label:`SoundCloud · ${n.pathname.split(`/`).filter(Boolean).slice(0,2).join(` / `)}`};let o=n.pathname+n.search,s=decodeURIComponent(n.pathname.split(`/`).filter(Boolean).pop()??n.hostname);return pt.test(o)?{kind:`list`,url:n.toString(),label:ht(n.toString())}:dt.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:N.test(o)||ft.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var yt=`nixamp.panels`;function bt(){return{order:[],placement:{},collapsed:[],closed:[]}}var xt=/^[a-z][a-z0-9-]{0,63}$/,St=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function Ct(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&xt.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function wt(e){if(!e)return bt();let t;try{t=JSON.parse(e)}catch{return bt()}if(!t||typeof t!=`object`||Array.isArray(t))return bt();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))xt.test(e)&&typeof t==`string`&&St.test(t)&&(r[e]=t);let i=e=>{let t=Ct(e),n=t.includes(`parties-panel`)?t.filter(e=>e!==`onair-panel`):t;return[...new Set(n.map(e=>e===`onair-panel`?`parties-panel`:e))]};return!r[`parties-panel`]&&r[`onair-panel`]&&(r[`parties-panel`]=r[`onair-panel`]),delete r[`onair-panel`],{order:i(n.order),placement:r,collapsed:i(n.collapsed),closed:i(n.closed)}}function Tt(e){return JSON.stringify(e)}function Et(e,t){let n=new Set(e),r=t.filter(e=>n.has(e)),i=new Set(r);return e.forEach((t,n)=>{if(i.has(t))return;let a=0;for(let t=n-1;t>=0;t--){let n=r.indexOf(e[t]);if(n>=0){a=n+1;break}}r.splice(a,0,t),i.add(t)}),r}function Dt(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function Ot(e,t=16e3){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}var kt=16e3,At=3e4;function jt(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function Mt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Nt=`nixamp.captions`,Pt=`nixamp.captions.native-v2.language`,Ft=[{code:``,label:`Original (auto-detect)`},...r];function It(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Ft.some(e=>e.code===t)?t:``}catch{return``}}function Lt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Rt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function zt(e,t,n){let r=[],i=[];for(let a of e)(a.at<=t-n?r:i).push(a);return r.sort((e,t)=>e.at-t.at),{ready:r,still:i}}function Bt(e,t,n,r=1500){let i=t-n;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.at<=i&&i<=n.until+r)return n;if(n.until+r<i)break}return null}function Vt(e){try{return e(Nt)!==`off`}catch{return!0}}function Ht(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Ut(e){let t=e?.status;return typeof t==`number`?[408,502,503,504].includes(t):e instanceof TypeError||e instanceof Error&&[`AbortError`,`TimeoutError`].includes(e.name)}function P(e,t){return Object.assign(Error(e),{status:t})}var Wt=12e3,Gt=class{options;context=null;gain=null;enabled=!1;generation=0;running=null;controller=null;next=[];sources=new Set;scheduledUntil=0;failures=0;seen=new Set;constructor(e){this.options=e}async enable(){this.enabled=!0,this.options.active(!0);try{this.context??=this.options.audioContext?.()??new AudioContext,this.gain||(this.gain=this.context.createGain(),this.gain.connect(this.context.destination)),await this.context.resume(),this.enabled&&this.options.status(`Waiting for the next translated line…`)}catch{this.fail(`Audio could not start. Enable translated audio again to retry.`)}}disable(){this.enabled=!1,this.reset()}reset(){this.generation++,this.controller?.abort(),this.controller=null,this.next=[],this.running=null,this.seen.clear(),this.failures=0;for(let e of this.sources)try{e.stop()}catch{}this.sources.clear(),this.scheduledUntil=0,this.options.active(this.enabled)}setVolume(){this.gain&&(this.gain.gain.value=Math.max(0,Math.min(1,this.options.volume())))}push(e,t,n){this.pushBatch([{line:e,url:t,lag:n}])}pushBatch(e){if(!this.enabled||!this.options.playing())return;let t=e.slice(0,12).filter(({line:e,lag:t})=>{let n=`${e.channel}|${e.at}|${e.language}|${e.speaker??``}`;return this.seen.has(n)||this.stale(e,t)?!1:(this.seen.add(n),this.seen.size>200&&this.seen.delete(this.seen.values().next().value),!0)});t.length&&(this.next=[...this.next.filter(e=>!this.stale(e.line,e.lag)),...t].slice(-24),this.running===null&&this.run(this.generation))}stale(e,t){return(this.options.now?.()??Date.now())-t-e.until>Wt}fail(e){this.disable(),this.options.status(`${e} Original audio restored.`),this.options.failed()}async run(e){this.running=e;try{for(;this.next.length&&this.enabled&&e===this.generation;){if(await this.waitForRoom(e,3),e!==this.generation)return;let t=this.next.shift();if(this.stale(t.line,t.lag)||!this.options.playing())continue;let n=new AbortController;this.controller=n;let r=setTimeout(()=>n.abort(),12e3);try{let i=new Headers(t.init?.headers);if(new Headers(await this.options.authorization?.(n.signal,t.line)).forEach((e,t)=>i.set(t,e)),e!==this.generation)return;let a=await(this.options.fetcher??fetch)(t.url,{...t.init,signal:n.signal,headers:i});if(clearTimeout(r),e!==this.generation){await a.body?.cancel();return}if(!a.ok)throw P((await a.json().catch(()=>({}))).error||`Translated audio is unavailable.`,a.status);if(!a.body||!a.headers.get(`content-type`)?.startsWith(`audio/pcm`))throw Error(`The server returned no voice audio.`);let o=a.body.getReader(),s=new Uint8Array,c=0;try{for(;;){let t,{done:r,value:i}=await Promise.race([o.read(),new Promise((e,r)=>{t=setTimeout(()=>{n.abort(),o.cancel().catch(()=>{}),r(new DOMException(`Voice connection timed out`,`TimeoutError`))},12e3)})]).finally(()=>clearTimeout(t));if(e!==this.generation){await o.cancel();return}if(r)break;let a=new Uint8Array(s.length+i.length);a.set(s),a.set(i,s.length);let l=a.length-a.length%2;s=a.slice(l);for(let t=0;t<l;t+=6400){if(await this.waitForRoom(e,8),e!==this.generation){await o.cancel();return}let n=a.subarray(t,Math.min(l,t+6400));this.schedule(n),c+=n.length}}}finally{o.releaseLock()}if(!c||s.length)throw P(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.failures>=3)throw t;this.options.status(`Voice interrupted · waiting for the next translated phrase…`)}finally{clearTimeout(r)}}}catch(t){e===this.generation&&this.fail(t instanceof Error?t.message:`Translated audio stopped.`)}finally{this.running===e&&(this.running=null)}}async waitForRoom(e,t){for(;e===this.generation&&this.context&&this.scheduledUntil-this.context.currentTime>t;)if(await new Promise(e=>setTimeout(e,25)),!this.options.playing()){this.reset();return}}schedule(e){let t=this.context;if(!t||!this.gain||!this.enabled)return;if(t.state!==`running`)throw Error(`Audio playback was suspended.`);let n=e.length/2,r=Math.max(t.currentTime+.03,this.scheduledUntil);if(r-t.currentTime+n/16e3>10)throw Error(`Translated audio fell too far behind.`);let i=t.createBuffer(1,n,16e3),a=i.getChannelData(0),o=new DataView(e.buffer,e.byteOffset,e.length);for(let e=0;e<n;e++)a[e]=o.getInt16(e*2,!0)/32768;let s=t.createBufferSource();s.buffer=i,s.connect(this.gain),this.setVolume(),this.sources.add(s),s.onended=()=>{this.sources.delete(s),s.disconnect()},s.start(r),this.scheduledUntil=r+i.duration,this.options.status(`Playing translated audio · a few seconds behind the video`)}},F=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,I=new WeakMap,Kt=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t,n=5){this.stop();let r=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(I.has(e)||I.set(e,e.audioWorklet.addModule(F).catch(t=>{throw I.delete(e),t})),await I.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=i;let a=e.createGain();a.gain.value=0,t.connect(i),i.connect(a),a.connect(e.destination);let o=new Float32Array(e.sampleRate*n),s=0,c=new Float32Array,l=Date.now();i.port.onmessage=t=>{if(r!==this.generation)return;let i=0,a=t.data;for(;i<a.length;){let t=Math.min(o.length-s,a.length-i);if(o.set(a.subarray(i,i+t),s),s+=t,i+=t,s!==o.length)continue;let r=new Float32Array(16e3*n),u=e.sampleRate/16e3;for(let e=0;e<r.length;e++){let t=Math.floor(e*u),n=Math.max(t+1,Math.floor((e+1)*u)),i=0;for(let e=t;e<n;e++)i+=o[e]??0;r[e]=i/(n-t)}l+=n*1e3,Math.abs(Date.now()-l)>1500&&(l=Date.now(),c=new Float32Array);let d=new Float32Array(c.length+r.length);d.set(c),d.set(r,c.length),this.take({samples:d,at:l-d.length/16,until:l,freshAt:l-n*1e3}),c=d.slice(-32e3*n),s=0}},this.disconnect=()=>{i.port.onmessage=null,i.port.close(),t.disconnect(i),i.disconnect(),a.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},L=3,qt=1,Jt=class e{failed;options;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;level=1;static loaded=new WeakMap;constructor(e,t={}){this.failed=e,this.options=t}async start(t,n){this.stop();let r=this.generation;try{if(this.options.process===!1){if(r!==this.generation)return!1;let e=t.createGain();return this.gain=e,e.gain.value=this.on?this.level*qt:0,this.input=n,n.connect(e),e.connect(t.destination),!0}if(t.sampleRate!==48e3)throw Error(`Unsupported background sample rate`);let i=e.loaded.get(t);if(i||(i=t.audioWorklet.addModule(new URL(`data:text/javascript;base64,LyogQXVkaW8gdHJhbnNwb3J0IG9ubHk6IG5ldXJhbCBpbmZlcmVuY2UgcnVucyBpbiBhIGRlZGljYXRlZCB3b3JrZXIuIEEgYnJpZWYKICogc3RhbGwgZHJvcHMgc3RhbGUgZnJhbWVzIGFuZCByZWNvdmVyczsgaXQgbXVzdCBub3QgcGVybWFuZW50bHkgbXV0ZSBhbWJpZW5jZS4KICogTmV2ZXIgYnlwYXNzIHRvIHJhdyBpbnB1dCwgd2hpY2ggd291bGQgcmVzdG9yZSB0aGUgb3JpZ2luYWwgZGlhbG9ndWUuICovCmNvbnN0IEhPUCA9IDUxMjsKY29uc3QgTUFYX1BFTkRJTkcgPSAzMjsgLy8gQm91bmQgd29yayB0byBhYm91dCAzNDAgbXMgYXQgNDgga0h6Lgpjb25zdCBNQVhfQUdFID0gMTI7IC8vIEtlZXAgYXVkaWJsZSBhbWJpZW5jZSB3aXRoaW4gYWJvdXQgMTMwIG1zIG9mIHRoZSBzb3VyY2UuCmNvbnN0IFBSRUJVRkZFUiA9IDQ7CmNsYXNzIEJhY2tncm91bmRUcmFuc3BvcnQgZXh0ZW5kcyBBdWRpb1dvcmtsZXRQcm9jZXNzb3IgewogIGNvbnN0cnVjdG9yKCkgewogICAgc3VwZXIoKTsKICAgIHRoaXMuY2hhbm5lbCA9IG51bGw7IHRoaXMuYWxpdmUgPSB0cnVlOyB0aGlzLnJlYWR5ID0gZmFsc2U7CiAgICB0aGlzLmlucHV0cyA9IFtdOwogICAgdGhpcy53cml0dGVuID0gMDsgdGhpcy5pZCA9IDA7IHRoaXMuaW5mbGlnaHQgPSAwOwogICAgdGhpcy5xdWV1ZSA9IFtdOyB0aGlzLm91dHB1dCA9IG51bGw7IHRoaXMucmVhZCA9IDA7CiAgICB0aGlzLnBvcnQub25tZXNzYWdlID0gZXZlbnQgPT4gewogICAgICBpZiAoZXZlbnQuZGF0YS5zdG9wKSB7IHRoaXMuYWxpdmUgPSBmYWxzZTsgdGhpcy5jaGFubmVsPy5jbG9zZSgpOyByZXR1cm47IH0KICAgICAgdGhpcy5jaGFubmVsID0gZXZlbnQuZGF0YS5wb3J0OwogICAgICB0aGlzLmNoYW5uZWwub25tZXNzYWdlID0gcmVzdWx0ID0+IHsKICAgICAgICBpZiAoIXRoaXMuYWxpdmUpIHJldHVybjsKICAgICAgICB0aGlzLmluZmxpZ2h0LS07CiAgICAgICAgY29uc3QgZnJhbWUgPSByZXN1bHQuZGF0YTsKICAgICAgICBpZiAoIU51bWJlci5pc1NhZmVJbnRlZ2VyKGZyYW1lLmlkKSB8fCAhQXJyYXkuaXNBcnJheShmcmFtZS5jaGFubmVscykgfHwgZnJhbWUuY2hhbm5lbHMubGVuZ3RoICE9PSAyCiAgICAgICAgICAgIHx8IGZyYW1lLmNoYW5uZWxzLnNvbWUoY2hhbm5lbCA9PiAhKGNoYW5uZWwgaW5zdGFuY2VvZiBGbG9hdDMyQXJyYXkpIHx8IGNoYW5uZWwubGVuZ3RoICE9PSBIT1ApKSB7IHRoaXMuZmFpbCgpOyByZXR1cm47IH0KICAgICAgICAvLyBMYXRlIGJhY2tncm91bmQgaXMgYXMgZGlzdHJhY3RpbmcgYXMgbWlzc2luZyBiYWNrZ3JvdW5kLiBEaXNjYXJkIGl0CiAgICAgICAgLy8gd2hpbGUga2VlcGluZyB0aGUgd29ya2VyIGFsaXZlIHRvIGhhbmRsZSB0aGUgbmV4dCBjdXJyZW50IGZyYW1lLgogICAgICAgIGlmIChmcmFtZS5pZCA8IHRoaXMuaWQgLSBNQVhfQUdFKSByZXR1cm47CiAgICAgICAgaWYgKHRoaXMucXVldWUubGVuZ3RoID49IE1BWF9QRU5ESU5HKSB0aGlzLnF1ZXVlLnNoaWZ0KCk7CiAgICAgICAgdGhpcy5xdWV1ZS5wdXNoKGZyYW1lKTsKICAgICAgICBpZiAodGhpcy5xdWV1ZS5sZW5ndGggPj0gUFJFQlVGRkVSKSB0aGlzLnJlYWR5ID0gdHJ1ZTsKICAgICAgfTsKICAgICAgdGhpcy5jaGFubmVsLnN0YXJ0KCk7CiAgICB9OwogIH0KICBmYWlsKCkgeyB0aGlzLmFsaXZlID0gZmFsc2U7IHRoaXMucXVldWUgPSBbXTsgdGhpcy5vdXRwdXQgPSBudWxsOyB0aGlzLnBvcnQucG9zdE1lc3NhZ2UoeyBlcnJvcjogdHJ1ZSB9KTsgfQogIHByb2Nlc3MoaW5wdXRzLCBvdXRwdXRzKSB7CiAgICBjb25zdCBvdXQgPSBvdXRwdXRzWzBdOwogICAgaWYgKCF0aGlzLmFsaXZlKSByZXR1cm4gZmFsc2U7CiAgICBjb25zdCBpbnB1dCA9IGlucHV0c1swXTsKICAgIGlmICghaW5wdXQ/LlswXSB8fCAhdGhpcy5jaGFubmVsKSByZXR1cm4gdHJ1ZTsKICAgIGlmICghWzEsIDIsIDQsIDYsIDhdLmluY2x1ZGVzKGlucHV0Lmxlbmd0aCkpIHsgdGhpcy5mYWlsKCk7IHJldHVybiBmYWxzZTsgfQogICAgaWYgKHRoaXMuaW5wdXRzLmxlbmd0aCAhPT0gaW5wdXQubGVuZ3RoKSB7CiAgICAgIGlmICh0aGlzLmlucHV0cy5sZW5ndGgpIHRoaXMuaWQrKzsgLy8gRGlzY2FyZCBhIHBhcnRpYWwgZnJhbWUgb24gYSBsYXlvdXQgY2hhbmdlLgogICAgICB0aGlzLmlucHV0cyA9IGlucHV0Lm1hcCgoKSA9PiBuZXcgRmxvYXQzMkFycmF5KEhPUCkpOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgY29uc3QgY291bnQgPSBpbnB1dFswXS5sZW5ndGg7CiAgICBmb3IgKGxldCBjaGFubmVsID0gMDsgY2hhbm5lbCA8IGlucHV0Lmxlbmd0aDsgY2hhbm5lbCsrKSB0aGlzLmlucHV0c1tjaGFubmVsXS5zZXQoaW5wdXRbY2hhbm5lbF0sIHRoaXMud3JpdHRlbik7CiAgICB0aGlzLndyaXR0ZW4gKz0gY291bnQ7CiAgICBpZiAodGhpcy53cml0dGVuID09PSBIT1ApIHsKICAgICAgaWYgKHRoaXMuaW5mbGlnaHQgPCBNQVhfUEVORElORykgewogICAgICAgIGNvbnN0IGNoYW5uZWxzID0gdGhpcy5pbnB1dHM7IHRoaXMuaW5mbGlnaHQrKzsKICAgICAgICB0aGlzLmNoYW5uZWwucG9zdE1lc3NhZ2UoeyBpZDogdGhpcy5pZCwgY2hhbm5lbHMgfSwgY2hhbm5lbHMubWFwKG9uZSA9PiBvbmUuYnVmZmVyKSk7CiAgICAgICAgdGhpcy5pbnB1dHMgPSBpbnB1dC5tYXAoKCkgPT4gbmV3IEZsb2F0MzJBcnJheShIT1ApKTsKICAgICAgfQogICAgICAvLyBTa2lwIGV4Y2VzcyB3b3JrIGluc3RlYWQgb2YgYnVpbGRpbmcgYSBiYWNrbG9nIG9yIGtpbGxpbmcgdGhlIGJyYW5jaC4KICAgICAgdGhpcy5pZCsrOyB0aGlzLndyaXR0ZW4gPSAwOwogICAgfQogICAgaWYgKCF0aGlzLnJlYWR5KSByZXR1cm4gdHJ1ZTsKICAgIGlmICghdGhpcy5vdXRwdXQgfHwgdGhpcy5yZWFkID09PSBIT1ApIHsKICAgICAgd2hpbGUgKHRoaXMucXVldWUubGVuZ3RoICYmIHRoaXMucXVldWVbMF0uaWQgPCB0aGlzLmlkIC0gTUFYX0FHRSkgdGhpcy5xdWV1ZS5zaGlmdCgpOwogICAgICB0aGlzLm91dHB1dCA9IHRoaXMucXVldWUuc2hpZnQoKT8uY2hhbm5lbHMgPz8gbnVsbDsgdGhpcy5yZWFkID0gMDsKICAgIH0KICAgIGlmICghdGhpcy5vdXRwdXQpIHsgdGhpcy5yZWFkeSA9IGZhbHNlOyByZXR1cm4gdHJ1ZTsgfQogICAgZm9yIChsZXQgY2hhbm5lbCA9IDA7IGNoYW5uZWwgPCBvdXQubGVuZ3RoOyBjaGFubmVsKyspIG91dFtjaGFubmVsXS5zZXQodGhpcy5vdXRwdXRbY2hhbm5lbF0uc3ViYXJyYXkodGhpcy5yZWFkLCB0aGlzLnJlYWQgKyBjb3VudCkpOwogICAgdGhpcy5yZWFkICs9IGNvdW50OwogICAgcmV0dXJuIHRydWU7CiAgfQp9CnJlZ2lzdGVyUHJvY2Vzc29yKCJuaXhhbXAtYmFja2dyb3VuZCIsIEJhY2tncm91bmRUcmFuc3BvcnQpOwo=`,``+import.meta.url)),e.loaded.set(t,i),i.catch(()=>e.loaded.delete(t))),await i,r!==this.generation)return!1;let a=new Worker(new URL(`/assets/background.worker-Hz7oaQ8X.js`,``+import.meta.url),{type:`module`});this.worker=a;let o=new MessageChannel;if(this.pendingPort=o.port1,await new Promise((e,t)=>{let n=!1,r=r=>{n||(n=!0,clearTimeout(i),this.cancelStart=null,r?t(r):e())},i=setTimeout(()=>r(Error(`Background model did not load`)),8e3);this.cancelStart=()=>r(Error(`Background loading cancelled`)),a.onerror=()=>r(Error(`Background worker failed`)),a.onmessage=e=>r(e.data.ready?void 0:Error(`Background model unavailable`)),a.postMessage({port:o.port2},[o.port2])}),r!==this.generation)return!1;let s=()=>{r===this.generation&&(this.stop(),this.failed())};a.onerror=s,a.onmessage=e=>{e.data.error&&s()};let c=new AudioWorkletNode(t,`nixamp-background`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],channelCount:8,channelCountMode:`clamped-max`,channelInterpretation:`speakers`});this.node=c,c.onprocessorerror=s,c.port.onmessage=e=>{e.data.error&&s()},c.port.postMessage({port:o.port1},[o.port1]),this.pendingPort=null;let l=t.createGain();return this.gain=l,l.gain.value=this.on?this.level*L:0,this.input=n,c.connect(l),l.connect(t.destination),n.connect(c),!0}catch{r===this.generation&&(this.stop(),this.failed())}return!1}active(e){this.on=e,this.gain&&(this.gain.gain.value=e?this.level*(this.options.process===!1?qt:L):0)}setLevel(e){Number.isFinite(e)&&(this.level=Math.max(0,Math.min(2,e)),this.gain&&(this.gain.gain.value=this.on?this.level*(this.options.process===!1?qt:L):0))}stop(){if(this.generation++,this.on=!1,this.cancelStart?.(),this.cancelStart=null,this.pendingPort?.close(),this.pendingPort=null,this.node){this.node.port.postMessage({stop:!0});try{this.input?.disconnect(this.node)}catch{}this.node.disconnect(),this.node.port.close()}if(!this.node&&this.input&&this.gain)try{this.input.disconnect(this.gain)}catch{}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},Yt=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t){this.stop();let n=new AbortController;this.controller=n;let r=async()=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e3),a=await(this.options.fetcher??fetch)(`/api/v1/speech/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,language:t}),signal:AbortSignal.any([n.signal,r.signal])}).finally(()=>clearTimeout(i));if(!a.ok||!a.body)throw P((await a.json().catch(()=>({}))).error||`Live translation is unavailable.`,a.status);return a.body},i=await r();if(this.controller!==n){await i.cancel();return}this.consume(i,n,r)}clearClips(){for(let e of this.clips.values())if(!e.ended)try{e.controller.error(new DOMException(`Playback stopped`,`AbortError`))}catch{}this.clips.clear()}stop(){this.controller?.abort(),this.controller=null,this.clearClips()}audio(e){let t=this.clips.get(e);if(!t||t.taken)throw P(`The live audio segment expired. Catching up…`,503);return t.taken=!0,new Response(t.stream,{headers:{"content-type":`audio/pcm`}})}async consume(e,t,n){let r=0;for(;!t.signal.aborted;){let i=Date.now();try{await this.read(e,t);return}catch(a){if(t.signal.aborted||this.controller!==t)return;Date.now()-i>6e4&&(r=0),this.options.reconnecting?.(),this.clearClips();let o=a;for(;!t.signal.aborted;){if(!Ut(o)||r>=5){this.stop(),this.options.failed(o instanceof Error?o.message:`Live audio was interrupted.`);return}if(this.options.status(`Live audio disconnected · reconnecting…`),await new Promise(e=>{let n=()=>{clearTimeout(i),t.signal.removeEventListener(`abort`,n),e()},i=setTimeout(n,500*2**r++);t.signal.addEventListener(`abort`,n,{once:!0})}),t.signal.aborted)return;try{e=await n();break}catch(e){o=e}}}}}async read(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.signal.addEventListener(`abort`,a,{once:!0});try{for(;!t.signal.aborted;){let e,{done:o,value:s}=await Promise.race([n.read(),new Promise((t,n)=>{e=setTimeout(()=>{n(P(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw P(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
2
2
|
|
|
3
|
-
`))>=0;){let e=i.slice(0,c);i=i.slice(c+2),e.startsWith(`data: `)&&this.event(JSON.parse(e.slice(6)))}if(i.length>128e3)throw Error(`Invalid live audio response.`)}}finally{t.signal.removeEventListener(`abort`,a),await n.cancel().catch(()=>{}),n.releaseLock()}}event(e){if(e.type===`error`)throw P(e.error,e.retryable?503:400);if(e.type===`status`){this.options.status(`Live translated audio · ${e.listeners} ${e.listeners===1?`listener`:`listeners`}`);return}let t=`nixamp-shared:${e.id}`;if(e.type===`line`){for(let[e,t]of this.clips)t.ended&&(t.taken||Date.now()-t.until>12e3)&&this.clips.delete(e);for(;this.clips.size>=24;){let e=this.clips.entries().next().value;e[1].ended||e[1].controller.error(P(`Catching up with live audio…`,503)),this.clips.delete(e[0])}let n,r=new ReadableStream({start:e=>{n=e},cancel:()=>{let e=this.clips.get(t);e&&(e.ended=!0),this.clips.delete(t)}});this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t);return}let n=this.clips.get(t);if(!n||n.ended)return;if(e.type===`end`){n.ended=!0,n.controller.close();return}let r=Uint8Array.from(atob(e.data),e=>e.charCodeAt(0));if(n.bytes+=r.length,n.bytes>2097152)throw Error(`The live audio segment was too large.`);n.controller.enqueue(r)}},R=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),z=e=>document.getElementById(e),Xt=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=z(`translation-purchase`);plan=z(`translation-plan`);coin=z(`translation-coin`);buy=z(`translation-checkout`);note=z(`translation-purchase-note`);checkoutLink=z(`translation-checkout-link`);constructor(e){this.options=e,z(`translation-purchase-close`).addEventListener(`click`,()=>this.dialog.close()),this.dialog.addEventListener(`close`,()=>{this.timer&&clearTimeout(this.timer),this.timer=null,this.opener?.focus({preventScroll:!0})}),z(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),z(`translation-check-payment`).addEventListener(`click`,()=>void this.check()),window.addEventListener(`pagehide`,()=>{this.timer&&clearTimeout(this.timer)}),setInterval(()=>{this.options.account()&&(!this.access||this.access.required)&&this.refresh()},3e4)}status(e){this.note.textContent!==e&&(this.note.textContent=e)}loaded(){return this.access!==null}loadingMessage(){return this.problem||`Checking free sessions and audio credit…`}ready(){let e=this.access;return e?.required===!1||!!(e&&((e.free?.remaining??0)>0||e.free?.activeUntil&&Date.parse(e.free.activeUntil)>Date.now()||e.balanceMicros>0&&e.expires&&Date.parse(e.expires)>Date.now()))}async startSession(e){if(this.access?.required===!1)return;let t=await fetch(`/api/v1/translation-passes/session`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({resource:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();if(!t.ok)throw Error(n.error||`This free session could not be started.`);this.refresh()}button(){let e=document.createElement(`button`);return e.type=`button`,e.textContent=`$`,_(e,`title`,()=>p(`Buy translated audio`)),_(e,`aria-label`,()=>p(`Buy translated audio`)),e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-controls`,`translation-purchase`),e.dataset.translationBuy=``,e.addEventListener(`click`,()=>this.open(e)),e}open(e){this.opener=e,this.dialog.open||this.dialog.showModal(),this.status(``),this.refresh().then(()=>{this.order&&this.dialog.open&&this.check()})}async refresh(){let e=this.options.account();this.problem=``,this.account!==e&&(this.account=e,this.access=null,this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0);try{let t=await fetch(`/api/v1/translation-passes`,{signal:AbortSignal.timeout(15e3)}),n=await t.json();if(this.account!==e||this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Purchases are unavailable.`);this.access=n;let r=this.access.coins??[];[...this.coin.options].map(e=>e.value).join()!==r.join()&&document.activeElement!==this.coin&&this.coin.replaceChildren(...r.map(e=>new Option(e.replaceAll(`_`,` · `),e)));let i=this.access.plans??[];this.plan.options.length||this.plan.replaceChildren(...i.map(e=>{let t=new Option(``,e.id);return g(t,()=>`${e.name} · ${R(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${R(a.balanceMicros)}${a.expires?` · ${new Date(a.expires).toLocaleString(f.language)}`:``}`:``,s=this.access.free,c=()=>a.required&&s?f.language===`en`?`${s.remaining} of ${s.limit} free sessions left today${s.activeUntil?` · free session active`:``}`:`${p(`Free sessions`)}: ${f.number(s.remaining)}/${f.number(s.limit)}${s.activeUntil?` · ✓`:``}`:``;g(z(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(z(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(z(`translation-free-description`),()=>s?`Each account gets ${s.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${s.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(s.resets).toLocaleString(f.language)} (midnight UTC). Free time is used before purchased credit.`:``),z(`translation-sign-in`).hidden=!!e,this.buy.disabled=!e||!this.access.available||this.loading,!this.access.available&&this.dialog.open&&this.status(this.access.required?`Checkout is temporarily unavailable. Free sessions and existing credit still work.`:`This server sponsors translated audio; no purchase is required.`);let l=new URLSearchParams(location.search).get(`translation_order`),u=this.access.orders?.find(e=>e.id===l||e.id===this.order)??this.access.orders?.[0];u&&!this.order&&(this.order=u.id,this.link(u.url)),l&&!this.order&&/^[a-f0-9-]{36}$/i.test(l)&&e&&(this.order=l,this.check()),this.options.changed(),this.order&&!this.dialog.open&&!this.checking&&this.check()}catch(e){this.problem=e instanceof Error?e.message:`Audio credit could not be checked. Use Buy to retry.`,this.dialog.open&&this.status(this.problem),this.options.changed()}}describe(){let e=this.access?.plans.find(e=>e.id===this.plan.value);if(!e)return;let t=Math.floor(e.priceCents/100/((.66/60+.05)*5));z(`translation-plan-description`).textContent=`${R(e.priceCents*1e4)} credit. Expires ${e.days===1?`24 hours`:`${e.days} days`} after payment. About ${t} minutes at 1,000 spoken characters/minute; usage varies. No automatic renewal.`}link(e){if(!/^https:\/\/coinpayportal\.com\/pay\/[a-f0-9-]{36}$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,z(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=`${this.plan.value}|${this.coin.value}`;(!this.requestKey||this.selected!==t)&&(this.requestKey=crypto.randomUUID(),this.selected=t),this.loading=!0,this.buy.disabled=!0,this.status(`Preparing secure checkout…`);try{let t=await fetch(`/api/v1/translation-passes/checkout`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({plan:this.plan.value,coin:this.coin.value,requestKey:this.requestKey}),signal:AbortSignal.timeout(2e4)}),n=await t.json();if(this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Checkout could not be opened.`);this.order=n.id,this.link(n.url),this.status(`Open secure checkout to pay. Your video keeps playing in this tab. Credit appears after payment confirmation.`),this.poll()}catch(e){this.status(e instanceof Error?e.message:`Checkout could not be opened.`)}finally{this.loading=!1,this.buy.disabled=!this.account||!this.access?.available}}poll(){this.timer&&clearTimeout(this.timer),this.dialog.open&&this.order&&(this.timer=setTimeout(()=>void this.check(),5e3))}async check(){if(!this.order||!this.account||this.checking)return;this.checking=!0;let e=this.order,t=this.account;try{let n=await fetch(`/api/v1/translation-passes/orders/${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(2e4)}),r=await n.json();if(this.account!==t||this.order!==e)return;if(!n.ok)throw Error(r.error||`Payment status could not be checked.`);if(r.status===`paid`){this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0,z(`translation-check-payment`).hidden=!0,this.status(`Payment confirmed. Enable Translate audio whenever you are ready.`);let e=new URL(location.href);e.searchParams.delete(`translation_order`),history.replaceState(history.state,``,e),await this.refresh();return}this.status(r.status===`pending`?`Waiting for payment confirmation…`:`Payment ${r.status}. Check again if you have already sent it.`),r.status===`pending`&&this.poll()}catch(e){this.status(e instanceof Error?e.message:`Payment status could not be checked.`)}finally{this.checking=!1}}},Zt=class{random;previous=[];sequence=0;speakers=new Map;constructor(e=Math.random){this.random=e}reset(){this.previous=[],this.sequence=0,this.speakers.clear()}reconcile(e,t,n){let r=new Map,i=new Set,a=[],o=new Map;for(let n of e)for(let e of this.previous){let r=Math.min(t+n.end*1e3,e.end)-Math.max(t+n.start*1e3,e.start);if(r>120){let t=`${n.speaker}|${e.speaker}`;o.set(t,(o.get(t)??0)+r)}}for(let[e,t]of o){let[n,r]=e.split(`|`);a.push({local:n,global:r,overlap:t})}for(let e of a.sort((e,t)=>t.overlap-e.overlap)){let t=this.speakers.get(e.global);t&&!r.has(e.local)&&!i.has(e.global)&&(r.set(e.local,t),i.add(e.global))}for(let t of e){let e=r.get(t.speaker);if(!e){let i=new Set([...this.speakers.values()].map(e=>e.voice)),a=n.filter(e=>!i.has(e.id)),o=a.length?a:n,s=o[Math.floor(this.random()*o.length)];e={id:`speaker-${++this.sequence}`,profile:t.profile,voice:s?.id??`auto`},this.speakers.set(e.id,e),r.set(t.speaker,e)}}this.previous=e.map(e=>({start:t+e.start*1e3,end:t+e.end*1e3,speaker:r.get(e.speaker).id}));let s=new Set(this.previous.map(e=>e.speaker));for(let e of this.speakers.keys())this.speakers.size>64&&!s.has(e)&&this.speakers.delete(e);return r}},Qt=class{options;tracker=new Zt;generation=0;pending=null;committedUntil=null;running=null;controller=null;translating=null;translationController=null;recognitionFailures=0;translationFailures=0;translations=[];constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.translationController?.abort(),this.pending=null,this.running=null,this.translating=null,this.recognitionFailures=this.translationFailures=0,this.translations=[],this.committedUntil=null,this.tracker.reset()}push(e){this.committedUntil??=e.freshAt,this.pending=e,this.running===null&&this.run(this.generation)}async json(e,t,n){let r=await(this.options.fetcher??fetch)(e,{...t,signal:n}),i=await r.json();if(!r.ok)throw P(i.error||`Audio translation is unavailable.`,r.status);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;this.pending=null;try{if(Date.now()-t.until>12e3)continue;let n=new AbortController;this.controller=n;let r=AbortSignal.any([n.signal,AbortSignal.timeout(12e3)]),i=this.options.speakers(),a=this.options.language(),o=await this.json(i?`/api/v1/speech/speakers`:`/api/v1/speech/transcribe?live=1`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Uint8Array(Ot(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;this.recognitionFailures=0;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=o.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),l=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),u=[],d=()=>{u.length&&(c.push({channel:this.options.channel(),at:t.at+u[0].start*1e3,until:t.at+u.at(-1).end*1e3,text:u.map(e=>e.text).join(` `).trim(),language:s,speaker:o.id,voiceProfile:a.profile}),u=[])};for(let e of l)u.length&&e.start-u.at(-1).end>=.45&&d(),u.push(e),(/[.!?。!?]$/.test(e.text)||u.map(e=>e.text).join(` `).length>=400)&&d();u.length&&(i<r.length-1||t.until-(t.at+u.at(-1).end*1e3)>=350||t.until-(t.at+u[0].start*1e3)>=3e3)&&d()}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(!c.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...c.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:c,language:s,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.recognitionFailures>=3)throw t;this.options.status(`Speech recognition interrupted · listening for the next phrase…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.running===e&&(this.running=null)}}async translate(e){this.translating=e;try{for(;this.translations.length&&e===this.generation;){let t=this.translations.shift();try{let{lines:n}=t,{language:r,target:i,until:a}=t;if(Date.now()-a>12e3)continue;let o=new AbortController;if(this.translationController=o,i&&r!==i){if(!r)throw P(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:n.map(e=>e.text),from:r,to:i})},AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]));if(e.texts.length!==n.length||e.texts.some(e=>!e.trim()))throw P(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((t,n)=>({...t,original:t.text,sourceLanguage:r,language:i,text:e.texts[n]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>$t(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.translationFailures>=3)throw t;this.options.status(`Translation interrupted · catching up with live speech…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.translating===e&&(this.translating=null)}}};function $t(e){let t=e.text.trim();if(!t)return[];let n=[],r=t;for(;r.length>600;){let e=r.lastIndexOf(` `,600),t=e>300?e:600;n.push(r.slice(0,t)),r=r.slice(t).trimStart()}r&&n.push(r);let i=0;return n.map(n=>{let r=e.at+(e.until-e.at)*i/t.length;return i+=n.length+1,{...e,text:n,at:r,until:Math.min(e.until,e.at+(e.until-e.at)*i/t.length)}})}var en=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,tn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,nn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,rn=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function an(e){let t=e.replace(tn,``).replace(tn,``).trim().split(nn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!rn.test(t)})}function on(e){let t=String(e??``).trim();return t===``?!1:an(t.replace(en,``))||an(t)}function sn(e,t){if(e.dataset.longStringScroller===`true`)return;e.dataset.longStringScroller=`true`,e.classList.add(`long-string-scroller`),t.classList.add(`long-string-scroller-content`),t.title=t.textContent??``;let n=0,r=0,i=0,a=!1,o=null,s=()=>{n=0;let c=matchMedia(`(prefers-reduced-motion: reduce)`).matches?r:i+(r-i)*.22;if(i=Math.abs(r-c)<.5?r:c,t.style.setProperty(`--path-shift`,`${i}px`),Math.abs(r-i)>=.5){n=requestAnimationFrame(s);return}a&&(a=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),o=setTimeout(()=>{o=null,e.style.removeProperty(`min-height`)},280))},c=()=>{n||=requestAnimationFrame(s)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&matchMedia(`(hover: hover) and (pointer: fine)`).matches&&(o!==null&&(clearTimeout(o),o=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,a=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;let i=getComputedStyle(e),a=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),o=Math.max(0,t.scrollWidth-(e.clientWidth-a));if(o<=0)return;let s=e.getBoundingClientRect(),l=Math.max(0,Math.min(1,(n.clientX-s.left)/Math.max(1,s.width)));if(l<=.02)r=0;else if(l>=.98)r=-o;else{let e=l*l*(3-2*l);r=-o*e}c()}),e.addEventListener(`pointerleave`,()=>{r=0,a=!0,c()})}var cn=`nixamp.remote`,ln=`nixamp.defaultServer`,un=`nixamp.volume`,dn=`nixamp.listenHere`,fn=1e4,pn=!1;function B(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function mn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`;document.body.classList.toggle(`classroom-embed`,e);let t=null;try{t=localStorage.getItem(ot)}catch{}let n=st(navigator.userAgent,location.search,navigator.maxTouchPoints,t);if(document.body.classList.toggle(`tv`,n),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(ot,n?`1`:`0`)}catch{}let r=document.getElementById(`tv-toggle`);r&&(g(r,()=>n?`TV mode: on`:p(`TV mode`)),r.title=n?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,r.addEventListener(`click`,()=>{try{localStorage.setItem(ot,n?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let i=lt(n),a={status:B(`status`),source:B(`source`),install:B(`install`),video:B(`video`),audio:B(`audio`),title:B(`title-line`),album:B(`album-line`),meta:B(`meta-line`),metaBlurb:B(`meta-blurb`),liveLine:B(`live-line`),downloadNow:B(`download-now`),wayInHere:B(`way-in-here`),embed:B(`embed`),embedFrame:B(`embed-frame`),linkForm:B(`link-form`),linkUrl:B(`link-url`),linkServer:B(`link-server`),linkGoLive:B(`link-go-live`),goLiveNow:B(`go-live-now`),elapsed:B(`elapsed`),total:B(`total`),seek:B(`seek`),fullscreen:B(`fullscreen`),copyNow:B(`copy-now`),copyNixamp:B(`copy-nixamp`),canvas:B(`spectrum`),glyphs:B(`glyphs`),levels:B(`levels`),playlist:B(`playlist`),livePlaylist:B(`live-playlist`),livePlaylistPanel:B(`live-playlist-panel`),playlistPager:B(`playlist-pager`),crumbs:B(`crumbs`),filter:B(`filter`),playlistTitle:B(`playlist-panel`),note:B(`note`),linkNote:B(`link-note`),logList:B(`log-list`),files:B(`files`),folder:B(`folder`),remoteUrl:B(`remote-url`),remoteServer:B(`remote-server`),remoteForm:B(`remote-form`),remoteState:B(`remote-state`),disconnect:B(`disconnect`),browse:B(`browse`),panelsToggle:B(`panels-toggle`),panelsPanel:B(`panels-panel`),panelsList:B(`panels-list`),panelsSave:B(`panels-save`),panelsReset:B(`panels-reset`),accountForm:B(`account-form`),accountEmail:B(`account-email`),accountPassword:B(`account-password`),accountSubmit:B(`account-submit`),accountToggle:B(`account-toggle`),accountProviders:B(`account-providers`),accountPanel:B(`account-panel`),accountElsewhere:B(`account-elsewhere`),welcome:B(`welcome`),welcomeCreate:B(`welcome-create`),welcomeBrowse:B(`welcome-browse`),welcomeHide:B(`welcome-hide`),accountSignOut:B(`account-signout`),accountNote:B(`account-note`),personaForm:B(`persona-form`),personaHandle:B(`persona-handle`),personaVoice:B(`persona-voice`),personaProfile:B(`persona-profile`),personaNote:B(`persona-note`),adminPanel:B(`admin-panel`),adminNote:B(`admin-note`),adminSaid:B(`admin-said`),adminConnections:B(`admin-connections`),publishPanel:B(`publish-panel`),publishNote:B(`publish-note`),publishList:B(`publish-list`),adminRestream:B(`admin-restream`),adminReplace:B(`admin-replace`),adminSource:B(`admin-source`),adminName:B(`admin-name`),adminAdd:B(`admin-add`),homeNote:B(`home-note`),loadHome:B(`load-home`),directory:B(`directory`),recentNote:B(`recent-note`),recentList:B(`recent-list`),followingNote:B(`following-note`),followingList:B(`following-list`),serversPanel:B(`servers-panel`),serversNote:B(`servers-note`),serversList:B(`servers-list`),favoritesPanel:B(`favorites-panel`),favoritesNote:B(`favorites-note`),favoritesList:B(`favorites-list`),favHere:B(`fav-here`),partiesPanel:B(`parties-panel`),partiesNote:B(`parties-note`),partiesList:B(`parties-list`),partyForm:B(`party-form`),partyCode:B(`party-code`),partyJoin:B(`party-join`),connectionsNote:B(`connections-note`),connectionsList:B(`connections-list`),catalogsPanel:B(`catalogs-panel`),catalogsNote:B(`catalogs-note`),catalogsForm:B(`catalogs-form`),catalogSource:B(`catalog-source`),catalogName:B(`catalog-name`),catalogsList:B(`catalogs-list`),catalogsCrumbs:B(`catalogs-crumbs`),catalogsFilter:B(`catalogs-filter`),catalogsEntries:B(`catalogs-entries`),notifyPanel:B(`notify-panel`),notifyNote:B(`notify-note`),notifyWeb:B(`notify-web`),notifyEmail:B(`notify-email`),notifySms:B(`notify-sms`),notifyPhone:B(`notify-phone`),notifyPhoneForm:B(`notify-phone-form`),notifyPhoneNote:B(`notify-phone-note`),directoryNote:B(`directory-note`),directoryList:B(`directory-list`),sharePanel:B(`share-panel`),trollboxPanel:B(`trollbox-panel`),trollboxNote:B(`trollbox-note`),trollboxList:B(`trollbox-list`),trollboxForm:B(`trollbox-form`),trollboxInput:B(`trollbox-input`),trollboxMic:B(`trollbox-mic`),trollboxEdit:B(`trollbox-edit`),trollboxEditLabel:B(`trollbox-edit-label`),transcriptPanel:B(`transcript-panel`),transcriptNote:B(`transcript-note`),transcriptOn:B(`transcript-on`),transcriptLanguage:B(`transcript-language`),transcriptAudio:B(`transcript-audio`),transcriptVoiceSettings:B(`transcript-voice-settings`),transcriptBackground:B(`transcript-background`),transcriptBackgroundLevel:B(`transcript-background-level`),transcriptBackgroundValue:B(`transcript-background-value`),transcriptAudioNote:B(`transcript-audio-note`),transcriptSpeakers:B(`transcript-speakers`),transcriptList:B(`transcript-list`),subtitle:B(`subtitle`),shareNote:B(`share-note`),shareLink:B(`share-link`),shareCopy:B(`share-copy`),sharePhone:B(`share-phone`),shareSend:B(`share-send`),liveControls:B(`live-controls`),goLive:B(`go-live`),stopLive:B(`stop-live`),shareTo:B(`share-to`),listenOnly:B(`listen-only`),listenHere:B(`listen-here`),volume:B(`volume`),volumeToggle:B(`volume-toggle`),prev:B(`prev`),playPause:B(`play-pause`),transport:B(`transport`),stop:B(`stop`),next:B(`next`),shareNow:B(`share-now`),refreshPlayer:B(`refresh-player`),appVersion:B(`app-version`)};a.appVersion.textContent=`nixamp 0.28.36`;let o=(e,t)=>{ae(e,t)};o(a.copyNixamp,`link`);let s=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,c=`local`,l=``,u=[],d=``,m=!0,h=``;function v(e){try{return new URL(e).origin}catch{return e}}let y=!1,b=``,ee=0,te=new Map,ne=e=>te.get(W(e))??null;function re(e,t){let n=n=>{y=n,b=``,a.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),a.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,o(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,o(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:q?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let ie=``,x=[],ce=0,S=je(),le=`idle`,C=``,T=`Pick files, or connect to a nixamp running somewhere else.`,de=!1,E=-1,he=null,ge=0,D=null;function _e(e){return e?/^https?:\/\//i.test(e)?e:F.url(e):``}let ve=0,ye=0,be=!1,xe=()=>!P.needsInteraction&&(ye>0||be);async function Se(e){ye+=1,V();try{return await e()}finally{--ye,V()}}let O=null,k=null,Ce=``,Te=null,Ee=``,A=null,j=null,Oe=0;function Ae(){a.embed.hidden||(a.embedFrame.src=`about:blank`),a.embed.hidden=!0}let Ne=null,Le=``,Re=null;function ze(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Le=i,Re&&clearTimeout(Re),Re=null,!r){if(Ne?.key===i)return;Ne=null}if(c!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(F.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Le!==i)return;Ne={key:i,match:r.match??null},V();let a=Ne.match;a?.kind===`fixture`&&rt(a)!==`post`&&(Re=setTimeout(()=>{Re=null,!(Le!==i||P.source===``&&!D)&&ze(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Be=!1,Ve=``,Ue=``,Ye=null,Xe=``,nt=``,it=``,M=Array(24).fill(0),ct=Array(24).fill(0),dt=[],N=()=>c===`remote`&&!a.listenHere.checked,ft=()=>c===`remote`&&!a.adminPanel.hidden,pt=!1,ht=()=>ft()||c===`remote`&&pt;function _t(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:a.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function xt(){if(c!==`remote`||A)return null;if(O?.catalog&&O.entry)return{kind:`entry`,catalog:O.catalog,entry:O.entry};if(D)return{kind:`channel`,id:D.id,name:D.name};let e=S.tracks[L()];return e&&(P.source!==``||N())?{kind:`track`,index:L(),name:Zt(e)}:null}async function St(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;T=`Putting ${n} on the air…`,V();try{let r=``,i=``,a=!0;{let t=e.kind===`folder`?`/api/folders/live`:e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(F.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),s=await o.json().catch(()=>({}));if(!o.ok){T=o.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:s.error??`${n} would not go on the air.`,V();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(ft()&&(Be?await fetch(F.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await Ao(!0)),await ao(),uo(),i!==``&&D?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await go({id:i,name:n,video:a},!0,t)}let o=wo(r),s=Ve?` Call ${Ue||`the line`} and key ${Ve} to talk about it.`:``;o===``?T=`${n} is on the air and you are watching it.${s}`:(await Co(o,t,`✓`),T=`${n} is on the air and you are watching it. Link copied.${s}`),V()}catch{T=`could not reach the server`,V()}finally{t.disabled=!1}}function Ct(e,t=`Join party`){o(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);g(n,()=>` ${p(t)}`),e.append(n),_(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}Ct(a.partyJoin);function Ut(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,o(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),St(e(),n)}),n}let P=new ke({audio:a.audio,video:a.video},{readable:e=>F.owns(e),onTime:(e,t)=>{let n=x[ce];c===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{_o()||Yn()||hn()||c===`remote`&&E<0&&!N()||yn(1)},onState:()=>V(),onBusy:e=>{be!==e&&(be=e,V())},onError:e=>{if(!_o()&&!(Oe!==0&&Date.now()-Oe<2e3)){if(j&&e===`this browser cannot play that format`){let e=j.url;if(j=null,Oe=Date.now(),ht()){T=`That site will not let a page play it directly; going live with it on ${l||`the server`} instead.`,V(),a.linkUrl.value=e,er();return}T=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,V();return}T=e,V(),mo()}}}),Wt=()=>N()&&!P.jinglePlaying,F=new He({onSnapshot:e=>{let t=e.tracks!==void 0||S.index!==e.index;if(S=Me(S,e),b.startsWith(`track:`)&&S.tracks.length>0){let e=Number(b.slice(6));if(b=``,Number.isInteger(e)&&e>=0&&e<S.tracks.length){let t=ee;_n(e).then(()=>{t>0&&(P.seek(t),setTimeout(()=>P.seek(t),600))})}}Wt()&&(M=e.bars.length>0?e.bars:M,ct=et(ct,M)),V(),t&&k&&fo(k)},onStatus:(e,t)=>{le=e,C=t??``,V()}}),I=()=>c===`remote`?S.tracks.length:x.length,L=()=>c===`remote`?N()||E<0?S.index:Math.min(E,Math.max(0,S.tracks.length-1)):ce,qt=()=>{let e=k?.server.nowPlaying||`Live`;return(!Te||Te.tracks!==S.tracks||Te.index!==S.index||Te.fallback!==e)&&(Te={tracks:S.tracks,index:S.index,fallback:e,value:me(S.tracks,S.index,e)}),Te.value},R=()=>c===`remote`&&!D&&O?.kind===`live`,z=()=>R()?qt().fullTitle:$t(),Zt=e=>{let t=se(e);return e.folder?`${e.folder} / ${t}`:t},$t=()=>{if(D){let e=D.id,t=k?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||D.name}if(A)return A.label;if(R())return qt().title;let e=c===`remote`?S.tracks[L()]:x[L()];return e?Zt(e):p(`Nothing loaded.`)},en=()=>{if(D)return`live on this server`;if(A)return`playing here, in this browser`;if(R()){let{context:e,position:t}=qt();return[e,t,`live on ${l||`this server`}`].filter(Boolean).join(` · `)}return(c===`remote`?S.tracks[L()]:x[L()])?.album||`—`};function tn(){if(c!==`remote`||D===null&&O?.kind!==`live`){a.liveLine.hidden=!0,a.liveLine.replaceChildren(),delete a.liveLine.dataset.drawn;return}let e=l||`this server`,t=D?D.name:qt().fullTitle,n=[D?`Live on ${e}: `:`Live from ${e}, now playing: `,jo(t)],r=D?k?.channels.find(e=>e.id===D?.id)?.code??``:Be?Ve:``;r&&n.push(`. To talk about it, call `,jo(Ue||`the line`),` and key `,jo(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);a.liveLine.dataset.drawn!==i&&(a.liveLine.dataset.drawn=i,a.liveLine.hidden=!1,a.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let nn=()=>N()?S.tracks[L()]?.duration??0:P.duration,rn=()=>N()?S.position:P.position,an=()=>N()?S.playing:P.playing;async function mn(e){if(c===`remote`){if(N()){await F.send({type:`play`,index:e});return}await _n(e);return}let t=x[e];t&&(ce=e,D=null,O={kind:`file`},await Se(()=>P.load(t,!0)),Wn(t.video),Gn(),V())}function hn(){return!he||he.length<2?!1:(ge=(ge+1)%he.length,mn(he[ge]),!0)}function gn(e){e.length!==0&&(he=[...e],ge=0,mn(he[0]))}async function _n(e){let t=S.tracks[e];t&&(E=e,D=null,O={kind:`file`},ze(t.title,`auto`),await Se(()=>P.load({title:Zt(t),artist:t.artist,album:t.album,duration:t.duration,url:F.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Wn(t.video===!0),Gn())}async function vn(){if(P.needsInteraction){await P.play(),V();return}if(N()){await F.send({type:`toggle`});return}I()!==0&&(P.playing?P.pause():P.position>0?await P.play():await mn(L()),V())}async function yn(e){he=null;let t=I();if(t!==0){if(N()){await F.send({type:e>0?`next`:`prev`});return}await mn((L()+e+t)%t)}}async function bn(){if(he=null,Ae(),A=null,j=null,N()){await F.send({type:`stop`});return}D=null,O=null,P.stop(),M=Array(24).fill(0),ct=[...M],V()}let xn=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Sn=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],Cn=``;function wn(){let e=[],t=``,n=null,r=D?k?.channels.find(e=>e.id===D?.id):void 0;D&&r?.ended&&Ee!==D.id&&(Ee=D.id,Lr(`${D.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=P.source===``&&!D&&!(N()&&S.tracks[L()]);if(!i){D&&r?.ended?e.push(`ENDED`):D?e.push(O?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):O?.kind===`vod`?e.push(`ON DEMAND`):O?.kind===`live`?e.push(`LIVE`):c===`remote`&&N()?e.push(`ON THE SERVER`):e.push(`FILE`),!a.video.hidden&&a.video.videoWidth>0?e.push(`${a.video.videoWidth}×${a.video.videoHeight}`):a.video.hidden?e.push(`audio`):e.push(`video`),r?(e.push(r.via===`pull`?`${r.listeners} watching`:`${r.listeners} listening · over ${r.via}`),r.startedAt>0&&e.push(`on air ${oe(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),ft()&&r.error&&e.push(r.error)):c===`remote`&&!D?(S.tracks[L()]&&I()>0&&e.push(`${R()?`library track`:`track`} ${L()+1} of ${I()}`),N()&&k&&e.push(`${k.server.playing?`playing`:`stopped`} on ${l||`the server`}`)):c===`local`&&I()>0&&e.push(`track ${L()+1} of ${I()}`),O?.catalog!==void 0&&(O.kind===`channel`?D!==null:O.kind===`vod`&&P.source!==``)&&O?.catalog&&(e.push(O.entry?.group?`${O.catalog.name} › ${O.entry.group}`:O.catalog.name),t=O.entry?.logo??``),t===``&&D&&(t=_e(r?.art??D.art));let i=Ne?.key===Le?Ne.match:null;if(i?.kind===`fixture`)n=at(i),e.unshift(n.status,...n.chips);else if(i){i.image&&(t=i.image);let n=i.data;if(i.kind===`title`){i.year&&e.push(String(i.year));let t=typeof n.rating==`number`?n.rating:null;t&&e.push(`★ ${t.toFixed(1)}`);let r=Array.isArray(n.genres)?n.genres.slice(0,2).map(String):[];r.length&&e.push(r.join(` · `));let a=typeof n.runtimeMin==`number`?n.runtimeMin:0;a&&e.push(`${a} min`)}else if(i.kind===`channel`){let t=typeof n.country==`string`?n.country:``,r=Array.isArray(n.categories)?n.categories.slice(0,2).map(String):[],i=typeof n.network==`string`?n.network:``;t&&e.push(t),r.length&&e.push(r.join(` · `)),i&&e.push(i)}}if(D&&O?.link){let t=``;try{t=new URL(O.link.url).hostname.replace(/^www\./,``)}catch{}e.push(O.link.extractor&&O.link.extractor!==`direct`&&O.link.extractor!==`generic`?`${O.link.extractor} · ${t}`:t||`link`)}Be&&Ve&&N()&&!D&&O?.kind!==`live`&&e.push(Ue?`☎ ${Ue} · key ${Ve}`:`☎ code ${Ve}`)}let o=Ne?.key===Le?Ne.match:null,s=!i&&!n&&o?.summary?o.summary:``,u=e.map(e=>/^on air \d/.test(e)?`on air`:e),d=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${u.join(`|`)}|${s}`;if(d===Cn){let t=a.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}Cn=d,a.meta.hidden=e.length===0,a.metaBlurb.textContent=s,a.metaBlurb.hidden=s===``;let f=[];if(n){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let r=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,r.push(i),n?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),r.push(t)}if(e.logo!==``){let n=document.createElement(`img`);n.className=`meta-team-logo`,n.alt=``,n.src=e.logo,n.addEventListener(`error`,()=>{n.hidden=!0}),t?r.unshift(n):r.push(n)}return r},r=document.createElement(`span`);r.className=`meta-dash`,r.textContent=`–`,e.replaceChildren(...t(n.away,!0),r,...t(n.home,!1)),f.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&t===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let t of e){let e=document.createElement(`span`);e.className=/^on air \d/.test(t)?`meta-chip meta-chip-clock`:n?.state===`in`&&t===n.status?`meta-chip chip-live`:`meta-chip`,e.textContent=t,f.push(e)}a.meta.replaceChildren(...f)}function V(){let e=I(),t=an(),n=xe();g(a.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),a.status.dataset.playing=n?`loading`:String(t),g(a.title,()=>$t()),a.title.classList.toggle(`with-context`,R()),a.album.classList.toggle(`with-context`,R()),(R()||D)&&Gn(),tn(),wn(),a.goLiveNow.hidden=!ht()||D!==null||R()||xt()===null;let r=t?`${z()} · ${s}`:s;document.title!==r&&(document.title=r),a.copyNow.hidden=P.source===``,a.copyNixamp.hidden=Ki()===``,a.shareNow.hidden=Gi()===``,wi(),Li(),a.downloadNow.hidden=!(D&&O?.link?.download),Zn(),a.album.textContent=en();let i=rn(),o=nn();a.elapsed.textContent=oe(i),a.total.textContent=o>0?oe(o):`--:--`,de||(a.seek.value=String(o>0?Math.round(i/o*1e3):0),a.seek.disabled=o<=0||N()),a.playPause.textContent=t?`❚❚`:`▶`,_(a.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),_(a.seek,`aria-valuetext`,()=>`${oe(P.position)} ${f.language===`en`?`of`:`/`} ${oe(P.duration)}`),_(a.volume,`aria-valuetext`,()=>f.number(Number(a.volume.value)/100,{style:`percent`})),_(a.playlistTitle,`data-title`,()=>c===`remote`?`Files on ${l||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),g(a.source,()=>c===`remote`?`connected · ${l||F.address.replace(/^https?:\/\//,``)||`—`}`:x.length>0?`local · ${x.length} files`:p(`no source`)),Un(),g(a.remoteState,()=>c===`remote`?`${le}${C?` — ${C}`:``}`:p(`not connected`)),a.remoteState.dataset.status=c===`remote`?le:`idle`,a.disconnect.hidden=c!==`remote`;let u=P.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:c===`remote`&&S.note!==``?S.note:T;a.note.textContent=u,a.note.hidden=u===``,a.linkNote.textContent=u,a.linkNote.hidden=u===``,Lr(u),Ln(),a.glyphs.textContent=M.map(Sn).join(``);let[d,m]=Wt()?S.levels:P.levels();a.levels.textContent=xn(d,m)}let Tn=``,H=``,En=0;function Dn(e){ue(a.playlist),H=e,En=0,Tn=``,Ln()}function On(e,t,n,r,i){if(a.playlistPager.hidden=n<=1,n<=1){a.playlistPager.replaceChildren();return}let o=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{ue(a.playlist),En=t,Tn=``,Ln()}),i},s=document.createElement(`span`);s.className=`pager-where`,g(s,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),a.playlistPager.replaceChildren(o(`‹ Previous`,t-1,`The page before this one`),s,o(`Next ›`,t+1,`The page after this one`))}function kn(e){if(a.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>Dn(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),a.crumbs.replaceChildren(...r)}function An(e,t,n){let r=document.createElement(`li`);r.className=`folder`;let i=document.createElement(`span`);i.className=`name`,i.textContent=`${e}/`;let a=document.createElement(`span`);a.className=`count`,a.textContent=`${t} file${t===1?``:`s`}`,r.append(i,a);let s=document.createElement(`button`);if(s.type=`button`,s.className=`row-main`,s.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),s.append(i,a),r.replaceChildren(s),s.addEventListener(`click`,t=>{t.stopPropagation(),Dn(H===``?e:`${H}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,o(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),gn(n)}),r.append(i)}return c===`remote`&&n.length>0&&ht()&&r.append(Ut(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let jn=null,Mn=``,Nn=``,Pn=[],Fn=(e,t)=>{t.title=t.textContent??``,sn(e,t)};function In(e,t){let n=document.createElement(`span`);n.className=`name row-file`,n.textContent=e;let r=document.createElement(`span`);r.className=`row-path`,r.textContent=t;let i=document.createElement(`span`);i.className=`row-label`;let a=document.createElement(`span`);a.className=`row-value`,a.append(n);let o=document.createElement(`span`);return o.className=`row-value`,o.append(r),i.append(a),Fn(a,n),Fn(o,r),{label:i,pathView:o}}function Ln(){let e=(D?k?.channels.find(e=>e.id===D?.id):void 0)?.playlist,t=!!(D&&e?.length);a.livePlaylistPanel.hidden===t&&(a.livePlaylistPanel.hidden=!t);let n=t?D.id:``,r=t?e:[];if(Nn!==n||Pn.length!==r.length||Pn.some((e,t)=>e!==r[t])){Nn=n,Pn=r;let e=r.map((e,t)=>{let n=document.createElement(`li`);n.className=`row file-row live-file-row`,n.dataset.index=String(t);let r=document.createElement(`span`);r.className=`n`,r.textContent=String(t+1);let{label:i,pathView:a}=In(e.slice(e.lastIndexOf(`/`)+1),e),o=document.createElement(`span`);return o.className=`row-main`,o.append(i,r),n.append(o,a),n});w(a.livePlaylist,...e)}let s=c===`remote`?S.tracks:x,l=`${c}:${D?.id??``}:${H}:${a.filter.value}:${En}:${ht()}:${a.adminPanel.hidden}`;if(Tn&&jn===s&&Mn===l){Rn();return}jn=s,Mn=l;let u=c===`remote`?S.tracks.map(e=>({name:se(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):x.map(e=>({name:se(e),seconds:e.duration,group:``,folder:``,remote:!1})),d=a.filter.value.trim().toLowerCase(),f=u.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>d===``||`${e.folder}/${e.name}`.toLowerCase().includes(d)),p=e=>d!==``||H===``||e===H||e.startsWith(`${H}/`),m=e=>e===H,h=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},g=new Map;for(let e of f){if(!p(e.folder)||m(e.folder))continue;let t=h(e.folder);t!==``&&g.set(t,(g.get(t)??0)+1)}let _=f.filter(e=>m(e.folder)&&p(e.folder)),v=[...g].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),y=ut(v.length+_.length,En,i);En=y.page;let b=v.slice(y.from,y.to),ee=_.slice(Math.max(0,y.from-v.length),Math.max(0,y.to-v.length)),te=`${c}:${H}:${d}:${y.page}/${i}:${v.join(`,`)}:${_.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==Tn){Tn=te,kn(d===``&&(v.length>0||H!==``)),On(v.length+_.length,y.page,y.pages,y.from,y.to);let e=[];for(let[t,n]of b){let r=H===``?t:`${H}/${t}`,i=f.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(An(t,n,i))}let t=``,n=_.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(zn(r.group)));let i=document.createElement(`li`);i.className=`row`,i.dataset.index=String(r.index);let a=document.createElement(`span`);a.className=`n`,a.textContent=String(r.index+1).padStart(2,` `);let s=r.folder?`${r.folder} / ${r.name}`:r.name,{label:l,pathView:u}=In(r.name,r.folder?`${r.folder}/${r.name}`:r.name),d=document.createElement(`span`);d.className=`time`,d.textContent=r.seconds>0?oe(r.seconds):`--:--`;let f=document.createElement(`button`);f.type=`button`,f.className=`row-main`,f.setAttribute(`aria-label`,`Play ${s}${r.seconds>0?`, ${oe(r.seconds)}`:``}`),f.append(l,a,d),i.append(f);let p=document.createElement(`span`);p.className=`row-play-glyph`,o(p,`play`),i.append(p),c===`remote`&&ht()&&D===null&&!R()&&i.append(Ut(()=>({kind:`track`,index:r.index,name:s}),s)),i.classList.add(`file-row`),i.append(u),e.push(i)}w(a.playlist,...e)}Rn()}function Rn(){let e=D?k?.channels.find(e=>e.id===D?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(a.livePlaylist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,i),n.classList.toggle(`live-file-current`,i),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}for(let n of Array.from(a.playlist.children)){let r=n,i=Number(r.dataset.index),a=S.tracks[i],o=a?`${a.folder?`${a.folder}/`:``}${se(a)}`:``,s=!!o&&o===e.playlist[t];r.classList.toggle(`selected`,s),r.classList.toggle(`playing`,!1),s?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}return}for(let e of Array.from(a.livePlaylist.children)){let t=e;t.classList.remove(`selected`,`playing`,`live-file-current`),t.removeAttribute(`aria-current`)}let t=L(),n=an();for(let e of Array.from(a.playlist.children)){let r=e,i=Number(r.dataset.index),a=Number.isInteger(i)&&i===t;r.classList.toggle(`selected`,a),r.classList.toggle(`playing`,a&&n),a?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}}function zn(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!a.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,r=>{r.stopPropagation(),So(t,n,()=>Bn(e),()=>Ln())}),t.append(n)}return t}async function Bn(e){try{let t=await fetch(F.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();return U(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`),t.ok}catch{return U(`could not reach the server`),!1}}function Vn(){let e=a.canvas,t=Math.min(2,globalThis.devicePixelRatio||1),n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);n>0&&r>0&&(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);if(Wt())ct=et(ct,M);else{let e=P.read();e.length>0&&(dt.length!==25&&(dt=Ze(24,e.length)),M=$e(M,Qe(e,dt)),ct=et(ct,M))}if(i){let t=getComputedStyle(document.documentElement);tt(i,{width:e.width,height:e.height},M,ct,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(an()||P.jinglePlaying){a.glyphs.textContent=M.map(Sn).join(``);let[e,t]=Wt()?S.levels:P.levels();a.levels.textContent=xn(e,t)}if(an()){a.elapsed.textContent=oe(rn());let e=nn();!de&&e>0&&(a.seek.value=String(Math.round(rn()/e*1e3)))}requestAnimationFrame(Vn)}let Hn=``;function Un(){if(c!==`remote`){a.wayInHere.hidden=!0,Hn=``;return}let e=ft()&&!y,t=ie||F.address,n=e?null:ne(F.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Hn)return;Hn=r;let[i,o]=re({name:l||`this server`,view:t,admin:n});i.hidden=!e,o.hidden=e,a.wayInHere.replaceChildren(i,o),a.wayInHere.hidden=!1}function Wn(e){a.video.hidden=!e,a.fullscreen.hidden=!e,Ae(),A=null,j=null}function Gn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=D?_e(k?.channels.find(e=>e.id===D?.id)?.art??D.art):``,t=JSON.stringify([$t(),en(),e]);t!==Ce&&(Ce=t,navigator.mediaSession.metadata=new MediaMetadata({title:$t(),album:en(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void vn()),navigator.mediaSession.setActionHandler(`pause`,()=>void vn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void yn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void yn(-1)))}document.addEventListener(`click`,()=>{P.resumeAfterInteraction().catch(()=>{})}),a.filter.addEventListener(`input`,()=>{En=0,Tn=``,Ln()}),a.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),a.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(he=null,mn(n))}),a.fullscreen.addEventListener(`click`,()=>{let e=a.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),a.prev.addEventListener(`click`,()=>void yn(-1)),a.next.addEventListener(`click`,()=>void yn(1)),a.stop.addEventListener(`click`,()=>void bn()),a.playPause.addEventListener(`click`,()=>void vn());async function Kn(e){let t=vt(e,_t());if(!t){if(!ht()){T=c===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,V();return}await Xn(e);return}if(D=null,P.stop(),t.kind===`embed`){O={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Wn(!1),a.embedFrame.src=t.src,a.embed.hidden=!1,A={url:e,label:t.label,kind:`embed`},T=`Playing ${t.label} here, in this browser.`,V();return}if(t.kind===`list`){await qn(e,t.label);return}O={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Se(()=>P.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Wn(t.video),A={url:e,label:t.label,kind:`direct`},T=`Playing ${t.label} here, in this browser.`,V()}async function qn(e,t){T=`Reading ${t}…`,V();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){T=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,V();return}let r=gt(n,e);if(r.entries.length===0){T=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,V();return}j={url:e,title:r.title||t,entries:r.entries,at:0},await Jn()}async function Jn(){let e=j,t=e?.entries[e.at];if(!e||!t)return;let n=mt(t.url);O={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Se(()=>P.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),j!==null&&(Wn(n),A={url:e.url,label:e.title,kind:`direct`},j=e,T=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,V())}function Yn(){let e=j;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Jn(),!0)}async function Xn(e){if(c!==`remote`){T=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}T=`Asking ${l||`the server`} to fetch ${e}…`,V(),await Se(async()=>{let t,n={};try{t=await fetch(F.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!t.ok||!n.channel){T=n.error??`that link would not play.`;return}try{await fetch(F.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await go({id:n.channel,name:n.name||e,video:n.video!==!1,art:n.art},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(T=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),V()}a.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.linkUrl.value.trim();t!==``&&Kn(t)});function Zn(){let e=c===`remote`?F.address:``,t=u.filter(t=>v(t.url)!==v(e)),n=JSON.stringify({here:e,name:l,carries:m,others:t});if(n===d||document.activeElement===a.linkServer)return;d=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${l||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}a.linkServer.replaceChildren(...r),a.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,a.linkServer.hidden=t.length===0}function Qn(){let e=c===`remote`?v(F.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!u.some(t=>v(t.url)===e)){let n=document.createElement(`option`);n.value=F.address,n.textContent=l||e,t.push(n)}for(let e of u){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}a.remoteServer.replaceChildren(...t);let r=u.find(t=>v(t.url)===e);a.remoteServer.value=r?.url??``}async function $n(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;u=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Zn(),Qn()}catch{}}async function er(){let e=a.linkUrl.value.trim()||A?.url||``;if(e===``){T=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=a.linkServer.value;if(t!==``&&(c!==`remote`||v(t)!==v(F.address))){let n=u.find(e=>e.url===t)?.name??t;h=e,T=`Connecting to ${n} to go live with it…`,V(),tr(t);return}if(c!==`remote`){T=u.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,V();return}if(!m){T=`${l||`This server`} has no ffmpeg, so it cannot carry a link.`+(u.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!ht()){T=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await Xn(e)}function tr(e){let t=a.linkUrl.value.trim();y=!0,b=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit(),a.linkUrl.value=t}a.linkGoLive.addEventListener(`click`,()=>{er()}),a.linkServer.addEventListener(`change`,()=>{let e=a.linkServer.value;e!==``&&tr(e)}),a.downloadNow.addEventListener(`click`,()=>{let e=O?.link;if(!e||c!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(F.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),T=`Fetching it through the server; your browser will save it when it arrives.`,V()}),a.goLiveNow.addEventListener(`click`,()=>{let e=xt();e&&St(e,a.goLiveNow)}),a.seek.addEventListener(`input`,()=>{de=!0}),a.seek.addEventListener(`change`,()=>{let e=nn();e>0&&P.seek(Number(a.seek.value)/1e3*e),de=!1}),a.volume.addEventListener(`input`,()=>{let e=Number(a.volume.value)/100;P.volume=e,a.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),a.volumeToggle.textContent=e===0?`🔇`:`🔊`,_(a.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(un,String(e))}catch{}}),a.volumeToggle.addEventListener(`click`,()=>{let e=Number(a.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(un));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}a.volume.value=e?String(t):`0`,a.volume.dispatchEvent(new Event(`input`))}),a.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let nr=e=>{e.addEventListener(`change`,()=>{let t=we(Array.from(e.files??[]));if(t.length===0){T=`Nothing playable in that selection.`,V();return}De(x),x=t,ce=0,c=`local`,F.close(),lo(!1),T=``,mn(0)})};nr(a.files),nr(a.folder),a.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.remoteUrl.value,{base:n,key:r}=Ie(t);if(n===``){T=`That is not an address.`,V();return}(async()=>{le=`connecting`,V();let e=Je(n);if(e){le=`error`,C=e,T=e,h=``,c=`local`,V();return}if(await qe(n,void 0,r)===null){le=`error`;let e=Ge(n);C=e?`needs the server's name`:`not answering`,T=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,c=`local`,V();return}let i=await Ke(n,r);if(i){le=`error`,C=i,T=i,h=``,c=`local`,V();return}c=`remote`,T=``;try{localStorage.setItem(cn,t.trim())}catch{}F.connect(t),lo(!0),aa(),mr(),ao(),V()})()}),a.remoteServer.addEventListener(`change`,()=>{let e=a.remoteServer.value;e!==``&&(y=!1,b=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit())});let rr=``,ir=null,ar=async(e=!1)=>{a.directory.hidden=!1,e||(a.directoryNote.textContent=`Looking for live streams…`,w(a.directoryList)),ir||=setInterval(()=>{!a.directory.hidden&&document.visibilityState===`visible`&&ar(!0)},fn);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],u=t.map(e=>({name:e.name,url:e.url})),Zn();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:q});if(e&&i===rr)return;rr=i,_r(r.recent??[])}catch{e||(a.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(w(a.directoryList),t.length===0){a.directoryNote.textContent=`Nobody is streaming right now.`;return}a.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let s=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?s.push(`playing ${e.nowPlaying}`):s.push(`player idle`),e.code&&s.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=s.join(` · `),i.title=i.textContent,n.append(r,i);let c=e.admin??ne(e.url),l=(t,n=``)=>{y=t,b=n,a.remoteUrl.value=t?e.url:c??e.url,a.directory.hidden=!0,document.body.classList.remove(`route-directory`),a.remoteForm.requestSubmit()},u=document.createElement(`ul`);u.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let s=e.lineup?.find(e=>e.name===t);if(s?.art&&/^https?:\/\//i.test(s.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=s.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}s?.about&&(r.title=s.about);let d=document.createElement(`button`);d.type=`button`,d.className=`icon`,o(d,`party`),d.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),d.title=`Join live: ${t} on ${e.name}`,d.addEventListener(`click`,()=>l(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,o(f,`link`),f.setAttribute(`aria-label`,`Copy live room link for ${t}`),f.title=`Copy a nixamp link to this live room`;let p=`${globalThis.location.origin}/?url=${encodeURIComponent(e.url)}&play=${encodeURIComponent(`channel:${s?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),Co(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,o(m,`copy`),m.setAttribute(`aria-label`,`Copy raw stream URL for ${t}`),m.title=`Copy the raw stream URL for VLC or another player`;let h=e.url;try{let n=new URL(e.url);n.pathname=`/api/channels/${encodeURIComponent(s?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),Co(h,m,`✓`)}),n.append(r,d,f,m),s?.startedBy&&q&&s.startedBy===q&&c){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,o(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),l(!1,`channel:${s?.id??t}`)}),n.append(e)}u.append(n)}let[d,p]=re({name:e.name,view:e.url,admin:c},()=>{a.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(n,d,p),q&&t.append(Fr(e.url,e.name)),e.ownerId&&q&&e.ownerId!==q&&t.append(ya(e.ownerId,e.name)),u.childElementCount>0&&t.append(u),e.ownerId&&q&&e.ownerId===q){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));a.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{a.directoryNote.textContent=`could not reach the directory`}finally{await ar()}})()}),t.append(n)}a.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!a.directory.hidden&&ar(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),ar()}let or=null,sr=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,cr=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,lr=``,ur=``,dr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===lr)return;lr=t,a.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}a.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[sr(t.network),`network-${t.network}`],[cr(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}a.adminConnections.append(e)}};function U(e){a.adminSaid.textContent=e,a.adminSaid.hidden=e===``}let fr=async()=>{try{let e=await fetch(F.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;a.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,dr(t.connections??[]),pr(t.publish??[],(t.channels??[]).map(e=>e.id)),ko(t.home??``,t.root??``),uo()}catch{a.adminNote.textContent=`lost touch with the server`}};function pr(e,t){a.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===ur)return;if(ur=n,e.length===0){w(a.publishList);return}let r=e.length-t.length;a.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,w(a.publishList,...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,g(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let mr=async()=>{if(c!==`remote`){a.adminPanel.hidden=!0,a.publishPanel.hidden=!0,or&&clearInterval(or),or=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(F.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;y&&(e=!1),pt=i&&!e;let o=a.partiesList.dataset.adminMode!==String(e);if(a.adminPanel.hidden=!e,o&&(a.partiesList.dataset.adminMode=String(e),a.partiesList.querySelectorAll(`details[open]`).forEach(e=>e.removeAttribute(`open`)),Tr()),io(e),h!==``){let e=h;h=``,ht()?Xn(e):(T=`Sign in to nixamp.com to go live here.`,V())}if(or&&clearInterval(or),or=null,uo(),aa(),ao(),a.listenOnly.hidden=e,!e){a.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}a.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,fr(),or=setInterval(()=>void fr(),2e3)};function hr(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;U(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(F.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),o=await i.json();if(!i.ok){U(o.error??`that did not work`);return}U(`${o.channel?.name||t||e} is on the air.`),a.adminSource.value=``,a.adminName.value=``,ao(),uo()}catch{U(`could not reach the server`)}})()}a.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=a.adminSource.value.trim();t&&hr(t,a.adminName.value.trim())}),a.adminAdd.addEventListener(`click`,()=>{let e=a.adminSource.value.trim();if(!e)return;U(`Reading ${e}…`);let t=a.adminReplace.checked,n=a.adminName.value.trim();(async()=>{try{let r=await fetch(F.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();U(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(a.adminSource.value=``,a.adminName.value=``,ao(),uo())}catch{U(`could not reach the server`)}})()});let gr=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},_r=e=>{let t=[],n=q?e.filter(e=>e.ownerId&&e.ownerId!==q):[];if(a.recentNote.hidden=n.length===0,n.length===0){w(a.recentList);return}for(let e of n){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${gr(e.endedAt)}`:`ended ${gr(e.endedAt)}`,r.append(i,a),n.append(r,ya(e.ownerId,e.name)),t.push(n)}w(a.recentList,...t)},vr=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function yr(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${vr(e.party.positionNow)}`:`❚❚ ${vr(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,Ct(a),a.title=`Join live on the site hosting this party (opens in a new tab)`;let o=document.createElement(`a`);o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.className=`party-row`,n.className=`party-name`,n.title=i.textContent,i.hidden=!0;let s=document.createElement(`details`);s.className=`party-actions`;let c=document.createElement(`summary`);return c.textContent=`⋯`,_(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let br=[],xr=[],Sr=!1,Cr=null,wr=``;function Tr(){let e=new Map,t=(t,n,r)=>{if(!r.length)return;let i=e.get(t);if(i){let e=new Set(i.rows.map(e=>e.dataset.liveKey));i.rows.push(...r.filter(t=>!e.has(t.dataset.liveKey)))}else e.set(t,{name:n,rows:r})},n=c===`remote`&&k?v(F.address):``;for(let e of br){let r=v(e.url);if(!r||r===n)continue;let i=[],o=(t,n)=>{let o=document.createElement(`li`);o.dataset.liveKey=`${r}:${t}`,o.className=`party-row`;let s=document.createElement(`span`);s.className=`party-name`,s.textContent=n,s.title=n;let c=document.createElement(`button`);c.type=`button`,Ct(c),_(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{y=!0,b=t,a.remoteUrl.value=e.url,a.remoteForm.requestSubmit()}),o.append(s,c),i.push(o)};e.playing!==!1&&e.nowPlaying&&o(`live`,pe(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);o(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&k&&t(n,k.server.name||l||n,po(k));for(let e of xr){let n=e.party.origin;try{n=new URL(e.links.partyUrl||e.party.partyUrl).origin}catch{}let r=e.party.origin;try{r=new URL(n).hostname}catch{}let i=yr(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...a.partiesList.children].map(e=>[e.dataset.liveKey,e])),i=[];for(let[t,n]of e){let e=r.get(t);if(!e){e=document.createElement(`li`),e.dataset.liveKey=t,e.className=`party-server`;let n=document.createElement(`h3`),r=document.createElement(`ul`);r.className=`party-rows`,e.append(n,r)}let a=e.querySelector(`h3`);a.textContent!==n.name&&(a.textContent=n.name),fe(e.querySelector(`ul`),n.rows),i.push(e)}fe(a.partiesList,i),a.partiesNote.hidden=e.size>0,e.size||g(a.partiesNote,()=>p(Sr?`No parties live right now.`:`Loading…`))}let Er=5e3,Dr=new Set,Or=(e,t)=>{t?Dr.add(e):Dr.delete(e),Dr.size?a.partiesPanel.dataset.loading=`true`:delete a.partiesPanel.dataset.loading};async function kr(){if(e||(wr!==q&&(Cr?.abort(),Cr=null,xr=[],wr=q,Tr()),Cr))return;let t=new AbortController;Cr=t;let n=!Sr;n&&Or(t,!0);let r=q,i=setTimeout(()=>t.abort(),8e3),o=async e=>{let n=await fetch(e,{signal:t.signal,cache:`no-store`});return{ok:n.ok,status:n.status,body:n.ok?await n.json():null}};try{let[e,n]=await Promise.allSettled([o(`/api/directory`),r?o(`/api/v1/watch-parties`):Promise.resolve(null)]);if(Cr!==t||r!==q||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(br=e.value.body.streams??[],Sr=!0,a.directory.dataset.available=String(br.length>0),no()),n.status===`fulfilled`&&n.value&&(n.value.ok?(xr=n.value.body.parties??[],Sr=!0):[401,403].includes(n.value.status)&&(xr=[])),Tr(),!Sr&&!k&&g(a.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(i),n&&Or(t,!1),Cr===t&&(Cr=null)}}a.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){T=n.error??`No party found with that invite code.`,V();return}a.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{T=`Could not look up that party. Try again.`,V()}})()});async function Ar(){if(!q){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];a.connectionsNote.hidden=t.length===0,a.connectionsList.hidden=t.length===0,w(a.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,g(a,()=>p(`Disconnect`)),a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Ar()})()}),t.append(n,a),t}))}catch{a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0}}let jr=new Set,W=e=>{try{return new URL(e).origin}catch{return e}},Mr=e=>[...jr].some(t=>W(t)===W(e));async function Nr(){if(!q){jr=new Set,a.favoritesPanel.hidden=!0,Ir();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){a.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];jr=new Set(t.map(e=>e.url)),a.favoritesPanel.hidden=t.length===0,a.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,w(a.favoritesList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...re({name:e.name||e.url,view:e.url,admin:ne(e.url)}),Fr(e.url,e.name)),t}))}catch{a.favoritesPanel.hidden=!0}Ir()}async function Pr(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){T=n?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{T=`could not reach nixamp.com`,V();return}if(n)jr.add(e);else for(let t of[...jr])W(t)===W(e)&&jr.delete(t);await Nr()}function Fr(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Mr(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...jr].find(t=>W(t)===W(e))??e;Pr(Mr(e)?i:e,t,!Mr(e)).then(r)}),n}function Ir(){let e=c===`remote`?F.shareLink:``;if(a.favHere.hidden=!(q&&e),a.favHere.hidden)return;let t=Mr(e);a.favHere.textContent=t?`♥`:`♡`,a.favHere.dataset.on=t?`yes`:`no`,a.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,a.favHere.setAttribute(`aria-label`,a.favHere.title)}o(a.copyNow,`copy`),a.copyNow.addEventListener(`click`,()=>{Co(P.source,a.copyNow,`✓`)});function Lr(e){if(e===``||e===it)return;it=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),g(n,()=>r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),a.logList.prepend(t);a.logList.children.length>100;)a.logList.lastElementChild?.remove()}let Rr=3e3,G=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,zr=``,Br=``,Vr=null,Hr=!1,Ur=new Set,Wr=``,Gr=null,Kr=!1,qr=Vt(e=>localStorage.getItem(e)),K=It(e=>localStorage.getItem(e)),Jr=new Set,Yr=new Set,Xr=null,Zr=``,Qr=``,q=``,$r=(()=>{try{let e=sessionStorage.getItem(`nixamp.translationSession`);if(e&&/^listener-[a-f0-9-]{36}$/.test(e))return e;let t=`listener-${crypto.randomUUID()}`;return sessionStorage.setItem(`nixamp.translationSession`,t),t}catch{return`listener-${crypto.randomUUID()}`}})(),ei=null,J=!1,ti=``,ni=!1,ri=!1,ii=``,ai=0,oi=!1,si=!1;try{a.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let ci=new Jt(()=>{si=!0,oi&&(a.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),li=()=>{let e=Number(a.transcriptBackgroundLevel.value);ci.setLevel(e/100),a.transcriptBackgroundValue.value=`${e}%`,_(a.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),a.transcriptBackgroundLevel.disabled=!a.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(a.transcriptBackgroundLevel.value=e)}catch{}li(),a.transcriptBackgroundLevel.addEventListener(`input`,()=>{li();try{localStorage.setItem(`nixamp.backgroundLevel`,a.transcriptBackgroundLevel.value)}catch{}});let Y=new Xt({account:()=>G===``?q:``,changed:()=>Hi()});B(`translation-buy-tools`).append(Y.button()),Y.refresh();let ui=new Yt({reconnecting:()=>X.reset(),line:(e,t)=>{vi=0,yi.push(e),Bi(),X.push(e,t,0)},status:e=>{a.transcriptAudioNote.textContent=e},failed:e=>{ti=e,Qr=e,J=!1,a.transcriptAudio.checked=!1,X.disable(),pi(),a.transcriptAudioNote.textContent=`${e} Original audio restored.`,Y.refresh()}}),X=new Gt({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(ui.audio(String(e))):fetch(e,t)),playing:()=>P.playing,volume:()=>P.volume,active:e=>{oi=e,P.translatedAudio(e),ci.active(e&&P.playing&&a.transcriptBackground.checked)},status:e=>{a.transcriptAudioNote.textContent=e+(si&&oi?` · background unavailable`:``)},failed:()=>{Qr=a.transcriptAudioNote.textContent||`Translated audio stopped.`,J=!1,a.transcriptAudio.checked=!1,pi()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!q||G!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!ei||ei.channel!==t.channel||ei.expires<Date.now()+2e4||ei.remaining<t.text.length){let n=await fetch(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),r=await n.json();if(!n.ok||!r.token||!r.expires)throw Error(r.error||`Sign in to enable translated audio.`);ei={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return ei.remaining-=t.text.length,{authorization:`Bearer ${ei.token}`}}}),di=new Qt({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,$r),fetch(e,{...t,headers:n})},language:()=>K,speakers:()=>a.transcriptAudio.checked,voices:()=>Xr?.voices??[],channel:()=>$r,status:e=>{!ni&&!J&&(ti=e),a.transcriptNote.textContent=e},failed:()=>{J=!1,a.transcriptAudio.checked=!1,X.disable(),pi()},lines:e=>{vi=0,yi.push(...e),Bi(),hi(),a.transcriptAudio.checked&&X.pushBatch(e.map(e=>({line:e,lag:0,url:`/api/v1/speech/synthesize`,init:{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:e.text,language:K,channel:$r,speaker:e.speaker,voice:di.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),fi=new Kt(e=>{ni&&P.playing&&di.push(e)});function pi(){ai++,ni=!1,ri=!1,ii=``,fi.stop(),di.reset(),ui.stop(),ci.stop(),X.reset(),w(a.transcriptSpeakers)}async function mi(){if((ni||ri)&&ii===P.mediaKey)return;pi();let e=ai;ri=!0,ii=P.mediaKey;try{if(!q||G!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=P.audioInput();if(si=!1,a.transcriptAudio.checked&&a.transcriptBackground.checked&&ci.start(t.context,t.node).then(t=>{t&&e===ai&&ci.active(oi&&P.playing&&a.transcriptBackground.checked)}),a.transcriptAudio.checked&&c===`remote`&&D)await ui.start(Wi(),K),Y.refresh();else{if(a.transcriptAudio.checked&&await Y.startSession($r),e!==ai)return;await fi.start(t.context,t.node,a.transcriptAudio.checked?2:5)}if(e!==ai)return;ni=!0,J=!0,vi=0,xi??=setInterval(Bi,250),a.transcriptNote.textContent=a.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==ai)return;J=!1,a.transcriptAudio.checked=!1,X.disable(),pi(),ti=t instanceof Error?t.message:`This audio could not be captured.`,a.transcriptNote.textContent=ti}finally{e===ai&&(ri=!1)}}function hi(){let e=[...di.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(a.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id;let n=document.createElement(`span`),r=t.id.split(`-`)[1];g(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,_(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of Xr?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,X.reset()}),e.append(i),a.transcriptSpeakers.append(e)}a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked;for(let e of a.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[a.audio,a.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(P.showingVideo?a.video:a.audio)&&pi()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(P.showingVideo?a.video:a.audio)&&J&&qr&&P.playing&&mi()});e.addEventListener(`volumechange`,()=>{X.setVolume()})}let gi=``,_i=null,vi=Rt(6,!1),yi=[],bi=[],xi=null;function Si(){if(c!==`remote`)return null;let{base:e}=Ie(To());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=D?D.id:O?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Ci(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${G}/api/v1/trollbox?${n.toString()}`}function wi(){let e=Si(),t=e?`${e.server}|${e.channel}`:``;t!==zr&&(zr=t,Br=``,Ur.clear(),a.trollboxList.replaceChildren(),Vr&&clearTimeout(Vr),Vr=null,a.trollboxPanel.hidden=e===null,a.trollboxForm.hidden=!0,Ai(!1),e&&(g(a.trollboxNote,()=>`The room for ${$t()||e.channel}. Loading…`),Ei()))}function Ti(e){let t=document.createElement(`li`);t.dataset.id=e.id;let n=document.createElement(`time`);n.className=`when`,n.dateTime=e.createdAt;let r=new Date(e.createdAt);g(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`}));let i=document.createElement(`span`);i.className=`who`,i.textContent=e.handle;let a=document.createElement(`span`);return a.className=`line`,a.textContent=e.body,a.dir=`auto`,a.translate=!1,t.append(n,i,a),t}async function Ei(){let e=Si(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===zr&&!Hr){Hr=!0;try{let n=await fetch(Ci(e,Br)),r=await n.json().catch(()=>({}));if(t!==zr)return;if(!n.ok){a.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!Ur.has(e.id));for(let e of i)Ur.add(e.id),a.trollboxList.append(Ti(e)),Br=e.createdAt;for(;a.trollboxList.children.length>200;)a.trollboxList.firstElementChild?.remove();let o=r.you??``,s=Wr!==o;Wr=o,s&&(ei=null,Hi()),a.trollboxForm.hidden=o===``,a.trollboxEditLabel.hidden=o===``||!Di,o===``&&Ai(!1),g(a.trollboxNote,()=>o===``?G===``?`The room for ${$t()||e.channel}. Sign in to say something.`:`The room for ${$t()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${$t()||e.channel}.`)}catch{t===zr&&(a.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Hr=!1,t===zr&&(Vr=setTimeout(()=>{document.visibilityState===`visible`?Ei():Vr=setTimeout(()=>void Ei(),Rr)},Rr))}}}a.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Si(),n=a.trollboxInput.value.trim();t&&n!==``&&(a.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${G}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.message){a.trollboxNote.textContent=r.error??`that did not send`;return}a.trollboxInput.value=``,Ur.has(r.message.id)||(Ur.add(r.message.id),a.trollboxList.append(Ti(r.message)),Br=r.message.createdAt)}catch{a.trollboxNote.textContent=`The trollbox is not answering.`}finally{a.trollboxInput.disabled=!1}})())});let Di=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Oi=Di?jt(e=>MediaRecorder.isTypeSupported(e)):``;a.trollboxMic.hidden=!Di;function ki(e){a.trollboxNote.textContent=e,Lr(e)}function Ai(e){let t=Gr;if(!t)return;Gr=null,clearTimeout(t.stop),clearInterval(t.tick),a.trollboxMic.setAttribute(`aria-pressed`,`false`),a.trollboxMic.textContent=`🎤`;let n=new Promise(e=>{t.recorder.addEventListener(`stop`,()=>e(),{once:!0})});t.recorder.state!==`inactive`&&t.recorder.stop();for(let e of t.stream.getTracks())e.stop();e&&n.then(()=>Mi(new Blob(t.chunks,{type:t.recorder.mimeType||Oi||`audio/webm`}),t.startedAt))}async function ji(){if(Gr||Kr||Wr===``||!Si())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){ki(e.name===`NotAllowedError`?`The microphone was refused. Allow it for nixamp.com and tap again.`:`No microphone could be opened here.`);return}let t;try{t=new MediaRecorder(e,Oi?{mimeType:Oi}:{})}catch{for(let t of e.getTracks())t.stop();ki(`This browser cannot record the microphone.`);return}let n=[];t.addEventListener(`dataavailable`,e=>{e.data.size>0&&n.push(e.data)});let r=Date.now();Gr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ai(!0),At),tick:setInterval(()=>{a.trollboxMic.textContent=Mt(r,Date.now())},500)},t.start(250),a.trollboxMic.setAttribute(`aria-pressed`,`true`),a.trollboxMic.textContent=Mt(r,r),ki(`Listening. Tap the mic again when you have said it (${Math.round(At/1e3)} s at most).`)}async function Mi(e,t){let n=Si();if(n&&Wr!==``){if(Date.now()-t<400||e.size===0){ki(`That was too short to hear. Tap, say it, then tap again.`);return}Kr=!0,a.trollboxMic.disabled=!0,a.trollboxMic.textContent=`…`,ki(`Hearing you…`);try{let t=new AudioContext,r;try{r=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let i=new OfflineAudioContext(1,Math.max(1,Math.ceil(r.duration*kt)),kt),o=i.createBufferSource();o.buffer=r,o.connect(i.destination),o.start();let s=Ot((await i.startRendering()).getChannelData(0),kt),c=a.trollboxEdit.checked,l=new URLSearchParams(c?{}:{server:n.server,channel:n.channel}),u=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(u)&&l.set(`language`,u);let d=await fetch(`${G}/api/v1/speech/transcribe?${l.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([s.buffer],{type:`audio/wav`})}),f=await d.json().catch(()=>({}));if(!d.ok){ki(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){ki(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=a.trollboxInput.value.trimEnd();a.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),ki(`Heard: “${p}”. Send it, or fix it first.`);return}Si()&&!Ur.has(f.message.id)&&(Ur.add(f.message.id),a.trollboxList.append(Ti(f.message)),Br=f.message.createdAt),ki(`Said: “${f.message.body}”`)}catch{ki(`That recording could not be read here.`)}finally{Kr=!1,a.trollboxMic.disabled=!1,a.trollboxMic.textContent=`🎤`}}}a.trollboxMic.addEventListener(`click`,()=>{Gr?Ai(!0):ji()});try{a.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}a.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,a.trollboxEdit.checked?`on`:`off`)}catch{}ki(a.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Ni(){try{let e=await fetch(`${G}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`Could not read your profile.`;return}a.personaHandle.value=t.chosen?t.handle??``:``,_(a.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),a.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,a.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;a.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${Pi(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${Pi(t.voice??``)}${n}.`}catch{a.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function Pi(e){return e===`female`?`in a woman's voice`:e===`male`?`in a man's voice`:e.includes(`.`)?`in the voice ${e}`:`in whichever voice your profile says, or one picked for you`}a.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.personaHandle.value.trim(),n={voice:a.personaVoice.value,profile:a.personaProfile.value.trim()};t!==``&&(n.handle=t),a.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${G}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`that did not save`;return}await Ni()}catch{a.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Gr&&Ai(!0)});function Fi(){return c===`remote`&&D?{id:D.id,name:D.name,hls:D.video&&_t()}:P.loaded||A?{id:$r,name:$t()||`This audio`,hls:!1}:null}function Ii(){pi(),ei=null,Jr.clear(),Yr.clear(),_i?.close(),_i=null,xi&&clearInterval(xi),xi=null,yi=[],bi=[],a.transcriptList.replaceChildren(),a.subtitle.hidden=!0,a.subtitle.textContent=``}function Li(){let e=Fi(),t=`${e?.id??``}|${P.mediaKey}|${qr}|${K}|${a.transcriptAudio.checked}|${J}|${q}`;if(t!==gi){if(gi=t,Ii(),a.transcriptPanel.hidden=!1,a.transcriptOn.checked=qr&&(!!D||J||a.transcriptAudio.checked),a.transcriptLanguage.options.length===0)for(let e of Ft){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),g(t,()=>e.code?e.label:p(`Original (auto-detect)`)),a.transcriptLanguage.append(t)}if(a.transcriptLanguage.value=K,Hi(),Ui(),!e){a.transcriptNote.textContent=`Play something to see its captions.`;return}if(!qr){a.transcriptNote.textContent=`Captions are off.`;return}if(ti){a.transcriptNote.textContent=ti;return}a.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,a.transcriptAudio.checked||J?P.playing?mi():a.transcriptNote.textContent=`Press Play to start listening.`:c===`remote`&&D?Ri(e,t):a.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Ri(e,t){let n=6,r=K?`?language=${encodeURIComponent(K)}`:``;try{let i=await fetch(F.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),o=await i.json().catch(()=>({}));if(t!==gi)return;if(!i.ok){a.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){q&&G===``?(J=!0,Li()):a.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=o.backlog??n}catch{t===gi&&(a.transcriptNote.textContent=`The server did not answer about captions.`);return}vi=Rt(n,e.hls);let i=new EventSource(F.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));_i=i;let o=(e,t=!1)=>{for(let n of e){if(!n||typeof n.text!=`string`||!Number.isFinite(n.at)||!Number.isFinite(n.until))continue;let e=`${n.at}|${n.language}`;Jr.has(e)||(Jr.add(e),Jr.size>600&&Jr.delete(Jr.values().next().value),yi.push(n),t&&a.transcriptAudio.checked&&Yr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==gi)return;let i=JSON.parse(r.data);vi=Rt(i.backlog??n,e.hls),o(i.lines??[]);let s=Ft.find(e=>e.code===i.language)?.label??i.language,c=Ft.find(e=>e.code===K)?.label??K;if(a.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:K?`${s||`Detected audio`} → ${c}`:`Original audio · ${s||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${G||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,a.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==gi)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=Ft.find(e=>e.code===i)?.label??i,c=Ft.find(e=>e.code===K)?.label??K;a.transcriptNote.textContent=K?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===gi&&i.readyState===EventSource.CLOSED&&(a.transcriptNote.textContent=`Captions stopped; the server went away.`)}),xi=setInterval(Bi,250)}function zi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),g(n,()=>Ht(e.at));let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text,r.dir=`auto`,r.translate=!1,(e.language||e.sourceLanguage)&&(r.lang=e.language||e.sourceLanguage);let i=Lt(e);if(i){let a=document.createElement(`span`);a.className=`lang`,a.textContent=i.trim(),e.original&&(r.title=e.original),t.append(n,a,r)}else t.append(n,r);return t}function Bi(){let e=Date.now(),{ready:t,still:n}=zt(yi,e,vi);yi=n;for(let e of t)if(bi.push(e),a.transcriptList.append(zi(e)),Yr.delete(e)&&a.transcriptAudio.checked&&K){let t=new URLSearchParams({at:String(e.at),language:K,voice:`auto`});X.push(e,F.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),vi)}for(;bi.length>200;)bi.shift();for(;a.transcriptList.children.length>200;)a.transcriptList.firstElementChild?.remove();let r=Bt(bi,e,vi),i=a.transcriptList.children,o=r?bi.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===o);let s=P.playing&&r!==null&&!a.video.hidden&&a.video.offsetHeight>0;a.subtitle.hidden=!s,s&&r&&(a.subtitle.textContent!==r.text&&(a.subtitle.textContent=r.text),a.subtitle.style.top=`${a.video.offsetTop+a.video.offsetHeight-a.subtitle.offsetHeight-10}px`)}a.transcriptOn.addEventListener(`change`,()=>{qr=a.transcriptOn.checked,J=qr&&(!D||a.transcriptAudio.checked),qr||(a.transcriptAudio.checked=!1,X.disable());try{localStorage.setItem(Nt,qr?`on`:`off`)}catch{}Li()}),a.transcriptLanguage.addEventListener(`change`,()=>{ti=``,Qr=``,K=It(()=>a.transcriptLanguage.value),!K&&a.transcriptAudio.checked&&(a.transcriptAudio.checked=!1,J=!1,X.disable());try{K?localStorage.setItem(Pt,K):localStorage.removeItem(Pt)}catch{}Li()});function Vi(){if(K)return K;let e=navigator.language.split(`-`)[0]||`en`;return Ft.some(t=>t.code===e)&&Xr?.languages.includes(e)?e:`en`}function Hi(){let e=q!==``&&G===``,t=e&&Y.loaded()&&!!Fi()&&!!Xr?.languages.includes(Vi());a.transcriptAudio.disabled=!t,a.transcriptVoiceSettings.contains(document.activeElement)||(a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked),t?a.transcriptAudio.checked||g(a.transcriptAudioNote,()=>Qr||p(`Original audio.`)):(a.transcriptAudio.checked=!1,X.disable(),a.transcriptAudioNote.textContent=e?Fi()?Y.loaded()?Qr||(Xr?`Audio translation is unavailable for this language.`:`Loading voices…`):Y.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function Ui(){if(!q||G!==``)return;let e=`/api/v1/speech/voices`;if(Zr!==e){Zr=e,Xr=null,Qr=``,Hi();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(Zr!==e)return;if(!t.ok)throw Error(n.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(n.voices)||!Array.isArray(n.languages))throw Error(`This server needs an update for translated audio.`);Xr=n}catch(t){if(Zr!==e)return;Qr=t instanceof Error?t.message:`Translated audio is unavailable.`}Hi()}}a.transcriptBackground.addEventListener(`change`,()=>{li();try{localStorage.setItem(`nixamp.backgroundSound`,a.transcriptBackground.checked?`on`:`off`)}catch{}if(ci.stop(),si=!1,a.transcriptBackground.checked&&a.transcriptAudio.checked&&P.playing){let e=ai,t=P.audioInput();ci.start(t.context,t.node).then(t=>{t&&e===ai&&ci.active(oi&&P.playing&&a.transcriptBackground.checked)})}}),a.transcriptAudio.addEventListener(`change`,()=>{if(ti=``,Qr=``,Yr.clear(),a.transcriptAudio.checked&&!Y.ready()){a.transcriptAudio.checked=!1,Y.open(a.transcriptAudio);return}if(a.transcriptAudio.checked){K=Vi();try{localStorage.setItem(Pt,K)}catch{}qr=!0,J=!0,X.enable()}else J=!1,X.disable();Li()});function Wi(){if(A)return A.url;if(c!==`remote`)return``;let{base:e,key:t}=Ie(To());if(e===``)return``;if(D)return Pe(e,`/api/channels/${encodeURIComponent(D.id)}`,t);if(O?.kind===`live`)return Pe(e,`/api/live`,t);if(P.source===``)return``;try{let n=new URL(P.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Gi(){let e=Wi();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function Ki(){return c===`remote`?D?wo(`channel:${D.id}`):O?.kind===`live`||R()?wo(`live`):``:``}a.shareNow.addEventListener(`click`,()=>{let e=Gi();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${z()} on nixamp`,url:e}).catch(()=>void 0);return}Co(e,a.shareNow,`Copied`)}),a.copyNixamp.addEventListener(`click`,()=>{let e=Ki();e!==``&&Co(e,a.copyNixamp,`✓`)}),a.favHere.addEventListener(`click`,()=>{let e=To()||F.shareLink;if(!e)return;let t=[...jr].find(t=>W(t)===W(e))??e;Pr(Mr(e)?t:e,l||F.address,!Mr(e)).then(Ir)});let qi=n?i:200,Ji=[],Z=null,Q=null,Yi=``,Xi=[],Zi=0,Qi=null,$i=0,ea=null,ta=null,na=new Map;function ra(e,t){$i++,ea?.abort(),Qi&&clearTimeout(Qi),Qi=null,ue(a.catalogsList),ue(a.catalogsEntries),Z=e,Q=t,Yi=``,a.catalogsFilter.value=``,Xi=[],Zi=0,a.catalogsEntries.setAttribute(`aria-busy`,`false`),sa(),e&&t!==null&&fa(0)}function ia(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}function aa(){let e=F.url(`/api/catalogs`);if(ta?.url===e)return ta.promise;let t=oa(e).finally(()=>{ta?.promise===t&&(ta=null)});return ta={url:e,promise:t},t}async function oa(e){if(c!==`remote`){a.catalogsPanel.hidden=!0;return}let t;try{t=await fetch(e)}catch{e===F.url(`/api/catalogs`)&&(a.catalogsPanel.hidden=!0);return}if(c===`remote`&&e===F.url(`/api/catalogs`)){if(!t.ok){a.catalogsPanel.hidden=!0;return}Ji=(await t.json().catch(()=>({}))).catalogs??[],Z&&=Ji.find(e=>e.id===Z?.id)??null,Z||(Q=null),a.catalogsPanel.hidden=!1,sa()}}function sa(){let e=!a.adminPanel.hidden;a.catalogsForm.hidden=!e;let t=Ji.reduce((e,t)=>e+t.live,0),n=Ji.reduce((e,t)=>e+t.vod,0);a.catalogsNote.textContent=Ji.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Ji.length} ${Ji.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,ca();let r=Z!==null&&Q!==null;if(a.catalogsList.hidden=r,a.catalogsFilter.hidden=!r,a.catalogsEntries.hidden=!r,r){pa();return}if(Z){ua(Z);return}w(a.catalogsList,...Ji.map(t=>la(t,e)))}function ca(){let e=Z!==null;if(a.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>ra(null,null),!1),n(),t(Z?.name??``,()=>ra(Z,null),Q===null)];Q!==null&&r.push(n(),t(Q===``?`All groups`:Q,()=>void 0,!0)),a.catalogsCrumbs.replaceChildren(...r)}function la(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,g(a,()=>[`${e.entries.toLocaleString(f.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(f.language)} live`,`${e.vod.toLocaleString(f.language)} on demand`,`refreshed ${ia(e.refreshedAt)}`].join(` · `)),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.setAttribute(`aria-label`,`Browse ${e.name}`),o.addEventListener(`click`,()=>{ra(e,null)}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{ha(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,g(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&So(n,r,()=>ga(e),()=>void aa())}),n.append(t,r)}return n}async function ua(e){let t=F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,r;a.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=na.get(n);e||(na.size>=20&&na.delete(na.keys().next().value),e=fetch(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),na.set(n,e)),r=await e}catch{if(na.delete(n),Z?.id!==e.id||Q!==null||t!==F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`),T=`Could not read the groups in ${e.name}.`,V();return}if(Z?.id!==e.id||Q!==null||t!==F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`);let i=[da(`All groups`,``,e.entries,e.live,e.vod),...r.map(e=>da(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];w(a.catalogsList,...i)}function da(e,t,n,r,i){let a=document.createElement(`li`),o=document.createElement(`span`);o.className=`server-label`;let s=document.createElement(`span`);s.className=`name`,s.textContent=e;let c=document.createElement(`span`);c.className=`detail`,g(c,()=>`${n.toLocaleString(f.language)} · ${r.toLocaleString(f.language)} live · ${i.toLocaleString(f.language)} on demand`),o.append(s,c);let l=document.createElement(`button`);return l.type=`button`,l.className=`button`,l.textContent=`Open`,l.setAttribute(`aria-label`,`Open ${e}`),l.addEventListener(`click`,()=>{ra(Z,t)}),a.append(o,l),a}async function fa(e){let t=Z,n=Q;if(!t||n===null)return;let r=++$i;ea?.abort();let i=new AbortController;ea=i;let o=F.url(`/api/catalogs`);a.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Yi,offset:String(e),limit:String(qi)}),c;try{let e=await fetch(F.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:i.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(i.signal.aborted||r!==$i)return;a.catalogsEntries.setAttribute(`aria-busy`,`false`),T=`Could not read ${t.name}.`,pa(),V();return}r===$i&&Z?.id===t.id&&Q===n&&o===F.url(`/api/catalogs`)&&(a.catalogsEntries.setAttribute(`aria-busy`,`false`),Zi=c.total??0,Xi=e===0?c.entries??[]:[...Xi,...c.entries??[]],pa())}function pa(){let e=Z;if(!e)return;let t=Xi.map(t=>{let n=document.createElement(`li`);n.className=`row`;let r=document.createElement(`span`);r.className=`name`,r.textContent=t.title;let i=document.createElement(`span`);i.className=t.live?`catalog-tag catalog-live`:`catalog-tag`,i.textContent=t.live?`LIVE`:t.duration>0?oe(t.duration):`VOD`;let a=document.createElement(`button`);if(a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Play ${t.title}`),a.append(r,i),n.append(a),a.addEventListener(`click`,()=>{ma(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,o(r,`copy`),r.title=`Copy this entry's URL`,r.setAttribute(`aria-label`,`Copy the URL of ${t.title}`),r.addEventListener(`click`,n=>{n.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/stream`;Co(F.url(i),r,`✓`)}),n.append(r)}return ht()&&n.append(Ut(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Xi.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Yi?`Nothing called "${Yi}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Xi.length<Zi){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,g(n,()=>`Show more (${Xi.length.toLocaleString(f.language)} of ${Zi.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),ue(a.catalogsEntries,!1),n.disabled=!0,fa(Xi.length)}),e.append(n),t.push(e)}w(a.catalogsEntries,...t)}async function ma(e,t,n){n?.classList.add(`loading`),T=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await Se(async()=>{let n,i={};try{n=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!n.ok){T=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await go({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){D=null,E=-1,O={kind:`vod`,...r},ze(a,`title`),await P.load({title:a,artist:``,album:``,duration:0,url:F.url(i.url),video:!0,objectUrl:!1},!0),Wn(!0),T=`Playing ${a}.`;return}T=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),V()}}async function ha(e){U(`Reading ${e.name} again…`);try{let t=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));U(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(f.language)} entries.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}aa()}async function ga(e){try{let t=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(U(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return U(`could not reach the server`),!1}return Z?.id===e.id&&(Z=null,Q=null),!0}a.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.catalogSource.value.trim(),n=a.catalogName.value.trim();t&&(async()=>{U(`Reading ${n||t}…`);try{let e=await fetch(F.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){U(r.error??`that did not work`);return}U(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`),a.catalogSource.value=``,a.catalogName.value=``}catch{U(`could not reach the server`)}aa()})()}),a.catalogsFilter.addEventListener(`input`,()=>{$i++,ea?.abort(),Qi&&clearTimeout(Qi),Qi=setTimeout(()=>{Qi=null,Yi=a.catalogsFilter.value.trim(),fa(0)},250)});let _a=async()=>{w(a.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){a.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];te=new Map(t.map(e=>[W(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),a.serversPanel.hidden=!1,a.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Arriving signed in, this page connects to your default one, or the first that answers; a link you arrive with goes live there.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=re({name:e.name,view:o,admin:o});qe(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=Pa()===W(e.url),u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=l?`✓ Default`:`Make default`,u.title=l?`The server this page connects to when you arrive signed in. Press to go back to the first that answers.`:`Connect to this server whenever you arrive signed in`,u.addEventListener(`click`,()=>{Fa(l?``:W(e.url)),_a()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await _a()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),a.serversList.append(t)}}catch{a.serversPanel.hidden=!0}},va=async()=>{w(a.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){a.followingNote.hidden=!0;return}let t=(await e.json()).following??[];a.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,g(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),a.followingList.children.length===0&&(a.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),a.followingList.append(t)}}catch{a.followingNote.hidden=!0}},ya=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,g(n,()=>p(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{g(n,()=>e?`Following`:p(`Follow`)),n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),va())}catch{}finally{n.disabled=!1}})()}),n},ba=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},xa=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Sa=async()=>{if(!xa())return a.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return a.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return a.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return a.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ba(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return a.notifyNote.textContent=`This device will be told.`,!0}catch{return a.notifyNote.textContent=`Could not set this device up.`,!1}},Ca=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},wa=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();a.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(a.notifyPhone.value=n.phone)}catch{a.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ta=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();a.notifyEmail.checked=t.wantsEmail!==!1,a.notifySms.checked=t.wantsSms===!0,a.notifyPhone.value=t.phone??``;let n=xa()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;a.notifyWeb.checked=t.wantsWeb!==!1&&n,a.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};a.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(a.notifyWeb.checked){let e=await Sa();a.notifyWeb.checked=e,await wa({wantsWeb:e});return}await Ca(),await wa({wantsWeb:!1}),a.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),a.notifyEmail.addEventListener(`change`,()=>{wa({wantsEmail:a.notifyEmail.checked})}),a.notifySms.addEventListener(`change`,()=>{(async()=>{if(a.notifySms.checked&&!a.notifyPhone.value.trim()){a.notifyPhoneNote.textContent=`Add a phone number first.`,a.notifySms.checked=!1;return}await wa({wantsSms:a.notifySms.checked})})()}),a.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),wa({phone:a.notifyPhone.value.trim()})});let Ea=!1,Da=!1,Oa=`nixamp.welcome`,ka=()=>{let e=!1;try{e=localStorage.getItem(Oa)===`hidden`}catch{}a.welcome.hidden=!Da||q!==``||e},Aa=e=>{let t=e!==null;Y.refresh(),Zr=``,ei=null,t||(J=!1,a.transcriptAudio.checked=!1,X.disable(),pi()),Li(),a.notifyPanel.hidden=!t,t?(Ta(),va(),_a()):(a.serversPanel.hidden=!0,a.followingNote.hidden=!0,w(a.followingList),a.recentNote.hidden=!0,a.recentList.replaceChildren()),a.accountForm.hidden=t,a.accountProviders.hidden=t||a.accountProviders.childElementCount===0,a.accountSignOut.hidden=!t,a.personaForm.hidden=!t,a.personaNote.hidden=!t,t&&Ni(),a.accountNote.textContent=t?`Signed in as ${e}.`:Ea?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,g(a.accountSubmit,()=>p(Ea?`Create account`:`Sign in`)),g(a.accountToggle,()=>Ea?`I have one`:p(`Create one`)),a.accountPassword.autocomplete=Ea?`new-password`:`current-password`,ka()},ja=async()=>{let e=[];Da=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Da=!0,e=(await t.json()).providers??[])}catch{}a.accountProviders.replaceChildren(),a.accountProviders.hidden=e.length===0,a.accountPanel.hidden=!Da,a.accountElsewhere.hidden=Da,ka();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,a.accountProviders.append(e)}},Ma=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();q=e.ok?t.account?.id??``:``,Aa(e.ok?t.account?.email??`you`:null)}catch{q=``,Aa(null)}if(F.session=``,q!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));F.session=e.ok&&typeof t.token==`string`?t.token:``}catch{F.session=``}c===`remote`&&mr()}Nr(),kr(),Ar(),Ia();let e=await Na();if(nt!==``){let t=nt;nt=``,e?b=`golive:${t}`:Kn(t)}};async function Na(){if(q===``||c===`remote`||Xe!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=Pa(),n=[...e].sort((e,n)=>Number(W(n.url)===t)-Number(W(e.url)===t));for(let e of n)if(await qe(e.url,void 0,e.key)!==null)return c!==`remote`&&(y=!1,b=``,a.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,T=`Connecting to ${e.name}, your server…`,V(),a.remoteForm.requestSubmit(),!0);return!1}function Pa(){try{return localStorage.getItem(ln)??``}catch{return``}}function Fa(e){try{e===``?localStorage.removeItem(ln):localStorage.setItem(ln,e)}catch{}}function Ia(){if(Xe===``)return;let e=Xe;Xe=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit()}a.accountToggle.addEventListener(`click`,()=>{Ea=!Ea,Aa(null)}),a.welcomeCreate.addEventListener(`click`,()=>{Ea=!0,Aa(null),a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),a.accountEmail.focus({preventScroll:!0})}),a.welcomeBrowse.addEventListener(`click`,()=>{a.directory.hidden?a.browse.click():a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Oa,`hidden`)}catch{}a.welcome.hidden=!0}),a.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.accountEmail.value.trim(),n=a.accountPassword.value;(async()=>{a.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${Ea?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){a.accountNote.textContent=r.error??`that did not work`;return}q=r.account?.id??``,a.accountPassword.value=``,Aa(r.account?.email??t),mr(),Ia()}catch{a.accountNote.textContent=`could not reach nixamp.com`}finally{a.accountSubmit.disabled=!1}})()}),a.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}q=``,Aa(null),kr(),F.close(),E=-1,c=`local`,le=`idle`,C=``,a.remoteUrl.value=``,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,a.listenOnly.hidden=!0,lo(!1);try{localStorage.removeItem(cn)}catch{}T=`Signed out, and disconnected from the server.`,mr(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Xe=t,b=e.get(`play`)??``,ee=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t,T=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(a.linkUrl.value=n,t!==``&&b===``?b=`link:${n}`:t===``&&(nt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=Fe(r);t?(Xe=t.view,b=t.what,ee=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t.view,T=`Opening the stream you were sent…`):(a.linkUrl.value=r,nt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let La=[`zone-top`,`zone-main`],Ra=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,za=e=>e.parentElement&&La.includes(e.parentElement.id)?e.parentElement:null,Ba=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Va=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Ra(e)&&za(e)!==null),Ha=e=>e.dataset.title??e.id,Ua=new Map,Wa=Va().map((e,t)=>(Ua.set(e.id,{zone:za(e)?.id??``,col:Ba(e),index:t}),e.id)),$=bt();try{$=wt(localStorage.getItem(yt))}catch{}let Ga=()=>$.order.length>0||Object.keys($.placement).length>0;function Ka(){$.order=Va().map(e=>e.id);try{localStorage.setItem(yt,Tt($))}catch{}}function qa(e,t,n){e.classList.remove(`col-a`,`col-b`),t.classList.contains(`split`)&&n!==``&&e.classList.add(`col-${n}`),t!==e.parentElement&&t.append(e)}function Ja(){if(e)return;for(let e of Va()){let t=$.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&La.includes(i.id)&&qa(e,i,r===`a`||r===`b`?r:``)}let t=Et(Va().map(e=>e.id),$.order);for(let e of La){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Ra),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((e,n)=>t.indexOf(e.id)-t.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Va())e.toggleAttribute(`data-collapsed`,$.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,$.closed.includes(e.id))}function Ya(e,t){e.toggleAttribute(`data-collapsed`,t),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),$.collapsed=Dt($.collapsed,e.id,t),Ka(),no()}function Xa(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===a.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===a.partiesPanel&&!t&&kr(),t&&n&&a.panelsToggle.focus({preventScroll:!0}),$.closed=Dt($.closed,e.id,t),Ka(),no()}function Za(e,t,n){let r=za(t);r&&e!==t&&(qa(e,r,Ba(t)),n?t.after(e):t.before(e),$.placement[e.id]=`${r.id}:${Ba(t)}`,Ka(),no())}let Qa=null,$a=()=>{for(let e of Va())e.classList.remove(`drop-before`,`drop-after`)},eo=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon-btn`,r.textContent=e,r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,e=>{e.stopPropagation(),n()}),r};function to(){for(let e of Va()){let t=Ha(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n));let r=n.querySelector(`.panel-heading-text`);if(!r){r=document.createElement(`span`),r.className=`panel-heading-text`;let e=document.createElement(`span`);e.className=`panel-loading-spinner`,e.setAttribute(`aria-hidden`,`true`),n.replaceChildren(r,e)}if(r.textContent!==t&&(r.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let i=document.createElement(`span`);i.className=`panel-tools`;let a=eo(`≡`,`Move ${Ha(e)}: Alt plus Up or Down, or drag`,()=>void 0);a.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=Va().filter(t=>za(t)===za(e)&&Ba(t)===Ba(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(Za(e,r,t.key===`ArrowDown`),a.focus({preventScroll:!0}))}),a.classList.add(`grip`),a.draggable=!0,a.addEventListener(`dragstart`,t=>{Qa=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),a.addEventListener(`dragend`,()=>{Qa=null,e.classList.remove(`dragging`),$a()});let o=eo(`▁`,`Shade ${Ha(e)} to its title`,()=>Ya(e,!e.hasAttribute(`data-collapsed`)));o.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let s=eo(`✕`,`Hide ${Ha(e)}; the Panels list turns it back on`,()=>Xa(e,!0));e.id===`transcript-panel`&&i.append(Y.button()),i.append(a,o,s),e.prepend(i),e.addEventListener(`dragover`,t=>{if(!Qa||Qa===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;$a(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Qa||Qa===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);$a(),Za(Qa,e,n)})}}function no(){if(a.panelsPanel.hidden||a.panelsList.contains(document.activeElement))return;let e=Va().filter(e=>e!==a.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,_(i,`aria-label`,()=>`${Ha(e)} on`),i.addEventListener(`change`,()=>Xa(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,g(a,()=>Ha(e)),r.append(i,a);let o=document.createElement(`span`);return o.className=`detail`,o.textContent=n?`off`:e.hasAttribute(`data-collapsed`)?`shaded`:e.hidden&&e.dataset.available!==`true`?`nothing to show right now`:``,t.append(r,o),t});a.panelsList.replaceChildren(...e)}function ro(){$=bt();for(let e of Wa){let t=document.getElementById(e),n=Ua.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(qa(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}$.order=[...Wa],Ja(),$=bt();try{localStorage.removeItem(yt)}catch{}no()}function io(e){if(!e||Ga())return;let t=za(a.adminPanel);if(!t)return;let n=[...t.children].filter(Ra).find(e=>Ba(e)===Ba(a.adminPanel));n&&n!==a.adminPanel&&n.before(a.adminPanel),a.adminPanel.removeAttribute(`data-collapsed`),a.adminPanel.removeAttribute(`data-closed`)}a.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=a.panelsPanel.hidden||a.panelsPanel.hasAttribute(`data-closed`)||a.panelsPanel.hasAttribute(`data-collapsed`);a.panelsPanel.hidden=!t,a.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(a.panelsPanel.hasAttribute(`data-closed`)&&Xa(a.panelsPanel,!1),a.panelsPanel.hasAttribute(`data-collapsed`)&&Ya(a.panelsPanel,!1),no(),a.panelsPanel.showPopover?.(),a.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):a.panelsPanel.hidePopover?.()}),a.panelsPanel.addEventListener(`toggle`,()=>{let e=a.panelsPanel.matches(`:popover-open`);a.panelsToggle.setAttribute(`aria-expanded`,String(e&&!a.panelsPanel.hasAttribute(`data-collapsed`))),e||(a.panelsPanel.hidden=!0)}),a.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof a.panelsPanel.hidePopover!=`function`&&(a.panelsPanel.hidden=!0,a.panelsToggle.setAttribute(`aria-expanded`,`false`),a.panelsToggle.focus({preventScroll:!0}))}),a.panelsReset.addEventListener(`click`,ro),a.panelsSave.addEventListener(`click`,()=>{Ka();let e=a.panelsSave.textContent??`Save setup`;a.panelsSave.textContent=`Saved`,window.setTimeout(()=>{a.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{to(),no()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),to(),Ja(),ja(),Ma(),mr(),$n(),a.browse.addEventListener(`click`,()=>{if(!a.directory.hidden){a.directory.hidden=!0;return}ar(),a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.disconnect.addEventListener(`click`,()=>{F.close(),a.listenOnly.hidden=!0,E=-1,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,_(a.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),l=``,ie=``,Ir(),lo(!1),c=`local`,le=`idle`,C=``,V()});async function ao(){if(c!==`remote`||F.shareLink===``){a.sharePanel.hidden=!0;return}a.sharePanel.hidden=!1;let e=To(),t=globalThis.location.origin;a.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,a.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,a.sharePhone.hidden=!0,a.shareSend.hidden=!0,a.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(F.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ie=r.url,a.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Be=r.live,Ve=r.live?r.code:``,Ue=n,a.liveControls.hidden=a.adminPanel.hidden||!r.possible,a.goLive.hidden=r.live,a.stopLive.hidden=!r.live,a.sharePhone.hidden=!1,!r.live){a.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){a.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,a.shareSend.hidden=!1;return}a.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),jo(n),document.createTextNode(` and key `),jo(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),a.shareSend.hidden=!1}}let oo=null,so=null,co=0,lo=e=>{oo&&clearInterval(oo),oo=null,co+=1,so?.abort(),so=null,k=null,Tr(),e&&(uo(),oo=setInterval(()=>{document.visibilityState===`visible`&&uo()},Er))};async function uo(){if(c!==`remote`||so)return;let e=new AbortController;so=e;let t=k===null;t&&Or(e,!0);let n=co,r=F.url(`/api/streams`),i=setTimeout(()=>e.abort(),8e3);try{let t=await fetch(r,{signal:e.signal,cache:`no-store`});if(!t.ok)return;let i=await t.json();if(e.signal.aborted||n!==co||c!==`remote`||r!==F.url(`/api/streams`))return;m=i.server.carries!==!1,i.server.name&&i.server.name!==l&&(l=i.server.name,a.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${l}`),Ir()),k=i,Eo(i),V(),fo(i)}catch{}finally{clearTimeout(i),t&&Or(e,!1),so===e&&(so=null)}}function fo(e){Tr(),D&&Ln()}function po(e){let t=qt(),n=e.restreams??[],r=[],i=e.server.playing,o=!a.adminPanel.hidden;i&&r.push(Do({key:`live`,title:pe(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${pe(e.server.nowPlaying)}`:`nothing loaded`,i&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:`Join party`,onPlay:()=>{i&&ho(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:wo(`live`)}:{},direct:i?F.url(`/api/live`):``}));for(let e of n)r.push(Do({key:`restream:${e.at}`,title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{mn(e.at)},link:``,direct:F.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=F.url(`/api/channels/${encodeURIComponent(t.id)}`),i=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&i.push(`☎ ${t.code}`),t.redials&&i.push(`redialled ${t.redials}×`),o&&t.error&&i.push(t.error),r.push(Do({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{go({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:wo(`channel:${t.id}`),direct:n,onRestart:(o||pt&&q!==``&&t.startedBy===q)&&t.via===`pull`?()=>{yo(t.id,t.name)}:void 0,onStop:o||pt&&q!==``&&t.startedBy===q?()=>xo(t.id,t.name):void 0,onRename:o||pt&&q!==``&&t.startedBy===q?()=>{bo(t.id,t.name)}:void 0}))}return r}async function mo(){if(c===`remote`)try{if((await fetch(F.media(L(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;T=q===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,q===``&&a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function ho(e){E=-1,D=null,O={kind:`live`},ze(e,`auto`),await Se(()=>P.load({title:e||`Live`,artist:``,album:``,duration:0,url:F.url(`/api/live`),video:!0,objectUrl:!1},!0)),Wn(!0),T=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function go(e,t=!0,n){let r=k?.channels.find(t=>t.id===e.id);!e.playlist&&r?.playlist&&(e={...e,playlist:r.playlist}),E=-1,D=e,t&&(ve=0),t&&(O=n??{kind:`channel`}),t&&ze(e.name,O?.link||on(e.name)?`auto`:`channel`);let i=e.video&&_t(),a=e.video&&((e.playlist?.length??0)>1||e.id.startsWith(`folder-`));await Se(()=>P.load({title:e.name,artist:``,album:``,duration:0,url:F.url(i||a?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Wn(e.video),D===e&&(T=`Watching ${e.name}, live on this server.`),V()}function _o(){let e=D;return e?Ye?!0:ve>=5?(T=`${e.name} stopped, and did not come back.`,D=null,O=null,V(),!0):(ve+=1,T=`${e.name} started over; rejoining…`,V(),Ye=setTimeout(()=>{Ye=null,D===e&&go(e,!1)},2e3),!0):!1}function vo(e){a.partiesNote.hidden=!1,a.partiesNote.textContent=e,U(e)}async function yo(e,t){vo(`Restarting ${t}…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));vo(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{vo(`could not reach the server`)}uo()}async function bo(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){vo(`Renaming ${t}…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));vo(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{vo(`could not reach the server`)}D?.id===e&&(D={...D,name:r}),uo(),V()}}async function xo(e,t){vo(`Taking ${t} off the air…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));if(vo(n.ok?`${t} is off the air.`:r.error??`that did not work`),!n.ok)return!1}catch{return vo(`could not reach the server`),!1}return D?.id===e&&(D=null,P.stop()),!0}function So(e,t,n,r){if(e.classList.contains(`removing`))return;t.disabled=!0,t.setAttribute(`aria-busy`,`true`);let i=document.createElement(`span`);i.className=`delete-spinner`,i.setAttribute(`role`,`status`),i.setAttribute(`aria-label`,`Removing`),i.textContent=``,t.after(i),n().then(n=>{if(!n){i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`);return}e.classList.add(`removing`),window.setTimeout(()=>{e.remove(),r?.()},260)}).catch(()=>{i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`)})}async function Co(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{T=e,V();return}n===`✓`||n===`✓`?o(t,`check`):g(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function wo(e,t=0){let n=To();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function To(){if(ie!==``)return ie;let e=c===`remote`?F.shareLink:``;return/\/admin\//.test(e)?``:e}function Eo(e){if(b===``)return;let t=b;if(t===`live`){b=``,e.server.playing?ho(e.server.nowPlaying):(T=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){b=``,Kn(t.slice(5));return}if(t.startsWith(`golive:`)){b=``,a.linkUrl.value=t.slice(7),mr().then(()=>er());return}if(t.startsWith(`track:`)){b=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&mn(e);return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(b=``,go({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Do(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${v(F.address)}:${e.key}`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`button`,Ct(s,e.playLabel??`Join party`),s.hidden=e.key.startsWith(`channel:`)&&D?.id===e.key.slice(8),s.addEventListener(`click`,e.onPlay),a.append(s);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,o(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Co(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Co(e.direct??``,t,`✓`)})),e.onRestart&&a.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(c(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(c(`remove`,`Remove: take it off the air`,n=>{So(t,n,e.onStop,()=>void uo())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,_(s,`aria-label`,()=>`${p(e.playLabel??`Join party`)}: ${e.title}`);let l=document.createElement(`details`);l.className=`party-actions`;let u=document.createElement(`summary`);return u.textContent=`⋯`,_(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(s),l.append(u,a),t.append(n,s),a.childElementCount&&t.append(l),t}let Oo=``;function ko(e,t){Oo=e;let n=e!==``&&t===e;a.loadHome.hidden=e===``,a.homeNote.hidden=e===``,e!==``&&(a.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,a.loadHome.disabled=!1)}a.loadHome.addEventListener(`click`,()=>{Oo!==``&&(a.loadHome.disabled=!0,U(`Reading this server's files…`),(async()=>{try{let e=await fetch(F.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Oo})}),t=await e.json();U(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{U(`could not reach the server`)}finally{a.loadHome.disabled=!1}})())});let Ao=async e=>{a.goLive.disabled=!0,a.stopLive.disabled=!0,a.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(F.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();a.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{a.shareNote.textContent=`could not reach the server`}finally{a.goLive.disabled=!1,a.stopLive.disabled=!1,await ao()}};a.goLive.addEventListener(`click`,()=>void Ao(!0)),a.stopLive.addEventListener(`click`,()=>void Ao(!1));function jo(e){let t=document.createElement(`b`);return t.textContent=e,t}a.shareCopy.addEventListener(`click`,()=>{a.shareLink.select(),navigator.clipboard?.writeText(a.shareLink.value).then(()=>{a.shareNote.textContent=`Copied. Send it to anybody.`},()=>{a.shareNote.textContent=`Copy it from the box above.`})}),a.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=a.shareTo.value.trim();t!==``&&(async()=>{a.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:To()})}),n=await e.json();a.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(a.shareTo.value=``)}catch{a.shareNote.textContent=`could not send that`}})()}),a.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(dn,a.listenHere.checked?`1`:`0`)}catch{}c===`remote`&&(async()=>{a.listenHere.checked?(await F.send({type:`stop`}),await _n(S.index)):(P.stop(),E=-1),V()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)&&!t?.closest(`input, textarea, select, button, a, [contenteditable], [role=button]`)&&t===a.transport)switch(e.key){case` `:e.preventDefault(),vn();return;case`s`:bn();return;case`n`:case`ArrowRight`:yn(1);return;case`p`:case`ArrowLeft`:yn(-1);return;case`ArrowDown`:e.preventDefault(),mn(Math.min(I()-1,L()+1));return;case`ArrowUp`:e.preventDefault(),mn(Math.max(0,L()-1));return}});let Mo=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Mo=e,a.install.hidden=!1}),a.install.addEventListener(`click`,()=>{Mo?.prompt(),Mo=null,a.install.hidden=!0});try{let e=localStorage.getItem(un);e!==null&&(a.volume.value=String(Math.round(Number(e)*100)),P.volume=Number(e));let t=localStorage.getItem(cn);t&&(a.remoteUrl.value=t),localStorage.getItem(dn)===`0`&&(a.listenHere.checked=!1)}catch{}(async()=>{if(a.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await qe(e)===null)return;let t=await We(e);t&&t.trackCount!==0&&(a.remoteUrl.value=e,c=`remote`,T=``,F.connect(e),lo(!0),aa(),V())})(),kr();let No=()=>{document.visibilityState===`visible`&&!a.partiesPanel.hasAttribute(`data-closed`)&&kr()},Po=setInterval(No,Er);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(kr(),uo())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(Po),oo&&clearInterval(oo),Cr?.abort(),so?.abort(),Cr=null,so=null,co+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(Po),Po=setInterval(No,Er),No(),c===`remote`&&lo(!0))}),(()=>{if(pn||Xe!==``)return;let e=()=>P.source!==``||P.playing||xe()||D!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{pn=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||P.playJingle(n).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,P.playJingle(n).then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),V(),requestAnimationFrame(Vn)}mn(),re(),le(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};
|
|
3
|
+
`))>=0;){let e=i.slice(0,c);i=i.slice(c+2),e.startsWith(`data: `)&&this.event(JSON.parse(e.slice(6)))}if(i.length>128e3)throw Error(`Invalid live audio response.`)}}finally{t.signal.removeEventListener(`abort`,a),await n.cancel().catch(()=>{}),n.releaseLock()}}event(e){if(e.type===`error`)throw P(e.error,e.retryable?503:400);if(e.type===`status`){this.options.status(`Live translated audio · ${e.listeners} ${e.listeners===1?`listener`:`listeners`}`);return}let t=`nixamp-shared:${e.id}`;if(e.type===`line`){for(let[e,t]of this.clips)t.ended&&(t.taken||Date.now()-t.until>12e3)&&this.clips.delete(e);for(;this.clips.size>=24;){let e=this.clips.entries().next().value;e[1].ended||e[1].controller.error(P(`Catching up with live audio…`,503)),this.clips.delete(e[0])}let n,r=new ReadableStream({start:e=>{n=e},cancel:()=>{let e=this.clips.get(t);e&&(e.ended=!0),this.clips.delete(t)}});this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t);return}let n=this.clips.get(t);if(!n||n.ended)return;if(e.type===`end`){n.ended=!0,n.controller.close();return}let r=Uint8Array.from(atob(e.data),e=>e.charCodeAt(0));if(n.bytes+=r.length,n.bytes>2097152)throw Error(`The live audio segment was too large.`);n.controller.enqueue(r)}},R=e=>new Intl.NumberFormat(f.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),z=e=>document.getElementById(e),Xt=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=z(`translation-purchase`);plan=z(`translation-plan`);coin=z(`translation-coin`);buy=z(`translation-checkout`);note=z(`translation-purchase-note`);checkoutLink=z(`translation-checkout-link`);constructor(e){this.options=e,z(`translation-purchase-close`).addEventListener(`click`,()=>this.dialog.close()),this.dialog.addEventListener(`close`,()=>{this.timer&&clearTimeout(this.timer),this.timer=null,this.opener?.focus({preventScroll:!0})}),z(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),z(`translation-check-payment`).addEventListener(`click`,()=>void this.check()),window.addEventListener(`pagehide`,()=>{this.timer&&clearTimeout(this.timer)}),setInterval(()=>{this.options.account()&&(!this.access||this.access.required)&&this.refresh()},3e4)}status(e){this.note.textContent!==e&&(this.note.textContent=e)}loaded(){return this.access!==null}loadingMessage(){return this.problem||`Checking free sessions and audio credit…`}ready(){let e=this.access;return e?.required===!1||!!(e&&((e.free?.remaining??0)>0||e.free?.activeUntil&&Date.parse(e.free.activeUntil)>Date.now()||e.balanceMicros>0&&e.expires&&Date.parse(e.expires)>Date.now()))}async startSession(e){if(this.access?.required===!1)return;let t=await fetch(`/api/v1/translation-passes/session`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({resource:e}),signal:AbortSignal.timeout(15e3)}),n=await t.json();if(!t.ok)throw Error(n.error||`This free session could not be started.`);this.refresh()}button(){let e=document.createElement(`button`);return e.type=`button`,e.textContent=`$`,_(e,`title`,()=>p(`Buy translated audio`)),_(e,`aria-label`,()=>p(`Buy translated audio`)),e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-controls`,`translation-purchase`),e.dataset.translationBuy=``,e.addEventListener(`click`,()=>this.open(e)),e}open(e){this.opener=e,this.dialog.open||this.dialog.showModal(),this.status(``),this.refresh().then(()=>{this.order&&this.dialog.open&&this.check()})}async refresh(){let e=this.options.account();this.problem=``,this.account!==e&&(this.account=e,this.access=null,this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0);try{let t=await fetch(`/api/v1/translation-passes`,{signal:AbortSignal.timeout(15e3)}),n=await t.json();if(this.account!==e||this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Purchases are unavailable.`);this.access=n;let r=this.access.coins??[];[...this.coin.options].map(e=>e.value).join()!==r.join()&&document.activeElement!==this.coin&&this.coin.replaceChildren(...r.map(e=>new Option(e.replaceAll(`_`,` · `),e)));let i=this.access.plans??[];this.plan.options.length||this.plan.replaceChildren(...i.map(e=>{let t=new Option(``,e.id);return g(t,()=>`${e.name} · ${R(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${p(`Audio credit`)}: ${R(a.balanceMicros)}${a.expires?` · ${new Date(a.expires).toLocaleString(f.language)}`:``}`:``,s=this.access.free,c=()=>a.required&&s?f.language===`en`?`${s.remaining} of ${s.limit} free sessions left today${s.activeUntil?` · free session active`:``}`:`${p(`Free sessions`)}: ${f.number(s.remaining)}/${f.number(s.limit)}${s.activeUntil?` · ✓`:``}`:``;g(z(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(z(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),g(z(`translation-free-description`),()=>s?`Each account gets ${s.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${s.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(s.resets).toLocaleString(f.language)} (midnight UTC). Free time is used before purchased credit.`:``),z(`translation-sign-in`).hidden=!!e,this.buy.disabled=!e||!this.access.available||this.loading,!this.access.available&&this.dialog.open&&this.status(this.access.required?`Checkout is temporarily unavailable. Free sessions and existing credit still work.`:`This server sponsors translated audio; no purchase is required.`);let l=new URLSearchParams(location.search).get(`translation_order`),u=this.access.orders?.find(e=>e.id===l||e.id===this.order)??this.access.orders?.[0];u&&!this.order&&(this.order=u.id,this.link(u.url)),l&&!this.order&&/^[a-f0-9-]{36}$/i.test(l)&&e&&(this.order=l,this.check()),this.options.changed(),this.order&&!this.dialog.open&&!this.checking&&this.check()}catch(e){this.problem=e instanceof Error?e.message:`Audio credit could not be checked. Use Buy to retry.`,this.dialog.open&&this.status(this.problem),this.options.changed()}}describe(){let e=this.access?.plans.find(e=>e.id===this.plan.value);if(!e)return;let t=Math.floor(e.priceCents/100/((.66/60+.05)*5));z(`translation-plan-description`).textContent=`${R(e.priceCents*1e4)} credit. Expires ${e.days===1?`24 hours`:`${e.days} days`} after payment. About ${t} minutes at 1,000 spoken characters/minute; usage varies. No automatic renewal.`}link(e){if(!/^https:\/\/coinpayportal\.com\/pay\/[a-f0-9-]{36}$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,z(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=`${this.plan.value}|${this.coin.value}`;(!this.requestKey||this.selected!==t)&&(this.requestKey=crypto.randomUUID(),this.selected=t),this.loading=!0,this.buy.disabled=!0,this.status(`Preparing secure checkout…`);try{let t=await fetch(`/api/v1/translation-passes/checkout`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({plan:this.plan.value,coin:this.coin.value,requestKey:this.requestKey}),signal:AbortSignal.timeout(2e4)}),n=await t.json();if(this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Checkout could not be opened.`);this.order=n.id,this.link(n.url),this.status(`Open secure checkout to pay. Your video keeps playing in this tab. Credit appears after payment confirmation.`),this.poll()}catch(e){this.status(e instanceof Error?e.message:`Checkout could not be opened.`)}finally{this.loading=!1,this.buy.disabled=!this.account||!this.access?.available}}poll(){this.timer&&clearTimeout(this.timer),this.dialog.open&&this.order&&(this.timer=setTimeout(()=>void this.check(),5e3))}async check(){if(!this.order||!this.account||this.checking)return;this.checking=!0;let e=this.order,t=this.account;try{let n=await fetch(`/api/v1/translation-passes/orders/${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(2e4)}),r=await n.json();if(this.account!==t||this.order!==e)return;if(!n.ok)throw Error(r.error||`Payment status could not be checked.`);if(r.status===`paid`){this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0,z(`translation-check-payment`).hidden=!0,this.status(`Payment confirmed. Enable Translate audio whenever you are ready.`);let e=new URL(location.href);e.searchParams.delete(`translation_order`),history.replaceState(history.state,``,e),await this.refresh();return}this.status(r.status===`pending`?`Waiting for payment confirmation…`:`Payment ${r.status}. Check again if you have already sent it.`),r.status===`pending`&&this.poll()}catch(e){this.status(e instanceof Error?e.message:`Payment status could not be checked.`)}finally{this.checking=!1}}},Zt=class{random;previous=[];sequence=0;speakers=new Map;constructor(e=Math.random){this.random=e}reset(){this.previous=[],this.sequence=0,this.speakers.clear()}reconcile(e,t,n){let r=new Map,i=new Set,a=[],o=new Map;for(let n of e)for(let e of this.previous){let r=Math.min(t+n.end*1e3,e.end)-Math.max(t+n.start*1e3,e.start);if(r>120){let t=`${n.speaker}|${e.speaker}`;o.set(t,(o.get(t)??0)+r)}}for(let[e,t]of o){let[n,r]=e.split(`|`);a.push({local:n,global:r,overlap:t})}for(let e of a.sort((e,t)=>t.overlap-e.overlap)){let t=this.speakers.get(e.global);t&&!r.has(e.local)&&!i.has(e.global)&&(r.set(e.local,t),i.add(e.global))}for(let t of e){let e=r.get(t.speaker);if(!e){let i=new Set([...this.speakers.values()].map(e=>e.voice)),a=n.filter(e=>!i.has(e.id)),o=a.length?a:n,s=o[Math.floor(this.random()*o.length)];e={id:`speaker-${++this.sequence}`,profile:t.profile,voice:s?.id??`auto`},this.speakers.set(e.id,e),r.set(t.speaker,e)}}this.previous=e.map(e=>({start:t+e.start*1e3,end:t+e.end*1e3,speaker:r.get(e.speaker).id}));let s=new Set(this.previous.map(e=>e.speaker));for(let e of this.speakers.keys())this.speakers.size>64&&!s.has(e)&&this.speakers.delete(e);return r}},Qt=class{options;tracker=new Zt;generation=0;pending=null;committedUntil=null;running=null;controller=null;translating=null;translationController=null;recognitionFailures=0;translationFailures=0;translations=[];constructor(e){this.options=e}reset(){this.generation++,this.controller?.abort(),this.translationController?.abort(),this.pending=null,this.running=null,this.translating=null,this.recognitionFailures=this.translationFailures=0,this.translations=[],this.committedUntil=null,this.tracker.reset()}push(e){this.committedUntil??=e.freshAt,this.pending=e,this.running===null&&this.run(this.generation)}async json(e,t,n){let r=await(this.options.fetcher??fetch)(e,{...t,signal:n}),i=await r.json();if(!r.ok)throw P(i.error||`Audio translation is unavailable.`,r.status);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;this.pending=null;try{if(Date.now()-t.until>12e3)continue;let n=new AbortController;this.controller=n;let r=AbortSignal.any([n.signal,AbortSignal.timeout(12e3)]),i=this.options.speakers(),a=this.options.language(),o=await this.json(i?`/api/v1/speech/speakers`:`/api/v1/speech/transcribe?live=1`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Uint8Array(Ot(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;this.recognitionFailures=0;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=o.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),l=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),u=[],d=()=>{u.length&&(c.push({channel:this.options.channel(),at:t.at+u[0].start*1e3,until:t.at+u.at(-1).end*1e3,text:u.map(e=>e.text).join(` `).trim(),language:s,speaker:o.id,voiceProfile:a.profile}),u=[])};for(let e of l)u.length&&e.start-u.at(-1).end>=.45&&d(),u.push(e),(/[.!?。!?]$/.test(e.text)||u.map(e=>e.text).join(` `).length>=400)&&d();u.length&&(i<r.length-1||t.until-(t.at+u.at(-1).end*1e3)>=350||t.until-(t.at+u[0].start*1e3)>=3e3)&&d()}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(!c.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...c.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:c,language:s,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.recognitionFailures>=3)throw t;this.options.status(`Speech recognition interrupted · listening for the next phrase…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.running===e&&(this.running=null)}}async translate(e){this.translating=e;try{for(;this.translations.length&&e===this.generation;){let t=this.translations.shift();try{let{lines:n}=t,{language:r,target:i,until:a}=t;if(Date.now()-a>12e3)continue;let o=new AbortController;if(this.translationController=o,i&&r!==i){if(!r)throw P(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:n.map(e=>e.text),from:r,to:i})},AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]));if(e.texts.length!==n.length||e.texts.some(e=>!e.trim()))throw P(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((t,n)=>({...t,original:t.text,sourceLanguage:r,language:i,text:e.texts[n]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>$t(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!Ut(t)||++this.translationFailures>=3)throw t;this.options.status(`Translation interrupted · catching up with live speech…`)}}}catch(t){if(e===this.generation){let e=t instanceof Error?t.message:`Live translation stopped.`;this.reset(),this.options.failed(e),this.options.status(e)}}finally{this.translating===e&&(this.translating=null)}}};function $t(e){let t=e.text.trim();if(!t)return[];let n=[],r=t;for(;r.length>600;){let e=r.lastIndexOf(` `,600),t=e>300?e:600;n.push(r.slice(0,t)),r=r.slice(t).trimStart()}r&&n.push(r);let i=0;return n.map(n=>{let r=e.at+(e.until-e.at)*i/t.length;return i+=n.length+1,{...e,text:n,at:r,until:Math.min(e.until,e.at+(e.until-e.at)*i/t.length)}})}var en=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,tn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,nn=/\s+(?:vs\.?|v\.?|at|@)\s+/i,rn=/^(?:the|a|an|live|tonight|recorded|filmed|concert|home|dinner|breakfast|lunch|midnight|night|one night|death|murder|meet me|panic|sunset|sunrise)\b/i;function an(e){let t=e.replace(tn,``).replace(tn,``).trim().split(nn);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!rn.test(t)})}function on(e){let t=String(e??``).trim();return t===``?!1:an(t.replace(en,``))||an(t)}function sn(e,t){if(e.dataset.longStringScroller===`true`)return;e.dataset.longStringScroller=`true`,e.classList.add(`long-string-scroller`),t.classList.add(`long-string-scroller-content`),t.title=t.textContent??``;let n=0,r=0,i=0,a=!1,o=null,s=()=>{n=0;let c=matchMedia(`(prefers-reduced-motion: reduce)`).matches?r:i+(r-i)*.22;if(i=Math.abs(r-c)<.5?r:c,t.style.setProperty(`--path-shift`,`${i}px`),Math.abs(r-i)>=.5){n=requestAnimationFrame(s);return}a&&(a=!1,delete t.dataset.pan,t.style.removeProperty(`--path-shift`),o=setTimeout(()=>{o=null,e.style.removeProperty(`min-height`)},280))},c=()=>{n||=requestAnimationFrame(s)};e.addEventListener(`pointerenter`,n=>{n.pointerType===`mouse`&&matchMedia(`(hover: hover) and (pointer: fine)`).matches&&(o!==null&&(clearTimeout(o),o=null),e.style.minHeight=`${e.getBoundingClientRect().height}px`,a=!1,t.dataset.pan=`true`)}),e.addEventListener(`pointermove`,n=>{if(t.dataset.pan!==`true`)return;let i=getComputedStyle(e),a=parseFloat(i.paddingLeft)+parseFloat(i.paddingRight),o=Math.max(0,t.scrollWidth-(e.clientWidth-a));if(o<=0)return;let s=e.getBoundingClientRect(),l=Math.max(0,Math.min(1,(n.clientX-s.left)/Math.max(1,s.width)));if(l<=.02)r=0;else if(l>=.98)r=-o;else{let e=l*l*(3-2*l);r=-o*e}c()}),e.addEventListener(`pointerleave`,()=>{r=0,a=!0,c()})}var cn=`nixamp.remote`,ln=`nixamp.defaultServer`,un=`nixamp.volume`,dn=`nixamp.listenHere`,fn=1e4,pn=!1;function B(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function mn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`;document.body.classList.toggle(`classroom-embed`,e);let t=null;try{t=localStorage.getItem(ot)}catch{}let n=st(navigator.userAgent,location.search,navigator.maxTouchPoints,t);if(document.body.classList.toggle(`tv`,n),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(ot,n?`1`:`0`)}catch{}let r=document.getElementById(`tv-toggle`);r&&(g(r,()=>n?`TV mode: on`:p(`TV mode`)),r.title=n?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,r.addEventListener(`click`,()=>{try{localStorage.setItem(ot,n?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let i=lt(n),a={status:B(`status`),source:B(`source`),install:B(`install`),video:B(`video`),audio:B(`audio`),title:B(`title-line`),album:B(`album-line`),meta:B(`meta-line`),metaBlurb:B(`meta-blurb`),liveLine:B(`live-line`),downloadNow:B(`download-now`),wayInHere:B(`way-in-here`),embed:B(`embed`),embedFrame:B(`embed-frame`),linkForm:B(`link-form`),linkUrl:B(`link-url`),linkServer:B(`link-server`),linkGoLive:B(`link-go-live`),goLiveNow:B(`go-live-now`),elapsed:B(`elapsed`),total:B(`total`),seek:B(`seek`),fullscreen:B(`fullscreen`),copyNow:B(`copy-now`),copyNixamp:B(`copy-nixamp`),canvas:B(`spectrum`),glyphs:B(`glyphs`),levels:B(`levels`),playlist:B(`playlist`),livePlaylist:B(`live-playlist`),livePlaylistPanel:B(`live-playlist-panel`),playlistPager:B(`playlist-pager`),crumbs:B(`crumbs`),filter:B(`filter`),playlistTitle:B(`playlist-panel`),note:B(`note`),linkNote:B(`link-note`),logList:B(`log-list`),files:B(`files`),folder:B(`folder`),remoteUrl:B(`remote-url`),remoteServer:B(`remote-server`),remoteForm:B(`remote-form`),remoteState:B(`remote-state`),disconnect:B(`disconnect`),browse:B(`browse`),panelsToggle:B(`panels-toggle`),panelsPanel:B(`panels-panel`),panelsList:B(`panels-list`),panelsSave:B(`panels-save`),panelsReset:B(`panels-reset`),accountForm:B(`account-form`),accountEmail:B(`account-email`),accountPassword:B(`account-password`),accountSubmit:B(`account-submit`),accountToggle:B(`account-toggle`),accountProviders:B(`account-providers`),accountPanel:B(`account-panel`),accountElsewhere:B(`account-elsewhere`),welcome:B(`welcome`),welcomeCreate:B(`welcome-create`),welcomeBrowse:B(`welcome-browse`),welcomeHide:B(`welcome-hide`),accountSignOut:B(`account-signout`),accountNote:B(`account-note`),personaForm:B(`persona-form`),personaHandle:B(`persona-handle`),personaVoice:B(`persona-voice`),personaProfile:B(`persona-profile`),personaNote:B(`persona-note`),adminPanel:B(`admin-panel`),adminNote:B(`admin-note`),adminSaid:B(`admin-said`),adminConnections:B(`admin-connections`),publishPanel:B(`publish-panel`),publishNote:B(`publish-note`),publishList:B(`publish-list`),adminRestream:B(`admin-restream`),adminReplace:B(`admin-replace`),adminSource:B(`admin-source`),adminName:B(`admin-name`),adminAdd:B(`admin-add`),homeNote:B(`home-note`),loadHome:B(`load-home`),directory:B(`directory`),recentNote:B(`recent-note`),recentList:B(`recent-list`),followingNote:B(`following-note`),followingList:B(`following-list`),serversPanel:B(`servers-panel`),serversNote:B(`servers-note`),serversList:B(`servers-list`),favoritesPanel:B(`favorites-panel`),favoritesNote:B(`favorites-note`),favoritesList:B(`favorites-list`),favHere:B(`fav-here`),partiesPanel:B(`parties-panel`),partiesNote:B(`parties-note`),partiesList:B(`parties-list`),partyForm:B(`party-form`),partyCode:B(`party-code`),partyJoin:B(`party-join`),connectionsNote:B(`connections-note`),connectionsList:B(`connections-list`),catalogsPanel:B(`catalogs-panel`),catalogsNote:B(`catalogs-note`),catalogsForm:B(`catalogs-form`),catalogSource:B(`catalog-source`),catalogName:B(`catalog-name`),catalogsList:B(`catalogs-list`),catalogsCrumbs:B(`catalogs-crumbs`),catalogsFilter:B(`catalogs-filter`),catalogsEntries:B(`catalogs-entries`),notifyPanel:B(`notify-panel`),notifyNote:B(`notify-note`),notifyWeb:B(`notify-web`),notifyEmail:B(`notify-email`),notifySms:B(`notify-sms`),notifyPhone:B(`notify-phone`),notifyPhoneForm:B(`notify-phone-form`),notifyPhoneNote:B(`notify-phone-note`),directoryNote:B(`directory-note`),directoryList:B(`directory-list`),sharePanel:B(`share-panel`),trollboxPanel:B(`trollbox-panel`),trollboxNote:B(`trollbox-note`),trollboxList:B(`trollbox-list`),trollboxForm:B(`trollbox-form`),trollboxInput:B(`trollbox-input`),trollboxMic:B(`trollbox-mic`),trollboxEdit:B(`trollbox-edit`),trollboxEditLabel:B(`trollbox-edit-label`),transcriptPanel:B(`transcript-panel`),transcriptNote:B(`transcript-note`),transcriptOn:B(`transcript-on`),transcriptLanguage:B(`transcript-language`),transcriptAudio:B(`transcript-audio`),transcriptVoiceSettings:B(`transcript-voice-settings`),transcriptBackground:B(`transcript-background`),transcriptBackgroundLevel:B(`transcript-background-level`),transcriptBackgroundValue:B(`transcript-background-value`),transcriptAudioNote:B(`transcript-audio-note`),transcriptSpeakers:B(`transcript-speakers`),transcriptList:B(`transcript-list`),subtitle:B(`subtitle`),shareNote:B(`share-note`),shareLink:B(`share-link`),shareCopy:B(`share-copy`),sharePhone:B(`share-phone`),shareSend:B(`share-send`),liveControls:B(`live-controls`),goLive:B(`go-live`),stopLive:B(`stop-live`),shareTo:B(`share-to`),listenOnly:B(`listen-only`),listenHere:B(`listen-here`),volume:B(`volume`),volumeToggle:B(`volume-toggle`),prev:B(`prev`),playPause:B(`play-pause`),transport:B(`transport`),stop:B(`stop`),next:B(`next`),shareNow:B(`share-now`),refreshPlayer:B(`refresh-player`),appVersion:B(`app-version`)};a.appVersion.textContent=`nixamp 0.28.37`;let o=(e,t)=>{ae(e,t)};o(a.copyNixamp,`link`);let s=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,c=`local`,l=``,u=[],d=``,m=!0,h=``;function v(e){try{return new URL(e).origin}catch{return e}}let y=!1,b=``,ee=0,te=new Map,ne=e=>te.get(W(e))??null;function re(e,t){let n=n=>{y=n,b=``,a.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),a.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,o(r,`eye`),r.title=`Viewer: browse and watch. Changes nothing on the server.`,r.setAttribute(`aria-label`,`View ${e.name}`),r.addEventListener(`click`,()=>n(!0));let i=document.createElement(`button`);return i.type=`button`,i.className=`icon way-in`,o(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:q?`Admin: you do not administer this server.`:`Admin: sign in as this server's owner to administer it.`,i.setAttribute(`aria-label`,`Administer ${e.name}`),i.addEventListener(`click`,()=>n(!1)),[r,i]}let ie=``,x=[],ce=0,S=je(),le=`idle`,C=``,T=`Pick files, or connect to a nixamp running somewhere else.`,de=!1,E=-1,he=null,ge=0,D=null;function _e(e){return e?/^https?:\/\//i.test(e)?e:F.url(e):``}let ve=0,ye=0,be=!1,xe=()=>!P.needsInteraction&&(ye>0||be);async function Se(e){ye+=1,V();try{return await e()}finally{--ye,V()}}let O=null,k=null,Ce=``,Te=null,Ee=``,A=null,j=null,Oe=0;function Ae(){a.embed.hidden||(a.embedFrame.src=`about:blank`),a.embed.hidden=!0}let Ne=null,Le=``,Re=null;function ze(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Le=i,Re&&clearTimeout(Re),Re=null,!r){if(Ne?.key===i)return;Ne=null}if(c!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(F.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Le!==i)return;Ne={key:i,match:r.match??null},V();let a=Ne.match;a?.kind===`fixture`&&rt(a)!==`post`&&(Re=setTimeout(()=>{Re=null,!(Le!==i||P.source===``&&!D)&&ze(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Be=!1,Ve=``,Ue=``,Ye=null,Xe=``,nt=``,it=``,M=Array(24).fill(0),ct=Array(24).fill(0),dt=[],N=()=>c===`remote`&&!a.listenHere.checked,ft=()=>c===`remote`&&!a.adminPanel.hidden,pt=!1,ht=()=>ft()||c===`remote`&&pt;function _t(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:a.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function xt(){if(c!==`remote`||A)return null;if(O?.catalog&&O.entry)return{kind:`entry`,catalog:O.catalog,entry:O.entry};if(D)return{kind:`channel`,id:D.id,name:D.name};let e=S.tracks[L()];return e&&(P.source!==``||N())?{kind:`track`,index:L(),name:Zt(e)}:null}async function St(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;T=`Putting ${n} on the air…`,V();try{let r=``,i=``,a=!0;{let t=e.kind===`folder`?`/api/folders/live`:e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(F.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),s=await o.json().catch(()=>({}));if(!o.ok){T=o.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:s.error??`${n} would not go on the air.`,V();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(ft()&&(Be?await fetch(F.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await Ao(!0)),await ao(),uo(),i!==``&&D?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await go({id:i,name:n,video:a},!0,t)}let o=wo(r),s=Ve?` Call ${Ue||`the line`} and key ${Ve} to talk about it.`:``;o===``?T=`${n} is on the air and you are watching it.${s}`:(await Co(o,t,`✓`),T=`${n} is on the air and you are watching it. Link copied.${s}`),V()}catch{T=`could not reach the server`,V()}finally{t.disabled=!1}}function Ct(e,t=`Join party`){o(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);g(n,()=>` ${p(t)}`),e.append(n),_(e,`title`,()=>p(/join/i.test(t)?`Join live`:t))}Ct(a.partyJoin);function Ut(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,o(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),St(e(),n)}),n}let P=new ke({audio:a.audio,video:a.video},{readable:e=>F.owns(e),onTime:(e,t)=>{let n=x[ce];c===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),V()},onEnded:()=>{_o()||Yn()||hn()||c===`remote`&&E<0&&!N()||yn(1)},onState:()=>V(),onBusy:e=>{be!==e&&(be=e,V())},onError:e=>{if(!_o()&&!(Oe!==0&&Date.now()-Oe<2e3)){if(j&&e===`this browser cannot play that format`){let e=j.url;if(j=null,Oe=Date.now(),ht()){T=`That site will not let a page play it directly; going live with it on ${l||`the server`} instead.`,V(),a.linkUrl.value=e,er();return}T=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,V();return}T=e,V(),mo()}}}),Wt=()=>N()&&!P.jinglePlaying,F=new He({onSnapshot:e=>{let t=e.tracks!==void 0||S.index!==e.index;if(S=Me(S,e),b.startsWith(`track:`)&&S.tracks.length>0){let e=Number(b.slice(6));if(b=``,Number.isInteger(e)&&e>=0&&e<S.tracks.length){let t=ee;_n(e).then(()=>{t>0&&(P.seek(t),setTimeout(()=>P.seek(t),600))})}}Wt()&&(M=e.bars.length>0?e.bars:M,ct=et(ct,M)),V(),t&&k&&fo(k)},onStatus:(e,t)=>{le=e,C=t??``,V()}}),I=()=>c===`remote`?S.tracks.length:x.length,L=()=>c===`remote`?N()||E<0?S.index:Math.min(E,Math.max(0,S.tracks.length-1)):ce,qt=()=>{let e=k?.server.nowPlaying||`Live`;return(!Te||Te.tracks!==S.tracks||Te.index!==S.index||Te.fallback!==e)&&(Te={tracks:S.tracks,index:S.index,fallback:e,value:me(S.tracks,S.index,e)}),Te.value},R=()=>c===`remote`&&!D&&O?.kind===`live`,z=()=>R()?qt().fullTitle:$t(),Zt=e=>{let t=se(e);return e.folder?`${e.folder} / ${t}`:t},$t=()=>{if(D){let e=D.id,t=k?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||D.name}if(A)return A.label;if(R())return qt().title;let e=c===`remote`?S.tracks[L()]:x[L()];return e?Zt(e):p(`Nothing loaded.`)},en=()=>{if(D)return`live on this server`;if(A)return`playing here, in this browser`;if(R()){let{context:e,position:t}=qt();return[e,t,`live on ${l||`this server`}`].filter(Boolean).join(` · `)}return(c===`remote`?S.tracks[L()]:x[L()])?.album||`—`};function tn(){if(c!==`remote`||D===null&&O?.kind!==`live`){a.liveLine.hidden=!0,a.liveLine.replaceChildren(),delete a.liveLine.dataset.drawn;return}let e=l||`this server`,t=D?D.name:qt().fullTitle,n=[D?`Live on ${e}: `:`Live from ${e}, now playing: `,jo(t)],r=D?k?.channels.find(e=>e.id===D?.id)?.code??``:Be?Ve:``;r&&n.push(`. To talk about it, call `,jo(Ue||`the line`),` and key `,jo(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);a.liveLine.dataset.drawn!==i&&(a.liveLine.dataset.drawn=i,a.liveLine.hidden=!1,a.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let nn=()=>N()?S.tracks[L()]?.duration??0:P.duration,rn=()=>N()?S.position:P.position,an=()=>N()?S.playing:P.playing;async function mn(e){if(c===`remote`){if(N()){await F.send({type:`play`,index:e});return}await _n(e);return}let t=x[e];t&&(ce=e,D=null,O={kind:`file`},await Se(()=>P.load(t,!0)),Wn(t.video),Gn(),V())}function hn(){return!he||he.length<2?!1:(ge=(ge+1)%he.length,mn(he[ge]),!0)}function gn(e){e.length!==0&&(he=[...e],ge=0,mn(he[0]))}async function _n(e){let t=S.tracks[e];t&&(E=e,D=null,O={kind:`file`},ze(t.title,`auto`),await Se(()=>P.load({title:Zt(t),artist:t.artist,album:t.album,duration:t.duration,url:F.media(e,0),video:t.video===!0,objectUrl:!1},!0)),Wn(t.video===!0),Gn())}async function vn(){if(P.needsInteraction){await P.play(),V();return}if(N()){await F.send({type:`toggle`});return}I()!==0&&(P.playing?P.pause():P.position>0?await P.play():await mn(L()),V())}async function yn(e){he=null;let t=I();if(t!==0){if(N()){await F.send({type:e>0?`next`:`prev`});return}await mn((L()+e+t)%t)}}async function bn(){if(he=null,Ae(),A=null,j=null,N()){await F.send({type:`stop`});return}D=null,O=null,P.stop(),M=Array(24).fill(0),ct=[...M],V()}let xn=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Sn=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],Cn=``;function wn(){let e=[],t=``,n=null,r=D?k?.channels.find(e=>e.id===D?.id):void 0;D&&r?.ended&&Ee!==D.id&&(Ee=D.id,Lr(`${D.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=P.source===``&&!D&&!(N()&&S.tracks[L()]);if(!i){D&&r?.ended?e.push(`ENDED`):D?e.push(O?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):O?.kind===`vod`?e.push(`ON DEMAND`):O?.kind===`live`?e.push(`LIVE`):c===`remote`&&N()?e.push(`ON THE SERVER`):e.push(`FILE`),!a.video.hidden&&a.video.videoWidth>0?e.push(`${a.video.videoWidth}×${a.video.videoHeight}`):a.video.hidden?e.push(`audio`):e.push(`video`),r?(e.push(r.via===`pull`?`${r.listeners} watching`:`${r.listeners} listening · over ${r.via}`),r.startedAt>0&&e.push(`on air ${oe(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),ft()&&r.error&&e.push(r.error)):c===`remote`&&!D?(S.tracks[L()]&&I()>0&&e.push(`${R()?`library track`:`track`} ${L()+1} of ${I()}`),N()&&k&&e.push(`${k.server.playing?`playing`:`stopped`} on ${l||`the server`}`)):c===`local`&&I()>0&&e.push(`track ${L()+1} of ${I()}`),O?.catalog!==void 0&&(O.kind===`channel`?D!==null:O.kind===`vod`&&P.source!==``)&&O?.catalog&&(e.push(O.entry?.group?`${O.catalog.name} › ${O.entry.group}`:O.catalog.name),t=O.entry?.logo??``),t===``&&D&&(t=_e(r?.art??D.art));let i=Ne?.key===Le?Ne.match:null;if(i?.kind===`fixture`)n=at(i),e.unshift(n.status,...n.chips);else if(i){i.image&&(t=i.image);let n=i.data;if(i.kind===`title`){i.year&&e.push(String(i.year));let t=typeof n.rating==`number`?n.rating:null;t&&e.push(`★ ${t.toFixed(1)}`);let r=Array.isArray(n.genres)?n.genres.slice(0,2).map(String):[];r.length&&e.push(r.join(` · `));let a=typeof n.runtimeMin==`number`?n.runtimeMin:0;a&&e.push(`${a} min`)}else if(i.kind===`channel`){let t=typeof n.country==`string`?n.country:``,r=Array.isArray(n.categories)?n.categories.slice(0,2).map(String):[],i=typeof n.network==`string`?n.network:``;t&&e.push(t),r.length&&e.push(r.join(` · `)),i&&e.push(i)}}if(D&&O?.link){let t=``;try{t=new URL(O.link.url).hostname.replace(/^www\./,``)}catch{}e.push(O.link.extractor&&O.link.extractor!==`direct`&&O.link.extractor!==`generic`?`${O.link.extractor} · ${t}`:t||`link`)}Be&&Ve&&N()&&!D&&O?.kind!==`live`&&e.push(Ue?`☎ ${Ue} · key ${Ve}`:`☎ code ${Ve}`)}let o=Ne?.key===Le?Ne.match:null,s=!i&&!n&&o?.summary?o.summary:``,u=e.map(e=>/^on air \d/.test(e)?`on air`:e),d=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${u.join(`|`)}|${s}`;if(d===Cn){let t=a.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}Cn=d,a.meta.hidden=e.length===0,a.metaBlurb.textContent=s,a.metaBlurb.hidden=s===``;let f=[];if(n){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let r=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,r.push(i),n?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),r.push(t)}if(e.logo!==``){let n=document.createElement(`img`);n.className=`meta-team-logo`,n.alt=``,n.src=e.logo,n.addEventListener(`error`,()=>{n.hidden=!0}),t?r.unshift(n):r.push(n)}return r},r=document.createElement(`span`);r.className=`meta-dash`,r.textContent=`–`,e.replaceChildren(...t(n.away,!0),r,...t(n.home,!1)),f.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&t===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let t of e){let e=document.createElement(`span`);e.className=/^on air \d/.test(t)?`meta-chip meta-chip-clock`:n?.state===`in`&&t===n.status?`meta-chip chip-live`:`meta-chip`,e.textContent=t,f.push(e)}a.meta.replaceChildren(...f)}function V(){let e=I(),t=an(),n=xe();g(a.status,()=>p(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),a.status.dataset.playing=n?`loading`:String(t),g(a.title,()=>$t()),a.title.classList.toggle(`with-context`,R()),a.album.classList.toggle(`with-context`,R()),(R()||D)&&Gn(),tn(),wn(),a.goLiveNow.hidden=!ht()||D!==null||R()||xt()===null;let r=t?`${z()} · ${s}`:s;document.title!==r&&(document.title=r),a.copyNow.hidden=P.source===``,a.copyNixamp.hidden=Ki()===``,a.shareNow.hidden=Gi()===``,wi(),Li(),a.downloadNow.hidden=!(D&&O?.link?.download),Zn(),a.album.textContent=en();let i=rn(),o=nn();a.elapsed.textContent=oe(i),a.total.textContent=o>0?oe(o):`--:--`,de||(a.seek.value=String(o>0?Math.round(i/o*1e3):0),a.seek.disabled=o<=0||N()),a.playPause.textContent=t?`❚❚`:`▶`,_(a.playPause,`aria-label`,()=>p(t?`Pause`:`Play`)),_(a.seek,`aria-valuetext`,()=>`${oe(P.position)} ${f.language===`en`?`of`:`/`} ${oe(P.duration)}`),_(a.volume,`aria-valuetext`,()=>f.number(Number(a.volume.value)/100,{style:`percent`})),_(a.playlistTitle,`data-title`,()=>c===`remote`?`Files on ${l||`this server`} (${e.toLocaleString(f.language)})`:`${p(`Playlist`)} (${f.number(e)})`),g(a.source,()=>c===`remote`?`connected · ${l||F.address.replace(/^https?:\/\//,``)||`—`}`:x.length>0?`local · ${x.length} files`:p(`no source`)),Un(),g(a.remoteState,()=>c===`remote`?`${le}${C?` — ${C}`:``}`:p(`not connected`)),a.remoteState.dataset.status=c===`remote`?le:`idle`,a.disconnect.hidden=c!==`remote`;let u=P.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:c===`remote`&&S.note!==``?S.note:T;a.note.textContent=u,a.note.hidden=u===``,a.linkNote.textContent=u,a.linkNote.hidden=u===``,Lr(u),Ln(),a.glyphs.textContent=M.map(Sn).join(``);let[d,m]=Wt()?S.levels:P.levels();a.levels.textContent=xn(d,m)}let Tn=``,H=``,En=0;function Dn(e){ue(a.playlist),H=e,En=0,Tn=``,Ln()}function On(e,t,n,r,i){if(a.playlistPager.hidden=n<=1,n<=1){a.playlistPager.replaceChildren();return}let o=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{ue(a.playlist),En=t,Tn=``,Ln()}),i},s=document.createElement(`span`);s.className=`pager-where`,g(s,()=>`${r+1}–${i} of ${e.toLocaleString(f.language)}`),a.playlistPager.replaceChildren(o(`‹ Previous`,t-1,`The page before this one`),s,o(`Next ›`,t+1,`The page after this one`))}function kn(e){if(a.crumbs.hidden=!e,!e)return;let t=H===``?[]:H.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>Dn(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),a.crumbs.replaceChildren(...r)}function An(e,t,n){let r=document.createElement(`li`);r.className=`folder`;let i=document.createElement(`span`);i.className=`name`,i.textContent=`${e}/`;let a=document.createElement(`span`);a.className=`count`,a.textContent=`${t} file${t===1?``:`s`}`,r.append(i,a);let s=document.createElement(`button`);if(s.type=`button`,s.className=`row-main`,s.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),s.append(i,a),r.replaceChildren(s),s.addEventListener(`click`,t=>{t.stopPropagation(),Dn(H===``?e:`${H}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,o(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),gn(n)}),r.append(i)}return c===`remote`&&n.length>0&&ht()&&r.append(Ut(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let jn=null,Mn=``,Nn=``,Pn=[],Fn=(e,t)=>{t.title=t.textContent??``,sn(e,t)};function In(e,t){let n=document.createElement(`span`);n.className=`name row-file`,n.textContent=e;let r=document.createElement(`span`);r.className=`row-path`,r.textContent=t;let i=document.createElement(`span`);i.className=`row-label`;let a=document.createElement(`span`);a.className=`row-value`,a.append(n);let o=document.createElement(`span`);return o.className=`row-value`,o.append(r),i.append(a),Fn(a,n),Fn(o,r),{label:i,pathView:o}}function Ln(){let e=(D?k?.channels.find(e=>e.id===D?.id):void 0)?.playlist,t=!!(D&&e?.length);a.livePlaylistPanel.hidden===t&&(a.livePlaylistPanel.hidden=!t);let n=t?D.id:``,r=t?e:[];if(Nn!==n||Pn.length!==r.length||Pn.some((e,t)=>e!==r[t])){Nn=n,Pn=r;let e=r.map((e,t)=>{let n=document.createElement(`li`);n.className=`row file-row live-file-row`,n.dataset.index=String(t);let r=document.createElement(`span`);r.className=`n`,r.textContent=String(t+1);let{label:i,pathView:a}=In(e.slice(e.lastIndexOf(`/`)+1),e),o=document.createElement(`span`);return o.className=`row-main`,o.append(i,r),n.append(o,a),n});w(a.livePlaylist,...e)}let s=c===`remote`?S.tracks:x,l=`${c}:${D?.id??``}:${H}:${a.filter.value}:${En}:${ht()}:${a.adminPanel.hidden}`;if(Tn&&jn===s&&Mn===l){Rn();return}jn=s,Mn=l;let u=c===`remote`?S.tracks.map(e=>({name:se(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):x.map(e=>({name:se(e),seconds:e.duration,group:``,folder:``,remote:!1})),d=a.filter.value.trim().toLowerCase(),f=u.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>d===``||`${e.folder}/${e.name}`.toLowerCase().includes(d)),p=e=>d!==``||H===``||e===H||e.startsWith(`${H}/`),m=e=>e===H,h=e=>{let t=H===``?e:e.slice(H.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},g=new Map;for(let e of f){if(!p(e.folder)||m(e.folder))continue;let t=h(e.folder);t!==``&&g.set(t,(g.get(t)??0)+1)}let _=f.filter(e=>m(e.folder)&&p(e.folder)),v=[...g].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),y=ut(v.length+_.length,En,i);En=y.page;let b=v.slice(y.from,y.to),ee=_.slice(Math.max(0,y.from-v.length),Math.max(0,y.to-v.length)),te=`${c}:${H}:${d}:${y.page}/${i}:${v.join(`,`)}:${_.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==Tn){Tn=te,kn(d===``&&(v.length>0||H!==``)),On(v.length+_.length,y.page,y.pages,y.from,y.to);let e=[];for(let[t,n]of b){let r=H===``?t:`${H}/${t}`,i=f.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(An(t,n,i))}let t=``,n=_.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(zn(r.group)));let i=document.createElement(`li`);i.className=`row`,i.dataset.index=String(r.index);let a=document.createElement(`span`);a.className=`n`,a.textContent=String(r.index+1).padStart(2,` `);let s=r.folder?`${r.folder} / ${r.name}`:r.name,{label:l,pathView:u}=In(r.name,r.folder?`${r.folder}/${r.name}`:r.name),d=document.createElement(`span`);d.className=`time`,d.textContent=r.seconds>0?oe(r.seconds):`--:--`;let f=document.createElement(`button`);f.type=`button`,f.className=`row-main`,f.setAttribute(`aria-label`,`Play ${s}${r.seconds>0?`, ${oe(r.seconds)}`:``}`),f.append(l,a,d),i.append(f);let p=document.createElement(`span`);p.className=`row-play-glyph`,o(p,`play`),i.append(p),c===`remote`&&ht()&&D===null&&!R()&&i.append(Ut(()=>({kind:`track`,index:r.index,name:s}),s)),i.classList.add(`file-row`),i.append(u),e.push(i)}w(a.playlist,...e)}Rn()}function Rn(){let e=D?k?.channels.find(e=>e.id===D?.id):void 0;if(e?.playlist&&e.playlist.length>0){let t=e.entry??0;for(let e of Array.from(a.livePlaylist.children)){let n=e,r=Number(n.dataset.index),i=Number.isInteger(r)&&r===t;n.classList.toggle(`selected`,i),n.classList.toggle(`playing`,i),n.classList.toggle(`live-file-current`,i),i?n.setAttribute(`aria-current`,`true`):n.removeAttribute(`aria-current`)}for(let n of Array.from(a.playlist.children)){let r=n,i=Number(r.dataset.index),a=S.tracks[i],o=a?`${a.folder?`${a.folder}/`:``}${se(a)}`:``,s=!!o&&o===e.playlist[t];r.classList.toggle(`selected`,s),r.classList.toggle(`playing`,!1),s?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}return}for(let e of Array.from(a.livePlaylist.children)){let t=e;t.classList.remove(`selected`,`playing`,`live-file-current`),t.removeAttribute(`aria-current`)}let t=L(),n=an();for(let e of Array.from(a.playlist.children)){let r=e,i=Number(r.dataset.index),a=Number.isInteger(i)&&i===t;r.classList.toggle(`selected`,a),r.classList.toggle(`playing`,a&&n),a?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}}function zn(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!a.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,r=>{r.stopPropagation(),So(t,n,()=>Bn(e),()=>Ln())}),t.append(n)}return t}async function Bn(e){try{let t=await fetch(F.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();return U(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`),t.ok}catch{return U(`could not reach the server`),!1}}function Vn(){let e=a.canvas,t=Math.min(2,globalThis.devicePixelRatio||1),n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);n>0&&r>0&&(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);if(Wt())ct=et(ct,M);else{let e=P.read();e.length>0&&(dt.length!==25&&(dt=Ze(24,e.length)),M=$e(M,Qe(e,dt)),ct=et(ct,M))}if(i){let t=getComputedStyle(document.documentElement);tt(i,{width:e.width,height:e.height},M,ct,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(an()||P.jinglePlaying){a.glyphs.textContent=M.map(Sn).join(``);let[e,t]=Wt()?S.levels:P.levels();a.levels.textContent=xn(e,t)}if(an()){a.elapsed.textContent=oe(rn());let e=nn();!de&&e>0&&(a.seek.value=String(Math.round(rn()/e*1e3)))}requestAnimationFrame(Vn)}let Hn=``;function Un(){if(c!==`remote`){a.wayInHere.hidden=!0,Hn=``;return}let e=ft()&&!y,t=ie||F.address,n=e?null:ne(F.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Hn)return;Hn=r;let[i,o]=re({name:l||`this server`,view:t,admin:n});i.hidden=!e,o.hidden=e,a.wayInHere.replaceChildren(i,o),a.wayInHere.hidden=!1}function Wn(e){a.video.hidden=!e,a.fullscreen.hidden=!e,Ae(),A=null,j=null}function Gn(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=D?_e(k?.channels.find(e=>e.id===D?.id)?.art??D.art):``,t=JSON.stringify([$t(),en(),e]);t!==Ce&&(Ce=t,navigator.mediaSession.metadata=new MediaMetadata({title:$t(),album:en(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void vn()),navigator.mediaSession.setActionHandler(`pause`,()=>void vn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void yn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void yn(-1)))}document.addEventListener(`click`,()=>{P.resumeAfterInteraction().catch(()=>{})}),a.filter.addEventListener(`input`,()=>{En=0,Tn=``,Ln()}),a.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),a.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(he=null,mn(n))}),a.fullscreen.addEventListener(`click`,()=>{let e=a.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),a.prev.addEventListener(`click`,()=>void yn(-1)),a.next.addEventListener(`click`,()=>void yn(1)),a.stop.addEventListener(`click`,()=>void bn()),a.playPause.addEventListener(`click`,()=>void vn());async function Kn(e){let t=vt(e,_t());if(!t){if(!ht()){T=c===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,V();return}await Xn(e);return}if(D=null,P.stop(),t.kind===`embed`){O={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},Wn(!1),a.embedFrame.src=t.src,a.embed.hidden=!1,A={url:e,label:t.label,kind:`embed`},T=`Playing ${t.label} here, in this browser.`,V();return}if(t.kind===`list`){await qn(e,t.label);return}O={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Se(()=>P.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),Wn(t.video),A={url:e,label:t.label,kind:`direct`},T=`Playing ${t.label} here, in this browser.`,V()}async function qn(e,t){T=`Reading ${t}…`,V();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){T=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,V();return}let r=gt(n,e);if(r.entries.length===0){T=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,V();return}j={url:e,title:r.title||t,entries:r.entries,at:0},await Jn()}async function Jn(){let e=j,t=e?.entries[e.at];if(!e||!t)return;let n=mt(t.url);O={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Se(()=>P.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),j!==null&&(Wn(n),A={url:e.url,label:e.title,kind:`direct`},j=e,T=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,V())}function Yn(){let e=j;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Jn(),!0)}async function Xn(e){if(c!==`remote`){T=`Pick a server to go live on, or connect to one, to put a link on the air.`,V();return}T=`Asking ${l||`the server`} to fetch ${e}…`,V(),await Se(async()=>{let t,n={};try{t=await fetch(F.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!t.ok||!n.channel){T=n.error??`that link would not play.`;return}try{await fetch(F.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await go({id:n.channel,name:n.name||e,video:n.video!==!1,art:n.art},!0,{kind:`channel`,link:{url:e,extractor:n.extractor??``,download:n.download===!0,live:n.live===!0,video:n.video!==!1}}),(n.entries??0)>1&&(T=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),V()}a.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.linkUrl.value.trim();t!==``&&Kn(t)});function Zn(){let e=c===`remote`?F.address:``,t=u.filter(t=>v(t.url)!==v(e)),n=JSON.stringify({here:e,name:l,carries:m,others:t});if(n===d||document.activeElement===a.linkServer)return;d=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${l||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}a.linkServer.replaceChildren(...r),a.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,a.linkServer.hidden=t.length===0}function Qn(){let e=c===`remote`?v(F.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!u.some(t=>v(t.url)===e)){let n=document.createElement(`option`);n.value=F.address,n.textContent=l||e,t.push(n)}for(let e of u){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}a.remoteServer.replaceChildren(...t);let r=u.find(t=>v(t.url)===e);a.remoteServer.value=r?.url??``}async function $n(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;u=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Zn(),Qn()}catch{}}async function er(){let e=a.linkUrl.value.trim()||A?.url||``;if(e===``){T=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,V();return}let t=a.linkServer.value;if(t!==``&&(c!==`remote`||v(t)!==v(F.address))){let n=u.find(e=>e.url===t)?.name??t;h=e,T=`Connecting to ${n} to go live with it…`,V(),tr(t);return}if(c!==`remote`){T=u.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,V();return}if(!m){T=`${l||`This server`} has no ffmpeg, so it cannot carry a link.`+(u.length>0?` Pick a server to go live on, beside the link.`:``),V();return}if(!ht()){T=`Sign in to nixamp.com to go live here, or use the server's control link.`,V();return}await Xn(e)}function tr(e){let t=a.linkUrl.value.trim();y=!0,b=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit(),a.linkUrl.value=t}a.linkGoLive.addEventListener(`click`,()=>{er()}),a.linkServer.addEventListener(`change`,()=>{let e=a.linkServer.value;e!==``&&tr(e)}),a.downloadNow.addEventListener(`click`,()=>{let e=O?.link;if(!e||c!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(F.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),T=`Fetching it through the server; your browser will save it when it arrives.`,V()}),a.goLiveNow.addEventListener(`click`,()=>{let e=xt();e&&St(e,a.goLiveNow)}),a.seek.addEventListener(`input`,()=>{de=!0}),a.seek.addEventListener(`change`,()=>{let e=nn();e>0&&P.seek(Number(a.seek.value)/1e3*e),de=!1}),a.volume.addEventListener(`input`,()=>{let e=Number(a.volume.value)/100;P.volume=e,a.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),a.volumeToggle.textContent=e===0?`🔇`:`🔊`,_(a.volumeToggle,`aria-label`,()=>p(e===0?`Unmute`:`Mute`));try{localStorage.setItem(un,String(e))}catch{}}),a.volumeToggle.addEventListener(`click`,()=>{let e=Number(a.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(un));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}a.volume.value=e?String(t):`0`,a.volume.dispatchEvent(new Event(`input`))}),a.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let nr=e=>{e.addEventListener(`change`,()=>{let t=we(Array.from(e.files??[]));if(t.length===0){T=`Nothing playable in that selection.`,V();return}De(x),x=t,ce=0,c=`local`,F.close(),lo(!1),T=``,mn(0)})};nr(a.files),nr(a.folder),a.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.remoteUrl.value,{base:n,key:r}=Ie(t);if(n===``){T=`That is not an address.`,V();return}(async()=>{le=`connecting`,V();let e=Je(n);if(e){le=`error`,C=e,T=e,h=``,c=`local`,V();return}if(await qe(n,void 0,r)===null){le=`error`;let e=Ge(n);C=e?`needs the server's name`:`not answering`,T=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,h=``,c=`local`,V();return}let i=await Ke(n,r);if(i){le=`error`,C=i,T=i,h=``,c=`local`,V();return}c=`remote`,T=``;try{localStorage.setItem(cn,t.trim())}catch{}F.connect(t),lo(!0),aa(),mr(),ao(),V()})()}),a.remoteServer.addEventListener(`change`,()=>{let e=a.remoteServer.value;e!==``&&(y=!1,b=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit())});let rr=``,ir=null,ar=async(e=!1)=>{a.directory.hidden=!1,e||(a.directoryNote.textContent=`Looking for live streams…`,w(a.directoryList)),ir||=setInterval(()=>{!a.directory.hidden&&document.visibilityState===`visible`&&ar(!0)},fn);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],u=t.map(e=>({name:e.name,url:e.url})),Zn();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:q});if(e&&i===rr)return;rr=i,_r(r.recent??[])}catch{e||(a.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(w(a.directoryList),t.length===0){a.directoryNote.textContent=`Nobody is streaming right now.`;return}a.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let s=[`${e.tracks.toLocaleString(f.language)} files to browse`];e.playing!==!1&&e.nowPlaying?s.push(`playing ${e.nowPlaying}`):s.push(`player idle`),e.code&&s.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=s.join(` · `),i.title=i.textContent,n.append(r,i);let c=e.admin??ne(e.url),l=(t,n=``)=>{y=t,b=n,a.remoteUrl.value=t?e.url:c??e.url,a.directory.hidden=!0,document.body.classList.remove(`route-directory`),a.remoteForm.requestSubmit()},u=document.createElement(`ul`);u.className=`server-lives`;for(let t of e.channels??[]){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`detail live`;let i=e.channelCodes?.[t]??``,a=e.channelCallers?.[t]??0;r.textContent=`● ${t}`+(i?` · ☎ ${i}${a?` · ${a} on the phone`:``}`:``);let s=e.lineup?.find(e=>e.name===t);if(s?.art&&/^https?:\/\//i.test(s.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=s.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}s?.about&&(r.title=s.about);let d=document.createElement(`button`);d.type=`button`,d.className=`icon`,o(d,`party`),d.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),d.title=`Join live: ${t} on ${e.name}`,d.addEventListener(`click`,()=>l(!0,`channel:${t}`));let f=document.createElement(`button`);f.type=`button`,f.className=`icon`,o(f,`link`),f.setAttribute(`aria-label`,`Copy live room link for ${t}`),f.title=`Copy a nixamp link to this live room`;let p=`${globalThis.location.origin}/?url=${encodeURIComponent(e.url)}&play=${encodeURIComponent(`channel:${s?.id??t}`)}`;f.addEventListener(`click`,e=>{e.stopPropagation(),Co(p,f,`✓`)});let m=document.createElement(`button`);m.type=`button`,m.className=`icon`,o(m,`copy`),m.setAttribute(`aria-label`,`Copy raw stream URL for ${t}`),m.title=`Copy the raw stream URL for VLC or another player`;let h=e.url;try{let n=new URL(e.url);n.pathname=`/api/channels/${encodeURIComponent(s?.id??t)}`,h=n.toString()}catch{}if(m.addEventListener(`click`,e=>{e.stopPropagation(),Co(h,m,`✓`)}),n.append(r,d,f,m),s?.startedBy&&q&&s.startedBy===q&&c){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,o(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),l(!1,`channel:${s?.id??t}`)}),n.append(e)}u.append(n)}let[d,p]=re({name:e.name,view:e.url,admin:c},()=>{a.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(n,d,p),q&&t.append(Fr(e.url,e.name)),e.ownerId&&q&&e.ownerId!==q&&t.append(ya(e.ownerId,e.name)),u.childElementCount>0&&t.append(u),e.ownerId&&q&&e.ownerId===q){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));a.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{a.directoryNote.textContent=`could not reach the directory`}finally{await ar()}})()}),t.append(n)}a.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!a.directory.hidden&&ar(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),ar()}let or=null,sr=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,cr=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,lr=``,ur=``,dr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===lr)return;lr=t,a.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}a.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[sr(t.network),`network-${t.network}`],[cr(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}a.adminConnections.append(e)}};function U(e){a.adminSaid.textContent=e,a.adminSaid.hidden=e===``}let fr=async()=>{try{let e=await fetch(F.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;a.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,dr(t.connections??[]),pr(t.publish??[],(t.channels??[]).map(e=>e.id)),ko(t.home??``,t.root??``),uo()}catch{a.adminNote.textContent=`lost touch with the server`}};function pr(e,t){a.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===ur)return;if(ur=n,e.length===0){w(a.publishList);return}let r=e.length-t.length;a.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,w(a.publishList,...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,g(o,()=>p(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let mr=async()=>{if(c!==`remote`){a.adminPanel.hidden=!0,a.publishPanel.hidden=!0,or&&clearInterval(or),or=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(F.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;y&&(e=!1),pt=i&&!e;let o=a.partiesList.dataset.adminMode!==String(e);if(a.adminPanel.hidden=!e,o&&(a.partiesList.dataset.adminMode=String(e),a.partiesList.querySelectorAll(`details[open]`).forEach(e=>e.removeAttribute(`open`)),Tr()),io(e),h!==``){let e=h;h=``,ht()?Xn(e):(T=`Sign in to nixamp.com to go live here.`,V())}if(or&&clearInterval(or),or=null,uo(),aa(),ao(),a.listenOnly.hidden=e,!e){a.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}a.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,fr(),or=setInterval(()=>void fr(),2e3)};function hr(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;U(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(F.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),o=await i.json();if(!i.ok){U(o.error??`that did not work`);return}U(`${o.channel?.name||t||e} is on the air.`),a.adminSource.value=``,a.adminName.value=``,ao(),uo()}catch{U(`could not reach the server`)}})()}a.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=a.adminSource.value.trim();t&&hr(t,a.adminName.value.trim())}),a.adminAdd.addEventListener(`click`,()=>{let e=a.adminSource.value.trim();if(!e)return;U(`Reading ${e}…`);let t=a.adminReplace.checked,n=a.adminName.value.trim();(async()=>{try{let r=await fetch(F.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();U(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(a.adminSource.value=``,a.adminName.value=``,ao(),uo())}catch{U(`could not reach the server`)}})()});let gr=e=>{let t=Math.max(1,Math.round((Date.now()-e)/6e4));if(t<60)return`${t} minute${t===1?``:`s`} ago`;let n=Math.round(t/60);return`${n} hour${n===1?``:`s`} ago`},_r=e=>{let t=[],n=q?e.filter(e=>e.ownerId&&e.ownerId!==q):[];if(a.recentNote.hidden=n.length===0,n.length===0){w(a.recentList);return}for(let e of n){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${gr(e.endedAt)}`:`ended ${gr(e.endedAt)}`,r.append(i,a),n.append(r,ya(e.ownerId,e.name)),t.push(n)}w(a.recentList,...t)},vr=e=>{let t=Math.max(0,Math.floor(e)),n=String(t%60).padStart(2,`0`),r=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(r).padStart(2,`0`)}:${n}`:`${r}:${n}`};function yr(e){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.event.title||e.party.partyCode;let i=document.createElement(`span`);i.className=e.party.playing?`detail live`:`detail`,i.textContent=[e.party.playing?`▶ ${vr(e.party.positionNow)}`:`❚❚ ${vr(e.party.positionNow)}`,e.party.mediaTitle,e.party.origin,e.host?`yours`:``].filter(Boolean).join(` · `),n.append(r,i);let a=document.createElement(`a`);a.className=`button`,a.href=e.links.partyUrl||e.links.nixampUrl,a.rel=`noopener`,a.target=`_blank`,Ct(a),a.title=`Join live on the site hosting this party (opens in a new tab)`;let o=document.createElement(`a`);o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.className=`party-row`,n.className=`party-name`,n.title=i.textContent,i.hidden=!0;let s=document.createElement(`details`);s.className=`party-actions`;let c=document.createElement(`summary`);return c.textContent=`⋯`,_(c,`aria-label`,()=>`${p(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let br=[],xr=[],Sr=!1,Cr=null,wr=``;function Tr(){let e=new Map,t=(t,n,r)=>{if(!r.length)return;let i=e.get(t);if(i){let e=new Set(i.rows.map(e=>e.dataset.liveKey));i.rows.push(...r.filter(t=>!e.has(t.dataset.liveKey)))}else e.set(t,{name:n,rows:r})},n=c===`remote`&&k?v(F.address):``;for(let e of br){let r=v(e.url);if(!r||r===n)continue;let i=[],o=(t,n)=>{let o=document.createElement(`li`);o.dataset.liveKey=`${r}:${t}`,o.className=`party-row`;let s=document.createElement(`span`);s.className=`party-name`,s.textContent=n,s.title=n;let c=document.createElement(`button`);c.type=`button`,Ct(c),_(c,`aria-label`,()=>`${p(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{y=!0,b=t,a.remoteUrl.value=e.url,a.remoteForm.requestSubmit()}),o.append(s,c),i.push(o)};e.playing!==!1&&e.nowPlaying&&o(`live`,pe(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);o(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&k&&t(n,k.server.name||l||n,po(k));for(let e of xr){let n=e.party.origin;try{n=new URL(e.links.partyUrl||e.party.partyUrl).origin}catch{}let r=e.party.origin;try{r=new URL(n).hostname}catch{}let i=yr(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...a.partiesList.children].map(e=>[e.dataset.liveKey,e])),i=[];for(let[t,n]of e){let e=r.get(t);if(!e){e=document.createElement(`li`),e.dataset.liveKey=t,e.className=`party-server`;let n=document.createElement(`h3`),r=document.createElement(`ul`);r.className=`party-rows`,e.append(n,r)}let a=e.querySelector(`h3`);a.textContent!==n.name&&(a.textContent=n.name),fe(e.querySelector(`ul`),n.rows),i.push(e)}fe(a.partiesList,i),a.partiesNote.hidden=e.size>0,e.size||g(a.partiesNote,()=>p(Sr?`No parties live right now.`:`Loading…`))}let Er=5e3,Dr=new Set,Or=(e,t)=>{t?Dr.add(e):Dr.delete(e),Dr.size?a.partiesPanel.dataset.loading=`true`:delete a.partiesPanel.dataset.loading};async function kr(){if(e||(wr!==q&&(Cr?.abort(),Cr=null,xr=[],wr=q,Tr()),Cr))return;let t=new AbortController;Cr=t;let n=!Sr;n&&Or(t,!0);let r=q,i=setTimeout(()=>t.abort(),8e3),o=async e=>{let n=await fetch(e,{signal:t.signal,cache:`no-store`});return{ok:n.ok,status:n.status,body:n.ok?await n.json():null}};try{let[e,n]=await Promise.allSettled([o(`/api/directory`),r?o(`/api/v1/watch-parties`):Promise.resolve(null)]);if(Cr!==t||r!==q||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(br=e.value.body.streams??[],Sr=!0,a.directory.dataset.available=String(br.length>0),no()),n.status===`fulfilled`&&n.value&&(n.value.ok?(xr=n.value.body.parties??[],Sr=!0):[401,403].includes(n.value.status)&&(xr=[])),Tr(),!Sr&&!k&&g(a.partiesNote,()=>p(`Could not refresh parties.`))}finally{clearTimeout(i),n&&Or(t,!1),Cr===t&&(Cr=null)}}a.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){T=n.error??`No party found with that invite code.`,V();return}a.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{T=`Could not look up that party. Try again.`,V()}})()});async function Ar(){if(!q){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];a.connectionsNote.hidden=t.length===0,a.connectionsList.hidden=t.length===0,w(a.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,g(a,()=>p(`Disconnect`)),a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Ar()})()}),t.append(n,a),t}))}catch{a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0}}let jr=new Set,W=e=>{try{return new URL(e).origin}catch{return e}},Mr=e=>[...jr].some(t=>W(t)===W(e));async function Nr(){if(!q){jr=new Set,a.favoritesPanel.hidden=!0,Ir();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){a.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];jr=new Set(t.map(e=>e.url)),a.favoritesPanel.hidden=t.length===0,a.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,w(a.favoritesList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...re({name:e.name||e.url,view:e.url,admin:ne(e.url)}),Fr(e.url,e.name)),t}))}catch{a.favoritesPanel.hidden=!0}Ir()}async function Pr(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){T=n?`Could not save that favourite.`:`Could not remove that favourite.`,V();return}}catch{T=`could not reach nixamp.com`,V();return}if(n)jr.add(e);else for(let t of[...jr])W(t)===W(e)&&jr.delete(t);await Nr()}function Fr(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Mr(e);n.textContent=t?`♥`:`♡`,n.dataset.on=t?`yes`:`no`,n.title=t?`Remove from favourites`:`Add to favourites`,n.setAttribute(`aria-label`,n.title)};return r(),n.addEventListener(`click`,n=>{n.stopPropagation();let i=[...jr].find(t=>W(t)===W(e))??e;Pr(Mr(e)?i:e,t,!Mr(e)).then(r)}),n}function Ir(){let e=c===`remote`?F.shareLink:``;if(a.favHere.hidden=!(q&&e),a.favHere.hidden)return;let t=Mr(e);a.favHere.textContent=t?`♥`:`♡`,a.favHere.dataset.on=t?`yes`:`no`,a.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,a.favHere.setAttribute(`aria-label`,a.favHere.title)}o(a.copyNow,`copy`),a.copyNow.addEventListener(`click`,()=>{Co(P.source,a.copyNow,`✓`)});function Lr(e){if(e===``||e===it)return;it=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),g(n,()=>r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),a.logList.prepend(t);a.logList.children.length>100;)a.logList.lastElementChild?.remove()}let Rr=3e3,G=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,zr=``,Br=``,Vr=null,Hr=!1,Ur=new Set,Wr=``,Gr=null,Kr=!1,qr=Vt(e=>localStorage.getItem(e)),K=It(e=>localStorage.getItem(e)),Jr=new Set,Yr=new Set,Xr=null,Zr=``,Qr=``,q=``,$r=(()=>{try{let e=sessionStorage.getItem(`nixamp.translationSession`);if(e&&/^listener-[a-f0-9-]{36}$/.test(e))return e;let t=`listener-${crypto.randomUUID()}`;return sessionStorage.setItem(`nixamp.translationSession`,t),t}catch{return`listener-${crypto.randomUUID()}`}})(),ei=null,J=!1,ti=``,ni=!1,ri=!1,ii=``,ai=0,oi=!1,si=!1;try{a.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let ci=new Jt(()=>{si=!0,oi&&(a.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),li=()=>{let e=Number(a.transcriptBackgroundLevel.value);ci.setLevel(e/100),a.transcriptBackgroundValue.value=`${e}%`,_(a.transcriptBackgroundLevel,`aria-valuetext`,()=>f.number(e/100,{style:`percent`})),a.transcriptBackgroundLevel.disabled=!a.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(a.transcriptBackgroundLevel.value=e)}catch{}li(),a.transcriptBackgroundLevel.addEventListener(`input`,()=>{li();try{localStorage.setItem(`nixamp.backgroundLevel`,a.transcriptBackgroundLevel.value)}catch{}});let Y=new Xt({account:()=>G===``?q:``,changed:()=>Hi()});B(`translation-buy-tools`).append(Y.button()),Y.refresh();let ui=new Yt({reconnecting:()=>X.reset(),line:(e,t)=>{vi=0,yi.push(e),Bi(),X.push(e,t,0)},status:e=>{a.transcriptAudioNote.textContent=e},failed:e=>{ti=e,Qr=e,J=!1,a.transcriptAudio.checked=!1,X.disable(),pi(),a.transcriptAudioNote.textContent=`${e} Original audio restored.`,Y.refresh()}}),X=new Gt({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(ui.audio(String(e))):fetch(e,t)),playing:()=>P.playing,volume:()=>P.volume,active:e=>{oi=e,P.translatedAudio(e),ci.active(e&&P.playing&&a.transcriptBackground.checked)},status:e=>{a.transcriptAudioNote.textContent=e+(si&&oi?` · background unavailable`:``)},failed:()=>{Qr=a.transcriptAudioNote.textContent||`Translated audio stopped.`,J=!1,a.transcriptAudio.checked=!1,pi()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!q||G!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!ei||ei.channel!==t.channel||ei.expires<Date.now()+2e4||ei.remaining<t.text.length){let n=await fetch(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),r=await n.json();if(!n.ok||!r.token||!r.expires)throw Error(r.error||`Sign in to enable translated audio.`);ei={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return ei.remaining-=t.text.length,{authorization:`Bearer ${ei.token}`}}}),di=new Qt({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,$r),fetch(e,{...t,headers:n})},language:()=>K,speakers:()=>a.transcriptAudio.checked,voices:()=>Xr?.voices??[],channel:()=>$r,status:e=>{!ni&&!J&&(ti=e),a.transcriptNote.textContent=e},failed:()=>{J=!1,a.transcriptAudio.checked=!1,X.disable(),pi()},lines:e=>{vi=0,yi.push(...e),Bi(),hi(),a.transcriptAudio.checked&&X.pushBatch(e.map(e=>({line:e,lag:0,url:`/api/v1/speech/synthesize`,init:{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({text:e.text,language:K,channel:$r,speaker:e.speaker,voice:di.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),fi=new Kt(e=>{ni&&P.playing&&di.push(e)});function pi(){ai++,ni=!1,ri=!1,ii=``,fi.stop(),di.reset(),ui.stop(),ci.stop(),X.reset(),w(a.transcriptSpeakers)}async function mi(){if((ni||ri)&&ii===P.mediaKey)return;pi();let e=ai;ri=!0,ii=P.mediaKey;try{if(!q||G!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=P.audioInput();if(si=!1,a.transcriptAudio.checked&&a.transcriptBackground.checked&&ci.start(t.context,t.node).then(t=>{t&&e===ai&&ci.active(oi&&P.playing&&a.transcriptBackground.checked)}),a.transcriptAudio.checked&&c===`remote`&&D)await ui.start(Wi(),K),Y.refresh();else{if(a.transcriptAudio.checked&&await Y.startSession($r),e!==ai)return;await fi.start(t.context,t.node,a.transcriptAudio.checked?2:5)}if(e!==ai)return;ni=!0,J=!0,vi=0,xi??=setInterval(Bi,250),a.transcriptNote.textContent=a.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==ai)return;J=!1,a.transcriptAudio.checked=!1,X.disable(),pi(),ti=t instanceof Error?t.message:`This audio could not be captured.`,a.transcriptNote.textContent=ti}finally{e===ai&&(ri=!1)}}function hi(){let e=[...di.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(a.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id;let n=document.createElement(`span`),r=t.id.split(`-`)[1];g(n,()=>`${p(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,_(i,`aria-label`,()=>`${p(`Speaker voices`)}: ${r}`);for(let e of Xr?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,X.reset()}),e.append(i),a.transcriptSpeakers.append(e)}a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked;for(let e of a.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[a.audio,a.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(P.showingVideo?a.video:a.audio)&&pi()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(P.showingVideo?a.video:a.audio)&&J&&qr&&P.playing&&mi()});e.addEventListener(`volumechange`,()=>{X.setVolume()})}let gi=``,_i=null,vi=Rt(6,!1),yi=[],bi=[],xi=null;function Si(){if(c!==`remote`)return null;let{base:e}=Ie(To());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=D?D.id:O?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Ci(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${G}/api/v1/trollbox?${n.toString()}`}function wi(){let e=Si(),t=e?`${e.server}|${e.channel}`:``;t!==zr&&(zr=t,Br=``,Ur.clear(),a.trollboxList.replaceChildren(),Vr&&clearTimeout(Vr),Vr=null,a.trollboxPanel.hidden=e===null,a.trollboxForm.hidden=!0,Ai(!1),e&&(g(a.trollboxNote,()=>`The room for ${$t()||e.channel}. Loading…`),Ei()))}function Ti(e){let t=document.createElement(`li`);t.dataset.id=e.id;let n=document.createElement(`time`);n.className=`when`,n.dateTime=e.createdAt;let r=new Date(e.createdAt);g(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(f.language,{hour:`2-digit`,minute:`2-digit`}));let i=document.createElement(`span`);i.className=`who`,i.textContent=e.handle;let a=document.createElement(`span`);return a.className=`line`,a.textContent=e.body,a.dir=`auto`,a.translate=!1,t.append(n,i,a),t}async function Ei(){let e=Si(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===zr&&!Hr){Hr=!0;try{let n=await fetch(Ci(e,Br)),r=await n.json().catch(()=>({}));if(t!==zr)return;if(!n.ok){a.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!Ur.has(e.id));for(let e of i)Ur.add(e.id),a.trollboxList.append(Ti(e)),Br=e.createdAt;for(;a.trollboxList.children.length>200;)a.trollboxList.firstElementChild?.remove();let o=r.you??``,s=Wr!==o;Wr=o,s&&(ei=null,Hi()),a.trollboxForm.hidden=o===``,a.trollboxEditLabel.hidden=o===``||!Di,o===``&&Ai(!1),g(a.trollboxNote,()=>o===``?G===``?`The room for ${$t()||e.channel}. Sign in to say something.`:`The room for ${$t()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${$t()||e.channel}.`)}catch{t===zr&&(a.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Hr=!1,t===zr&&(Vr=setTimeout(()=>{document.visibilityState===`visible`?Ei():Vr=setTimeout(()=>void Ei(),Rr)},Rr))}}}a.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Si(),n=a.trollboxInput.value.trim();t&&n!==``&&(a.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${G}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.message){a.trollboxNote.textContent=r.error??`that did not send`;return}a.trollboxInput.value=``,Ur.has(r.message.id)||(Ur.add(r.message.id),a.trollboxList.append(Ti(r.message)),Br=r.message.createdAt)}catch{a.trollboxNote.textContent=`The trollbox is not answering.`}finally{a.trollboxInput.disabled=!1}})())});let Di=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Oi=Di?jt(e=>MediaRecorder.isTypeSupported(e)):``;a.trollboxMic.hidden=!Di;function ki(e){a.trollboxNote.textContent=e,Lr(e)}function Ai(e){let t=Gr;if(!t)return;Gr=null,clearTimeout(t.stop),clearInterval(t.tick),a.trollboxMic.setAttribute(`aria-pressed`,`false`),a.trollboxMic.textContent=`🎤`;let n=new Promise(e=>{t.recorder.addEventListener(`stop`,()=>e(),{once:!0})});t.recorder.state!==`inactive`&&t.recorder.stop();for(let e of t.stream.getTracks())e.stop();e&&n.then(()=>Mi(new Blob(t.chunks,{type:t.recorder.mimeType||Oi||`audio/webm`}),t.startedAt))}async function ji(){if(Gr||Kr||Wr===``||!Si())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){ki(e.name===`NotAllowedError`?`The microphone was refused. Allow it for nixamp.com and tap again.`:`No microphone could be opened here.`);return}let t;try{t=new MediaRecorder(e,Oi?{mimeType:Oi}:{})}catch{for(let t of e.getTracks())t.stop();ki(`This browser cannot record the microphone.`);return}let n=[];t.addEventListener(`dataavailable`,e=>{e.data.size>0&&n.push(e.data)});let r=Date.now();Gr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>Ai(!0),At),tick:setInterval(()=>{a.trollboxMic.textContent=Mt(r,Date.now())},500)},t.start(250),a.trollboxMic.setAttribute(`aria-pressed`,`true`),a.trollboxMic.textContent=Mt(r,r),ki(`Listening. Tap the mic again when you have said it (${Math.round(At/1e3)} s at most).`)}async function Mi(e,t){let n=Si();if(n&&Wr!==``){if(Date.now()-t<400||e.size===0){ki(`That was too short to hear. Tap, say it, then tap again.`);return}Kr=!0,a.trollboxMic.disabled=!0,a.trollboxMic.textContent=`…`,ki(`Hearing you…`);try{let t=new AudioContext,r;try{r=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let i=new OfflineAudioContext(1,Math.max(1,Math.ceil(r.duration*kt)),kt),o=i.createBufferSource();o.buffer=r,o.connect(i.destination),o.start();let s=Ot((await i.startRendering()).getChannelData(0),kt),c=a.trollboxEdit.checked,l=new URLSearchParams(c?{}:{server:n.server,channel:n.channel}),u=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(u)&&l.set(`language`,u);let d=await fetch(`${G}/api/v1/speech/transcribe?${l.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([s.buffer],{type:`audio/wav`})}),f=await d.json().catch(()=>({}));if(!d.ok){ki(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){ki(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=a.trollboxInput.value.trimEnd();a.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),ki(`Heard: “${p}”. Send it, or fix it first.`);return}Si()&&!Ur.has(f.message.id)&&(Ur.add(f.message.id),a.trollboxList.append(Ti(f.message)),Br=f.message.createdAt),ki(`Said: “${f.message.body}”`)}catch{ki(`That recording could not be read here.`)}finally{Kr=!1,a.trollboxMic.disabled=!1,a.trollboxMic.textContent=`🎤`}}}a.trollboxMic.addEventListener(`click`,()=>{Gr?Ai(!0):ji()});try{a.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}a.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,a.trollboxEdit.checked?`on`:`off`)}catch{}ki(a.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Ni(){try{let e=await fetch(`${G}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`Could not read your profile.`;return}a.personaHandle.value=t.chosen?t.handle??``:``,_(a.personaHandle,`placeholder`,()=>t.handle||p(`handle`)),a.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,a.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;a.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${Pi(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${Pi(t.voice??``)}${n}.`}catch{a.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function Pi(e){return e===`female`?`in a woman's voice`:e===`male`?`in a man's voice`:e.includes(`.`)?`in the voice ${e}`:`in whichever voice your profile says, or one picked for you`}a.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.personaHandle.value.trim(),n={voice:a.personaVoice.value,profile:a.personaProfile.value.trim()};t!==``&&(n.handle=t),a.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${G}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`that did not save`;return}await Ni()}catch{a.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Gr&&Ai(!0)});function Fi(){return c===`remote`&&D?{id:D.id,name:D.name,hls:D.video&&_t()}:P.loaded||A?{id:$r,name:$t()||`This audio`,hls:!1}:null}function Ii(){pi(),ei=null,Jr.clear(),Yr.clear(),_i?.close(),_i=null,xi&&clearInterval(xi),xi=null,yi=[],bi=[],a.transcriptList.replaceChildren(),a.subtitle.hidden=!0,a.subtitle.textContent=``}function Li(){let e=Fi(),t=`${e?.id??``}|${P.mediaKey}|${qr}|${K}|${a.transcriptAudio.checked}|${J}|${q}`;if(t!==gi){if(gi=t,Ii(),a.transcriptPanel.hidden=!1,a.transcriptOn.checked=qr&&(!!D||J||a.transcriptAudio.checked),a.transcriptLanguage.options.length===0)for(let e of Ft){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),g(t,()=>e.code?e.label:p(`Original (auto-detect)`)),a.transcriptLanguage.append(t)}if(a.transcriptLanguage.value=K,Hi(),Ui(),!e){a.transcriptNote.textContent=`Play something to see its captions.`;return}if(!qr){a.transcriptNote.textContent=`Captions are off.`;return}if(ti){a.transcriptNote.textContent=ti;return}a.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,a.transcriptAudio.checked||J?P.playing?mi():a.transcriptNote.textContent=`Press Play to start listening.`:c===`remote`&&D?Ri(e,t):a.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Ri(e,t){let n=6,r=K?`?language=${encodeURIComponent(K)}`:``;try{let i=await fetch(F.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),o=await i.json().catch(()=>({}));if(t!==gi)return;if(!i.ok){a.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){q&&G===``?(J=!0,Li()):a.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=o.backlog??n}catch{t===gi&&(a.transcriptNote.textContent=`The server did not answer about captions.`);return}vi=Rt(n,e.hls);let i=new EventSource(F.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));_i=i;let o=(e,t=!1)=>{for(let n of e){if(!n||typeof n.text!=`string`||!Number.isFinite(n.at)||!Number.isFinite(n.until))continue;let e=`${n.at}|${n.language}`;Jr.has(e)||(Jr.add(e),Jr.size>600&&Jr.delete(Jr.values().next().value),yi.push(n),t&&a.transcriptAudio.checked&&Yr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==gi)return;let i=JSON.parse(r.data);vi=Rt(i.backlog??n,e.hls),o(i.lines??[]);let s=Ft.find(e=>e.code===i.language)?.label??i.language,c=Ft.find(e=>e.code===K)?.label??K;if(a.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:K?`${s||`Detected audio`} → ${c}`:`Original audio · ${s||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${G||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,a.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==gi)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=Ft.find(e=>e.code===i)?.label??i,c=Ft.find(e=>e.code===K)?.label??K;a.transcriptNote.textContent=K?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===gi&&i.readyState===EventSource.CLOSED&&(a.transcriptNote.textContent=`Captions stopped; the server went away.`)}),xi=setInterval(Bi,250)}function zi(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),g(n,()=>Ht(e.at));let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text,r.dir=`auto`,r.translate=!1,(e.language||e.sourceLanguage)&&(r.lang=e.language||e.sourceLanguage);let i=Lt(e);if(i){let a=document.createElement(`span`);a.className=`lang`,a.textContent=i.trim(),e.original&&(r.title=e.original),t.append(n,a,r)}else t.append(n,r);return t}function Bi(){let e=Date.now(),{ready:t,still:n}=zt(yi,e,vi);yi=n;for(let e of t)if(bi.push(e),a.transcriptList.append(zi(e)),Yr.delete(e)&&a.transcriptAudio.checked&&K){let t=new URLSearchParams({at:String(e.at),language:K,voice:`auto`});X.push(e,F.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),vi)}for(;bi.length>200;)bi.shift();for(;a.transcriptList.children.length>200;)a.transcriptList.firstElementChild?.remove();let r=Bt(bi,e,vi),i=a.transcriptList.children,o=r?bi.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===o);let s=P.playing&&r!==null&&!a.video.hidden&&a.video.offsetHeight>0;a.subtitle.hidden=!s,s&&r&&(a.subtitle.textContent!==r.text&&(a.subtitle.textContent=r.text),a.subtitle.style.top=`${a.video.offsetTop+a.video.offsetHeight-a.subtitle.offsetHeight-10}px`)}a.transcriptOn.addEventListener(`change`,()=>{qr=a.transcriptOn.checked,J=qr&&(!D||a.transcriptAudio.checked),qr||(a.transcriptAudio.checked=!1,X.disable());try{localStorage.setItem(Nt,qr?`on`:`off`)}catch{}Li()}),a.transcriptLanguage.addEventListener(`change`,()=>{ti=``,Qr=``,K=It(()=>a.transcriptLanguage.value),!K&&a.transcriptAudio.checked&&(a.transcriptAudio.checked=!1,J=!1,X.disable());try{K?localStorage.setItem(Pt,K):localStorage.removeItem(Pt)}catch{}Li()});function Vi(){if(K)return K;let e=navigator.language.split(`-`)[0]||`en`;return Ft.some(t=>t.code===e)&&Xr?.languages.includes(e)?e:`en`}function Hi(){let e=q!==``&&G===``,t=e&&Y.loaded()&&!!Fi()&&!!Xr?.languages.includes(Vi());a.transcriptAudio.disabled=!t,a.transcriptVoiceSettings.contains(document.activeElement)||(a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked),t?a.transcriptAudio.checked||g(a.transcriptAudioNote,()=>Qr||p(`Original audio.`)):(a.transcriptAudio.checked=!1,X.disable(),a.transcriptAudioNote.textContent=e?Fi()?Y.loaded()?Qr||(Xr?`Audio translation is unavailable for this language.`:`Loading voices…`):Y.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function Ui(){if(!q||G!==``)return;let e=`/api/v1/speech/voices`;if(Zr!==e){Zr=e,Xr=null,Qr=``,Hi();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(Zr!==e)return;if(!t.ok)throw Error(n.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(n.voices)||!Array.isArray(n.languages))throw Error(`This server needs an update for translated audio.`);Xr=n}catch(t){if(Zr!==e)return;Qr=t instanceof Error?t.message:`Translated audio is unavailable.`}Hi()}}a.transcriptBackground.addEventListener(`change`,()=>{li();try{localStorage.setItem(`nixamp.backgroundSound`,a.transcriptBackground.checked?`on`:`off`)}catch{}if(ci.stop(),si=!1,a.transcriptBackground.checked&&a.transcriptAudio.checked&&P.playing){let e=ai,t=P.audioInput();ci.start(t.context,t.node).then(t=>{t&&e===ai&&ci.active(oi&&P.playing&&a.transcriptBackground.checked)})}}),a.transcriptAudio.addEventListener(`change`,()=>{if(ti=``,Qr=``,Yr.clear(),a.transcriptAudio.checked&&!Y.ready()){a.transcriptAudio.checked=!1,Y.open(a.transcriptAudio);return}if(a.transcriptAudio.checked){K=Vi();try{localStorage.setItem(Pt,K)}catch{}qr=!0,J=!0,X.enable()}else J=!1,X.disable();Li()});function Wi(){if(A)return A.url;if(c!==`remote`)return``;let{base:e,key:t}=Ie(To());if(e===``)return``;if(D)return Pe(e,`/api/channels/${encodeURIComponent(D.id)}`,t);if(O?.kind===`live`)return Pe(e,`/api/live`,t);if(P.source===``)return``;try{let n=new URL(P.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Gi(){let e=Wi();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function Ki(){return c===`remote`?D?wo(`channel:${D.id}`):O?.kind===`live`||R()?wo(`live`):``:``}a.shareNow.addEventListener(`click`,()=>{let e=Gi();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${z()} on nixamp`,url:e}).catch(()=>void 0);return}Co(e,a.shareNow,`Copied`)}),a.copyNixamp.addEventListener(`click`,()=>{let e=Ki();e!==``&&Co(e,a.copyNixamp,`✓`)}),a.favHere.addEventListener(`click`,()=>{let e=To()||F.shareLink;if(!e)return;let t=[...jr].find(t=>W(t)===W(e))??e;Pr(Mr(e)?t:e,l||F.address,!Mr(e)).then(Ir)});let qi=n?i:200,Ji=[],Z=null,Q=null,Yi=``,Xi=[],Zi=0,Qi=null,$i=0,ea=null,ta=null,na=new Map;function ra(e,t){$i++,ea?.abort(),Qi&&clearTimeout(Qi),Qi=null,ue(a.catalogsList),ue(a.catalogsEntries),Z=e,Q=t,Yi=``,a.catalogsFilter.value=``,Xi=[],Zi=0,a.catalogsEntries.setAttribute(`aria-busy`,`false`),sa(),e&&t!==null&&fa(0)}function ia(e){if(!e)return`never`;let t=Math.max(0,Math.round((Date.now()-e)/1e3));if(t<90)return`just now`;let n=Math.round(t/60);if(n<90)return`${n} min ago`;let r=Math.round(n/60);return r<36?`${r} h ago`:`${Math.round(r/24)} d ago`}function aa(){let e=F.url(`/api/catalogs`);if(ta?.url===e)return ta.promise;let t=oa(e).finally(()=>{ta?.promise===t&&(ta=null)});return ta={url:e,promise:t},t}async function oa(e){if(c!==`remote`){a.catalogsPanel.hidden=!0;return}let t;try{t=await fetch(e)}catch{e===F.url(`/api/catalogs`)&&(a.catalogsPanel.hidden=!0);return}if(c===`remote`&&e===F.url(`/api/catalogs`)){if(!t.ok){a.catalogsPanel.hidden=!0;return}Ji=(await t.json().catch(()=>({}))).catalogs??[],Z&&=Ji.find(e=>e.id===Z?.id)??null,Z||(Q=null),a.catalogsPanel.hidden=!1,sa()}}function sa(){let e=!a.adminPanel.hidden;a.catalogsForm.hidden=!e;let t=Ji.reduce((e,t)=>e+t.live,0),n=Ji.reduce((e,t)=>e+t.vod,0);a.catalogsNote.textContent=Ji.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Ji.length} ${Ji.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,ca();let r=Z!==null&&Q!==null;if(a.catalogsList.hidden=r,a.catalogsFilter.hidden=!r,a.catalogsEntries.hidden=!r,r){pa();return}if(Z){ua(Z);return}w(a.catalogsList,...Ji.map(t=>la(t,e)))}function ca(){let e=Z!==null;if(a.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>ra(null,null),!1),n(),t(Z?.name??``,()=>ra(Z,null),Q===null)];Q!==null&&r.push(n(),t(Q===``?`All groups`:Q,()=>void 0,!0)),a.catalogsCrumbs.replaceChildren(...r)}function la(e,t){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);if(a.className=`detail`,g(a,()=>[`${e.entries.toLocaleString(f.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(f.language)} live`,`${e.vod.toLocaleString(f.language)} on demand`,`refreshed ${ia(e.refreshedAt)}`].join(` · `)),r.append(i,a),t&&e.error){let t=document.createElement(`span`);t.className=`detail`,t.textContent=e.error,r.append(t)}let o=document.createElement(`button`);if(o.type=`button`,o.className=`button`,o.textContent=`Browse`,o.setAttribute(`aria-label`,`Browse ${e.name}`),o.addEventListener(`click`,()=>{ra(e,null)}),n.append(r,o),t){let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Refresh`,t.title=`Read the list again`,t.addEventListener(`click`,()=>{ha(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,g(r,()=>p(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&So(n,r,()=>ga(e),()=>void aa())}),n.append(t,r)}return n}async function ua(e){let t=F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,r;a.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=na.get(n);e||(na.size>=20&&na.delete(na.keys().next().value),e=fetch(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),na.set(n,e)),r=await e}catch{if(na.delete(n),Z?.id!==e.id||Q!==null||t!==F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`),T=`Could not read the groups in ${e.name}.`,V();return}if(Z?.id!==e.id||Q!==null||t!==F.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`);let i=[da(`All groups`,``,e.entries,e.live,e.vod),...r.map(e=>da(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];w(a.catalogsList,...i)}function da(e,t,n,r,i){let a=document.createElement(`li`),o=document.createElement(`span`);o.className=`server-label`;let s=document.createElement(`span`);s.className=`name`,s.textContent=e;let c=document.createElement(`span`);c.className=`detail`,g(c,()=>`${n.toLocaleString(f.language)} · ${r.toLocaleString(f.language)} live · ${i.toLocaleString(f.language)} on demand`),o.append(s,c);let l=document.createElement(`button`);return l.type=`button`,l.className=`button`,l.textContent=`Open`,l.setAttribute(`aria-label`,`Open ${e}`),l.addEventListener(`click`,()=>{ra(Z,t)}),a.append(o,l),a}async function fa(e){let t=Z,n=Q;if(!t||n===null)return;let r=++$i;ea?.abort();let i=new AbortController;ea=i;let o=F.url(`/api/catalogs`);a.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Yi,offset:String(e),limit:String(qi)}),c;try{let e=await fetch(F.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:i.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(i.signal.aborted||r!==$i)return;a.catalogsEntries.setAttribute(`aria-busy`,`false`),T=`Could not read ${t.name}.`,pa(),V();return}r===$i&&Z?.id===t.id&&Q===n&&o===F.url(`/api/catalogs`)&&(a.catalogsEntries.setAttribute(`aria-busy`,`false`),Zi=c.total??0,Xi=e===0?c.entries??[]:[...Xi,...c.entries??[]],pa())}function pa(){let e=Z;if(!e)return;let t=Xi.map(t=>{let n=document.createElement(`li`);n.className=`row`;let r=document.createElement(`span`);r.className=`name`,r.textContent=t.title;let i=document.createElement(`span`);i.className=t.live?`catalog-tag catalog-live`:`catalog-tag`,i.textContent=t.live?`LIVE`:t.duration>0?oe(t.duration):`VOD`;let a=document.createElement(`button`);if(a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Play ${t.title}`),a.append(r,i),n.append(a),a.addEventListener(`click`,()=>{ma(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,o(r,`copy`),r.title=`Copy this entry's URL`,r.setAttribute(`aria-label`,`Copy the URL of ${t.title}`),r.addEventListener(`click`,n=>{n.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/stream`;Co(F.url(i),r,`✓`)}),n.append(r)}return ht()&&n.append(Ut(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Xi.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Yi?`Nothing called "${Yi}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Xi.length<Zi){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,g(n,()=>`Show more (${Xi.length.toLocaleString(f.language)} of ${Zi.toLocaleString(f.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),ue(a.catalogsEntries,!1),n.disabled=!0,fa(Xi.length)}),e.append(n),t.push(e)}w(a.catalogsEntries,...t)}async function ma(e,t,n){n?.classList.add(`loading`),T=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await Se(async()=>{let n,i={};try{n=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{T=`could not reach the server`;return}if(!n.ok){T=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await go({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){D=null,E=-1,O={kind:`vod`,...r},ze(a,`title`),await P.load({title:a,artist:``,album:``,duration:0,url:F.url(i.url),video:!0,objectUrl:!1},!0),Wn(!0),T=`Playing ${a}.`;return}T=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),V()}}async function ha(e){U(`Reading ${e.name} again…`);try{let t=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));U(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(f.language)} entries.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}aa()}async function ga(e){try{let t=await fetch(F.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(U(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return U(`could not reach the server`),!1}return Z?.id===e.id&&(Z=null,Q=null),!0}a.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.catalogSource.value.trim(),n=a.catalogName.value.trim();t&&(async()=>{U(`Reading ${n||t}…`);try{let e=await fetch(F.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){U(r.error??`that did not work`);return}U(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString(f.language)} entries.`),a.catalogSource.value=``,a.catalogName.value=``}catch{U(`could not reach the server`)}aa()})()}),a.catalogsFilter.addEventListener(`input`,()=>{$i++,ea?.abort(),Qi&&clearTimeout(Qi),Qi=setTimeout(()=>{Qi=null,Yi=a.catalogsFilter.value.trim(),fa(0)},250)});let _a=async()=>{w(a.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){a.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];te=new Map(t.map(e=>[W(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),a.serversPanel.hidden=!1,a.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Arriving signed in, this page connects to your default one, or the first that answers; a link you arrive with goes live there.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=re({name:e.name,view:o,admin:o});qe(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=Pa()===W(e.url),u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=l?`✓ Default`:`Make default`,u.title=l?`The server this page connects to when you arrive signed in. Press to go back to the first that answers.`:`Connect to this server whenever you arrive signed in`,u.addEventListener(`click`,()=>{Fa(l?``:W(e.url)),_a()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await _a()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),a.serversList.append(t)}}catch{a.serversPanel.hidden=!0}},va=async()=>{w(a.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){a.followingNote.hidden=!0;return}let t=(await e.json()).following??[];a.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,g(o,()=>p(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),a.followingList.children.length===0&&(a.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),a.followingList.append(t)}}catch{a.followingNote.hidden=!0}},ya=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,g(n,()=>p(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{g(n,()=>e?`Following`:p(`Follow`)),n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),va())}catch{}finally{n.disabled=!1}})()}),n},ba=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},xa=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Sa=async()=>{if(!xa())return a.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return a.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return a.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return a.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:ba(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return a.notifyNote.textContent=`This device will be told.`,!0}catch{return a.notifyNote.textContent=`Could not set this device up.`,!1}},Ca=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},wa=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();a.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(a.notifyPhone.value=n.phone)}catch{a.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Ta=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();a.notifyEmail.checked=t.wantsEmail!==!1,a.notifySms.checked=t.wantsSms===!0,a.notifyPhone.value=t.phone??``;let n=xa()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;a.notifyWeb.checked=t.wantsWeb!==!1&&n,a.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};a.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(a.notifyWeb.checked){let e=await Sa();a.notifyWeb.checked=e,await wa({wantsWeb:e});return}await Ca(),await wa({wantsWeb:!1}),a.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),a.notifyEmail.addEventListener(`change`,()=>{wa({wantsEmail:a.notifyEmail.checked})}),a.notifySms.addEventListener(`change`,()=>{(async()=>{if(a.notifySms.checked&&!a.notifyPhone.value.trim()){a.notifyPhoneNote.textContent=`Add a phone number first.`,a.notifySms.checked=!1;return}await wa({wantsSms:a.notifySms.checked})})()}),a.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),wa({phone:a.notifyPhone.value.trim()})});let Ea=!1,Da=!1,Oa=`nixamp.welcome`,ka=()=>{let e=!1;try{e=localStorage.getItem(Oa)===`hidden`}catch{}a.welcome.hidden=!Da||q!==``||e},Aa=e=>{let t=e!==null;Y.refresh(),Zr=``,ei=null,t||(J=!1,a.transcriptAudio.checked=!1,X.disable(),pi()),Li(),a.notifyPanel.hidden=!t,t?(Ta(),va(),_a()):(a.serversPanel.hidden=!0,a.followingNote.hidden=!0,w(a.followingList),a.recentNote.hidden=!0,a.recentList.replaceChildren()),a.accountForm.hidden=t,a.accountProviders.hidden=t||a.accountProviders.childElementCount===0,a.accountSignOut.hidden=!t,a.personaForm.hidden=!t,a.personaNote.hidden=!t,t&&Ni(),a.accountNote.textContent=t?`Signed in as ${e}.`:Ea?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,g(a.accountSubmit,()=>p(Ea?`Create account`:`Sign in`)),g(a.accountToggle,()=>Ea?`I have one`:p(`Create one`)),a.accountPassword.autocomplete=Ea?`new-password`:`current-password`,ka()},ja=async()=>{let e=[];Da=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(Da=!0,e=(await t.json()).providers??[])}catch{}a.accountProviders.replaceChildren(),a.accountProviders.hidden=e.length===0,a.accountPanel.hidden=!Da,a.accountElsewhere.hidden=Da,ka();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,a.accountProviders.append(e)}},Ma=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();q=e.ok?t.account?.id??``:``,Aa(e.ok?t.account?.email??`you`:null)}catch{q=``,Aa(null)}if(F.session=``,q!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));F.session=e.ok&&typeof t.token==`string`?t.token:``}catch{F.session=``}c===`remote`&&mr()}Nr(),kr(),Ar(),Ia();let e=await Na();if(nt!==``){let t=nt;nt=``,e?b=`golive:${t}`:Kn(t)}};async function Na(){if(q===``||c===`remote`||Xe!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=Pa(),n=[...e].sort((e,n)=>Number(W(n.url)===t)-Number(W(e.url)===t));for(let e of n)if(await qe(e.url,void 0,e.key)!==null)return c!==`remote`&&(y=!1,b=``,a.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,T=`Connecting to ${e.name}, your server…`,V(),a.remoteForm.requestSubmit(),!0);return!1}function Pa(){try{return localStorage.getItem(ln)??``}catch{return``}}function Fa(e){try{e===``?localStorage.removeItem(ln):localStorage.setItem(ln,e)}catch{}}function Ia(){if(Xe===``)return;let e=Xe;Xe=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit()}a.accountToggle.addEventListener(`click`,()=>{Ea=!Ea,Aa(null)}),a.welcomeCreate.addEventListener(`click`,()=>{Ea=!0,Aa(null),a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),a.accountEmail.focus({preventScroll:!0})}),a.welcomeBrowse.addEventListener(`click`,()=>{a.directory.hidden?a.browse.click():a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(Oa,`hidden`)}catch{}a.welcome.hidden=!0}),a.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.accountEmail.value.trim(),n=a.accountPassword.value;(async()=>{a.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${Ea?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){a.accountNote.textContent=r.error??`that did not work`;return}q=r.account?.id??``,a.accountPassword.value=``,Aa(r.account?.email??t),mr(),Ia()}catch{a.accountNote.textContent=`could not reach nixamp.com`}finally{a.accountSubmit.disabled=!1}})()}),a.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}q=``,Aa(null),kr(),F.close(),E=-1,c=`local`,le=`idle`,C=``,a.remoteUrl.value=``,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,a.listenOnly.hidden=!0,lo(!1);try{localStorage.removeItem(cn)}catch{}T=`Signed out, and disconnected from the server.`,mr(),V()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Xe=t,b=e.get(`play`)??``,ee=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t,T=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(a.linkUrl.value=n,t!==``&&b===``?b=`link:${n}`:t===``&&(nt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=Fe(r);t?(Xe=t.view,b=t.what,ee=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t.view,T=`Opening the stream you were sent…`):(a.linkUrl.value=r,nt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let La=[`zone-top`,`zone-main`],Ra=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,za=e=>e.parentElement&&La.includes(e.parentElement.id)?e.parentElement:null,Ba=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Va=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Ra(e)&&za(e)!==null),Ha=e=>e.dataset.title??e.id,Ua=new Map,Wa=Va().map((e,t)=>(Ua.set(e.id,{zone:za(e)?.id??``,col:Ba(e),index:t}),e.id)),$=bt();try{$=wt(localStorage.getItem(yt))}catch{}let Ga=()=>$.order.length>0||Object.keys($.placement).length>0;function Ka(){$.order=Va().map(e=>e.id);try{localStorage.setItem(yt,Tt($))}catch{}}function qa(e,t,n){e.classList.remove(`col-a`,`col-b`),t.classList.contains(`split`)&&n!==``&&e.classList.add(`col-${n}`),t!==e.parentElement&&t.append(e)}function Ja(){if(e)return;for(let e of Va()){let t=$.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&La.includes(i.id)&&qa(e,i,r===`a`||r===`b`?r:``)}let t=Et(Va().map(e=>e.id),$.order);for(let e of La){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(Ra),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((e,n)=>t.indexOf(e.id)-t.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of Va())e.toggleAttribute(`data-collapsed`,$.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,$.closed.includes(e.id))}function Ya(e,t){e.toggleAttribute(`data-collapsed`,t),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),$.collapsed=Dt($.collapsed,e.id,t),Ka(),no()}function Xa(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===a.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===a.partiesPanel&&!t&&kr(),t&&n&&a.panelsToggle.focus({preventScroll:!0}),$.closed=Dt($.closed,e.id,t),Ka(),no()}function Za(e,t,n){let r=za(t);r&&e!==t&&(qa(e,r,Ba(t)),n?t.after(e):t.before(e),$.placement[e.id]=`${r.id}:${Ba(t)}`,Ka(),no())}let Qa=null,$a=()=>{for(let e of Va())e.classList.remove(`drop-before`,`drop-after`)},eo=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon-btn`,r.textContent=e,r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,e=>{e.stopPropagation(),n()}),r};function to(){for(let e of Va()){let t=Ha(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n));let r=n.querySelector(`.panel-heading-text`);if(!r){r=document.createElement(`span`),r.className=`panel-heading-text`;let e=document.createElement(`span`);e.className=`panel-loading-spinner`,e.setAttribute(`aria-hidden`,`true`),n.replaceChildren(r,e)}if(r.textContent!==t&&(r.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let i=document.createElement(`span`);i.className=`panel-tools`;let a=eo(`≡`,`Move ${Ha(e)}: Alt plus Up or Down, or drag`,()=>void 0);a.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=Va().filter(t=>za(t)===za(e)&&Ba(t)===Ba(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(Za(e,r,t.key===`ArrowDown`),a.focus({preventScroll:!0}))}),a.classList.add(`grip`),a.draggable=!0,a.addEventListener(`dragstart`,t=>{Qa=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),a.addEventListener(`dragend`,()=>{Qa=null,e.classList.remove(`dragging`),$a()});let o=eo(`▁`,`Shade ${Ha(e)} to its title`,()=>Ya(e,!e.hasAttribute(`data-collapsed`)));o.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let s=eo(`✕`,`Hide ${Ha(e)}; the Panels list turns it back on`,()=>Xa(e,!0));e.id===`transcript-panel`&&i.append(Y.button()),i.append(a,o,s),e.prepend(i),e.addEventListener(`dragover`,t=>{if(!Qa||Qa===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;$a(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Qa||Qa===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);$a(),Za(Qa,e,n)})}}function no(){if(a.panelsPanel.hidden||a.panelsList.contains(document.activeElement))return;let e=Va().filter(e=>e!==a.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,_(i,`aria-label`,()=>`${Ha(e)} on`),i.addEventListener(`change`,()=>Xa(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,g(a,()=>Ha(e)),r.append(i,a);let o=document.createElement(`span`);return o.className=`detail`,o.textContent=n?`off`:e.hasAttribute(`data-collapsed`)?`shaded`:e.hidden&&e.dataset.available!==`true`?`nothing to show right now`:``,t.append(r,o),t});a.panelsList.replaceChildren(...e)}function ro(){$=bt();for(let e of Wa){let t=document.getElementById(e),n=Ua.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(qa(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}$.order=[...Wa],Ja(),$=bt();try{localStorage.removeItem(yt)}catch{}no()}function io(e){if(!e||Ga())return;let t=za(a.adminPanel);if(!t)return;let n=[...t.children].filter(Ra).find(e=>Ba(e)===Ba(a.adminPanel));n&&n!==a.adminPanel&&n.before(a.adminPanel),a.adminPanel.removeAttribute(`data-collapsed`),a.adminPanel.removeAttribute(`data-closed`)}a.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=a.panelsPanel.hidden||a.panelsPanel.hasAttribute(`data-closed`)||a.panelsPanel.hasAttribute(`data-collapsed`);a.panelsPanel.hidden=!t,a.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(a.panelsPanel.hasAttribute(`data-closed`)&&Xa(a.panelsPanel,!1),a.panelsPanel.hasAttribute(`data-collapsed`)&&Ya(a.panelsPanel,!1),no(),a.panelsPanel.showPopover?.(),a.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):a.panelsPanel.hidePopover?.()}),a.panelsPanel.addEventListener(`toggle`,()=>{let e=a.panelsPanel.matches(`:popover-open`);a.panelsToggle.setAttribute(`aria-expanded`,String(e&&!a.panelsPanel.hasAttribute(`data-collapsed`))),e||(a.panelsPanel.hidden=!0)}),a.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof a.panelsPanel.hidePopover!=`function`&&(a.panelsPanel.hidden=!0,a.panelsToggle.setAttribute(`aria-expanded`,`false`),a.panelsToggle.focus({preventScroll:!0}))}),a.panelsReset.addEventListener(`click`,ro),a.panelsSave.addEventListener(`click`,()=>{Ka();let e=a.panelsSave.textContent??`Save setup`;a.panelsSave.textContent=`Saved`,window.setTimeout(()=>{a.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{to(),no()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),to(),Ja(),ja(),Ma(),mr(),$n(),a.browse.addEventListener(`click`,()=>{if(!a.directory.hidden){a.directory.hidden=!0;return}ar(),a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.disconnect.addEventListener(`click`,()=>{F.close(),a.listenOnly.hidden=!0,E=-1,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,_(a.catalogsPanel,`data-title`,()=>p(`Catalogs on this server`)),l=``,ie=``,Ir(),lo(!1),c=`local`,le=`idle`,C=``,V()});async function ao(){if(c!==`remote`||F.shareLink===``){a.sharePanel.hidden=!0;return}a.sharePanel.hidden=!1;let e=To(),t=globalThis.location.origin;a.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,a.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,a.sharePhone.hidden=!0,a.shareSend.hidden=!0,a.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(F.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ie=r.url,a.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Be=r.live,Ve=r.live?r.code:``,Ue=n,a.liveControls.hidden=a.adminPanel.hidden||!r.possible,a.goLive.hidden=r.live,a.stopLive.hidden=!r.live,a.sharePhone.hidden=!1,!r.live){a.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){a.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,a.shareSend.hidden=!1;return}a.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),jo(n),document.createTextNode(` and key `),jo(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),a.shareSend.hidden=!1}}let oo=null,so=null,co=0,lo=e=>{oo&&clearInterval(oo),oo=null,co+=1,so?.abort(),so=null,k=null,Tr(),e&&(uo(),oo=setInterval(()=>{document.visibilityState===`visible`&&uo()},Er))};async function uo(){if(c!==`remote`||so)return;let e=new AbortController;so=e;let t=k===null;t&&Or(e,!0);let n=co,r=F.url(`/api/streams`),i=setTimeout(()=>e.abort(),8e3);try{let t=await fetch(r,{signal:e.signal,cache:`no-store`});if(!t.ok)return;let i=await t.json();if(e.signal.aborted||n!==co||c!==`remote`||r!==F.url(`/api/streams`))return;m=i.server.carries!==!1,i.server.name&&i.server.name!==l&&(l=i.server.name,a.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${l}`),Ir()),k=i,Eo(i),V(),fo(i)}catch{}finally{clearTimeout(i),t&&Or(e,!1),so===e&&(so=null)}}function fo(e){Tr(),D&&Ln()}function po(e){let t=qt(),n=e.restreams??[],r=[],i=e.server.playing,o=!a.adminPanel.hidden;i&&r.push(Do({key:`live`,title:pe(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${pe(e.server.nowPlaying)}`:`nothing loaded`,i&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:`Join party`,onPlay:()=>{i&&ho(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:wo(`live`)}:{},direct:i?F.url(`/api/live`):``}));for(let e of n)r.push(Do({key:`restream:${e.at}`,title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{mn(e.at)},link:``,direct:F.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=F.url(`/api/channels/${encodeURIComponent(t.id)}`),i=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&i.push(`☎ ${t.code}`),t.redials&&i.push(`redialled ${t.redials}×`),o&&t.error&&i.push(t.error),r.push(Do({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{go({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:wo(`channel:${t.id}`),direct:n,onRestart:(o||pt&&q!==``&&t.startedBy===q)&&t.via===`pull`?()=>{yo(t.id,t.name)}:void 0,onStop:o||pt&&q!==``&&t.startedBy===q?()=>xo(t.id,t.name):void 0,onRename:o||pt&&q!==``&&t.startedBy===q?()=>{bo(t.id,t.name)}:void 0}))}return r}async function mo(){if(c===`remote`)try{if((await fetch(F.media(L(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;T=q===``?`This stream is busy enough to be charging for. Sign in to nixamp.com to pay for a pass.`:`This stream is charging for a pass. Follow the payment prompt to keep listening.`,q===``&&a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),V()}catch{}}async function ho(e){E=-1,D=null,O={kind:`live`},ze(e,`auto`),await Se(()=>P.load({title:e||`Live`,artist:``,album:``,duration:0,url:F.url(`/api/live`),video:!0,objectUrl:!1},!0)),Wn(!0),T=`Watching what this server is playing. Everyone here sees the same thing.`,V()}async function go(e,t=!0,n){let r=k?.channels.find(t=>t.id===e.id);!e.playlist&&r?.playlist&&(e={...e,playlist:r.playlist}),E=-1,D=e,t&&(ve=0),t&&(O=n??{kind:`channel`}),t&&ze(e.name,O?.link||on(e.name)?`auto`:`channel`);let i=e.video&&_t(),a=e.video&&((e.playlist?.length??0)>1||e.id.startsWith(`folder-`));await Se(()=>P.load({title:e.name,artist:``,album:``,duration:0,url:F.url(i||a?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),Wn(e.video),D===e&&(T=`Watching ${e.name}, live on this server.`),V()}function _o(){let e=D;return e?Ye?!0:ve>=5?(T=`${e.name} stopped, and did not come back.`,D=null,O=null,V(),!0):(ve+=1,T=`${e.name} started over; rejoining…`,V(),Ye=setTimeout(()=>{Ye=null,D===e&&go(e,!1)},2e3),!0):!1}function vo(e){a.partiesNote.hidden=!1,a.partiesNote.textContent=e,U(e)}async function yo(e,t){vo(`Restarting ${t}…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));vo(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{vo(`could not reach the server`)}uo()}async function bo(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){vo(`Renaming ${t}…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));vo(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{vo(`could not reach the server`)}D?.id===e&&(D={...D,name:r}),uo(),V()}}async function xo(e,t){vo(`Taking ${t} off the air…`);try{let n=await fetch(F.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));if(vo(n.ok?`${t} is off the air.`:r.error??`that did not work`),!n.ok)return!1}catch{return vo(`could not reach the server`),!1}return D?.id===e&&(D=null,P.stop()),!0}function So(e,t,n,r){if(e.classList.contains(`removing`))return;t.disabled=!0,t.setAttribute(`aria-busy`,`true`);let i=document.createElement(`span`);i.className=`delete-spinner`,i.setAttribute(`role`,`status`),i.setAttribute(`aria-label`,`Removing`),i.textContent=``,t.after(i),n().then(n=>{if(!n){i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`);return}e.classList.add(`removing`),window.setTimeout(()=>{e.remove(),r?.()},260)}).catch(()=>{i.remove(),t.disabled=!1,t.removeAttribute(`aria-busy`)})}async function Co(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{T=e,V();return}n===`✓`||n===`✓`?o(t,`check`):g(t,()=>p(n)),setTimeout(()=>{t.innerHTML=r},1200)}function wo(e,t=0){let n=To();if(n===``)return``;let r=globalThis.location.origin,i=t>1?`&t=${Math.floor(t)}`:``;return`${r}/?url=${encodeURIComponent(n)}&play=${encodeURIComponent(e)}${i}`}function To(){if(ie!==``)return ie;let e=c===`remote`?F.shareLink:``;return/\/admin\//.test(e)?``:e}function Eo(e){if(b===``)return;let t=b;if(t===`live`){b=``,e.server.playing?ho(e.server.nowPlaying):(T=`Nothing is playing on this server right now.`,V());return}if(t.startsWith(`link:`)){b=``,Kn(t.slice(5));return}if(t.startsWith(`golive:`)){b=``,a.linkUrl.value=t.slice(7),mr().then(()=>er());return}if(t.startsWith(`track:`)){b=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&mn(e);return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n)??e.channels.find(e=>e.name===n);r&&(b=``,go({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Do(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${v(F.address)}:${e.key}`;let n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.title;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.detail,n.append(r,i);let a=document.createElement(`span`);a.className=`onair-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`button`,Ct(s,e.playLabel??`Join party`),s.hidden=e.key.startsWith(`channel:`)&&D?.id===e.key.slice(8),s.addEventListener(`click`,e.onPlay),a.append(s);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,o(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Co(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Co(e.direct??``,t,`✓`)})),e.onRestart&&a.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(c(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(c(`remove`,`Remove: take it off the air`,n=>{So(t,n,e.onStop,()=>void uo())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,_(s,`aria-label`,()=>`${p(e.playLabel??`Join party`)}: ${e.title}`);let l=document.createElement(`details`);l.className=`party-actions`;let u=document.createElement(`summary`);return u.textContent=`⋯`,_(u,`aria-label`,()=>`${p(`Show more`)}: ${e.title}`),a.removeChild(s),l.append(u,a),t.append(n,s),a.childElementCount&&t.append(l),t}let Oo=``;function ko(e,t){Oo=e;let n=e!==``&&t===e;a.loadHome.hidden=e===``,a.homeNote.hidden=e===``,e!==``&&(a.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,a.loadHome.disabled=!1)}a.loadHome.addEventListener(`click`,()=>{Oo!==``&&(a.loadHome.disabled=!0,U(`Reading this server's files…`),(async()=>{try{let e=await fetch(F.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Oo})}),t=await e.json();U(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{U(`could not reach the server`)}finally{a.loadHome.disabled=!1}})())});let Ao=async e=>{a.goLive.disabled=!0,a.stopLive.disabled=!0,a.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(F.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();a.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{a.shareNote.textContent=`could not reach the server`}finally{a.goLive.disabled=!1,a.stopLive.disabled=!1,await ao()}};a.goLive.addEventListener(`click`,()=>void Ao(!0)),a.stopLive.addEventListener(`click`,()=>void Ao(!1));function jo(e){let t=document.createElement(`b`);return t.textContent=e,t}a.shareCopy.addEventListener(`click`,()=>{a.shareLink.select(),navigator.clipboard?.writeText(a.shareLink.value).then(()=>{a.shareNote.textContent=`Copied. Send it to anybody.`},()=>{a.shareNote.textContent=`Copy it from the box above.`})}),a.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=a.shareTo.value.trim();t!==``&&(async()=>{a.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:To()})}),n=await e.json();a.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(a.shareTo.value=``)}catch{a.shareNote.textContent=`could not send that`}})()}),a.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(dn,a.listenHere.checked?`1`:`0`)}catch{}c===`remote`&&(async()=>{a.listenHere.checked?(await F.send({type:`stop`}),await _n(S.index)):(P.stop(),E=-1),V()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)&&!t?.closest(`input, textarea, select, button, a, [contenteditable], [role=button]`)&&t===a.transport)switch(e.key){case` `:e.preventDefault(),vn();return;case`s`:bn();return;case`n`:case`ArrowRight`:yn(1);return;case`p`:case`ArrowLeft`:yn(-1);return;case`ArrowDown`:e.preventDefault(),mn(Math.min(I()-1,L()+1));return;case`ArrowUp`:e.preventDefault(),mn(Math.max(0,L()-1));return}});let Mo=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Mo=e,a.install.hidden=!1}),a.install.addEventListener(`click`,()=>{Mo?.prompt(),Mo=null,a.install.hidden=!0});try{let e=localStorage.getItem(un);e!==null&&(a.volume.value=String(Math.round(Number(e)*100)),P.volume=Number(e));let t=localStorage.getItem(cn);t&&(a.remoteUrl.value=t),localStorage.getItem(dn)===`0`&&(a.listenHere.checked=!1)}catch{}(async()=>{if(a.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await qe(e)===null)return;let t=await We(e);t&&t.trackCount!==0&&(a.remoteUrl.value=e,c=`remote`,T=``,F.connect(e),lo(!0),aa(),V())})(),kr();let No=()=>{document.visibilityState===`visible`&&!a.partiesPanel.hasAttribute(`data-closed`)&&kr()},Po=setInterval(No,Er);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(kr(),uo())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(Po),oo&&clearInterval(oo),Cr?.abort(),so?.abort(),Cr=null,so=null,co+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(Po),Po=setInterval(No,Er),No(),c===`remote`&&lo(!0))}),(()=>{if(pn||Xe!==``)return;let e=()=>P.source!==``||P.playing||xe()||D!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{pn=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||P.playJingle(n).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,P.playJingle(n).then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),V(),requestAnimationFrame(Vn)}mn(),re(),le(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{e as n,u as t};
|