nixamp 0.77.2 → 0.78.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backtoschool/dist/assets/{ar-Cj5WpObc.js → ar-CYu0byMf.js} +1 -1
- package/backtoschool/dist/assets/{cs-DOYgXvWh.js → cs-BTTM7DeB.js} +1 -1
- package/backtoschool/dist/assets/{da-CmgimT0P.js → da-iixezQtd.js} +1 -1
- package/backtoschool/dist/assets/{de-D_AUWuE3.js → de-Sx3acevR.js} +1 -1
- package/backtoschool/dist/assets/{es-B4QfiG7X.js → es-ByCnw8ja.js} +1 -1
- package/backtoschool/dist/assets/{fi-Clf9SZn5.js → fi-BCeFoeH5.js} +1 -1
- package/backtoschool/dist/assets/{fr-DpLIxvgd.js → fr-Nz5hMzAE.js} +1 -1
- package/backtoschool/dist/assets/{hi-a9HR1j7t.js → hi-x5-IG1rl.js} +1 -1
- package/backtoschool/dist/assets/hls-CydbS6hn.js +42 -0
- package/backtoschool/dist/assets/hls-OR5FY6YP-O3qhTXm4.js +1 -0
- package/backtoschool/dist/assets/{hu-CXw_ATKN.js → hu-QqIkGcMe.js} +1 -1
- package/backtoschool/dist/assets/{id-B8GHWT99.js → id-OVwO1Uoi.js} +1 -1
- package/backtoschool/dist/assets/index-Dgqs6yM_.js +112 -0
- package/backtoschool/dist/assets/{it-D8K-Cjn9.js → it-CmssY5Ut.js} +1 -1
- package/backtoschool/dist/assets/mpegts-RQlLEU1A.js +3 -0
- package/backtoschool/dist/assets/mpegts-Y2FARLFE-y49QH7a5.js +1 -0
- package/backtoschool/dist/assets/{nl-BTHM_tIM.js → nl-VkQxlPku.js} +1 -1
- package/backtoschool/dist/assets/{ru-cwqVc7z_.js → ru-Dk8FAbDx.js} +1 -1
- package/backtoschool/dist/assets/{sv-De7KSFg-.js → sv-CNs1UySx.js} +1 -1
- package/backtoschool/dist/assets/{uk-COyId2km.js → uk-BDB1YayY.js} +1 -1
- package/backtoschool/dist/assets/{vi-3djg7AGj.js → vi-DnEIKzy7.js} +1 -1
- package/backtoschool/dist/assets/{zh-DNAab67I.js → zh-B_atHA4S.js} +1 -1
- package/backtoschool/dist/index.html +1 -1
- package/dist/ai-label.js +368 -0
- package/dist/partyline.d.ts +41 -201
- package/dist/partyline.js +65 -601
- package/package.json +13 -12
- package/src/ai-label.ts +368 -0
- package/src/partyline.ts +88 -671
- package/web/dist/assets/{ar-D11SvZiO.js → ar-D7oGrIBc.js} +1 -1
- package/web/dist/assets/background.worker-F49brs4A.js +547 -0
- package/web/dist/assets/chunk-55GBNX64-BDcCEJUP.js +1 -0
- package/web/dist/assets/client-D7waX8NA.js +1 -0
- package/web/dist/assets/{cs-C9A8mi2r.js → cs-Do_NVHzs.js} +1 -1
- package/web/dist/assets/{da-CIp_Ajuh.js → da-BIzsUdfm.js} +1 -1
- package/web/dist/assets/{de-5HI3ODDg.js → de-BIvKiWjR.js} +1 -1
- package/web/dist/assets/{es-B7jsPXIF.js → es-DlwX4mPV.js} +1 -1
- package/web/dist/assets/{fi-CDifgjAY.js → fi-DSxAbrPX.js} +1 -1
- package/web/dist/assets/{fr-CWCMwXQf.js → fr-DlPaqVof.js} +1 -1
- package/web/dist/assets/{hi-D9A8GEcr.js → hi-CGj6w2rC.js} +1 -1
- package/web/dist/assets/hls-CydbS6hn.js +42 -0
- package/web/dist/assets/hls-OR5FY6YP-_WOdANsC.js +1 -0
- package/web/dist/assets/{hu-BQnB41QA.js → hu-C3hnXVMS.js} +1 -1
- package/web/dist/assets/{id-BiRd7S38.js → id-CXTixL8r.js} +1 -1
- package/web/dist/assets/{it-Qyw9ho6m.js → it-kiPCXGt4.js} +1 -1
- package/web/dist/assets/main-DFt__4mL.js +26 -0
- package/web/dist/assets/mpegts-CL9RC5Ls.js +3 -0
- package/web/dist/assets/mpegts-Y2FARLFE-C91SD8Pl.js +1 -0
- package/web/dist/assets/music-ByEeUk4Z.js +1 -0
- package/web/dist/assets/{nl-BO3ykanC.js → nl-BMVfOLOI.js} +1 -1
- package/web/dist/assets/radio-BnQ78a-O.js +1 -0
- package/web/dist/assets/{ru-EoEoXLPn.js → ru-BbFlZrrY.js} +1 -1
- package/web/dist/assets/{station-UibBpdBh.js → station-C_6L4CDU.js} +2 -2
- package/web/dist/assets/{sv-BzFjGhqA.js → sv-DSYI0dH8.js} +1 -1
- package/web/dist/assets/{uk-DMWjHo-5.js → uk-CgzzaOY_.js} +1 -1
- package/web/dist/assets/{vi-DlSMYqgm.js → vi-CLwyMANh.js} +1 -1
- package/web/dist/assets/{vod-CkR6hzN7.js → vod-CbSC5NFA.js} +1 -1
- package/web/dist/assets/{watch-BO-wMY8T.js → watch-D-ZRxfJ_.js} +1 -1
- package/web/dist/assets/{zh-cB0Zpdge.js → zh-8uXFdsMm.js} +1 -1
- package/web/dist/index.html +5 -5
- package/web/dist/music.html +2 -2
- package/web/dist/radio.html +3 -3
- package/web/dist/station.html +3 -3
- package/web/dist/sw.js +32 -32
- package/web/dist/vod.html +3 -3
- package/web/dist/watch.html +3 -3
- package/backtoschool/dist/assets/hls-OR5FY6YP-nOjNFW0f.js +0 -1
- package/backtoschool/dist/assets/hls-n74Cnh8A.js +0 -42
- package/backtoschool/dist/assets/index-BPJoeY65.js +0 -112
- package/backtoschool/dist/assets/mpegts-7CN75AI2-cUtR703j.js +0 -1
- package/backtoschool/dist/assets/mpegts-CixmcUbS.js +0 -3
- package/web/dist/assets/background.worker-Hz7oaQ8X.js +0 -547
- package/web/dist/assets/chunk-Q2XQMA4B-OBCD3Aev.js +0 -1
- package/web/dist/assets/client-B_mfdrFh.js +0 -1
- package/web/dist/assets/hls-OR5FY6YP-B2RNEz5K.js +0 -1
- package/web/dist/assets/hls-n74Cnh8A.js +0 -42
- package/web/dist/assets/main-D4Tyu9aM.js +0 -26
- package/web/dist/assets/mpegts-7CN75AI2-1Qj6py7N.js +0 -1
- package/web/dist/assets/mpegts-BcF3gJrf.js +0 -3
- package/web/dist/assets/music-Day-DtFd.js +0 -1
- package/web/dist/assets/radio-Dx44o-ug.js +0 -1
- /package/web/dist/assets/{chunk-Q2XQMA4B-DR1XNWCJ.css → chunk-55GBNX64-DR1XNWCJ.css} +0 -0
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import"./modulepreload-polyfill-P2Xu9kJm.js";import{c as e,i as t,n,t as r}from"./chunk-Q2XQMA4B-OBCD3Aev.js";import{a as i,i as a,n as o,r as s,t as c}from"./client-B_mfdrFh.js";import{n as l}from"./now-playing-DVQqWQIu.js";import{a as u,c as d,d as f,i as p,l as ee,n as te,o as ne,r as re,s as ie,t as ae,u as oe}from"./remote-DJqvFdE6.js";var se={"Nixamp Share link or HTTPS media URL":`Nixamp Share link or HTTPS media URL`,"For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.":`For TV playback, use a Nixamp Share link or a direct HTTPS media URL. Pairux viewing opens separately.`,Paused:`Paused`,"Broadcast ended":`Broadcast ended`,"Class broadcast":`Class broadcast`,Play:`Play`,Pause:`Pause`,"Retry playback":`Retry playback`,"Back 10 seconds":`Back 10 seconds`,"Forward 10 seconds":`Forward 10 seconds`,Mute:`Mute`,Unmute:`Unmute`,"Full screen":`Full screen`,"Exit full screen":`Exit full screen`,Playing:`Playing`,"Select Play to watch the broadcast.":`Select Play to watch the broadcast.`,"The broadcast could not be loaded. Try again.":`The broadcast could not be loaded. Try again.`,"This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.":`This Pairux broadcast opens separately. For playback here on Fire TV, the host needs to share a Nixamp stream or direct media link.`,"Open on Pairux":`Open on Pairux`,"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.`},ce={...se,"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`},le={"■ 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`},ue=[{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`}],m=`nixamp.ui.language`;function h(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return ue.find(e=>e.code===t)?.code??`en`}function de(e,t=[]){let n=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return ue.find(e=>e.code===t)?.code};return n(e)??t.map(n).find(Boolean)??`en`}var fe={en:async()=>({default:ce}),de:()=>e(()=>import(`./de-5HI3ODDg.js`),[]),sv:()=>e(()=>import(`./sv-BzFjGhqA.js`),[]),es:()=>e(()=>import(`./es-B7jsPXIF.js`),[]),fr:()=>e(()=>import(`./fr-CWCMwXQf.js`),[]),it:()=>e(()=>import(`./it-Qyw9ho6m.js`),[]),nl:()=>e(()=>import(`./nl-BO3ykanC.js`),[]),da:()=>e(()=>import(`./da-CIp_Ajuh.js`),[]),fi:()=>e(()=>import(`./fi-CDifgjAY.js`),[]),ru:()=>e(()=>import(`./ru-EoEoXLPn.js`),[]),uk:()=>e(()=>import(`./uk-DMWjHo-5.js`),[]),cs:()=>e(()=>import(`./cs-C9A8mi2r.js`),[]),hu:()=>e(()=>import(`./hu-BQnB41QA.js`),[]),zh:()=>e(()=>import(`./zh-cB0Zpdge.js`),[]),ar:()=>e(()=>import(`./ar-D11SvZiO.js`),[]),hi:()=>e(()=>import(`./hi-D9A8GEcr.js`),[]),vi:()=>e(()=>import(`./vi-DlSMYqgm.js`),[]),id:()=>e(()=>import(`./id-BiRd7S38.js`),[])},g=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await fe[e]()).default){this.load=e}messages=ce;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=h(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 n=this.language!==`en`&&Object.hasOwn(le,e)?le[e]:e,r=Object.hasOwn(this.messages,n)?this.messages[n]:e;return this.language!==`en`&&Object.hasOwn(le,e)&&(r=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+r+(e.endsWith(` ✓`)?` ✓`:``)),r.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`}},_=(e,t)=>g.text(e,t),v=[`active`,`trialing`];function y(e,t,n=new Date){if(!e?.length)return!1;let r=new Set(v);return e.some(e=>{if(e.product!==t||!r.has(e.status))return!1;let i=e.period?.end?Date.parse(e.period.end):NaN;if(Number.isFinite(i)&&i<n.getTime())return!1;let a=e.period?.start?Date.parse(e.period.start):NaN;return!(Number.isFinite(a)&&a>n.getTime())})}async function pe(e){let t=null;try{t=await e.entitlements()??null}catch{return e.ads}let n=e.now?.()??new Date;return y(t,e.product,n)?null:e.ads}var me=600,he=`https://crawlproof.com/api/ads/stream`,ge=`nixamp.pro`;function _e(){let e=document.querySelector(`#video`);return e&&!e.hidden&&e.currentSrc&&!e.paused?`video`:`audio`}async function ve(){try{let e=await fetch(`/api/entitlements`,{credentials:`include`,headers:{accept:`application/json`}});if(!e.ok)return[];let t=await e.json();return Array.isArray(t)?t:t.entitlements??[]}catch{return[]}}var ye=`7e0ea02c-c40f-4cdd-b4d3-93b2baca8f2c`;function b(e){let t=new URLSearchParams(e),n=t.get(`ads`),r=Number(t.get(`adsEvery`)),i=t.get(`adNow`);return{enabled:i===null?n===null?null:n!==`0`&&n!==`false`:!0,everySeconds:Number.isFinite(r)&&r>0?Math.min(3600,Math.max(5,r)):null,adUrl:xe(t.get(`adUrl`)),now:i!==null&&i!==`0`&&i!==`false`}}function be(e=location.search){return b(e).now}function xe(e){if(!e)return null;try{let t=new URL(e,location.origin);return t.protocol===`https:`?t.toString():null}catch{return null}}var Se=null;function Ce(e){if(Se)try{let t=`${Se.endpoint}?d=${encodeURIComponent(Se.decision)}&t=${encodeURIComponent(e)}&s=player`;new Image().src=t}catch{}}async function we(e={},t=location.search){let n=b(t);if(n.enabled===!1)return null;let r={everySeconds:n.everySeconds??e.everySeconds??me,next:async()=>{if(n.adUrl)return{url:n.adUrl};try{let t=`${he}?slot=${encodeURIComponent(e.slot??ye)}&kind=${_e()}`,n=await fetch(t,{headers:{accept:`application/json`}});if(!n.ok)return null;let r=await n.json();return r.url?(Se=r.decisionId&&r.eventsUrl?{decision:r.decisionId,endpoint:r.eventsUrl,url:r.url}:null,{url:r.url,kind:r.kind}):null}catch{return null}},onBreakStart:e=>{Se&&Se.url!==e.url&&(Se=null),Ce(`start`)},onBreakEnd:e=>{Ce(e.skipped?`abandon`:`complete`),Se=null},onError:e=>{Ce(`error`),Se=null,console.warn(`advert failed`,e)}};return n.enabled===!0?r:e.paid===!0?null:pe({product:ge,entitlements:ve,ads:r})}var x=new Map;function Te(e,t,n){let r=x.get(e);r||(r=new Map,x.set(e,r)),r.set(t,n),n()}function S(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return Te(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){x.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function C(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return Te(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){x.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var w=[`aria-label`,`title`,`placeholder`,`data-title`],Ee=[`[data-i18n]`,...w.map(e=>`[data-i18n-${e}]`)].join(`,`);function T(e){let t=[...e.querySelectorAll(Ee)];e instanceof HTMLElement&&e.matches(Ee)&&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;Te(e,`text`,()=>{if(e.textContent!==n){x.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=_(t),e.textContent!==n&&(e.textContent=n)})}for(let t of w){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);Te(e,t,()=>{if(e.getAttribute(t)!==r){x.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=_(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function De(){document.documentElement.lang=g.language,document.documentElement.dir=g.direction;for(let[e,t]of x){if(!e.isConnected){x.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=g.language}var Oe=0;async function E(e){let t=++Oe;try{if(!await g.setLanguage(e)||t!==Oe)return;try{localStorage.setItem(m,g.language)}catch{}window.nixampLanguage?.set(g.language).catch(()=>{})}catch{De()}}async function ke(){let e=de(null,navigator.languages);try{e=de(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...ue.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{E(e.value)});T(document),De(),g.onChange(De),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&T(e);for(let e of x.keys())e.isConnected||x.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&g.setLanguage(de(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==g.language&&g.setLanguage(e).catch(()=>{})});try{await g.setLanguage(e)}catch{}}var Ae={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 je(e,t){e.innerHTML=Ae[t]}function Me(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 Ne(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function Pe(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var Fe=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function D(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&Fe.has(e.slice(n+1).toLowerCase())}function Ie(){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 Le=new WeakMap;function Re(e,t=!0){let n=e.contains(document.activeElement);Le.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function O(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){Le.delete(e),e.replaceChildren(...t);return}let n=Le.has(e);if(Le.set(e,t),n)return;let r=()=>{let t=Le.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}Le.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var ze=new WeakMap,Be=new WeakSet;function Ve(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?ze.set(e,t):ze.delete(e),Be.has(e))return;Be.add(e);let a=()=>{let t=ze.get(e);t&&Ve(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function He(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 Ue(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 We(e,t,n=`Live`){let r=e[t];if(!r){let e=He(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${He(r.title)}`:He(r.title),a=Ue(r.folder??``),o=Ue(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}}function Ge(e,t=160){let n=e.replace(/[-]/g,` `).trim();if(n.length<=t)return n;let r=n.split(/\s›\s|[\\/]/).map(e=>e.replace(/_+/g,` `).trim()).filter(Boolean),i=He(r.pop()??``);if(r.length===0)return Ke(i,t);let a=r.shift(),o=e=>[a,...e,i].join(` › `),s=[];for(let e=r.length-1;e>=0&&!(o([r[e],...s]).length>t);--e)s.unshift(r[e]);let c=o(s);if(c.length<=t)return c;let l=t-i.length-3;return l>=12?`${Ke(a,l)} › ${i}`:Ke(i,t)}function Ke(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=e[t-1]===` `?n.length:n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}var k=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`]),A=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function qe(e){let t=e.lastIndexOf(`.`);return t>0&&A.has(e.slice(t+1).toLowerCase())}function Je(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&k.has(e.slice(n+1).toLowerCase())}function Ye(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function Xe(e){return e.filter(e=>Je(e.name,e.type)).sort((e,t)=>Ye(j(e),j(t))).map(e=>({title:Pe(e.name),artist:``,album:Ze(j(e)),duration:0,url:URL.createObjectURL(e),video:D(e.name,e.type),objectUrl:!0,...qe(e.name)?{kind:`mpegts`}:{}}))}function j(e){return e.webkitRelativePath||e.name}function Ze(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function Qe(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var $e=2048;function et(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 tt(e,t){return e||t===`hls`||t===`mpegts`}var nt=class{elements;handlers;attach;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;ads=null;adOptions=null;adRoot=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t,r=n){this.elements=e,this.handlers=t,this.attach=r,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(rt(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}enableAds(e,t){this.adRoot=t?e:null,this.adOptions=t,this.rebindAds()}get adPlaying(){return this.ads?.playing??!1}async playAdNow(){await this.ads?.play()}rebindAds(){this.ads?.destroy(),this.ads=null,this.adOptions&&this.adRoot&&(this.ads=r(this.adRoot,this.active,this.adOptions))}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=$e,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,n){this.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let r=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:t({src:e.url})),i=tt(e.video,r)?this.elements.video:this.elements.audio,a=e.objectUrl||et(e.url)||(this.handlers.readable?.(e.url)??!1);i.crossOrigin=a?`anonymous`:null,i!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=i,this.rebindAds()),this.attached?.destroy(),this.attached=null;try{this.attached=await this.attach(this.active,{src:e.url,kind:r,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 o=this.active.currentSrc||this.active.src||e.url;this.analysable=a||o.startsWith(`blob:`)||et(o),n&&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 rt(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`}}var it=.14,at=.02;function ot(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 st(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 ct(e,t,n=it){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function lt(e,t,n=at){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function ut(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 dt(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 ft(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function pt(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??g.language,i)===r.toLocaleDateString(t.locale??g.language,i);return n.toLocaleString(t.locale??g.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function mt(e,t={}){let n=e.data,r=dt(n.away,n.awayScore),i=dt(n.home,n.homeScore),a=ft(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=pt(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 ht=`nixamp.tv`,gt=/\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 _t(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?vt(r):/\bSilk\b/.test(e)&&n===0?!0:gt.test(e):vt(i)}function vt(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function yt(e){return e?12:100}function bt(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 xt=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,St=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,Ct=/\.m3u8(\?.*)?$/i,M=/\.(m3u|pls)(\?.*)?$/i;function wt(e){try{let t=new URL(e);return St.test(t.pathname+t.search)}catch{return!1}}function Tt(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 Et(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Tt(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(!xt.test(a)&&!St.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 Dt(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 Ot(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=Dt(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 M.test(o)?{kind:`list`,url:n.toString(),label:Tt(n.toString())}:xt.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:St.test(o)||Ct.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var kt=`nixamp.panels`;function At(){return{order:[],placement:{},collapsed:[],closed:[]}}var N=/^[a-z][a-z0-9-]{0,63}$/,jt=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function Mt(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&N.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Nt(e){if(!e)return At();let t;try{t=JSON.parse(e)}catch{return At()}if(!t||typeof t!=`object`||Array.isArray(t))return At();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))N.test(e)&&typeof t==`string`&&jt.test(t)&&(r[e]=t);let i=e=>{let t=Mt(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 Pt(e){return JSON.stringify(e)}function Ft(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 It(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function Lt(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}function P(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 F(e,t){return Object.assign(Error(e),{status:t})}var Rt=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}},zt=class{options;tracker=new Rt;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 F(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=this.options.sourceLanguage?.()??``,s=new Uint8Array(Lt(i?t.samples:t.samples.slice(-8e4))),c=this.options.hear?await this.options.hear(s,{speakers:i,language:o,signal:r}):await this.json(Bt(i?this.options.paths?.speakers??`/api/v1/speech/speakers`:this.options.paths?.transcribe??`/api/v1/speech/transcribe?live=1`,o),{method:`POST`,headers:{"content-type":`audio/wav`},body:s},r);if(e!==this.generation)return;this.recognitionFailures=0;let l=c.language,u=[];if(i){let e=this.tracker.reconcile(c.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=c.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),s=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),c=[],d=()=>{c.length&&(u.push({channel:this.options.channel(),at:t.at+c[0].start*1e3,until:t.at+c.at(-1).end*1e3,text:c.map(e=>e.text).join(` `).trim(),language:l,speaker:o.id,voiceProfile:a.profile}),c=[])},f=(this.options.phrase?.gapMs??450)/1e3,p=this.options.phrase?.pauseMs??350,ee=this.options.phrase?.maxMs??3e3;for(let e of s)c.length&&e.start-c.at(-1).end>=f&&d(),c.push(e),(/[.!?。!?]$/.test(e.text)||c.map(e=>e.text).join(` `).length>=400)&&d();c.length&&(i<r.length-1||t.until-(t.at+c.at(-1).end*1e3)>=p||t.until-(t.at+c[0].start*1e3)>=ee)&&d()}}else c.text&&(u=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:c.text,language:l}]);if(!u.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...u.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:u,language:l,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!P(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 F(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]),t=n.map(e=>e.text),a=this.options.translate?await this.options.translate(t,r,i,e):await this.json(this.options.paths?.translate??`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:t,from:r,to:i})},e);if(a.texts.length!==n.length||a.texts.some(e=>!e.trim()))throw F(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((e,t)=>({...e,original:e.text,sourceLanguage:r,language:i,text:a.texts[t]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>Vt(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!P(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 Bt(e,t){return/^[a-z]{2,3}$/.test(t)?`${e}${e.includes(`?`)?`&`:`?`}language=${t}`:e}function Vt(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 Ht=16e3,Ut=3e4;function Wt(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function Gt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Kt=`nixamp.captions`,qt=`nixamp.captions.native-v2.language`,Jt=[{code:``,label:`Original (auto-detect)`},...ue];function Yt(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Jt.some(e=>e.code===t)?t:``}catch{return``}}function Xt(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Zt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function Qt(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 $t(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 en(e){try{return e(Kt)!==`off`}catch{return!0}}function tn(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(g.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var nn=`live-translate-audio-tap`,rn=`// The render thread copies small mono blocks. All networking stays off it.
|
|
2
|
-
class LiveTranslateAudioTap extends AudioWorkletProcessor {
|
|
3
|
-
constructor() { super(); this.block = new Float32Array(2048); this.at = 0; }
|
|
4
|
-
process(inputs) {
|
|
5
|
-
const channels = inputs[0];
|
|
6
|
-
if (!channels?.length) return true;
|
|
7
|
-
for (let i = 0; i < channels[0].length; i++) {
|
|
8
|
-
let value = 0;
|
|
9
|
-
for (const channel of channels) value += channel[i] || 0;
|
|
10
|
-
this.block[this.at++] = value / channels.length;
|
|
11
|
-
if (this.at === this.block.length) {
|
|
12
|
-
this.port.postMessage(this.block, [this.block.buffer]);
|
|
13
|
-
this.block = new Float32Array(2048); this.at = 0;
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
return true;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
registerProcessor("live-translate-audio-tap", LiveTranslateAudioTap);
|
|
20
|
-
`,an=null;function on(){return an??=URL.createObjectURL(new Blob([rn],{type:`text/javascript`})),an}var sn=new WeakMap,cn=class{take;options;tap=null;generation=0;constructor(e,t={}){this.take=e,this.options=t}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(sn.has(e)||sn.set(e,e.audioWorklet.addModule(this.options.workletUrl??on()).catch(t=>{throw sn.delete(e),t})),await sn.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,this.options.workletUrl?this.options.processor??`live-translate-audio-tap`:nn);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}},ln=12e3,un=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>ln}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 F((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 F(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!P(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`)}},dn=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t,n={}){this.stop();let r=new AbortController;this.controller=r;let i=async()=>{let i=new AbortController,a=setTimeout(()=>i.abort(),12e3),o=await(this.options.fetcher??fetch)(this.options.path??`/api/translation/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n,source:e,language:t}),signal:AbortSignal.any([r.signal,i.signal])}).finally(()=>clearTimeout(a));if(!o.ok||!o.body)throw F((await o.json().catch(()=>({}))).error||`Live translation is unavailable.`,o.status);return o.body},a=await i();if(this.controller!==r){await a.cancel();return}this.consume(a,r,i)}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 F(`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(!P(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(F(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw F(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
21
|
-
|
|
22
|
-
`))>=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`){if(this.options.error?.(e))return;throw F(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=`${this.options.scheme??`live-translate`}:${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(F(`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)}});if(this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t,e),e.audio===!1){let e=this.clips.get(t);e.ended=!0,e.taken=!0,e.controller.close()}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)}},I=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,fn=class extends cn{constructor(e){super(e,{workletUrl:I,processor:`nixamp-audio-tap`})}},pn=3,mn=1,hn=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*mn: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*pn: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?mn:pn):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?mn:pn):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}},gn=class extends dn{constructor(e){super({path:`/api/v1/speech/shared`,scheme:`nixamp-shared`,...e})}},L=e=>new Intl.NumberFormat(g.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),R=e=>document.getElementById(e),_n=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=R(`translation-purchase`);plan=R(`translation-plan`);buy=R(`translation-checkout`);note=R(`translation-purchase-note`);checkoutLink=R(`translation-checkout-link`);constructor(e){this.options=e,R(`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})}),R(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),R(`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=`$`,C(e,`title`,()=>_(`Buy translated audio`)),C(e,`aria-label`,()=>_(`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.plans??[];this.plan.options.length||this.plan.replaceChildren(...r.map(e=>{let t=new Option(``,e.id);return S(t,()=>`${e.name} · ${L(e.priceCents*1e4)}`),t})),this.describe();let i=this.access,a=()=>i.required?`${_(`Audio credit`)}: ${L(i.balanceMicros)}${i.expires?` · ${new Date(i.expires).toLocaleString(g.language)}`:``}`:``,o=this.access.free,s=()=>i.required&&o?g.language===`en`?`${o.remaining} of ${o.limit} free sessions left today${o.activeUntil?` · free session active`:``}`:`${_(`Free sessions`)}: ${g.number(o.remaining)}/${g.number(o.limit)}${o.activeUntil?` · ✓`:``}`:``;S(R(`translation-balance`),()=>[s(),a()].filter(Boolean).join(` · `)),S(R(`translation-purchase-balance`),()=>[s(),a()].filter(Boolean).join(` · `)),S(R(`translation-free-description`),()=>o?`Each account gets ${o.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${o.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(o.resets).toLocaleString(g.language)} (midnight UTC). Free time is used before purchased credit.`:``),R(`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 c=new URLSearchParams(location.search).get(`translation_order`),l=this.access.orders?.find(e=>e.id===c||e.id===this.order)??this.access.orders?.[0];l&&!this.order&&(this.order=l.id,this.link(l.url)),c&&!this.order&&/^[a-f0-9-]{36}$/i.test(c)&&e&&(this.order=c,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));R(`translation-plan-description`).textContent=`${L(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\/(?:checkout\/cs_[A-Za-z0-9]{16,64}|pay\/[a-f0-9-]{36})$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,R(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=this.plan.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,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,R(`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}}},z=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,vn=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,B=/\s+(?:vs\.?|v\.?|at|@)\s+/i,yn=/^(?: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 bn(e){let t=e.replace(vn,``).replace(vn,``).trim().split(B);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!yn.test(t)})}function xn(e){let t=String(e??``).trim();return t===``?!1:bn(t.replace(z,``))||bn(t)}var Sn=Object.freeze([`email`,`first_name`,`last_name`,`company_domain`,`job_title`,`linkedin_url`]),Cn=Object.freeze([`email`,`first_name`,`last_name`]);Object.freeze([`email`,`first_name`,`last_name`,`company_domain`,`job_title`]);var wn=Object.freeze([{name:`email`,label:`Email`,type:`email`,autocomplete:`email`,inputmode:`email`,maxLength:254,placeholder:`you@company.com`},{name:`first_name`,label:`First name`,type:`text`,autocomplete:`given-name`,maxLength:100},{name:`last_name`,label:`Last name`,type:`text`,autocomplete:`family-name`,maxLength:100},{name:`company_domain`,label:`Company website`,type:`text`,autocomplete:`url`,inputmode:`url`,maxLength:253,placeholder:`company.com`,hint:`Filled from a work email.`},{name:`job_title`,label:`Job title`,type:`text`,autocomplete:`organization-title`,maxLength:120},{name:`linkedin_url`,label:`LinkedIn`,type:`url`,autocomplete:`url`,inputmode:`url`,maxLength:200,placeholder:`linkedin.com/in/you`}]),Tn=Object.freeze(Object.fromEntries(wn.map(e=>[e.name,e]))),En=class extends Error{constructor(e,t){super(t),this.name=`ProfileFieldError`,this.field=e}},Dn=e=>e==null||String(e).trim()===``;function On(e){return String(e).replace(/[\u0000-\u001f\u007f\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff]/g,` `).replace(/\s+/g,` `).trim()}var kn=e=>/(https?:\/\/|www\.|@|\.(com|net|org|io|ru|xyz|top|info)\b)/i.test(e),An=new Set(`gmail.com,googlemail.com,yahoo.com,ymail.com,rocketmail.com,hotmail.com,outlook.com,live.com,msn.com,passport.com,icloud.com,me.com,mac.com,aol.com,aim.com,proton.me,protonmail.com,protonmail.ch,pm.me,gmx.com,gmx.net,gmx.de,web.de,mail.com,email.com,yandex.com,yandex.ru,ya.ru,mail.ru,inbox.ru,list.ru,bk.ru,qq.com,163.com,126.com,sina.com,foxmail.com,fastmail.com,fastmail.fm,hey.com,tutanota.com,tuta.io,tutamail.com,duck.com,passmail.net,passmail.com,aleeas.com,simplelogin.com,anonaddy.me,addy.io,relay.firefox.com,mozmail.com,privaterelay.appleid.com,mailinator.com,guerrillamail.com,10minutemail.com,temp-mail.org,yopmail.com,hushmail.com,zohomail.com,rediffmail.com,libero.it,orange.fr,free.fr,laposte.net,btinternet.com,comcast.net,verizon.net,att.net,sbcglobal.net,cox.net,charter.net,earthlink.net,t-online.de,seznam.cz,naver.com,daum.net,hanmail.net,uol.com.br,bol.com.br,terra.com.br`.split(`,`));function jn(e){if(Dn(e))return null;let t=String(e).trim().toLowerCase();if(t.length>254||!/^[^\s@]+@[^\s@]+\.[a-z0-9-]{2,}$/i.test(t))throw new En(`email`,`Enter an email address like you@company.com.`);return t}function Mn(e,t){return n=>{if(Dn(n))return null;let r=On(n);if(r.length>100)throw new En(e,`${t} is too long.`);if(kn(r))throw new En(e,`${t} cannot be a link or an email.`);return r}}var Nn=Mn(`first_name`,`First name`),Pn=Mn(`last_name`,`Last name`);function Fn(e){if(Dn(e))return null;let t=String(e).trim().toLowerCase();t.includes(`@`)&&(t=t.slice(t.lastIndexOf(`@`)+1)),t=t.replace(/^[a-z][a-z0-9+.-]*:\/\//,``),t=t.split(/[/?#]/)[0].split(`:`)[0].replace(/\.$/,``),t=t.replace(/^www\d*\./,``);let n=RegExp(`^(?:[a-z0-9\\u00a1-\\uffff](?:[a-z0-9\\u00a1-\\uffff-]{0,61}[a-z0-9\\u00a1-\\uffff])?\\.)+(?:[a-z\\u00a1-\\uffff]{2,63}|xn--[a-z0-9-]{1,59})$`);if(t.length>253||!n.test(t))throw new En(`company_domain`,`Enter your company's website, like company.com.`);return t}function In(e){if(Dn(e))return null;let t=On(e);if(t.length>120)throw new En(`job_title`,`Job title is too long.`);if(/(https?:\/\/|www\.)/i.test(t))throw new En(`job_title`,`Job title cannot be a link.`);return t}function Ln(e){if(Dn(e))return null;let t=()=>new En(`linkedin_url`,`Enter your LinkedIn profile, like linkedin.com/in/yourname.`),n=String(e).trim(),r,i=n.replace(/^@/,``).replace(/^\/?in\//i,``).replace(/\/$/,``);if(!/[.:]/.test(n)&&/^[\p{L}\p{N}%_-]{3,100}$/u.test(i))r=i;else{/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||(n=`https://${n}`);let e;try{e=new URL(n)}catch{throw t()}if(!/(^|\.)linkedin\.com$/i.test(e.hostname))throw t();let i=e.pathname.match(/^\/(?:in|pub)\/([^/]+)/i);if(!i)throw t();r=i[1]}try{r=decodeURIComponent(r)}catch{throw t()}if(r=r.toLowerCase(),!/^[\p{L}\p{N}_-]{3,100}$/u.test(r))throw t();return`https://www.linkedin.com/in/${encodeURIComponent(r)}`}Object.freeze({email:jn,first_name:Nn,last_name:Pn,company_domain:Fn,job_title:In,linkedin_url:Ln});var V=e=>String(e??``).replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e]);function Rn({values:e={},errors:t={},required:n=Cn,fields:r=Sn,idPrefix:i=`profile-`,className:a=`pfs-profile`,labels:o={}}={}){let s=r.map(r=>{let s=Tn[r];if(!s)throw Error(`profile: unknown field ${r}`);let c=`${i}${r}`,l=n.includes(r),u=t[r],d=[`id="${V(c)}"`,`name="${r}"`,`type="${s.type}"`,`autocomplete="${s.autocomplete}"`,s.inputmode&&`inputmode="${s.inputmode}"`,`maxlength="${s.maxLength}"`,s.placeholder&&`placeholder="${V(s.placeholder)}"`,e[r]!=null&&`value="${V(e[r])}"`,l&&`required`,u&&`aria-invalid="true" aria-describedby="${V(c)}-error"`,r===`email`&&`spellcheck="false" autocapitalize="off"`].filter(Boolean);return`<div class="${V(a)}__row" data-field="${r}">
|
|
23
|
-
<label for="${V(c)}">${V(o[r]??s.label)}${l?``:` <span class="${V(a)}__optional">(optional)</span>`}</label>
|
|
24
|
-
<input ${d.join(` `)}>${u?`\n <p class="${V(a)}__error" id="${V(c)}-error" role="alert">${V(u)}</p>`:``}
|
|
25
|
-
</div>`});return`<fieldset class="${V(a)}">\n${s.join(`
|
|
26
|
-
`)}\n</fieldset>`}`${JSON.stringify([...An])}`;function zn(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 Bn=`nixamp.remote`,Vn=`nixamp.defaultServer`,Hn=`nixamp.volume`,Un=`nixamp.listenHere`,Wn=1e4,Gn=!1,Kn=[`first_name`,`last_name`,`company_domain`,`job_title`,`linkedin_url`];function qn(e){let t={};for(let n of Kn){let r=e.elements.namedItem(n);r instanceof HTMLInputElement&&(t[n]=r.value.trim())}return t}function H(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function Jn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`,t=``;function r(e,n){let r=new URL(e instanceof Request?e.url:String(e),location.href);if(!t||r.origin!==location.origin||!r.pathname.startsWith(`/api/v1/`))return globalThis.fetch(e,n);let i=new Headers(n?.headers??(e instanceof Request?e.headers:void 0));return i.set(`authorization`,`Bearer ${t}`),globalThis.fetch(e,{...n,headers:i})}document.body.classList.toggle(`classroom-embed`,e);let se=null;try{se=localStorage.getItem(ht)}catch{}let ce=_t(navigator.userAgent,location.search,navigator.maxTouchPoints,se);if(document.body.classList.toggle(`tv`,ce),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(ht,ce?`1`:`0`)}catch{}let le=document.getElementById(`tv-toggle`);le&&(S(le,()=>ce?`TV mode: on`:_(`TV mode`)),le.title=ce?`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.`,le.addEventListener(`click`,()=>{try{localStorage.setItem(ht,ce?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let ue=yt(ce),m={status:H(`status`),source:H(`source`),install:H(`install`),video:H(`video`),audio:H(`audio`),title:H(`title-line`),album:H(`album-line`),meta:H(`meta-line`),metaBlurb:H(`meta-blurb`),liveLine:H(`live-line`),downloadNow:H(`download-now`),wayInHere:H(`way-in-here`),embed:H(`embed`),embedFrame:H(`embed-frame`),linkForm:H(`link-form`),linkUrl:H(`link-url`),linkServer:H(`link-server`),linkGoLive:H(`link-go-live`),goLiveNow:H(`go-live-now`),elapsed:H(`elapsed`),total:H(`total`),seek:H(`seek`),fullscreen:H(`fullscreen`),copyNow:H(`copy-now`),copyNixamp:H(`copy-nixamp`),schoolLive:H(`school-live`),streamingLive:H(`streaming-live`),streamingPublish:H(`streaming-publish`),canvas:H(`spectrum`),glyphs:H(`glyphs`),levels:H(`levels`),playlist:H(`playlist`),livePlaylist:H(`live-playlist`),livePlaylistPanel:H(`live-playlist-panel`),playlistPager:H(`playlist-pager`),crumbs:H(`crumbs`),filter:H(`filter`),playlistTitle:H(`playlist-panel`),note:H(`note`),linkNote:H(`link-note`),logList:H(`log-list`),files:H(`files`),folder:H(`folder`),remoteUrl:H(`remote-url`),remoteServer:H(`remote-server`),remoteForm:H(`remote-form`),remoteState:H(`remote-state`),disconnect:H(`disconnect`),browse:H(`browse`),panelsToggle:H(`panels-toggle`),panelsPanel:H(`panels-panel`),panelsList:H(`panels-list`),panelsSave:H(`panels-save`),panelsReset:H(`panels-reset`),accountForm:H(`account-form`),accountEmail:H(`account-email`),accountPassword:H(`account-password`),accountSubmit:H(`account-submit`),accountToggle:H(`account-toggle`),accountForgot:H(`account-forgot`),accountProviders:H(`account-providers`),accountPanel:H(`account-panel`),accountElsewhere:H(`account-elsewhere`),adnet:H(`adnet`),welcome:H(`welcome`),welcomeCreate:H(`welcome-create`),welcomeBrowse:H(`welcome-browse`),welcomeHide:H(`welcome-hide`),accountSignOut:H(`account-signout`),accountNote:H(`account-note`),personaForm:H(`persona-form`),personaHandle:H(`persona-handle`),personaVoice:H(`persona-voice`),personaProfile:H(`persona-profile`),personaNote:H(`persona-note`),accountProfile:H(`account-profile`),contactForm:H(`contact-form`),contactFields:H(`contact-fields`),contactNote:H(`contact-note`),adminPanel:H(`admin-panel`),adminNote:H(`admin-note`),adminSaid:H(`admin-said`),adminConnections:H(`admin-connections`),publishPanel:H(`publish-panel`),publishNote:H(`publish-note`),publishList:H(`publish-list`),adminRestream:H(`admin-restream`),adminReplace:H(`admin-replace`),adminSource:H(`admin-source`),adminName:H(`admin-name`),adminAdd:H(`admin-add`),homeNote:H(`home-note`),loadHome:H(`load-home`),directory:H(`directory`),recentNote:H(`recent-note`),recentList:H(`recent-list`),followingNote:H(`following-note`),followingList:H(`following-list`),serversPanel:H(`servers-panel`),serversNote:H(`servers-note`),serversList:H(`servers-list`),favoritesPanel:H(`favorites-panel`),favoritesNote:H(`favorites-note`),favoritesList:H(`favorites-list`),favHere:H(`fav-here`),partyRoom:H(`party-room`),partyTitle:H(`party-title`),partyMeta:H(`party-meta`),partyRoomNote:H(`party-note`),partyWatch:H(`party-watch`),partyCopy:H(`party-copy`),partyEnd:H(`party-end`),partyChat:H(`party-chat`),partyChatForm:H(`party-chat-form`),partyChatInput:H(`party-chat-input`),partyChatSend:H(`party-chat-send`),partyChatNote:H(`party-chat-note`),partiesPanel:H(`parties-panel`),partiesNote:H(`parties-note`),partiesList:H(`parties-list`),partyForm:H(`party-form`),partyCode:H(`party-code`),partyJoin:H(`party-join`),connectionsNote:H(`connections-note`),connectionsList:H(`connections-list`),catalogsPanel:H(`catalogs-panel`),catalogsNote:H(`catalogs-note`),catalogsForm:H(`catalogs-form`),catalogSource:H(`catalog-source`),catalogName:H(`catalog-name`),catalogsList:H(`catalogs-list`),catalogsCrumbs:H(`catalogs-crumbs`),catalogsFilter:H(`catalogs-filter`),catalogsEntries:H(`catalogs-entries`),notifyPanel:H(`notify-panel`),notifyNote:H(`notify-note`),notifyWeb:H(`notify-web`),notifyEmail:H(`notify-email`),notifySms:H(`notify-sms`),notifyPhone:H(`notify-phone`),notifyPhoneForm:H(`notify-phone-form`),notifyPhoneNote:H(`notify-phone-note`),directoryNote:H(`directory-note`),directoryList:H(`directory-list`),sharePanel:H(`share-panel`),trollboxPanel:H(`trollbox-panel`),trollboxNote:H(`trollbox-note`),trollboxList:H(`trollbox-list`),trollboxForm:H(`trollbox-form`),trollboxInput:H(`trollbox-input`),trollboxMic:H(`trollbox-mic`),trollboxEdit:H(`trollbox-edit`),trollboxEditLabel:H(`trollbox-edit-label`),transcriptPanel:H(`transcript-panel`),transcriptNote:H(`transcript-note`),transcriptOn:H(`transcript-on`),transcriptLanguage:H(`transcript-language`),transcriptAudio:H(`transcript-audio`),transcriptVoiceSettings:H(`transcript-voice-settings`),transcriptBackground:H(`transcript-background`),transcriptBackgroundLevel:H(`transcript-background-level`),transcriptBackgroundValue:H(`transcript-background-value`),transcriptAudioNote:H(`transcript-audio-note`),transcriptSpeakers:H(`transcript-speakers`),transcriptList:H(`transcript-list`),subtitle:H(`subtitle`),shareNote:H(`share-note`),shareLink:H(`share-link`),shareCopy:H(`share-copy`),sharePhone:H(`share-phone`),shareSend:H(`share-send`),liveControls:H(`live-controls`),goLive:H(`go-live`),stopLive:H(`stop-live`),shareTo:H(`share-to`),listenOnly:H(`listen-only`),listenHere:H(`listen-here`),volume:H(`volume`),volumeToggle:H(`volume-toggle`),prev:H(`prev`),playPause:H(`play-pause`),transport:H(`transport`),stop:H(`stop`),next:H(`next`),shareNow:H(`share-now`),refreshPlayer:H(`refresh-player`),appVersion:H(`app-version`)};m.appVersion.textContent=`nixamp 0.77.2`,m.accountProfile.innerHTML=Rn({fields:[...Kn],idPrefix:`account-`}),m.contactFields.innerHTML=Rn({fields:[...Kn],idPrefix:`contact-`});let h=(e,t)=>{je(e,t)};h(m.copyNixamp,`link`);let de=document.createElement(`a`);if(de.className=`button`,de.href=`#account-panel`,de.hidden=!0,S(de,()=>_(`Sign in`)),m.trollboxNote.after(de),e){let e=document.createElement(`div`);e.className=`classroom-caption-controls`,e.append(m.transcriptOn.closest(`label`),m.transcriptLanguage.closest(`label`)),m.transcriptPanel.prepend(e),m.transcriptPanel.classList.remove(`panel`,`col-b`),m.transcriptPanel.hidden=!1,document.querySelector(`.classroom-player`).append(m.transcriptPanel),document.querySelector(`#app`).append(m.trollboxPanel);let t=document.createElement(`dialog`);t.className=`classroom-sign-in`,C(t,`aria-label`,()=>_(`Sign in`));let n=document.createElement(`button`);n.type=`button`,n.className=`button`,S(n,()=>_(`Close`)),n.addEventListener(`click`,()=>t.close()),m.accountPanel.classList.remove(`panel`,`col-a`),t.append(n,m.accountPanel),document.body.append(t),de.addEventListener(`click`,e=>{e.preventDefault(),t.showModal()}),t.addEventListener(`close`,()=>{(de.hidden?m.trollboxList:de).focus({preventScroll:!0})})}let fe=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,v=`local`,y=``,pe=[],me=``,he=!0,ge=``;function _e(e){try{return new URL(e).origin}catch{return e}}let ve=!1,ye=globalThis.location?.search??``,b=``,xe=0,Se=new Map,Ce=e=>Se.get(K(e))??null;function x(e,t){let n=n=>{ve=n,b=``,m.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),m.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,h(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`,h(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:Y?`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 Te=``,w=[],Ee=0,T=oe(),De=`idle`,Oe=``,E=`Pick files, or connect to a nixamp running somewhere else.`,ke=!1,Ae=-1,Pe=null,Fe=0,D=null;function Ie(e){return e?/^https?:\/\//i.test(e)?e:L.url(e):``}let Le=0,ze=0,Be=!1,Ue=()=>!I.needsInteraction&&(ze>0||Be);async function Ke(e){ze+=1,U();try{return await e()}finally{--ze,U()}}let k=null,A=null,qe=``,Je=null,Ye=``,j=null,Ze=null,$e=0;function et(){m.embed.hidden||(m.embedFrame.src=`about:blank`),m.embed.hidden=!0}let tt=null,rt=``,it=null;function at(e,t,n=null,i=!1){let a=`${t}|${e}`;if(rt=a,it&&clearTimeout(it),it=null,!i){if(tt?.key===a)return;tt=null}if(v!==`remote`||e.trim()===``)return;let o=new URLSearchParams({name:e,kind:t});n&&o.set(`year`,String(n)),r(L.url(`/api/enrich?${o}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(rt!==a)return;tt={key:a,match:r.match??null},U();let i=tt.match;i?.kind===`fixture`&&ft(i)!==`post`&&(it=setTimeout(()=>{it=null,!(rt!==a||I.source===``&&!D)&&at(e,t,n,!0)},6e4))}).catch(()=>void 0)}let dt=!1,pt=``,gt=``,vt=null,xt=``,St=``,Ct=``,M=Array(24).fill(0),Tt=Array(24).fill(0),Dt=[],N=()=>v===`remote`&&!m.listenHere.checked,jt=()=>v===`remote`&&!m.adminPanel.hidden,Mt=!1,P=()=>jt()||v===`remote`&&Mt;function F(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:m.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function Rt(){if(v!==`remote`||j)return null;if(k?.catalog&&k.entry)return{kind:`entry`,catalog:k.catalog,entry:k.entry};if(D)return{kind:`channel`,id:D.id,name:D.name};let e=T.tracks[z()];return e&&(I.source!==``||N())?{kind:`track`,index:z(),name:bn(e)}:null}async function Bt(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;E=`Putting ${n} on the air…`,U();try{let i=``,a=``,o=!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`,s=await r(L.url(t),{method:`POST`,...e.kind===`folder`?{headers:{"content-type":`application/json`},body:JSON.stringify({indices:e.indices,name:e.name})}:{}}),c=await s.json().catch(()=>({}));if(!s.ok){E=s.status===404&&e.kind===`folder`?`This server needs an update before folders can go live.`:c.error??`${n} would not go on the air.`,U();return}a=e.kind===`channel`?e.id:c.channel??``,o=c.video!==!1,i=`channel:${a}`}if(jt()&&(dt?await r(L.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await hs(!0)),await Go(),Xo(),a!==``&&D?.id!==a){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 ts({id:a,name:n,video:o},!0,t)}let s=ls(i),c=pt?` Call ${gt||`the line`} and key ${pt} to talk about it.`:``;s===``?E=`${n} is on the air and you are watching it.${c}`:(await cs(s,t,`✓`),E=`${n} is on the air and you are watching it. Link copied.${c}`),U()}catch{E=`could not reach the server`,U()}finally{t.disabled=!1}}function Vt(e,t=`Join party`){h(e,/join/i.test(t)?`party`:`live`);let n=document.createTextNode(``);S(n,()=>` ${_(t)}`),e.append(n),C(e,`title`,()=>_(/join/i.test(t)?`Join live`:t))}Vt(m.partyJoin);function nn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,h(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(),Bt(e(),n)}),n}let rn=0,an=0,on=0,sn=null;function cn(e){let t=performance.now(),n=!I.adPlaying&&I.playing;n&&on>0&&t-on<2e3&&(an+=(t-on)/1e3),on=n?t:0,rn>0&&(e<=0||I.showingVideo)&&an>=rn&&(an=0,I.playAdNow())}function ln(){return new Promise(e=>{let t=()=>{sn=null,clearTimeout(n),e()},n=setTimeout(t,9e4);sn=t,I.playAdNow().then(()=>{I.adPlaying||t()},t)})}function dn(){ns()||yr()||An()||v===`remote`&&Ae<0&&!N()||Pn(1)}let I=new nt({audio:m.audio,video:m.video},{readable:e=>L.owns(e),onTime:(e,t)=>{let n=w[Ee];v===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),cn(t),U()},onEnded:()=>{if(rn>0&&an>=rn&&I.duration>0){an=0,ln().then(dn);return}dn()},onState:()=>U(),onBusy:e=>{Be!==e&&(Be=e,U())},onError:e=>{if(!ns()&&!($e!==0&&Date.now()-$e<2e3)){if(Ze&&e===`this browser cannot play that format`){let e=Ze.url;if(Ze=null,$e=Date.now(),P()){E=`That site will not let a page play it directly; going live with it on ${y||`the server`} instead.`,U(),m.linkUrl.value=e,wr();return}E=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,U();return}E=e,U(),$o()}}}),pn=m.video.closest(`section`)??m.video.parentElement;pn&&(async()=>{let e=!1;try{e=(await r(`${location.hostname===`nixamp.com`?``:`https://nixamp.com`}/api/v1/me/pass`,{credentials:`include`,cache:`no-store`,signal:AbortSignal.timeout(3e3)})).ok}catch{}let t=await we(e?{paid:!0}:{},ye);if(rn=t?.everySeconds??0,I.enableAds(pn,t&&{...t,everySeconds:31536e3,onBreakEnd:e=>{t.onBreakEnd?.(e),sn?.()}}),be(ye)){let e=()=>{pn.scrollIntoView({block:`center`}),I.playAdNow()};addEventListener(`pointerdown`,e,{once:!0}),addEventListener(`keydown`,e,{once:!0})}})();let mn=()=>N()&&!I.jinglePlaying,L=new ae({onSnapshot:e=>{let t=e.tracks!==void 0||T.index!==e.index;if(T=f(T,e),b.startsWith(`track:`)&&T.tracks.length>0){let e=Number(b.slice(6));if(b=``,Number.isInteger(e)&&e>=0&&e<T.tracks.length){let t=xe;Mn(e).then(()=>{t>0&&(I.seek(t),setTimeout(()=>I.seek(t),600))})}}mn()&&(M=e.bars.length>0?e.bars:M,Tt=lt(Tt,M)),U(),t&&A&&Zo(A)},onStatus:(e,t)=>{De=e,Oe=t??``,U()}}),R=()=>v===`remote`?T.tracks.length:w.length,z=()=>v===`remote`?N()||Ae<0?T.index:Math.min(Ae,Math.max(0,T.tracks.length-1)):Ee,vn=()=>{let e=A?.server.nowPlaying||`Live`;return(!Je||Je.tracks!==T.tracks||Je.index!==T.index||Je.fallback!==e)&&(Je={tracks:T.tracks,index:T.index,fallback:e,value:We(T.tracks,T.index,e)}),Je.value},B=()=>v===`remote`&&!D&&k?.kind===`live`,yn=()=>B()?vn().fullTitle:Sn(),bn=e=>{let t=Ne(e);return e.folder?`${e.folder} / ${t}`:t},Sn=()=>{if(D){let e=D.id,t=A?.channels.find(t=>t.id===e);return t?.playlist?.[t.entry??0]||D.name}if(j)return j.label;if(B())return vn().title;let e=v===`remote`?T.tracks[z()]:w[z()];return e?bn(e):_(`Nothing loaded.`)},Cn=()=>{if(D)return`live on this server`;if(j)return`playing here, in this browser`;if(B()){let{context:e,position:t}=vn();return[e,t,`live on ${y||`this server`}`].filter(Boolean).join(` · `)}return(v===`remote`?T.tracks[z()]:w[z()])?.album||`—`},wn=()=>{if(!D&&!j&&!B()){let e=v===`remote`?T.tracks[z()]:w[z()];if(e?.artist)return e.artist}return y||`nixamp`};function Tn(){if(v!==`remote`||D===null&&k?.kind!==`live`){m.liveLine.hidden=!0,m.liveLine.replaceChildren(),delete m.liveLine.dataset.drawn;return}let e=y||`this server`,t=D?D.name:vn().fullTitle,n=[D?`Live on ${e}: `:`Live from ${e}, now playing: `,gs(t)],r=D?A?.channels.find(e=>e.id===D?.id)?.code??``:dt?pt:``;if(r){let e=gt?document.createElement(`a`):gs(`the line`);gt&&(e.textContent=gt,e.setAttribute(`href`,`tel:${gt.replace(/[^+\d]/g,``)}`)),n.push(`. To talk about it, call `,e,` and key `,gs(r),`.`)}let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);m.liveLine.dataset.drawn!==i&&(m.liveLine.dataset.drawn=i,m.liveLine.hidden=!1,m.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let En=()=>N()?T.tracks[z()]?.duration??0:I.duration,Dn=()=>N()?T.position:I.position,On=()=>N()?T.playing:I.playing;async function kn(e){if(v===`remote`){if(N()){await L.send({type:`play`,index:e});return}await Mn(e);return}let t=w[e];t&&(Ee=e,D=null,k={kind:`file`},await Ke(()=>I.load(t,!0)),mr(t.video),hr(),U())}function An(){return!Pe||Pe.length<2?!1:(Fe=(Fe+1)%Pe.length,kn(Pe[Fe]),!0)}function jn(e){e.length!==0&&(Pe=[...e],Fe=0,kn(Pe[0]))}async function Mn(e){let t=T.tracks[e];t&&(Ae=e,D=null,k={kind:`file`},at(t.title,`auto`),await Ke(()=>I.load({title:bn(t),artist:t.artist,album:t.album,duration:t.duration,url:L.media(e,0),video:t.video===!0,objectUrl:!1},!0)),mr(t.video===!0),hr())}async function Nn(){if(I.needsInteraction){await I.play(),U();return}if(N()){await L.send({type:`toggle`});return}R()!==0&&(I.playing?I.pause():I.position>0?await I.play():await kn(z()),U())}async function Pn(e){Pe=null;let t=R();if(t!==0){if(N()){await L.send({type:e>0?`next`:`prev`});return}await kn((z()+e+t)%t)}}async function Fn(){if(Pe=null,et(),j=null,Ze=null,N()){await L.send({type:`stop`});return}D=null,k=null,I.stop(),M=Array(24).fill(0),Tt=[...M],U()}let In=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Ln=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],V=``;function Jn(){let e=[],t=``,n=null,r=D?A?.channels.find(e=>e.id===D?.id):void 0;D&&r?.ended&&Ye!==D.id&&(Ye=D.id,ci(`${D.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=I.source===``&&!D&&!(N()&&T.tracks[z()]);if(!i){D&&r?.ended?e.push(`ENDED`):D?e.push(k?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):k?.kind===`vod`?e.push(`ON DEMAND`):k?.kind===`live`?e.push(`LIVE`):v===`remote`&&N()?e.push(`ON THE SERVER`):e.push(`FILE`),!m.video.hidden&&m.video.videoWidth>0?e.push(`${m.video.videoWidth}×${m.video.videoHeight}`):m.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 ${Me(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),jt()&&r.error&&e.push(r.error)):v===`remote`&&!D?(T.tracks[z()]&&R()>0&&e.push(`${B()?`library track`:`track`} ${z()+1} of ${R()}`),N()&&A&&e.push(`${A.server.playing?`playing`:`stopped`} on ${y||`the server`}`)):v===`local`&&R()>0&&e.push(`track ${z()+1} of ${R()}`),k?.catalog!==void 0&&(k.kind===`channel`?D!==null:k.kind===`vod`&&I.source!==``)&&k?.catalog&&(e.push(k.entry?.group?`${k.catalog.name} › ${k.entry.group}`:k.catalog.name),t=k.entry?.logo??``),t===``&&D&&(t=Ie(r?.art??D.art));let i=tt?.key===rt?tt.match:null;if(i?.kind===`fixture`)n=mt(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&&k?.link){let t=``;try{t=new URL(k.link.url).hostname.replace(/^www\./,``)}catch{}e.push(k.link.extractor&&k.link.extractor!==`direct`&&k.link.extractor!==`generic`?`${k.link.extractor} · ${t}`:t||`link`)}dt&&pt&&N()&&!D&&k?.kind!==`live`&&e.push(gt?`☎ ${gt} · key ${pt}`:`☎ code ${pt}`)}let a=tt?.key===rt?tt.match:null,o=!i&&!n&&a?.summary?a.summary:``,s=e.map(e=>/^on air \d/.test(e)?`on air`:e),c=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${s.join(`|`)}|${o}`;if(c===V){let t=m.meta.querySelector(`.meta-chip-clock`),n=e.find(e=>/^on air \d/.test(e));t&&n&&(t.textContent=n);return}V=c,m.meta.hidden=e.length===0,m.metaBlurb.textContent=o,m.metaBlurb.hidden=o===``;let l=[];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)),l.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=a?.kind===`title`&&t===a.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),l.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,l.push(e)}m.meta.replaceChildren(...l)}function U(){let e=R(),t=On(),n=Ue();S(m.status,()=>_(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),m.status.dataset.playing=n?`loading`:String(t),S(m.title,()=>Sn()),m.title.classList.toggle(`with-context`,B()),m.album.classList.toggle(`with-context`,B()),(B()||D)&&hr(),Tn(),Jn(),m.goLiveNow.hidden=!P()||D!==null||B()||Rt()===null;let r=t?`${yn()} · ${fe}`:fe;document.title!==r&&(document.title=r),m.copyNow.hidden=I.source===``,m.copyNixamp.hidden=ya()===``,m.schoolLive.hidden=ba()===``||!uo||Y===``,m.streamingLive.hidden=Sa()===``&&Ca()===null||L.session===``,m.shareNow.hidden=va()===``,Xi(),ua(),m.downloadNow.hidden=!(D&&k?.link?.download),xr(),m.album.textContent=Cn();let i=Dn(),a=En();m.elapsed.textContent=Me(i),m.total.textContent=a>0?Me(a):`--:--`,ke||(m.seek.value=String(a>0?Math.round(i/a*1e3):0),m.seek.disabled=a<=0||N()),m.playPause.textContent=t?`❚❚`:`▶`,C(m.playPause,`aria-label`,()=>_(t?`Pause`:`Play`)),C(m.seek,`aria-valuetext`,()=>`${Me(I.position)} ${g.language===`en`?`of`:`/`} ${Me(I.duration)}`),C(m.volume,`aria-valuetext`,()=>g.number(Number(m.volume.value)/100,{style:`percent`})),C(m.playlistTitle,`data-title`,()=>v===`remote`?`Files on ${y||`this server`} (${e.toLocaleString(g.language)})`:`${_(`Playlist`)} (${g.number(e)})`),S(m.source,()=>v===`remote`?`connected · ${y||L.address.replace(/^https?:\/\//,``)||`—`}`:w.length>0?`local · ${w.length} files`:_(`no source`)),pr(),S(m.remoteState,()=>v===`remote`?`${De}${Oe?` — ${Oe}`:``}`:_(`not connected`)),m.remoteState.dataset.status=v===`remote`?De:`idle`,m.disconnect.hidden=v!==`remote`;let o=I.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:v===`remote`&&T.note!==``?T.note:E;m.note.textContent=o,m.note.hidden=o===``,m.linkNote.textContent=o,m.linkNote.hidden=o===``,ci(o),sr(),m.glyphs.textContent=M.map(Ln).join(``);let[s,c]=mn()?T.levels:I.levels();m.levels.textContent=In(s,c)}let Yn=``,W=``,Xn=0;function Zn(e){Re(m.playlist),W=e,Xn=0,Yn=``,sr()}function Qn(e,t,n,r,i){if(m.playlistPager.hidden=n<=1,n<=1){m.playlistPager.replaceChildren();return}let a=(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`,()=>{Re(m.playlist),Xn=t,Yn=``,sr()}),i},o=document.createElement(`span`);o.className=`pager-where`,S(o,()=>`${r+1}–${i} of ${e.toLocaleString(g.language)}`),m.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),o,a(`Next ›`,t+1,`The page after this one`))}function $n(e){if(m.crumbs.hidden=!e,!e)return;let t=W===``?[]:W.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`,()=>Zn(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))}),m.crumbs.replaceChildren(...r)}function er(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 o=document.createElement(`button`);if(o.type=`button`,o.className=`row-main`,o.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),o.append(i,a),r.replaceChildren(o),o.addEventListener(`click`,t=>{t.stopPropagation(),Zn(W===``?e:`${W}/${e}`)}),n.length>0){let i=document.createElement(`button`);i.type=`button`,i.className=`row-copy`,h(i,`play`),i.title=`Play all ${t} files in ${e}`,i.setAttribute(`aria-label`,`Play folder ${e}`),i.addEventListener(`click`,e=>{e.stopPropagation(),jn(n)}),r.append(i)}return v===`remote`&&n.length>0&&P()&&r.append(nn(()=>({kind:`folder`,indices:n,name:`${e}/`}),`${e}/`)),r}let tr=null,nr=``,rr=``,ir=[],ar=(e,t)=>{t.title=t.textContent??``,zn(e,t)};function or(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),ar(a,n),ar(o,r),{label:i,pathView:o}}function sr(){let e=(D?A?.channels.find(e=>e.id===D?.id):void 0)?.playlist,t=!!(D&&e?.length);m.livePlaylistPanel.hidden===t&&(m.livePlaylistPanel.hidden=!t);let n=t?D.id:``,r=t?e:[];if(rr!==n||ir.length!==r.length||ir.some((e,t)=>e!==r[t])){rr=n,ir=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}=or(e.slice(e.lastIndexOf(`/`)+1),e),o=document.createElement(`span`);return o.className=`row-main`,o.append(i,r),n.append(o,a),n});O(m.livePlaylist,...e)}let i=v===`remote`?T.tracks:w,a=`${v}:${D?.id??``}:${W}:${m.filter.value}:${Xn}:${P()}:${m.adminPanel.hidden}`;if(Yn&&tr===i&&nr===a){cr();return}tr=i,nr=a;let o=v===`remote`?T.tracks.map(e=>({name:Ne(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):w.map(e=>({name:Ne(e),seconds:e.duration,group:``,folder:``,remote:!1})),s=m.filter.value.trim().toLowerCase(),c=o.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>s===``||`${e.folder}/${e.name}`.toLowerCase().includes(s)),l=e=>s!==``||W===``||e===W||e.startsWith(`${W}/`),u=e=>e===W,d=e=>{let t=W===``?e:e.slice(W.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of c){if(!l(e.folder)||u(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=c.filter(e=>u(e.folder)&&l(e.folder)),ee=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),te=bt(ee.length+p.length,Xn,ue);Xn=te.page;let ne=ee.slice(te.from,te.to),re=p.slice(Math.max(0,te.from-ee.length),Math.max(0,te.to-ee.length)),ie=`${v}:${W}:${s}:${te.page}/${ue}:${ee.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(ie!==Yn){Yn=ie,$n(s===``&&(ee.length>0||W!==``)),Qn(ee.length+p.length,te.page,te.pages,te.from,te.to);let e=[];for(let[t,n]of ne){let r=W===``?t:`${W}/${t}`,i=c.filter(e=>e.folder===r||e.folder.startsWith(`${r}/`)).map(e=>e.index);e.push(er(t,n,i))}let t=``,n=p.some(e=>e.group!==``);for(let r of re){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(lr(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 o=r.folder?`${r.folder} / ${r.name}`:r.name,{label:s,pathView:c}=or(r.name,r.folder?`${r.folder}/${r.name}`:r.name),l=document.createElement(`span`);l.className=`time`,l.textContent=r.seconds>0?Me(r.seconds):`--:--`;let u=document.createElement(`button`);u.type=`button`,u.className=`row-main`,u.setAttribute(`aria-label`,`Play ${o}${r.seconds>0?`, ${Me(r.seconds)}`:``}`),u.append(s,a,l),i.append(u);let d=document.createElement(`span`);d.className=`row-play-glyph`,h(d,`play`),i.append(d),v===`remote`&&P()&&D===null&&!B()&&i.append(nn(()=>({kind:`track`,index:r.index,name:o}),o)),i.classList.add(`file-row`),i.append(c),e.push(i)}O(m.playlist,...e)}cr()}function cr(){let e=D?A?.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(m.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(m.playlist.children)){let r=n,i=Number(r.dataset.index),a=T.tracks[i],o=a?`${a.folder?`${a.folder}/`:``}${Ne(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(m.livePlaylist.children)){let t=e;t.classList.remove(`selected`,`playing`,`live-file-current`),t.removeAttribute(`aria-current`)}let t=z(),n=On();for(let e of Array.from(m.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 lr(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!==``&&!m.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(),ss(t,n,()=>ur(e),()=>sr())}),t.append(n)}return t}async function ur(e){try{let t=await r(L.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();return G(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`),t.ok}catch{return G(`could not reach the server`),!1}}function dr(){let e=m.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(mn())Tt=lt(Tt,M);else{let e=I.read();e.length>0&&(Dt.length!==25&&(Dt=ot(24,e.length)),M=ct(M,st(e,Dt)),Tt=lt(Tt,M))}if(i){let t=getComputedStyle(document.documentElement);ut(i,{width:e.width,height:e.height},M,Tt,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(On()||I.jinglePlaying){m.glyphs.textContent=M.map(Ln).join(``);let[e,t]=mn()?T.levels:I.levels();m.levels.textContent=In(e,t)}if(On()){m.elapsed.textContent=Me(Dn());let e=En();!ke&&e>0&&(m.seek.value=String(Math.round(Dn()/e*1e3)))}requestAnimationFrame(dr)}let fr=``;function pr(){if(v!==`remote`){m.wayInHere.hidden=!0,fr=``;return}let e=jt()&&!ve,t=Te||L.address,n=e?null:Ce(L.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===fr)return;fr=r;let[i,a]=x({name:y||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,m.wayInHere.replaceChildren(i,a),m.wayInHere.hidden=!1}function mr(e){m.video.hidden=!e,m.fullscreen.hidden=!e,et(),j=null,Ze=null}function hr(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=D?Ie(A?.channels.find(e=>e.id===D?.id)?.art??D.art):``,t=JSON.stringify([Sn(),Cn(),wn(),e]);t!==qe&&(qe=t,l({title:Sn(),album:Cn(),artist:wn(),art:e}),navigator.mediaSession.setActionHandler(`play`,()=>void Nn()),navigator.mediaSession.setActionHandler(`pause`,()=>void Nn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void Pn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void Pn(-1)))}document.addEventListener(`click`,()=>{I.resumeAfterInteraction().catch(()=>{})}),m.filter.addEventListener(`input`,()=>{Xn=0,Yn=``,sr()}),m.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())}),m.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&(Pe=null,kn(n))}),m.fullscreen.addEventListener(`click`,()=>{let e=m.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),m.prev.addEventListener(`click`,()=>void Pn(-1)),m.next.addEventListener(`click`,()=>void Pn(1)),m.stop.addEventListener(`click`,()=>void Fn()),m.playPause.addEventListener(`click`,()=>void Nn());async function gr(e){let t=Ot(e,F());if(!t){if(!P()){E=v===`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.`,U();return}await br(e);return}if(D=null,I.stop(),t.kind===`embed`){k={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},mr(!1),m.embedFrame.src=t.src,m.embed.hidden=!1,j={url:e,label:t.label,kind:`embed`},E=`Playing ${t.label} here, in this browser.`,U();return}if(t.kind===`list`){await _r(e,t.label);return}k={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Ke(()=>I.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),mr(t.video),j={url:e,label:t.label,kind:`direct`},E=`Playing ${t.label} here, in this browser.`,U()}async function _r(e,t){E=`Reading ${t}…`,U();let n=``;try{let t=await r(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){E=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,U();return}let i=Et(n,e);if(i.entries.length===0){E=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,U();return}Ze={url:e,title:i.title||t,entries:i.entries,at:0},await vr()}async function vr(){let e=Ze,t=e?.entries[e.at];if(!e||!t)return;let n=wt(t.url);k={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Ke(()=>I.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),Ze!==null&&(mr(n),j={url:e.url,label:e.title,kind:`direct`},Ze=e,E=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,U())}function yr(){let e=Ze;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,vr(),!0)}async function br(e){if(v!==`remote`){E=`Pick a server to go live on, or connect to one, to put a link on the air.`,U();return}E=`Asking ${y||`the server`} to fetch ${e}…`,U(),await Ke(async()=>{let t,n={};try{t=await r(L.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{E=`could not reach the server`;return}if(!t.ok||!n.channel){E=n.error??`that link would not play.`;return}try{await r(L.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await ts({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&&(E=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),U()}m.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=m.linkUrl.value.trim();t!==``&&gr(t)});function xr(){let e=v===`remote`?L.address:``,t=pe.filter(t=>_e(t.url)!==_e(e)),n=JSON.stringify({here:e,name:y,carries:he,others:t});if(n===me||document.activeElement===m.linkServer)return;me=n;let r=[];if(e!==``&&he){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${y||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)}m.linkServer.replaceChildren(...r),m.linkServer.value=e!==``&&!he&&t[0]?t[0].url:``,m.linkServer.hidden=t.length===0}function Sr(){let e=v===`remote`?_e(L.address):``,t=[],n=document.createElement(`option`);if(n.value=``,n.textContent=`Select a server…`,t.push(n),e!==``&&!pe.some(t=>_e(t.url)===e)){let n=document.createElement(`option`);n.value=L.address,n.textContent=y||e,t.push(n)}for(let e of pe){let n=document.createElement(`option`);n.value=e.url,n.textContent=e.name,t.push(n)}m.remoteServer.replaceChildren(...t);let r=pe.find(t=>_e(t.url)===e);m.remoteServer.value=r?.url??``}async function Cr(){try{let e=await r(`/api/directory`);if(!e.ok)return;pe=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),xr(),Sr()}catch{}}async function wr(){let e=m.linkUrl.value.trim()||j?.url||``;if(e===``){E=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,U();return}let t=m.linkServer.value;if(t!==``&&(v!==`remote`||_e(t)!==_e(L.address))){let n=pe.find(e=>e.url===t)?.name??t;ge=e,E=`Connecting to ${n} to go live with it…`,U(),Tr(t);return}if(v!==`remote`){E=pe.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.`,U();return}if(!he){E=`${y||`This server`} has no ffmpeg, so it cannot carry a link.`+(pe.length>0?` Pick a server to go live on, beside the link.`:``),U();return}if(!P()){E=`Sign in to nixamp.com to go live here, or use the server's control link.`,U();return}await br(e)}function Tr(e){let t=m.linkUrl.value.trim();ve=!0,b=``,m.remoteUrl.value=e,m.remoteForm.requestSubmit(),m.linkUrl.value=t}m.linkGoLive.addEventListener(`click`,()=>{wr()}),m.linkServer.addEventListener(`change`,()=>{let e=m.linkServer.value;e!==``&&Tr(e)}),m.downloadNow.addEventListener(`click`,()=>{let e=k?.link;if(!e||v!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(L.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),E=`Fetching it through the server; your browser will save it when it arrives.`,U()}),m.goLiveNow.addEventListener(`click`,()=>{let e=Rt();e&&Bt(e,m.goLiveNow)}),m.seek.addEventListener(`input`,()=>{ke=!0}),m.seek.addEventListener(`change`,()=>{let e=En();e>0&&I.seek(Number(m.seek.value)/1e3*e),ke=!1}),m.volume.addEventListener(`input`,()=>{let e=Number(m.volume.value)/100;I.volume=e,m.volumeToggle.setAttribute(`aria-pressed`,e===0?`true`:`false`),m.volumeToggle.textContent=e===0?`🔇`:`🔊`,C(m.volumeToggle,`aria-label`,()=>_(e===0?`Unmute`:`Mute`));try{localStorage.setItem(Hn,String(e))}catch{}}),m.volumeToggle.addEventListener(`click`,()=>{let e=Number(m.volume.value)===0,t=100;try{let e=Number(localStorage.getItem(Hn));Number.isFinite(e)&&e>0&&(t=Math.round(e*100))}catch{}m.volume.value=e?String(t):`0`,m.volume.dispatchEvent(new Event(`input`))}),m.refreshPlayer.addEventListener(`click`,()=>window.location.reload());let Er=e=>{e.addEventListener(`change`,()=>{let t=Xe(Array.from(e.files??[]));if(t.length===0){E=`Nothing playable in that selection.`,U();return}Qe(w),w=t,Ee=0,v=`local`,L.close(),Yo(!1),E=``,kn(0)})};Er(m.files),Er(m.folder),m.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=m.remoteUrl.value,{base:n,key:r}=ee(t);if(n===``){E=`That is not an address.`,U();return}(async()=>{De=`connecting`,U();let e=re(n);if(e){De=`error`,Oe=e,E=e,ge=``,v=`local`,U();return}if(await ne(n,void 0,r)===null){De=`error`;let e=u(n);Oe=e?`needs the server's name`:`not answering`,E=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,ge=``,v=`local`,U();return}let i=await ie(n,r);if(i){De=`error`,Oe=i,E=i,ge=``,v=`local`,U();return}v=`remote`,E=``;try{localStorage.setItem(Bn,t.trim())}catch{}L.connect(t),Yo(!0),Wa(),zr(),Go(),U()})()}),m.remoteServer.addEventListener(`change`,()=>{let e=m.remoteServer.value;e!==``&&(ve=!1,b=``,m.remoteUrl.value=e,m.remoteForm.requestSubmit())});let Dr=``,Or=null,kr=async(e=!1)=>{m.directory.hidden=!1,e||(m.directoryNote.textContent=`Looking for live streams…`,O(m.directoryList)),Or||=setInterval(()=>{!m.directory.hidden&&document.visibilityState===`visible`&&kr(!0)},Wn);let t;try{let n=await r(`/api/directory`);if(!n.ok)throw Error(String(n.status));let i=await n.json();t=i.streams??[],pe=t.map(e=>({name:e.name,url:e.url})),xr();let a=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:i.recent??[],me:Y});if(e&&a===Dr)return;Dr=a,Hr(i.recent??[])}catch{e||(m.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(O(m.directoryList),t.length===0){m.directoryNote.textContent=`Nobody is streaming right now.`;return}m.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 i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`;let o=[`${e.tracks.toLocaleString(g.language)} files to browse`];e.playing!==!1&&e.nowPlaying?o.push(`playing ${e.nowPlaying}`):o.push(`player idle`),e.code&&o.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),a.textContent=o.join(` · `),a.title=a.textContent,n.append(i,a);let s=e.admin??Ce(e.url),c=(t,n=``)=>{ve=t,b=n,m.remoteUrl.value=t?e.url:s??e.url,m.directory.hidden=!0,document.body.classList.remove(`route-directory`),m.remoteForm.requestSubmit()},l=document.createElement(`ul`);l.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 o=e.lineup?.find(e=>e.name===t);if(o?.art&&/^https?:\/\//i.test(o.art)){let e=document.createElement(`img`);e.className=`live-art`,e.alt=``,e.loading=`lazy`,e.src=o.art,e.addEventListener(`error`,()=>{e.hidden=!0}),n.append(e)}o?.about&&(r.title=o.about);let u=document.createElement(`button`);u.type=`button`,u.className=`icon`,h(u,`party`),u.setAttribute(`aria-label`,`Join ${t} live on ${e.name}`),u.title=`Join live: ${t} on ${e.name}`,u.addEventListener(`click`,()=>c(!0,`channel:${t}`));let d=document.createElement(`button`);d.type=`button`,d.className=`icon`,h(d,`link`),d.setAttribute(`aria-label`,`Copy live room link for ${t}`),d.title=`Copy a nixamp link to this live room`;let f=`${globalThis.location.origin}/?url=${encodeURIComponent(e.url)}&play=${encodeURIComponent(`channel:${o?.id??t}`)}`;d.addEventListener(`click`,e=>{e.stopPropagation(),cs(f,d,`✓`)});let p=document.createElement(`button`);p.type=`button`,p.className=`icon`,h(p,`copy`),p.setAttribute(`aria-label`,`Copy raw stream URL for ${t}`),p.title=`Copy the raw stream URL for VLC or another player`;let ee=e.url;try{let n=new URL(e.url);n.pathname=`/api/channels/${encodeURIComponent(o?.id??t)}`,ee=n.toString()}catch{}if(p.addEventListener(`click`,e=>{e.stopPropagation(),cs(ee,p,`✓`)}),n.append(r,u,d,p),o?.startedBy&&Y&&o.startedBy===Y&&s){let e=document.createElement(`button`);e.type=`button`,e.className=`icon`,h(e,`gear`),e.setAttribute(`aria-label`,`Administer ${t}`),e.title=`Administer ${t}`,e.addEventListener(`click`,e=>{e.stopPropagation(),c(!1,`channel:${o?.id??t}`)}),n.append(e)}l.append(n)}let[u,d]=x({name:e.name,view:e.url,admin:s},()=>{m.directory.hidden=!0,document.body.classList.remove(`route-directory`)});if(t.append(n,u,d),Y&&t.append(oi(e.url,e.name)),e.ownerId&&Y&&e.ownerId!==Y&&t.append(io(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&Y&&e.ownerId===Y){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 r(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));m.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{m.directoryNote.textContent=`could not reach the directory`}finally{await kr()}})()}),t.append(n)}m.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!m.directory.hidden&&kr(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),kr()}let Ar=/^\/live\/([^/]+)\/?$/.exec(location.pathname);if(Ar){document.body.classList.add(`route-party`),m.partyRoom.hidden=!1;let e=decodeURIComponent(Ar[1]??``),t=null,n=0,i=``,a=new Set,o=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}`},s=(e,t=!1)=>{let n=t?m.partyChatNote:m.partyRoomNote;n.hidden=e===``,n.textContent=e},c=()=>{if(!t)return;let e=t.party.playing?(Date.now()-n)/1e3:0,r=t.party.positionNow+e,i=[t.event.status===`live`?t.party.playing?`▶ ${o(r)}`:`❚❚ ${o(r)}`:`ended`,t.party.mediaTitle,`code ${t.party.partyCode}`,t.host?`yours`:``].filter(Boolean);m.partyMeta.textContent=i.join(` · `)},l=()=>{if(!t)return;document.title=`${t.event.title} — nixamp`,m.partyTitle.textContent=t.event.title||t.party.partyCode;let e=t.links.partyUrl||t.party.partyUrl;m.partyWatch.href=e||`#`,m.partyWatch.hidden=e===``;let n=t.party.origin;try{n=new URL(e).hostname}catch{}m.partyWatch.title=`The film plays on ${n} (opens in a new tab)`,m.partyEnd.hidden=!t.host||t.event.status!==`live`;let r=t.event.chatEnabled!==!1&&t.event.status===`live`;m.partyChatForm.hidden=!r,m.partyChatInput.disabled=!r||Y===``,m.partyChatSend.disabled=!r||Y===``,s(r?Y===``?`Sign in to say something; everybody can read.`:``:t.event.status===`live`?`Chat is off for this party.`:`This party has ended.`,!0),c()},u=async()=>{try{let i=await r(`/api/v1/watch-parties/${encodeURIComponent(e)}`,{cache:`no-store`});if(!i.ok){s(i.status===404?`No party here. It may have ended, or the link is not one.`:`Could not open this party. Try again in a moment.`);return}t=await i.json(),n=Date.now(),s(``),l()}catch{s(`Could not open this party. Try again in a moment.`)}},d=async()=>{if(t&&t.event.chatEnabled!==!1)try{let e=new URL(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,location.origin);i&&e.searchParams.set(`after`,i);let n=await r(e.toString(),{cache:`no-store`});if(!n.ok)return;let o=((await n.json()).messages??[]).filter(e=>!a.has(e.id));if(!o.length){if(!m.partyChat.childElementCount){let e=document.createElement(`li`);e.className=`hint`,e.textContent=`No messages yet. Say hi!`,m.partyChat.replaceChildren(e)}return}m.partyChat.querySelector(`.hint`)&&m.partyChat.replaceChildren();let s=m.partyChat.scrollHeight-m.partyChat.scrollTop-m.partyChat.clientHeight<60;for(let e of o){a.add(e.id),i=e.createdAt;let t=document.createElement(`li`),n=document.createElement(`b`);n.textContent=e.authorName,t.append(n,document.createTextNode(e.body)),m.partyChat.append(t)}for(;m.partyChat.childElementCount>200;)m.partyChat.firstElementChild?.remove();s&&(m.partyChat.scrollTop=m.partyChat.scrollHeight)}catch{}};m.partyChatForm.addEventListener(`submit`,e=>{e.preventDefault();let n=m.partyChatInput.value.trim();t&&n!==``&&(m.partyChatSend.disabled=!0,(async()=>{try{let e=await r(`/api/v1/events/${encodeURIComponent(t.event.id)}/chat`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({body:n})}),i=await e.json().catch(()=>({}));if(!e.ok){s(i.error??`That did not send.`,!0);return}m.partyChatInput.value=``,s(``,!0),await d()}catch{s(`That did not send.`,!0)}finally{m.partyChatSend.disabled=Y===``}})())}),m.partyCopy.addEventListener(`click`,()=>{navigator.clipboard?.writeText(t?.links.nixampUrl||location.href).then(()=>{m.partyCopy.textContent=`Copied`,setTimeout(()=>{m.partyCopy.textContent=`Copy room link`},2e3)},()=>s(`Could not copy that.`))}),m.partyEnd.addEventListener(`click`,()=>{t&&t.host&&(async()=>{if(!(await r(`/api/v1/watch-parties/${encodeURIComponent(t.party.partyCode)}/end`,{method:`POST`})).ok){s(`Could not end it.`);return}await u()})()}),(async()=>{await u(),await d()})(),setInterval(c,1e3),setInterval(()=>void u(),1e4),setInterval(()=>void d(),4e3),document.addEventListener(`nixamp:account`,()=>l())}let jr=null,Mr=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Nr=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Pr=``,Fr=``,Ir=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Pr)return;Pr=t,m.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)}m.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,``],[Mr(t.network),`network-${t.network}`],[Nr(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)}m.adminConnections.append(e)}};function G(e){m.adminSaid.textContent=e,m.adminSaid.hidden=e===``}let Lr=async()=>{try{let e=await r(L.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,i=t.active??0;m.adminNote.textContent=n===0?`${i} listening now.`:`${i} listening now, and ${n} with the page open.`,Ir(t.connections??[]),Rr(t.publish??[],(t.channels??[]).map(e=>e.id)),ms(t.home??``,t.root??``),Xo()}catch{m.adminNote.textContent=`lost touch with the server`}};function Rr(e,t){m.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Fr)return;if(Fr=n,e.length===0){O(m.publishList);return}let r=e.length-t.length;m.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,O(m.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`,S(o,()=>_(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let zr=async()=>{if(v!==`remote`){m.adminPanel.hidden=!0,m.publishPanel.hidden=!0,jr&&clearInterval(jr),jr=null;return}let e=!1,t=null,n=!1,i=!1;try{let a=await r(L.url(`/api/admin`));if(a.ok){let r=await a.json();e=r.allowed===!0,t=r.as??null,n=r.claimed===!0,i=r.member===!0}}catch{e=!1}let a=e||i;ve&&(e=!1),Mt=a&&!e;let o=m.partiesList.dataset.adminMode!==String(e);if(m.adminPanel.hidden=!e,o&&(m.partiesList.dataset.adminMode=String(e),m.partiesList.querySelectorAll(`details[open]`).forEach(e=>e.removeAttribute(`open`)),Xr()),Wo(e),ge!==``){let e=ge;ge=``,P()?br(e):(E=`Sign in to nixamp.com to go live here.`,U())}if(jr&&clearInterval(jr),jr=null,Xo(),Wa(),Go(),m.listenOnly.hidden=e,!e){m.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}m.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Lr(),jr=setInterval(()=>void Lr(),2e3)};function Br(e,t,n){let i=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;G(`Starting ${t||e}…`),(async()=>{try{let a=await r(L.url(`/api/channels/${encodeURIComponent(i)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),o=await a.json();if(!a.ok){G(o.error??`that did not work`);return}G(`${o.channel?.name||t||e} is on the air.`),m.adminSource.value=``,m.adminName.value=``,Go(),Xo()}catch{G(`could not reach the server`)}})()}m.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=m.adminSource.value.trim();t&&Br(t,m.adminName.value.trim())}),m.adminAdd.addEventListener(`click`,()=>{let e=m.adminSource.value.trim();if(!e)return;G(`Reading ${e}…`);let t=m.adminReplace.checked,n=m.adminName.value.trim();(async()=>{try{let i=await r(L.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),a=await i.json();G(i.ok?t?`Now serving ${e}.`:a.added===0?`Everything there was already in the playlist.`:`Added ${a.added??0} tracks from ${e}.`:a.error??`that did not work`),i.ok&&(m.adminSource.value=``,m.adminName.value=``,Go(),Xo())}catch{G(`could not reach the server`)}})()});let Vr=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`},Hr=e=>{let t=[],n=Y?e.filter(e=>e.ownerId&&e.ownerId!==Y):[];if(m.recentNote.hidden=n.length===0,n.length===0){O(m.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 ${Vr(e.endedAt)}`:`ended ${Vr(e.endedAt)}`,r.append(i,a),n.append(r,io(e.ownerId,e.name)),t.push(n)}O(m.recentList,...t)},Ur=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 Wr(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?`▶ ${Ur(e.party.positionNow)}`:`❚❚ ${Ur(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`,Vt(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(c,`aria-label`,()=>`${_(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let Gr=[],Kr=[],qr=!1,Jr=null,Yr=``;function Xr(){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=v===`remote`&&A?_e(L.address):``;for(let e of Gr){let r=_e(e.url);if(!r||r===n)continue;let i=[],a=(t,n)=>{let a=document.createElement(`li`);a.dataset.liveKey=`${r}:${t}`,a.className=`party-row`;let o=document.createElement(`span`);o.className=`party-name`,o.textContent=n,o.title=n;let s=document.createElement(`button`);s.type=`button`,Vt(s),C(s,`aria-label`,()=>`${_(`Join party`)}: ${n} · ${e.name}`),s.addEventListener(`click`,()=>{ve=!0,b=t,m.remoteUrl.value=e.url,m.remoteForm.requestSubmit()}),a.append(o,s),i.push(a)};e.playing!==!1&&e.nowPlaying&&a(`live`,He(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);a(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&A&&t(n,A.server.name||y||n,Qo(A));for(let e of Kr){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=Wr(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...m.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),Ve(e.querySelector(`ul`),n.rows),i.push(e)}Ve(m.partiesList,i),m.partiesNote.hidden=e.size>0,e.size||S(m.partiesNote,()=>_(qr?`No parties live right now.`:`Loading…`))}let Zr=5e3,Qr=new Set,$r=(e,t)=>{t?Qr.add(e):Qr.delete(e),Qr.size?m.partiesPanel.dataset.loading=`true`:delete m.partiesPanel.dataset.loading};async function ei(){if(e||(Yr!==Y&&(Jr?.abort(),Jr=null,Kr=[],Yr=Y,Xr()),Jr))return;let t=new AbortController;Jr=t;let n=!qr;n&&$r(t,!0);let i=Y,a=setTimeout(()=>t.abort(),8e3),o=async e=>{let n=await r(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`),i?o(`/api/v1/watch-parties`):Promise.resolve(null)]);if(Jr!==t||i!==Y||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(Gr=e.value.body.streams??[],qr=!0,m.directory.dataset.available=String(Gr.length>0),Ho()),n.status===`fulfilled`&&n.value&&(n.value.ok?(Kr=n.value.body.parties??[],qr=!0):[401,403].includes(n.value.status)&&(Kr=[])),Xr(),!qr&&!A&&S(m.partiesNote,()=>_(`Could not refresh parties.`))}finally{clearTimeout(a),n&&$r(t,!1),Jr===t&&(Jr=null)}}m.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=m.partyCode.value.trim();t!==``&&(async()=>{try{let e=await r(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){E=n.error??`No party found with that invite code.`,U();return}m.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{E=`Could not look up that party. Try again.`,U()}})()});async function ti(){if(!Y){m.connectionsNote.hidden=!0,m.connectionsList.hidden=!0;return}try{let e=await r(`/api/v1/oauth/connections`);if(!e.ok){m.connectionsNote.hidden=!0,m.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];m.connectionsNote.hidden=t.length===0,m.connectionsList.hidden=t.length===0,O(m.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.clientName;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(i,a);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,S(o,()=>_(`Disconnect`)),o.addEventListener(`click`,()=>{(async()=>{try{await r(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await ti()})()}),t.append(n,o),t}))}catch{m.connectionsNote.hidden=!0,m.connectionsList.hidden=!0}}let ni=new Set,K=e=>{try{return new URL(e).origin}catch{return e}},ri=e=>[...ni].some(t=>K(t)===K(e));async function ii(){if(!Y){ni=new Set,m.favoritesPanel.hidden=!0,si();return}try{let e=await r(`/api/v1/favorites`);if(!e.ok){m.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];ni=new Set(t.map(e=>e.url)),m.favoritesPanel.hidden=t.length===0,m.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,O(m.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,...x({name:e.name||e.url,view:e.url,admin:Ce(e.url)}),oi(e.url,e.name)),t}))}catch{m.favoritesPanel.hidden=!0}si()}async function ai(e,t,n){try{if(!(n?await r(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await r(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){E=n?`Could not save that favourite.`:`Could not remove that favourite.`,U();return}}catch{E=`could not reach nixamp.com`,U();return}if(n)ni.add(e);else for(let t of[...ni])K(t)===K(e)&&ni.delete(t);await ii()}function oi(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=ri(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=[...ni].find(t=>K(t)===K(e))??e;ai(ri(e)?i:e,t,!ri(e)).then(r)}),n}function si(){let e=v===`remote`?L.shareLink:``;if(m.favHere.hidden=!(Y&&e),m.favHere.hidden)return;let t=ri(e);m.favHere.textContent=t?`♥`:`♡`,m.favHere.dataset.on=t?`yes`:`no`,m.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,m.favHere.setAttribute(`aria-label`,m.favHere.title)}h(m.copyNow,`copy`),m.copyNow.addEventListener(`click`,()=>{cs(I.source,m.copyNow,`✓`)});function ci(e){if(e===``||e===Ct)return;Ct=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),S(n,()=>r.toLocaleTimeString(g.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),m.logList.prepend(t);m.logList.children.length>100;)m.logList.lastElementChild?.remove()}let li=3e3,q=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,ui=``,di=``,fi=null,pi=!1,mi=new Set,hi=``,gi=null,_i=!1,vi=en(e=>localStorage.getItem(e)),J=Yt(e=>localStorage.getItem(e)),yi=new Set,bi=new Set,xi=null,Si=``,Ci=``,Y=``,wi=(()=>{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()}`}})(),Ti=null,X=!1,Ei=``,Di=!1,Oi=!1,ki=``,Ai=0,ji=!1,Mi=!1;try{m.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let Ni=new hn(()=>{Mi=!0,ji&&(m.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)},{process:!1}),Pi=()=>{let e=Number(m.transcriptBackgroundLevel.value);Ni.setLevel(e/100),m.transcriptBackgroundValue.value=`${e}%`,C(m.transcriptBackgroundLevel,`aria-valuetext`,()=>g.number(e/100,{style:`percent`})),m.transcriptBackgroundLevel.disabled=!m.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(m.transcriptBackgroundLevel.value=e)}catch{}Pi(),m.transcriptBackgroundLevel.addEventListener(`input`,()=>{Pi();try{localStorage.setItem(`nixamp.backgroundLevel`,m.transcriptBackgroundLevel.value)}catch{}});let Fi=new _n({account:()=>q===``?Y:``,changed:()=>ha()});H(`translation-buy-tools`).append(Fi.button()),Fi.refresh();let Ii=new gn({reconnecting:()=>Z.reset(),line:(e,t)=>{Wi=0,Gi.push(e),pa(),Z.push(e,t,0)},status:e=>{m.transcriptAudioNote.textContent=e},failed:e=>{Ei=e,Ci=e,X=!1,m.transcriptAudio.checked=!1,Z.disable(),zi(),m.transcriptAudioNote.textContent=`${e} Original audio restored.`,Fi.refresh()}}),Z=new un({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(Ii.audio(String(e))):r(e,t)),playing:()=>I.playing,volume:()=>I.volume,active:e=>{ji=e,I.translatedAudio(e),Ni.active(e&&I.playing&&m.transcriptBackground.checked)},status:e=>{m.transcriptAudioNote.textContent=e+(Mi&&ji?` · background unavailable`:``)},failed:()=>{Ci=m.transcriptAudioNote.textContent||`Translated audio stopped.`,X=!1,m.transcriptAudio.checked=!1,zi()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!Y||q!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!Ti||Ti.channel!==t.channel||Ti.expires<Date.now()+2e4||Ti.remaining<t.text.length){let n=await r(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),i=await n.json();if(!n.ok||!i.token||!i.expires)throw Error(i.error||`Sign in to enable translated audio.`);Ti={channel:t.channel,token:i.token,expires:i.expires,remaining:2e3}}return Ti.remaining-=t.text.length,{authorization:`Bearer ${Ti.token}`}}}),Li=new zt({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,wi),r(e,{...t,headers:n})},language:()=>J,speakers:()=>m.transcriptAudio.checked,voices:()=>xi?.voices??[],channel:()=>wi,status:e=>{!Di&&!X&&(Ei=e),m.transcriptNote.textContent=e},failed:()=>{X=!1,m.transcriptAudio.checked=!1,Z.disable(),zi()},lines:e=>{Wi=0,Gi.push(...e),pa(),Vi(),m.transcriptAudio.checked&&Z.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:J,channel:wi,speaker:e.speaker,voice:Li.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),Ri=new fn(e=>{Di&&I.playing&&Li.push(e)});function zi(){Ai++,Di=!1,Oi=!1,ki=``,Ri.stop(),Li.reset(),Ii.stop(),Ni.stop(),Z.reset(),O(m.transcriptSpeakers)}async function Bi(){if((Di||Oi)&&ki===I.mediaKey)return;zi();let e=Ai;Oi=!0,ki=I.mediaKey;try{if(!Y||q!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=I.audioInput();if(Mi=!1,m.transcriptAudio.checked&&m.transcriptBackground.checked&&Ni.start(t.context,t.node).then(t=>{t&&e===Ai&&Ni.active(ji&&I.playing&&m.transcriptBackground.checked)}),m.transcriptAudio.checked&&v===`remote`&&D)await Ii.start(_a(),J),Fi.refresh();else{if(m.transcriptAudio.checked&&await Fi.startSession(wi),e!==Ai)return;await Ri.start(t.context,t.node,m.transcriptAudio.checked?2:5)}if(e!==Ai)return;Di=!0,X=!0,Wi=0,qi??=setInterval(pa,250),m.transcriptNote.textContent=m.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==Ai)return;X=!1,m.transcriptAudio.checked=!1,Z.disable(),zi(),Ei=t instanceof Error?t.message:`This audio could not be captured.`,m.transcriptNote.textContent=Ei}finally{e===Ai&&(Oi=!1)}}function Vi(){let e=[...Li.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(m.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];S(n,()=>`${_(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,C(i,`aria-label`,()=>`${_(`Speaker voices`)}: ${r}`);for(let e of xi?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,Z.reset()}),e.append(i),m.transcriptSpeakers.append(e)}m.transcriptVoiceSettings.hidden=!m.transcriptAudio.checked;for(let e of m.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[m.audio,m.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(I.showingVideo?m.video:m.audio)&&zi()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(I.showingVideo?m.video:m.audio)&&X&&vi&&I.playing&&Bi()});e.addEventListener(`volumechange`,()=>{Z.setVolume()})}let Hi=``,Ui=null,Wi=Zt(6,!1),Gi=[],Ki=[],qi=null;function Ji(){if(v!==`remote`)return null;let{base:e}=ee(us());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=D?D.id:k?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function Yi(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${q}/api/v1/trollbox?${n.toString()}`}function Xi(){let e=Ji(),t=e?`${e.server}|${e.channel}`:``;t!==ui&&(ui=t,di=``,mi.clear(),m.trollboxList.replaceChildren(),fi&&clearTimeout(fi),fi=null,m.trollboxPanel.hidden=e===null,m.trollboxForm.hidden=!0,na(!1),e&&(S(m.trollboxNote,()=>`The room for ${Sn()||e.channel}. Loading…`),Qi()))}function Zi(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);S(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(g.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 Qi(){let e=Ji(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===ui&&!pi){pi=!0;try{let n=await r(Yi(e,di)),i=await n.json().catch(()=>({}));if(t!==ui)return;if(!n.ok){m.trollboxNote.textContent=i.error??`The trollbox is not answering.`;return}let a=(i.messages??[]).filter(e=>!mi.has(e.id));for(let e of a)mi.add(e.id),m.trollboxList.append(Zi(e)),di=e.createdAt;for(;m.trollboxList.children.length>200;)m.trollboxList.firstElementChild?.remove();let o=i.you??``,s=hi!==o;hi=o,de.hidden=o!==``,q!==``&&(de.href=`${q}/?url=${encodeURIComponent(us())}&play=${encodeURIComponent(`channel:${e.channel}`)}#account-panel`),s&&(Ti=null,ha()),m.trollboxForm.hidden=o===``,m.trollboxEditLabel.hidden=o===``||!$i,o===``&&na(!1),S(m.trollboxNote,()=>o===``?q===``?`The room for ${Sn()||e.channel}. Sign in to say something.`:`The room for ${Sn()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${Sn()||e.channel}.`)}catch{t===ui&&(m.trollboxNote.textContent=`The trollbox is not answering.`)}finally{pi=!1,t===ui&&(fi=setTimeout(()=>{document.visibilityState===`visible`?Qi():fi=setTimeout(()=>void Qi(),li)},li))}}}m.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=Ji(),n=m.trollboxInput.value.trim();t&&n!==``&&(m.trollboxInput.disabled=!0,(async()=>{try{let e=await r(`${q}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),i=await e.json().catch(()=>({}));if(!e.ok||!i.message){m.trollboxNote.textContent=i.error??`that did not send`;return}m.trollboxInput.value=``,mi.has(i.message.id)||(mi.add(i.message.id),m.trollboxList.append(Zi(i.message)),di=i.message.createdAt)}catch{m.trollboxNote.textContent=`The trollbox is not answering.`}finally{m.trollboxInput.disabled=!1}})())});let $i=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,ea=$i?Wt(e=>MediaRecorder.isTypeSupported(e)):``;m.trollboxMic.hidden=!$i;function ta(e){m.trollboxNote.textContent=e,ci(e)}function na(e){let t=gi;if(!t)return;gi=null,clearTimeout(t.stop),clearInterval(t.tick),m.trollboxMic.setAttribute(`aria-pressed`,`false`),m.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(()=>ia(new Blob(t.chunks,{type:t.recorder.mimeType||ea||`audio/webm`}),t.startedAt))}async function ra(){if(gi||_i||hi===``||!Ji())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){ta(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,ea?{mimeType:ea}:{})}catch{for(let t of e.getTracks())t.stop();ta(`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();gi={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>na(!0),Ut),tick:setInterval(()=>{m.trollboxMic.textContent=Gt(r,Date.now())},500)},t.start(250),m.trollboxMic.setAttribute(`aria-pressed`,`true`),m.trollboxMic.textContent=Gt(r,r),ta(`Listening. Tap the mic again when you have said it (${Math.round(Ut/1e3)} s at most).`)}async function ia(e,t){let n=Ji();if(n&&hi!==``){if(Date.now()-t<400||e.size===0){ta(`That was too short to hear. Tap, say it, then tap again.`);return}_i=!0,m.trollboxMic.disabled=!0,m.trollboxMic.textContent=`…`,ta(`Hearing you…`);try{let t=new AudioContext,i;try{i=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let a=new OfflineAudioContext(1,Math.max(1,Math.ceil(i.duration*Ht)),Ht),o=a.createBufferSource();o.buffer=i,o.connect(a.destination),o.start();let s=Lt((await a.startRendering()).getChannelData(0),Ht),c=m.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 r(`${q}/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){ta(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){ta(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=m.trollboxInput.value.trimEnd();m.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),ta(`Heard: “${p}”. Send it, or fix it first.`);return}Ji()&&!mi.has(f.message.id)&&(mi.add(f.message.id),m.trollboxList.append(Zi(f.message)),di=f.message.createdAt),ta(`Said: “${f.message.body}”`)}catch{ta(`That recording could not be read here.`)}finally{_i=!1,m.trollboxMic.disabled=!1,m.trollboxMic.textContent=`🎤`}}}m.trollboxMic.addEventListener(`click`,()=>{gi?na(!0):ra()});try{m.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}m.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,m.trollboxEdit.checked?`on`:`off`)}catch{}ta(m.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function aa(){try{let e=await r(`${q}/api/v1/me/profile/fields`),t=await e.json().catch(()=>({}));if(!e.ok){m.contactNote.textContent=t.error??`Could not read your details.`;return}for(let e of Kn){let n=m.contactForm.elements.namedItem(e);n instanceof HTMLInputElement&&(n.value=t.profile?.[e]??``)}m.contactNote.textContent=`Your name and work details. Only you see these.`}catch{m.contactNote.textContent=`Could not reach nixamp.com for your details.`}}m.contactForm.addEventListener(`submit`,e=>{e.preventDefault(),m.contactNote.textContent=`Saving…`,(async()=>{try{let e=await r(`${q}/api/v1/me/profile/fields`,{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify(qn(m.contactForm))}),t=await e.json().catch(()=>({}));m.contactNote.textContent=e.ok?`Saved.`:Object.values(t.errors??{})[0]??t.error??`that did not save`}catch{m.contactNote.textContent=`Could not reach nixamp.com.`}})()});async function oa(){try{let e=await r(`${q}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){m.personaNote.textContent=t.error??`Could not read your profile.`;return}m.personaHandle.value=t.chosen?t.handle??``:``,C(m.personaHandle,`placeholder`,()=>t.handle||_(`handle`)),m.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,m.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;m.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${sa(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${sa(t.voice??``)}${n}.`}catch{m.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function sa(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`}m.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=m.personaHandle.value.trim(),n={voice:m.personaVoice.value,profile:m.personaProfile.value.trim()};t!==``&&(n.handle=t),m.personaNote.textContent=`Saving…`,(async()=>{try{let e=await r(`${q}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){m.personaNote.textContent=t.error??`that did not save`;return}await oa()}catch{m.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&gi&&na(!0)});function ca(){return v===`remote`&&D?{id:D.id,name:D.name,hls:D.video&&F()}:I.loaded||j?{id:wi,name:Sn()||`This audio`,hls:!1}:null}function la(){zi(),Ti=null,yi.clear(),bi.clear(),Ui?.close(),Ui=null,qi&&clearInterval(qi),qi=null,Gi=[],Ki=[],m.transcriptList.replaceChildren(),m.subtitle.hidden=!0,m.subtitle.textContent=``}function ua(){let e=ca(),t=`${e?.id??``}|${I.mediaKey}|${vi}|${J}|${m.transcriptAudio.checked}|${X}|${Y}`;if(t!==Hi){if(Hi=t,la(),m.transcriptPanel.hidden=!1,m.transcriptOn.checked=vi&&(!!D||X||m.transcriptAudio.checked),m.transcriptLanguage.options.length===0)for(let e of Jt){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),S(t,()=>e.code?e.label:_(`Original (auto-detect)`)),m.transcriptLanguage.append(t)}if(m.transcriptLanguage.value=J,ha(),ga(),!e){m.transcriptNote.textContent=`Play something to see its captions.`;return}if(!vi){m.transcriptNote.textContent=`Captions are off.`;return}if(Ei){m.transcriptNote.textContent=Ei;return}m.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,m.transcriptAudio.checked||X?I.playing?Bi():m.transcriptNote.textContent=`Press Play to start listening.`:v===`remote`&&D?da(e,t):m.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function da(e,t){let n=6,i=J?`?language=${encodeURIComponent(J)}`:``;try{let a=await r(L.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${i}`)),o=await a.json().catch(()=>({}));if(t!==Hi)return;if(!a.ok){m.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){Y&&q===``?(X=!0,ua()):m.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===Hi&&(m.transcriptNote.textContent=`The server did not answer about captions.`);return}Wi=Zt(n,e.hls);let a=new EventSource(L.url(`/api/channels/${encodeURIComponent(e.id)}/captions${i}`));Ui=a;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}`;yi.has(e)||(yi.add(e),yi.size>600&&yi.delete(yi.values().next().value),Gi.push(n),t&&m.transcriptAudio.checked&&bi.add(n))}};a.addEventListener(`hello`,r=>{if(t!==Hi)return;let i=JSON.parse(r.data);Wi=Zt(i.backlog??n,e.hls),o(i.lines??[]);let a=Jt.find(e=>e.code===i.language)?.label??i.language,s=Jt.find(e=>e.code===J)?.label??J;if(m.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:J?`${a||`Detected audio`} → ${s}`:`Original audio · ${a||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${q||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,m.transcriptNote.append(` `,e,`.`)}}),a.addEventListener(`line`,n=>{if(t!==Hi)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),a=Jt.find(e=>e.code===i)?.label??i,s=Jt.find(e=>e.code===J)?.label??J;m.transcriptNote.textContent=J?`${e.name} · ${a||`Detected audio`} → ${s}`:`${e.name} · Original audio language: ${a||`detecting…`}`}),a.addEventListener(`error`,()=>{t===Hi&&a.readyState===EventSource.CLOSED&&(m.transcriptNote.textContent=`Captions stopped; the server went away.`)}),qi=setInterval(pa,250)}function fa(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),S(n,()=>tn(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=Xt(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 pa(){let e=Date.now(),{ready:t,still:n}=Qt(Gi,e,Wi);Gi=n;for(let e of t)if(Ki.push(e),m.transcriptList.append(fa(e)),bi.delete(e)&&m.transcriptAudio.checked&&J){let t=new URLSearchParams({at:String(e.at),language:J,voice:`auto`});Z.push(e,L.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),Wi)}for(;Ki.length>200;)Ki.shift();for(;m.transcriptList.children.length>200;)m.transcriptList.firstElementChild?.remove();let r=$t(Ki,e,Wi),i=m.transcriptList.children,a=r?Ki.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let o=I.playing&&r!==null&&!m.video.hidden&&m.video.offsetHeight>0;m.subtitle.hidden=!o,o&&r&&(m.subtitle.textContent!==r.text&&(m.subtitle.textContent=r.text),m.subtitle.style.top=`${m.video.offsetTop+m.video.offsetHeight-m.subtitle.offsetHeight-10}px`)}m.transcriptOn.addEventListener(`change`,()=>{vi=m.transcriptOn.checked,X=vi&&(!D||m.transcriptAudio.checked),vi||(m.transcriptAudio.checked=!1,Z.disable());try{localStorage.setItem(Kt,vi?`on`:`off`)}catch{}ua()}),m.transcriptLanguage.addEventListener(`change`,()=>{Ei=``,Ci=``,J=Yt(()=>m.transcriptLanguage.value),!J&&m.transcriptAudio.checked&&(m.transcriptAudio.checked=!1,X=!1,Z.disable());try{J?localStorage.setItem(qt,J):localStorage.removeItem(qt)}catch{}ua()});function ma(){if(J)return J;let e=navigator.language.split(`-`)[0]||`en`;return Jt.some(t=>t.code===e)&&xi?.languages.includes(e)?e:`en`}function ha(){let e=Y!==``&&q===``,t=e&&Fi.loaded()&&!!ca()&&!!xi?.languages.includes(ma());m.transcriptAudio.disabled=!t,m.transcriptVoiceSettings.contains(document.activeElement)||(m.transcriptVoiceSettings.hidden=!m.transcriptAudio.checked),t?m.transcriptAudio.checked||S(m.transcriptAudioNote,()=>Ci||_(`Original audio.`)):(m.transcriptAudio.checked=!1,Z.disable(),m.transcriptAudioNote.textContent=e?ca()?Fi.loaded()?Ci||(xi?`Audio translation is unavailable for this language.`:`Loading voices…`):Fi.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function ga(){if(!Y||q!==``)return;let e=`/api/v1/speech/voices`;if(Si!==e){Si=e,xi=null,Ci=``,ha();try{let t=await r(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(Si!==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.`);xi=n}catch(t){if(Si!==e)return;Ci=t instanceof Error?t.message:`Translated audio is unavailable.`}ha()}}m.transcriptBackground.addEventListener(`change`,()=>{Pi();try{localStorage.setItem(`nixamp.backgroundSound`,m.transcriptBackground.checked?`on`:`off`)}catch{}if(Ni.stop(),Mi=!1,m.transcriptBackground.checked&&m.transcriptAudio.checked&&I.playing){let e=Ai,t=I.audioInput();Ni.start(t.context,t.node).then(t=>{t&&e===Ai&&Ni.active(ji&&I.playing&&m.transcriptBackground.checked)})}}),m.transcriptAudio.addEventListener(`change`,()=>{if(Ei=``,Ci=``,bi.clear(),m.transcriptAudio.checked&&!Fi.ready()){m.transcriptAudio.checked=!1,Fi.open(m.transcriptAudio);return}if(m.transcriptAudio.checked){J=ma();try{localStorage.setItem(qt,J)}catch{}vi=!0,X=!0,Z.enable()}else X=!1,Z.disable();ua()});function _a(){if(j)return j.url;if(v!==`remote`)return``;let{base:e,key:t}=ee(us());if(e===``)return``;if(D)return te(e,`/api/channels/${encodeURIComponent(D.id)}`,t);if(k?.kind===`live`)return te(e,`/api/live`,t);if(I.source===``)return``;try{let n=new URL(I.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function va(){let e=_a();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}function ya(){return v===`remote`?D?ls(`channel:${D.id}`):k?.kind===`live`||B()?ls(`live`):``:``}m.shareNow.addEventListener(`click`,()=>{let e=va();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${yn()} on nixamp`,url:e}).catch(()=>void 0);return}cs(e,m.shareNow,`Copied`)}),m.copyNixamp.addEventListener(`click`,()=>{let e=ya();e!==``&&cs(e,m.copyNixamp,`✓`)});function ba(){let e=ya();if(e!==``)return e;let t=Ca();return t===null?``:ls(`track:${t}`)}async function xa(){let e=ba();if(e===``||m.schoolLive.disabled)return;let t=m.schoolLive.textContent;m.schoolLive.disabled=!0,m.schoolLive.textContent=`Opening a classroom…`;let n={"content-type":`application/json`};try{let t=await r(`/api/v1/events`,{method:`POST`,headers:n,body:JSON.stringify({kind:`class`,title:Ge(yn())||`Live class`,broadcastUrl:e,visibility:`public`})}),i=await t.json().catch(()=>({}));if(!t.ok||!i.event)throw Error(i.error??`the class could not be made`);let a=i.event,o=await r(`/api/v1/events/${encodeURIComponent(a.id)}/start`,{method:`POST`,headers:n,body:JSON.stringify({version:a.version})}),s=`https://backtoschool.help/live/${encodeURIComponent(a.slug)}`;E=o.ok?`Your class is live on backtoschool.help: ${s}`:`The class is made but not started yet. Open it to start: ${s}`,U(),globalThis.open(s,`_blank`,`noopener`)}catch(e){E=`Could not open a classroom: ${e.message}`,U()}finally{m.schoolLive.disabled=!1,m.schoolLive.textContent=t}}m.schoolLive.addEventListener(`click`,()=>{xa()});function Sa(){if(v!==`remote`)return``;let e=/^(https:\/\/[^/]+)\/view\/([A-Za-z0-9_-]+)\/?$/.exec(us());return e?D?`${e[1]}/api/channels/${encodeURIComponent(D.id)}?k=${e[2]}`:k?.kind===`live`||B()?`${e[1]}/api/live?k=${e[2]}`:``:``}function Ca(){if(v!==`remote`||D||k?.kind===`live`||B()||!/^https:\/\/[^/]+\/view\/[A-Za-z0-9_-]+\/?$/.test(us()))return null;let e=z();return T.tracks?.[e]?e:null}async function wa(e){let t=/^(https:\/\/[^/]+)\/view\/([A-Za-z0-9_-]+)\/?$/.exec(us());if(!t)throw Error(`this server has no view link to share`);let n=await r(`${t[1]}/api/media/${e}/item?k=${t[2]}`,{cache:`no-store`}),i=await n.json().catch(()=>({}));if(n.status===404&&i.error===`no such track`)throw Error("this server needs nixamp 0.48 or newer; run `nixamp update` on it");if(!n.ok||!i.id)throw Error(i.error??`that file is not in the server's library`);return`${t[1]}/api/v1/library/items/${i.id}/play?k=${t[2]}`}let Ta=H(`streaming-publish-note`),Ea=H(`streaming-publish-title-input`),Da=H(`streaming-publish-basis`),Oa=H(`streaming-publish-agree`),ka=H(`streaming-publish-go`);m.streamingLive.addEventListener(`click`,()=>{(Sa()!==``||Ca()!==null)&&(Ea.value=yn(),Ta.textContent=``,m.streamingPublish.showModal())}),H(`streaming-publish-close`).addEventListener(`click`,()=>m.streamingPublish.close()),H(`streaming-publish-form`).addEventListener(`submit`,e=>{e.preventDefault(),Aa()});async function Aa(){let e=Sa(),t=e===``?Ca():null;if(!(e===``&&t===null||ka.disabled)){if(!Oa.checked){Ta.textContent=`Tick the box to confirm you may broadcast it.`;return}ka.disabled=!0,Ta.textContent=`Publishing…`;try{let n=e||await wa(t),i=await r(`https://live.streaming.pit.world/api/v1/guide/${e?`rooms`:`vods`}`,{method:`POST`,headers:{"content-type":`application/json`,authorization:`Bearer ${L.session}`},body:JSON.stringify({play:n,basis:Da.value,title:Ea.value.trim(),agree:!0})}),a=await i.json().catch(()=>({}));if(!i.ok||!a.page)throw Error(a.error??`it could not be published`);m.streamingPublish.close(),E=e?`Live on live.streaming: ${a.page}`:`On demand on live.streaming: ${a.page}`,navigator.clipboard?.writeText(a.page).catch(()=>void 0),U(),globalThis.open(a.page,`_blank`,`noopener`)}catch(e){Ta.textContent=`Could not publish: ${e.message}`}finally{ka.disabled=!1}}}m.favHere.addEventListener(`click`,()=>{let e=us()||L.shareLink;if(!e)return;let t=[...ni].find(t=>K(t)===K(e))??e;ai(ri(e)?t:e,y||L.address,!ri(e)).then(si)});let ja=ce?ue:200,Ma=[],Q=null,Na=null,Pa=``,Fa=[],Ia=0,La=null,Ra=0,za=null,Ba=null,Va=new Map;function Ha(e,t){Ra++,za?.abort(),La&&clearTimeout(La),La=null,Re(m.catalogsList),Re(m.catalogsEntries),Q=e,Na=t,Pa=``,m.catalogsFilter.value=``,Fa=[],Ia=0,m.catalogsEntries.setAttribute(`aria-busy`,`false`),Ka(),e&&t!==null&&Za(0)}function Ua(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 Wa(){let e=L.url(`/api/catalogs`);if(Ba?.url===e)return Ba.promise;let t=Ga(e).finally(()=>{Ba?.promise===t&&(Ba=null)});return Ba={url:e,promise:t},t}async function Ga(e){if(v!==`remote`){m.catalogsPanel.hidden=!0;return}let t;try{t=await r(e)}catch{e===L.url(`/api/catalogs`)&&(m.catalogsPanel.hidden=!0);return}if(v===`remote`&&e===L.url(`/api/catalogs`)){if(!t.ok){m.catalogsPanel.hidden=!0;return}Ma=(await t.json().catch(()=>({}))).catalogs??[],Q&&=Ma.find(e=>e.id===Q?.id)??null,Q||(Na=null),m.catalogsPanel.hidden=!1,Ka()}}function Ka(){let e=!m.adminPanel.hidden;m.catalogsForm.hidden=!e;let t=Ma.reduce((e,t)=>e+t.live,0),n=Ma.reduce((e,t)=>e+t.vod,0);m.catalogsNote.textContent=Ma.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Ma.length} ${Ma.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,qa();let r=Q!==null&&Na!==null;if(m.catalogsList.hidden=r,m.catalogsFilter.hidden=!r,m.catalogsEntries.hidden=!r,r){Qa();return}if(Q){Ya(Q);return}O(m.catalogsList,...Ma.map(t=>Ja(t,e)))}function qa(){let e=Q!==null;if(m.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`,()=>Ha(null,null),!1),n(),t(Q?.name??``,()=>Ha(Q,null),Na===null)];Na!==null&&r.push(n(),t(Na===``?`All groups`:Na,()=>void 0,!0)),m.catalogsCrumbs.replaceChildren(...r)}function Ja(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`,S(a,()=>[`${e.entries.toLocaleString(g.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(g.language)} live`,`${e.vod.toLocaleString(g.language)} on demand`,`refreshed ${Ua(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`,()=>{Ha(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`,()=>{eo(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,S(r,()=>_(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&ss(n,r,()=>to(e),()=>void Wa())}),n.append(t,r)}return n}async function Ya(e){let t=L.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,i;m.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=Va.get(n);e||(Va.size>=20&&Va.delete(Va.keys().next().value),e=r(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),Va.set(n,e)),i=await e}catch{if(Va.delete(n),Q?.id!==e.id||Na!==null||t!==L.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;m.catalogsList.setAttribute(`aria-busy`,`false`),E=`Could not read the groups in ${e.name}.`,U();return}if(Q?.id!==e.id||Na!==null||t!==L.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;m.catalogsList.setAttribute(`aria-busy`,`false`);let a=[Xa(`All groups`,``,e.entries,e.live,e.vod),...i.map(e=>Xa(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];O(m.catalogsList,...a)}function Xa(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`,S(c,()=>`${n.toLocaleString(g.language)} · ${r.toLocaleString(g.language)} live · ${i.toLocaleString(g.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`,()=>{Ha(Q,t)}),a.append(o,l),a}async function Za(e){let t=Q,n=Na;if(!t||n===null)return;let i=++Ra;za?.abort();let a=new AbortController;za=a;let o=L.url(`/api/catalogs`);m.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Pa,offset:String(e),limit:String(ja)}),c;try{let e=await r(L.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:a.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(a.signal.aborted||i!==Ra)return;m.catalogsEntries.setAttribute(`aria-busy`,`false`),E=`Could not read ${t.name}.`,Qa(),U();return}i===Ra&&Q?.id===t.id&&Na===n&&o===L.url(`/api/catalogs`)&&(m.catalogsEntries.setAttribute(`aria-busy`,`false`),Ia=c.total??0,Fa=e===0?c.entries??[]:[...Fa,...c.entries??[]],Qa())}function Qa(){let e=Q;if(!e)return;let t=Fa.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?Me(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`,()=>{$a(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,h(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`;cs(L.url(i),r,`✓`)}),n.append(r)}return P()&&n.append(nn(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Fa.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Pa?`Nothing called "${Pa}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Fa.length<Ia){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,S(n,()=>`Show more (${Fa.length.toLocaleString(g.language)} of ${Ia.toLocaleString(g.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),Re(m.catalogsEntries,!1),n.disabled=!0,Za(Fa.length)}),e.append(n),t.push(e)}O(m.catalogsEntries,...t)}async function $a(e,t,n){n?.classList.add(`loading`),E=`Starting ${t.title}…`;let i={catalog:{id:e.id,name:e.name},entry:t};try{await Ke(async()=>{let n,a={};try{n=await r(L.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),a=await n.json().catch(()=>({}))}catch{E=`could not reach the server`;return}if(!n.ok){E=a.error??`${t.title} would not play.`;return}let o=a.name||t.title;if(a.kind===`live`&&a.channel){await ts({id:a.channel,name:o,video:!0},!0,{kind:`channel`,...i});return}if(a.kind===`vod`&&a.url){D=null,Ae=-1,k={kind:`vod`,...i},at(o,`title`),await I.load({title:o,artist:``,album:``,duration:0,url:L.url(a.url),video:!0,objectUrl:!1},!0),mr(!0),E=`Playing ${o}.`;return}E=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),U()}}async function eo(e){G(`Reading ${e.name} again…`);try{let t=await r(L.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));G(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(g.language)} entries.`:n.error??`that did not work`)}catch{G(`could not reach the server`)}Wa()}async function to(e){try{let t=await r(L.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`});if(G(t.ok?`${e.name} is off the server.`:`that did not work`),!t.ok)return!1}catch{return G(`could not reach the server`),!1}return Q?.id===e.id&&(Q=null,Na=null),!0}m.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=m.catalogSource.value.trim(),n=m.catalogName.value.trim();t&&(async()=>{G(`Reading ${n||t}…`);try{let e=await r(L.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),i=await e.json().catch(()=>({}));if(!e.ok){G(i.error??`that did not work`);return}G(`${i.catalog?.name??n??t}: ${(i.catalog?.entries??0).toLocaleString(g.language)} entries.`),m.catalogSource.value=``,m.catalogName.value=``}catch{G(`could not reach the server`)}Wa()})()}),m.catalogsFilter.addEventListener(`input`,()=>{Ra++,za?.abort(),La&&clearTimeout(La),La=setTimeout(()=>{La=null,Pa=m.catalogsFilter.value.trim(),Za(0)},250)});let no=async()=>{O(m.serversList);try{let e=await r(`/api/v1/servers`);if(!e.ok){m.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];Se=new Map(t.map(e=>[K(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),m.serversPanel.hidden=!1,m.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 i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.url,n.append(i,a);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=x({name:e.name,view:o,admin:o});ne(e.url).then(n=>{if(n!==null){a.textContent=`${e.url} · ${n}`;return}a.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=bo()===K(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`,()=>{xo(l?``:K(e.url)),no()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await r(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await no()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),m.serversList.append(t)}}catch{m.serversPanel.hidden=!0}},ro=async()=>{O(m.followingList);try{let e=await r(`/api/v1/follows`);if(!e.ok){m.followingNote.hidden=!0;return}let t=(await e.json()).following??[];m.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name||`a nixamp`;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.live?`live now`:`not streaming`,n.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,S(o,()=>_(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await r(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),m.followingList.children.length===0&&(m.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),m.followingList.append(t)}}catch{m.followingNote.hidden=!0}},io=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,S(n,()=>_(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let i=e=>{S(n,()=>e?`Following`:_(`Follow`)),n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await r(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&i((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await r(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(i(!t),ro())}catch{}finally{n.disabled=!1}})()}),n},ao=async()=>{let e=s();if(!e.supported)return m.notifyNote.textContent=e.message,!1;try{return await a({vapidKeyUrl:`/api/v1/notify/key`,serviceWorkerUrl:`/sw.js`,saveUrl:`/api/v1/notify/subscribe`}),m.notifyNote.textContent=`This device will be told.`,!0}catch(e){return m.notifyNote.textContent=e instanceof c&&e.reason!==`save-failed`?e.message:`Could not set this device up.`,!1}},oo=async()=>{try{await i({removeUrl:`/api/v1/notify/subscribe`})}catch{}},so=async e=>{try{let t=await r(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();m.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(m.notifyPhone.value=n.phone)}catch{m.notifyPhoneNote.textContent=`could not reach nixamp.com`}},co=async()=>{try{let e=await r(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();m.notifyEmail.checked=t.wantsEmail!==!1,m.notifySms.checked=t.wantsSms===!0,m.notifyPhone.value=t.phone??``;let n=s(),i=n.supported&&n.permission===`granted`?await o()!==null:!1;m.notifyWeb.checked=t.wantsWeb!==!1&&i,m.notifyNote.textContent=i?`Get told when someone you follow goes live.`:n.message??`Turn on “On this device” to be told here.`}catch{}};m.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(m.notifyWeb.checked){let e=await ao();m.notifyWeb.checked=e,await so({wantsWeb:e});return}await oo(),await so({wantsWeb:!1}),m.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),m.notifyEmail.addEventListener(`change`,()=>{so({wantsEmail:m.notifyEmail.checked})}),m.notifySms.addEventListener(`change`,()=>{(async()=>{if(m.notifySms.checked&&!m.notifyPhone.value.trim()){m.notifyPhoneNote.textContent=`Add a phone number first.`,m.notifySms.checked=!1;return}await so({wantsSms:m.notifySms.checked})})()}),m.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),so({phone:m.notifyPhone.value.trim()})});let lo=!1,uo=!1,fo=`nixamp.welcome`,po=()=>{let e=!1;try{e=localStorage.getItem(fo)===`hidden`}catch{}m.welcome.hidden=!uo||Y!==``||e},mo=!1,ho=()=>{if(mo||!uo||location.pathname.replace(/\/+$/,``)===``)return;mo=!0,m.adnet.dataset.adNetwork=`SSXBxU06ZRXMrzpJ`,m.adnet.dataset.slot=`514646f2-8299-40c1-9d9e-37d60d2d5892`,m.adnet.dataset.format=`text_link`,m.adnet.setAttribute(`data-cp-ad`,``),m.adnet.hidden=!1;let e=()=>window.crawlproofAds;if(!document.querySelector(`script[src="https://crawlproof.com/ad.js"]`)){let e=document.createElement(`script`);e.src=`https://crawlproof.com/ad.js`,e.async=!0,document.head.append(e)}let t=0,n=()=>{let r=e();if(r?.scan){r.scan();return}++t<=25&&setTimeout(n,200)};n()},go=t=>{document.dispatchEvent(new CustomEvent(`nixamp:account`,{detail:{email:t}}));let n=t!==null;Fi.refresh(),Si=``,Ti=null,n||(X=!1,m.transcriptAudio.checked=!1,Z.disable(),zi()),ua(),m.notifyPanel.hidden=!n,n?(co(),ro(),no()):(m.serversPanel.hidden=!0,m.followingNote.hidden=!0,O(m.followingList),m.recentNote.hidden=!0,m.recentList.replaceChildren()),m.accountForm.hidden=n,m.accountProviders.hidden=n||m.accountProviders.childElementCount===0,m.accountSignOut.hidden=!n,m.personaForm.hidden=!n,m.personaNote.hidden=!n,n&&oa(),m.accountProfile.hidden=n||!lo;let r=m.accountProfile.querySelector(`fieldset`);r&&(r.disabled=n||!lo),m.contactForm.hidden=!n,m.contactNote.hidden=!n,n&&aa(),m.accountNote.textContent=n?`Signed in as ${t}.`:lo?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,S(m.accountSubmit,()=>_(lo?`Create account`:`Sign in`)),S(m.accountToggle,()=>lo?`I have one`:_(`Create one`)),m.accountPassword.autocomplete=lo?`new-password`:`current-password`,m.accountForgot.hidden=lo,e&&(m.accountForgot.target=`_blank`,m.accountForgot.rel=`noopener`),po()},_o=async()=>{let e=[];uo=!1;try{let t=await r(`/api/v1/auth/providers`);t.ok&&(uo=!0,e=(await t.json()).providers??[])}catch{}m.accountProviders.replaceChildren(),m.accountProviders.hidden=e.length===0,m.accountPanel.hidden=!uo,m.accountElsewhere.hidden=uo,po(),ho();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start?redirect=${encodeURIComponent(location.pathname+location.search)}`,e.textContent=`Continue with ${t.name}`,m.accountProviders.append(e)}},vo=async()=>{try{let e=await r(`/api/v1/auth/me`),t=await e.json();Y=e.ok?t.account?.id??``:``,go(e.ok?t.account?.email??`you`:null)}catch{Y=``,go(null)}if(L.session=``,Y!==``){try{let e=await r(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));L.session=e.ok&&typeof t.token==`string`?t.token:``}catch{L.session=``}v===`remote`&&zr()}ii(),ei(),ti(),So();let e=await yo();if(St!==``){let t=St;St=``,e?b=`golive:${t}`:gr(t)}};async function yo(){if(Y===``||v===`remote`||xt!==``)return!1;let e=[];try{let t=await r(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=bo(),n=[...e].sort((e,n)=>Number(K(n.url)===t)-Number(K(e.url)===t));for(let e of n)if(await ne(e.url,void 0,e.key)!==null)return v!==`remote`&&(ve=!1,b=``,m.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,E=`Connecting to ${e.name}, your server…`,U(),m.remoteForm.requestSubmit(),!0);return!1}function bo(){try{return localStorage.getItem(Vn)??``}catch{return``}}function xo(e){try{e===``?localStorage.removeItem(Vn):localStorage.setItem(Vn,e)}catch{}}function So(){if(xt===``)return;let e=xt;xt=``,m.remoteUrl.value=e,m.remoteForm.requestSubmit()}m.accountToggle.addEventListener(`click`,()=>{lo=!lo,go(null)}),m.welcomeCreate.addEventListener(`click`,()=>{lo=!0,go(null),m.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),m.accountEmail.focus({preventScroll:!0})}),m.welcomeBrowse.addEventListener(`click`,()=>{m.directory.hidden?m.browse.click():m.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),m.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(fo,`hidden`)}catch{}m.welcome.hidden=!0}),m.accountForm.addEventListener(`submit`,n=>{n.preventDefault();let i=m.accountEmail.value.trim(),a=m.accountPassword.value;(async()=>{m.accountSubmit.disabled=!0;try{let n=await r(`/api/v1/auth/${lo?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:i,password:a,...lo?qn(m.accountForm):{}})}),o=await n.json();if(!n.ok){m.accountNote.textContent=o.error??`that did not work`;return}e&&(t=o.token??``),Y=o.account?.id??``,m.accountPassword.value=``,go(o.account?.email??i),zr(),So();let s=new URLSearchParams(location.search).get(`redirect`)??``;s.startsWith(`/`)&&!s.startsWith(`//`)&&!s.startsWith(`/\\`)&&location.assign(s)}catch{m.accountNote.textContent=`could not reach nixamp.com`}finally{m.accountSubmit.disabled=!1}})()}),m.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await r(`/api/v1/auth/logout`,{method:`POST`})}catch{}t=``,Y=``,go(null),ei(),L.close(),Ae=-1,v=`local`,De=`idle`,Oe=``,m.remoteUrl.value=``,m.sharePanel.hidden=!0,m.publishPanel.hidden=!0,m.adminPanel.hidden=!0,m.catalogsPanel.hidden=!0,m.listenOnly.hidden=!0,Yo(!1);try{localStorage.removeItem(Bn)}catch{}E=`Signed out, and disconnected from the server.`,zr(),U()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(xt=t,b=e.get(`play`)??``,xe=Math.max(0,Number(e.get(`t`)??`0`)||0),m.remoteUrl.value=t,E=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(m.linkUrl.value=n,t!==``&&b===``?b=`link:${n}`:t===``&&(St=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=d(r);t?(xt=t.view,b=t.what,xe=Math.max(0,Number(e.get(`t`)??`0`)||0),m.remoteUrl.value=t.view,E=`Opening the stream you were sent…`):(m.linkUrl.value=r,St=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Co=[`zone-top`,`zone-main`],wo=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,To=e=>e.parentElement&&Co.includes(e.parentElement.id)?e.parentElement:null,Eo=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Do=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>wo(e)&&To(e)!==null),Oo=e=>e.dataset.title??e.id,ko=new Map,Ao=Do().map((e,t)=>(ko.set(e.id,{zone:To(e)?.id??``,col:Eo(e),index:t}),e.id)),$=At();try{$=Nt(localStorage.getItem(kt))}catch{}let jo=()=>$.order.length>0||Object.keys($.placement).length>0;function Mo(){$.order=Do().map(e=>e.id);try{localStorage.setItem(kt,Pt($))}catch{}}function No(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 Po(){if(e)return;for(let e of Do()){let t=$.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Co.includes(i.id)&&No(e,i,r===`a`||r===`b`?r:``)}let t=Ft(Do().map(e=>e.id),$.order);for(let e of Co){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(wo),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 Do())e.toggleAttribute(`data-collapsed`,$.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,$.closed.includes(e.id))}function Fo(e,t){e.toggleAttribute(`data-collapsed`,t),e===m.panelsPanel&&m.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),$.collapsed=It($.collapsed,e.id,t),Mo(),Ho()}function Io(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),!t&&e.dataset.available===`true`&&(e.hidden=!1),e===m.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===m.panelsPanel&&m.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===m.partiesPanel&&!t&&ei(),t&&n&&m.panelsToggle.focus({preventScroll:!0}),$.closed=It($.closed,e.id,t),Mo(),Ho()}function Lo(e,t,n){let r=To(t);r&&e!==t&&(No(e,r,Eo(t)),n?t.after(e):t.before(e),$.placement[e.id]=`${r.id}:${Eo(t)}`,Mo(),Ho())}let Ro=null,zo=()=>{for(let e of Do())e.classList.remove(`drop-before`,`drop-after`)},Bo=(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 Vo(){for(let e of Do()){let t=Oo(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=Bo(`≡`,`Move ${Oo(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=Do().filter(t=>To(t)===To(e)&&Eo(t)===Eo(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(Lo(e,r,t.key===`ArrowDown`),a.focus({preventScroll:!0}))}),a.classList.add(`grip`),a.draggable=!0,a.addEventListener(`dragstart`,t=>{Ro=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),a.addEventListener(`dragend`,()=>{Ro=null,e.classList.remove(`dragging`),zo()});let o=Bo(`▁`,`Shade ${Oo(e)} to its title`,()=>Fo(e,!e.hasAttribute(`data-collapsed`)));o.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let s=Bo(`✕`,`Hide ${Oo(e)}; the Panels list turns it back on`,()=>Io(e,!0));e.id===`transcript-panel`&&i.append(Fi.button()),i.append(a,o,s),e.prepend(i),e.addEventListener(`dragover`,t=>{if(!Ro||Ro===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;zo(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Ro||Ro===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);zo(),Lo(Ro,e,n)})}}function Ho(){if(m.panelsPanel.hidden||m.panelsList.contains(document.activeElement))return;let e=Do().filter(e=>e!==m.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,C(i,`aria-label`,()=>`${Oo(e)} on`),i.addEventListener(`change`,()=>Io(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,S(a,()=>Oo(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});m.panelsList.replaceChildren(...e)}function Uo(){$=At();for(let e of Ao){let t=document.getElementById(e),n=ko.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(No(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}$.order=[...Ao],Po(),$=At();try{localStorage.removeItem(kt)}catch{}Ho()}function Wo(e){if(!e||jo())return;let t=To(m.adminPanel);if(!t)return;let n=[...t.children].filter(wo).find(e=>Eo(e)===Eo(m.adminPanel));n&&n!==m.adminPanel&&n.before(m.adminPanel),m.adminPanel.removeAttribute(`data-collapsed`),m.adminPanel.removeAttribute(`data-closed`)}m.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=m.panelsPanel.hidden||m.panelsPanel.hasAttribute(`data-closed`)||m.panelsPanel.hasAttribute(`data-collapsed`);m.panelsPanel.hidden=!t,m.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(m.panelsPanel.hasAttribute(`data-closed`)&&Io(m.panelsPanel,!1),m.panelsPanel.hasAttribute(`data-collapsed`)&&Fo(m.panelsPanel,!1),Ho(),m.panelsPanel.showPopover?.(),m.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):m.panelsPanel.hidePopover?.()}),m.panelsPanel.addEventListener(`toggle`,()=>{let e=m.panelsPanel.matches(`:popover-open`);m.panelsToggle.setAttribute(`aria-expanded`,String(e&&!m.panelsPanel.hasAttribute(`data-collapsed`))),e||(m.panelsPanel.hidden=!0)}),m.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof m.panelsPanel.hidePopover!=`function`&&(m.panelsPanel.hidden=!0,m.panelsToggle.setAttribute(`aria-expanded`,`false`),m.panelsToggle.focus({preventScroll:!0}))}),m.panelsReset.addEventListener(`click`,Uo),m.panelsSave.addEventListener(`click`,()=>{Mo();let e=m.panelsSave.textContent??`Save setup`;m.panelsSave.textContent=`Saved`,window.setTimeout(()=>{m.panelsSave.textContent=e},1200)}),new MutationObserver(()=>{Vo(),Ho()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Vo(),Po(),_o(),vo(),zr(),Cr(),m.browse.addEventListener(`click`,()=>{if(!m.directory.hidden){m.directory.hidden=!0;return}kr(),m.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),m.disconnect.addEventListener(`click`,()=>{L.close(),m.listenOnly.hidden=!0,Ae=-1,m.sharePanel.hidden=!0,m.publishPanel.hidden=!0,m.adminPanel.hidden=!0,m.catalogsPanel.hidden=!0,C(m.catalogsPanel,`data-title`,()=>_(`Catalogs on this server`)),y=``,Te=``,si(),Yo(!1),v=`local`,De=`idle`,Oe=``,U()});async function Go(){if(v!==`remote`||L.shareLink===``){m.sharePanel.hidden=!0;return}m.sharePanel.hidden=!1;let e=us(),t=globalThis.location.origin;m.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,m.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,m.sharePhone.hidden=!0,m.shareSend.hidden=!0,m.liveControls.hidden=!0;let n=``;try{let e=await r(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}gt=n,Tn();let i=null;try{let n=await r(L.url(`/api/live/state`));n.ok&&(i=await n.json()),i?.url&&(e=i.url,Te=i.url,m.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(i){if(dt=i.live,pt=i.live?i.code:``,gt=n,m.liveControls.hidden=m.adminPanel.hidden||!i.possible,m.goLive.hidden=i.live,m.stopLive.hidden=!i.live,m.sharePhone.hidden=!1,!i.live){m.sharePhone.textContent=i.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){m.sharePhone.textContent=`Listed. The code for the phone line is ${i.code}.`,m.shareSend.hidden=!1;return}m.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),gs(n),document.createTextNode(` and key `),gs(i.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),m.shareSend.hidden=!1}}let Ko=null,qo=null,Jo=0,Yo=e=>{Ko&&clearInterval(Ko),Ko=null,Jo+=1,qo?.abort(),qo=null,A=null,Xr(),e&&(Xo(),Ko=setInterval(()=>{document.visibilityState===`visible`&&Xo()},Zr))};async function Xo(){if(v!==`remote`||qo)return;let e=new AbortController;qo=e;let t=A===null;t&&$r(e,!0);let n=Jo,i=L.url(`/api/streams`),a=setTimeout(()=>e.abort(),8e3);try{let t=await r(i,{signal:e.signal,cache:`no-store`});if(!t.ok)return;let a=await t.json();if(e.signal.aborted||n!==Jo||v!==`remote`||i!==L.url(`/api/streams`))return;he=a.server.carries!==!1,a.server.name&&a.server.name!==y&&(y=a.server.name,m.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${y}`),si()),A=a,ds(a),U(),Zo(a)}catch{}finally{clearTimeout(a),t&&$r(e,!1),qo===e&&(qo=null)}}function Zo(e){Xr(),D&&sr()}function Qo(e){let t=vn(),n=e.restreams??[],r=[],i=e.server.playing,a=!m.adminPanel.hidden;i&&r.push(fs({key:`live`,title:He(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${He(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&&es(e.server.nowPlaying)},link:e.server.live?e.server.url:``,...i?{page:ls(`live`)}:{},direct:i?L.url(`/api/live`):``}));for(let e of n)r.push(fs({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:()=>{kn(e.at)},link:``,direct:L.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=L.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}×`),a&&t.error&&i.push(t.error),r.push(fs({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{ts({id:t.id,name:t.name,video:e,art:t.art,playlist:t.playlist})},link:n,page:ls(`channel:${t.id}`),direct:n,onRestart:(a||Mt&&Y!==``&&t.startedBy===Y)&&t.via===`pull`?()=>{is(t.id,t.name)}:void 0,onStop:a||Mt&&Y!==``&&t.startedBy===Y?()=>os(t.id,t.name):void 0,onRename:a||Mt&&Y!==``&&t.startedBy===Y?()=>{as(t.id,t.name)}:void 0}))}return r}async function $o(){if(v===`remote`)try{if((await r(L.media(z(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;E=Y===``?`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.`,Y===``&&m.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),U()}catch{}}async function es(e){Ae=-1,D=null,k={kind:`live`},at(e,`auto`),await Ke(()=>I.load({title:e||`Live`,artist:``,album:``,duration:0,url:L.url(`/api/live`),video:!0,objectUrl:!1},!0)),mr(!0),E=`Watching what this server is playing. Everyone here sees the same thing.`,U()}async function ts(e,t=!0,n){let r=A?.channels.find(t=>t.id===e.id);!e.playlist&&r?.playlist&&(e={...e,playlist:r.playlist}),Ae=-1,D=e,t&&(Le=0),t&&(k=n??{kind:`channel`}),t&&at(e.name,k?.link||xn(e.name)?`auto`:`channel`);let i=e.video&&F(),a=e.video&&((e.playlist?.length??0)>1||e.id.startsWith(`folder-`));await Ke(()=>I.load({title:e.name,artist:``,album:``,duration:0,url:L.url(i||a?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),mr(e.video),D===e&&(E=`Watching ${e.name}, live on this server.`),U()}function ns(){let e=D;return e?vt?!0:Le>=5?(E=`${e.name} stopped, and did not come back.`,D=null,k=null,U(),!0):(Le+=1,E=`${e.name} started over; rejoining…`,U(),vt=setTimeout(()=>{vt=null,D===e&&ts(e,!1)},2e3),!0):!1}function rs(e){m.partiesNote.hidden=!1,m.partiesNote.textContent=e,G(e)}async function is(e,t){rs(`Restarting ${t}…`);try{let n=await r(L.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),i=await n.json().catch(()=>({}));rs(n.ok?`${t} is dialling its source again.`:i.error??`that did not work`)}catch{rs(`could not reach the server`)}Xo()}async function as(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let i=n.trim();if(i!==``&&i!==t){rs(`Renaming ${t}…`);try{let n=await r(L.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:i})}),a=await n.json().catch(()=>({}));rs(n.ok?`${t} is now ${i}.`:a.error??`that did not work`)}catch{rs(`could not reach the server`)}D?.id===e&&(D={...D,name:i}),Xo(),U()}}async function os(e,t){rs(`Taking ${t} off the air…`);try{let n=await r(L.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),i=await n.json().catch(()=>({}));if(rs(n.ok?`${t} is off the air.`:i.error??`that did not work`),!n.ok)return!1}catch{return rs(`could not reach the server`),!1}return D?.id===e&&(D=null,I.stop()),!0}function ss(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 cs(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{E=e,U();return}n===`✓`||n===`✓`?h(t,`check`):S(t,()=>_(n)),setTimeout(()=>{t.innerHTML=r},1200)}function ls(e,t=0){let n=us();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 us(){if(Te!==``)return Te;let e=v===`remote`?L.shareLink:``;return/\/admin\//.test(e)?``:e}function ds(e){if(b===``)return;let t=b;if(t===`live`){b=``,e.server.playing?es(e.server.nowPlaying):(E=`Nothing is playing on this server right now.`,U());return}if(t.startsWith(`link:`)){b=``,gr(t.slice(5));return}if(t.startsWith(`golive:`)){b=``,m.linkUrl.value=t.slice(7),zr().then(()=>wr());return}if(t.startsWith(`track:`)){b=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&kn(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=``,ts({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function fs(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${_e(L.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 o=document.createElement(`button`);o.type=`button`,o.className=`button`,Vt(o,e.playLabel??`Join party`),o.hidden=e.key.startsWith(`channel:`)&&D?.id===e.key.slice(8),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,h(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;cs(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{cs(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,n=>{ss(t,n,e.onStop,()=>void Xo())})),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,C(o,`aria-label`,()=>`${_(e.playLabel??`Join party`)}: ${e.title}`);let c=document.createElement(`details`);c.className=`party-actions`;let l=document.createElement(`summary`);return l.textContent=`⋯`,C(l,`aria-label`,()=>`${_(`Show more`)}: ${e.title}`),a.removeChild(o),c.append(l,a),t.append(n,o),a.childElementCount&&t.append(c),t}let ps=``;function ms(e,t){ps=e;let n=e!==``&&t===e;m.loadHome.hidden=e===``,m.homeNote.hidden=e===``,e!==``&&(m.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,m.loadHome.disabled=!1)}m.loadHome.addEventListener(`click`,()=>{ps!==``&&(m.loadHome.disabled=!0,G(`Reading this server's files…`),(async()=>{try{let e=await r(L.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:ps})}),t=await e.json();G(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{G(`could not reach the server`)}finally{m.loadHome.disabled=!1}})())});let hs=async e=>{m.goLive.disabled=!0,m.stopLive.disabled=!0,m.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await r(L.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();m.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{m.shareNote.textContent=`could not reach the server`}finally{m.goLive.disabled=!1,m.stopLive.disabled=!1,await Go()}};m.goLive.addEventListener(`click`,()=>void hs(!0)),m.stopLive.addEventListener(`click`,()=>void hs(!1));function gs(e){let t=document.createElement(`b`);return t.textContent=e,t}m.shareCopy.addEventListener(`click`,()=>{m.shareLink.select(),navigator.clipboard?.writeText(m.shareLink.value).then(()=>{m.shareNote.textContent=`Copied. Send it to anybody.`},()=>{m.shareNote.textContent=`Copy it from the box above.`})}),m.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=m.shareTo.value.trim();t!==``&&(async()=>{m.shareNote.textContent=`Sending…`;try{let e=await r(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:us()})}),n=await e.json();m.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(m.shareTo.value=``)}catch{m.shareNote.textContent=`could not send that`}})()}),m.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(Un,m.listenHere.checked?`1`:`0`)}catch{}v===`remote`&&(async()=>{m.listenHere.checked?(await L.send({type:`stop`}),await Mn(T.index)):(I.stop(),Ae=-1),U()})()}),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===m.transport)switch(e.key){case` `:e.preventDefault(),Nn();return;case`s`:Fn();return;case`n`:case`ArrowRight`:Pn(1);return;case`p`:case`ArrowLeft`:Pn(-1);return;case`ArrowDown`:e.preventDefault(),kn(Math.min(R()-1,z()+1));return;case`ArrowUp`:e.preventDefault(),kn(Math.max(0,z()-1));return}});let _s=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),_s=e,m.install.hidden=!1}),m.install.addEventListener(`click`,()=>{_s?.prompt(),_s=null,m.install.hidden=!0});try{let e=localStorage.getItem(Hn);e!==null&&(m.volume.value=String(Math.round(Number(e)*100)),I.volume=Number(e));let t=localStorage.getItem(Bn);t&&(m.remoteUrl.value=t),localStorage.getItem(Un)===`0`&&(m.listenHere.checked=!1)}catch{}(async()=>{if(m.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await ne(e)===null)return;let t=await p(e);t&&t.trackCount!==0&&(m.remoteUrl.value=e,v=`remote`,E=``,L.connect(e),Yo(!0),Wa(),U())})(),ei();let vs=()=>{document.visibilityState===`visible`&&!m.partiesPanel.hasAttribute(`data-closed`)&&ei()},ys=setInterval(vs,Zr);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(ei(),Xo())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(ys),Ko&&clearInterval(Ko),Jr?.abort(),qo?.abort(),Jr=null,qo=null,Jo+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(ys),ys=setInterval(vs,Zr),vs(),v===`remote`&&Yo(!0))}),(()=>{if(Gn||xt!==``)return;let e=()=>I.source!==``||I.playing||Ue()||D!==null,t=async()=>{try{let e=await(await r(`/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``},i=new Audio;i.volume=.7;let a=()=>{Gn=!0},o=()=>{document.removeEventListener(`pointerdown`,o),document.removeEventListener(`keydown`,o),a(),setTimeout(()=>{e()||I.playJingle(i).catch(()=>{})},150)};t().then(async t=>{if(!(t===``||e()))return await n(i,{src:t,kind:`audio`}),I.playJingle(i).then(a,()=>{document.addEventListener(`pointerdown`,o,{once:!0}),document.addEventListener(`keydown`,o,{once:!0})})})})(),U(),requestAnimationFrame(dr)}Jn(),ke(),Ie(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{se as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as e}from"./chunk-Q2XQMA4B-OBCD3Aev.js";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule||!o.call(e,`default`)?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=[[/^(hvc1|hev1)/i,`H.265`],[/^av01/i,`AV1`],[/^(vp09|vp9)/i,`VP9`],[/^(ec-3|ec3)/i,`Dolby Digital Plus audio`],[/^(ac-3|ac3)/i,`Dolby Digital audio`],[/^dts/i,`DTS audio`],[/^(mp4a\.69|mp4a\.6b)/i,`MP2 audio`],[/^mp3$/i,`MP3 audio`],[/^mp4a\.40\./i,`AAC audio`]];function d(e){if(!e)return null;for(let[t,n]of u)if(t.test(e))return n;return e}function f(e,t){if(!t||!e)return[];if(e===`audio`){if(/^mp4a\.40\./i.test(t))return[`audio/mp4; codecs="mp4a.40.2"`];if(/^mp3$/i.test(t))return[`audio/mpeg`,`audio/mp4; codecs="mp3"`];if(/^opus$/i.test(t))return[`audio/mp4; codecs="opus"`,`audio/mp4; codecs="Opus"`]}return[`${e}/mp4; codecs="${t}"`]}function p(e,t,n=``,r=`stream`){if(!e||typeof t!=`function`)return null;let i=[[`video`,e.videoCodec],[`audio`,e.audioCodec]],a=[];for(let[e,n]of i)if(n&&!f(e,n).some(e=>{try{return t(e)}catch{return!1}})){let e=d(n);e&&a.push(e)}if(a.length===0)return null;let o=a.length===1?a[0]:`${String(a[0])} and ${String(a[1])}`;return`This ${r} is ${String(o)}, which this browser cannot decode.${n?` ${n}`:``}`}var m=2e3,h=5e3,g=3;function _(e,t={}){return{enableWorker:t.enableWorker??!1,enableStashBuffer:!0,stashInitialSize:393216,liveBufferLatencyChasing:!1,liveBufferLatencyMaxLatency:5,liveBufferLatencyMinRemain:1,autoCleanupSourceBuffer:!0,autoCleanupMaxBackwardDuration:30,autoCleanupMinBackwardDuration:10,lazyLoad:!1,lazyLoadMaxDuration:60,lazyLoadRecoverDuration:30,seekType:`range`}}async function v(t,n={}){let{media:r,src:i,isTv:a}=t,o=await e(()=>import(`./mpegts-BcF3gJrf.js`).then(e=>l(e.default,1)),[]),s=o.default??o;if(!s.getFeatureList().mseLivePlayback)return t.onError(`This browser cannot play transport streams.`),{destroy:()=>void 0,levels:()=>[]};let c=_(a,n),u=null,d=!1,f=0,v=null,y=null,b=-1,x=0,S=()=>{v&&clearTimeout(v),y&&clearInterval(y),v=null,y=null},C=()=>{if(!u)return;let e=u;u=null;try{e.destroy()}catch{}},w=e=>{d||(d=!0,S(),C(),t.onError(e))},T=e=>{if(!d){if(f>=5){w(e);return}f+=1,S(),C(),t.onNotice(`Reconnecting\u2026 (${String(f)}/5)`),v=setTimeout(()=>{v=null,d||D()},m*2**(f-1))}},E=()=>{y&&clearInterval(y),b=r.currentTime,x=0,y=setInterval(()=>{if(!d&&u){if(r.paused||r.ended||r.seeking){x=0,b=r.currentTime;return}if(r.currentTime===b){x+=1,x>=g&&(x=0,T(`The stream stopped sending.`));return}b=r.currentTime,x=0}},h)};function D(){u=s.createPlayer({type:`mpegts`,isLive:t.live,url:i,withCredentials:n.withCredentials??!1},t.headers&&Object.keys(t.headers).length>0?{...c,headers:{...t.headers}}:c),u.on(s.Events.MEDIA_INFO??`media_info`,(...e)=>{let t=e[0],r=p(t,e=>globalThis.MediaSource?.isTypeSupported?.(e)??!1,n.unplayableAdvice??``);r&&w(r)}),u.on(s.Events.ERROR??`error`,(...e)=>{let t=String(e[1]??``);T(`This stream could not be played (${t}).`)}),u.attachMediaElement(r),u.load(),E(),t.onReady?.({live:t.live,levels:[]})}let O=()=>{f=0,t.onNotice(null)};return r.addEventListener(`playing`,O),D(),{destroy(){d=!0,S(),r.removeEventListener(`playing`,O),C()},levels:()=>[]}}export{v as createMpegtsEngine,s as t};
|