nixamp 0.28.1 → 0.28.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/directory.d.ts +2 -0
- package/dist/directory.js +3 -0
- package/dist/owner.js +4 -0
- package/dist/server.js +85 -8
- package/dist/translation-passes.d.ts +2 -7
- package/dist/translation-passes.js +2 -3
- package/dist/upgrade-allowance.d.ts +1 -1
- package/dist/upgrade-allowance.js +6 -3
- package/package.json +1 -1
- package/src/directory.ts +5 -0
- package/src/owner.ts +2 -0
- package/src/server.ts +76 -8
- package/src/translation-passes.ts +2 -3
- package/src/upgrade-allowance.ts +6 -3
- package/web/dist/assets/{hls-3VKVEQE3-DQXeuMAN.js → hls-3VKVEQE3-B4Sk5BbY.js} +1 -1
- package/web/dist/assets/index-B33hHbmF.js +3 -0
- package/web/dist/assets/{mpegts-BRcpX4rU.js → mpegts-CoCC1wqt.js} +1 -1
- package/web/dist/assets/{mpegts-LO6RVLD6-tqmB8BfI.js → mpegts-LO6RVLD6-Ct0Biz5E.js} +1 -1
- package/web/dist/index.html +14 -4
- package/web/dist/sw.js +5 -5
- package/web/dist/assets/index-HDrZHpqb.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./index-
|
|
1
|
+
import{t as e}from"./index-B33hHbmF.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-CoCC1wqt.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},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};
|
package/web/dist/index.html
CHANGED
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
<meta property="og:title" content="nixamp: broadcast live radio, TV and film from your own machine" />
|
|
18
18
|
<meta property="og:description" content="Launch your own live radio, TV and film network from your machine. Listen free, go live in one command, get paid with x402." />
|
|
19
19
|
<meta property="og:type" content="website" />
|
|
20
|
-
<script type="module" crossorigin src="/assets/index-
|
|
20
|
+
<script type="module" crossorigin src="/assets/index-B33hHbmF.js"></script>
|
|
21
21
|
<link rel="stylesheet" crossorigin href="/assets/index-BKyAT0fX.css">
|
|
22
22
|
</head>
|
|
23
23
|
<body>
|
|
@@ -96,7 +96,7 @@
|
|
|
96
96
|
session, which the site will serve when it refuses a server's. -->
|
|
97
97
|
<div id="embed" class="embed" hidden>
|
|
98
98
|
<iframe id="embed-frame" title="The link, played" allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
|
|
99
|
-
|
|
99
|
+
referrerpolicy="strict-origin-when-cross-origin"></iframe>
|
|
100
100
|
</div>
|
|
101
101
|
<audio id="audio"></audio>
|
|
102
102
|
<div id="title-line" class="track-title" data-i18n="Nothing loaded.">Nothing loaded.</div>
|
|
@@ -120,6 +120,9 @@
|
|
|
120
120
|
<button id="copy-now" type="button" class="icon" hidden
|
|
121
121
|
title="Copy this stream's URL, to play it in VLC or another player"
|
|
122
122
|
aria-label="Copy this stream's URL" data-i18n-aria-label="Copy this stream's URL">⧉</button>
|
|
123
|
+
<button id="copy-nixamp" type="button" class="icon" hidden
|
|
124
|
+
title="Copy a nixamp link to this live room"
|
|
125
|
+
aria-label="Copy live room link" data-i18n-aria-label="Copy live room link">↗</button>
|
|
123
126
|
<button id="fullscreen" type="button" class="ghost" hidden
|
|
124
127
|
title="Full screen" data-i18n-title="Full screen" aria-label="Full screen" data-i18n-aria-label="Full screen">⛶</button>
|
|
125
128
|
<button id="download-now" type="button" class="ghost" hidden
|
|
@@ -132,7 +135,7 @@
|
|
|
132
135
|
<p class="hint" id="translation-balance"></p>
|
|
133
136
|
<details id="transcript-voice-settings" hidden>
|
|
134
137
|
<summary data-i18n="Audio options">Audio options</summary>
|
|
135
|
-
<label class="transcript-switch"><input type="checkbox" id="transcript-background" checked /><span data-i18n="Keep background
|
|
138
|
+
<label class="transcript-switch"><input type="checkbox" id="transcript-background" checked /><span data-i18n="Keep source background audio"> Keep source background audio</span></label>
|
|
136
139
|
<label class="background-level"><span data-i18n="Background level">Background level </span><input id="transcript-background-level" type="range" min="0" max="200" step="5" value="100" aria-valuetext="100 percent" /> <output id="transcript-background-value" for="transcript-background-level">100%</output></label>
|
|
137
140
|
<p class="hint">Speech removal is approximate; turn this off if original voices bleed through.</p>
|
|
138
141
|
<div id="transcript-speakers" role="group" aria-label="Speaker voices" data-i18n-aria-label="Speaker voices"></div>
|
|
@@ -445,6 +448,7 @@
|
|
|
445
448
|
<p class="hint">Every panel, on or off. Move a panel by dragging its ≡ handle, or focus that handle and press Alt + Up or Down. ▁ shades it to its title bar; ✕ hides it.</p>
|
|
446
449
|
<ul id="panels-list" class="directory-list panels-list"></ul>
|
|
447
450
|
<div class="picker">
|
|
451
|
+
<button id="panels-save" type="button" class="button" title="Save this panel setup on this device" data-i18n="Save setup">Save setup</button>
|
|
448
452
|
<button id="panels-reset" type="button" class="ghost" title="Every panel back where the page puts it" data-i18n="Reset layout">Reset layout</button>
|
|
449
453
|
</div>
|
|
450
454
|
</section>
|
|
@@ -457,6 +461,12 @@
|
|
|
457
461
|
nixamp.com knew about servers at all. -->
|
|
458
462
|
<section class="panel player-only col-a" data-title="Server" data-i18n-data-title="Server" id="remote-panel">
|
|
459
463
|
<p class="hint" data-i18n="Pick a server in the directory, or paste its link here.">Pick a server in the directory, or paste its link here.</p>
|
|
464
|
+
<label class="picker" for="remote-server">
|
|
465
|
+
<span data-i18n="Choose a server">Choose a server</span>
|
|
466
|
+
<select id="remote-server" aria-label="Choose a server" data-i18n-aria-label="Choose a server">
|
|
467
|
+
<option value="">Select a server…</option>
|
|
468
|
+
</select>
|
|
469
|
+
</label>
|
|
460
470
|
<form id="remote-form" class="picker">
|
|
461
471
|
<input id="remote-url" type="text" inputmode="url" placeholder="a server's link, https://…:4321/view/…" aria-label="A server's link" data-i18n-aria-label="A server's link" />
|
|
462
472
|
<button type="submit" class="button" data-i18n="Connect">Connect</button>
|
|
@@ -506,7 +516,7 @@
|
|
|
506
516
|
<a href="#account-panel" id="translation-sign-in">Sign in for free sessions or to purchase</a>
|
|
507
517
|
<div class="purchase-actions"><button type="button" class="button" id="translation-checkout" disabled data-i18n="Buy pass">Buy pass</button><a id="translation-checkout-link" target="_blank" rel="noopener noreferrer" hidden data-i18n="Open secure checkout ↗ (new tab)">Open secure checkout ↗ (new tab)</a><button type="button" id="translation-check-payment" hidden data-i18n="Check payment">Check payment</button></div>
|
|
508
518
|
<details class="purchase-terms"><summary data-i18n="Usage rates and expiry">Usage rates and expiry</summary>
|
|
509
|
-
<p class="hint">After the
|
|
519
|
+
<p class="hint">After the ten free sessions, new sessions draw from purchased credit at 5× the base speech API rates: $0.25 per 1,000 voice characters plus $1.10 per submitted audio hour. Live recognition includes repeated context, usually three submitted hours per listening hour. Shared live audio has the same paid access price for every listener.</p>
|
|
510
520
|
<p class="hint">Unused credit expires. Buying before expiry adds credit and keeps the later expiry date. Your pass works across players on this account.</p>
|
|
511
521
|
</details>
|
|
512
522
|
<p id="translation-purchase-note" role="status" aria-live="polite" aria-atomic="true"></p>
|
package/web/dist/sw.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/* nixamp service worker — generated, do not edit */
|
|
2
|
-
const CACHE = "nixamp-
|
|
2
|
+
const CACHE = "nixamp-1789437659330";
|
|
3
3
|
const PRECACHE = [
|
|
4
4
|
"/",
|
|
5
5
|
"/.well-known/openaccess.json",
|
|
@@ -13,15 +13,15 @@ const PRECACHE = [
|
|
|
13
13
|
"/assets/fi-3Awdi4xT.js",
|
|
14
14
|
"/assets/fr-ChJB95FS.js",
|
|
15
15
|
"/assets/hi-OutMojZO.js",
|
|
16
|
-
"/assets/hls-3VKVEQE3-
|
|
16
|
+
"/assets/hls-3VKVEQE3-B4Sk5BbY.js",
|
|
17
17
|
"/assets/hls-n74Cnh8A.js",
|
|
18
18
|
"/assets/hu-fhESdEDW.js",
|
|
19
19
|
"/assets/id-DEiYuHM3.js",
|
|
20
|
+
"/assets/index-B33hHbmF.js",
|
|
20
21
|
"/assets/index-BKyAT0fX.css",
|
|
21
|
-
"/assets/index-HDrZHpqb.js",
|
|
22
22
|
"/assets/it-BWr9AXgr.js",
|
|
23
|
-
"/assets/mpegts-
|
|
24
|
-
"/assets/mpegts-LO6RVLD6-
|
|
23
|
+
"/assets/mpegts-CoCC1wqt.js",
|
|
24
|
+
"/assets/mpegts-LO6RVLD6-Ct0Biz5E.js",
|
|
25
25
|
"/assets/native-C7JTKWJH-BUyIoj0P.js",
|
|
26
26
|
"/assets/nl-CRyTjXF_.js",
|
|
27
27
|
"/assets/ru-B9x7d0z_.js",
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={"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`},t={"■ 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`},n=[{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`}],r=`nixamp.ui.language`;function i(e){let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return n.find(e=>e.code===t)?.code??`en`}function a(e,t=[]){let r=e=>{let t=typeof e==`string`?e.trim().toLowerCase().split(/[-_.@]/)[0]:``;return n.find(e=>e.code===t)?.code};return r(e)??t.map(r).find(Boolean)??`en`}var o=`modulepreload`,s=function(e){return`/`+e},c={},l=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=l(t.map(t=>{if(t=s(t,n),t=u(t),t in c)return;c[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:o,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},u={en:async()=>({default:e}),de:()=>l(()=>import(`./de-vZHKX4Ec.js`),[]),sv:()=>l(()=>import(`./sv-Bj-BJsv_.js`),[]),es:()=>l(()=>import(`./es-DXYBTMqx.js`),[]),fr:()=>l(()=>import(`./fr-ChJB95FS.js`),[]),it:()=>l(()=>import(`./it-BWr9AXgr.js`),[]),nl:()=>l(()=>import(`./nl-CRyTjXF_.js`),[]),da:()=>l(()=>import(`./da-tGj_pE2V.js`),[]),fi:()=>l(()=>import(`./fi-3Awdi4xT.js`),[]),ru:()=>l(()=>import(`./ru-B9x7d0z_.js`),[]),uk:()=>l(()=>import(`./uk-C1-8NwOQ.js`),[]),cs:()=>l(()=>import(`./cs-_3DVOugI.js`),[]),hu:()=>l(()=>import(`./hu-fhESdEDW.js`),[]),zh:()=>l(()=>import(`./zh-DHLUyAFs.js`),[]),ar:()=>l(()=>import(`./ar-D-Ld5vpy.js`),[]),hi:()=>l(()=>import(`./hi-OutMojZO.js`),[]),vi:()=>l(()=>import(`./vi-z6CDEBrS.js`),[]),id:()=>l(()=>import(`./id-DEiYuHM3.js`),[])},d=new class{load;code=`en`;get language(){return this.code}constructor(e=async e=>(await u[e]()).default){this.load=e}messages=e;revision=0;numberFormats=new Map;dateFormats=new Map;listeners=new Set;async setLanguage(e){let t=++this.revision,n=i(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,n={}){let r=this.language!==`en`&&Object.hasOwn(t,e)?t[e]:e,i=Object.hasOwn(this.messages,r)?this.messages[r]:e;return this.language!==`en`&&Object.hasOwn(t,e)&&(i=(e.match(/^[▶■●⤓]\s+/)?.[0]??``)+i+(e.endsWith(` ✓`)?` ✓`:``)),i.replace(/\{([\w]+)\}/g,(e,t)=>Object.hasOwn(n,t)?String(n[t]):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`}},f=(e,t)=>d.text(e,t),p=new Map;function m(e,t,n){let r=p.get(e);r||(r=new Map,p.set(e,r)),r.set(t,n),n()}function h(e,t){e instanceof Element&&e.removeAttribute(`data-i18n`);let n=``,r;return m(e,`text`,()=>{if(r!==void 0&&e.textContent!==r){p.get(e)?.delete(`text`);return}n=t()??``,r=n,e.textContent!==n&&(e.textContent=n)}),n}function g(e,t,n){e.removeAttribute(`data-i18n-${t}`);let r=``,i;return m(e,t,()=>{if(i!==void 0&&e.getAttribute(t)!==i){p.get(e)?.delete(t);return}r=n()??``,i=r,e.getAttribute(t)!==r&&e.setAttribute(t,r)}),r}var ee=[`aria-label`,`title`,`placeholder`,`data-title`],te=[`[data-i18n]`,...ee.map(e=>`[data-i18n-${e}]`)].join(`,`);function ne(e){let t=[...e.querySelectorAll(te)];e instanceof HTMLElement&&e.matches(te)&&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;m(e,`text`,()=>{if(e.textContent!==n){p.get(e)?.delete(`text`),e.removeAttribute(`data-i18n`);return}n=f(t),e.textContent!==n&&(e.textContent=n)})}for(let t of ee){let n=e.getAttribute(`data-i18n-${t}`);if(n){let r=e.getAttribute(t);m(e,t,()=>{if(e.getAttribute(t)!==r){p.get(e)?.delete(t),e.removeAttribute(`data-i18n-${t}`);return}r=f(n),e.getAttribute(t)!==r&&e.setAttribute(t,r)})}}}}function re(){document.documentElement.lang=d.language,document.documentElement.dir=d.direction;for(let[e,t]of p){if(!e.isConnected){p.delete(e);continue}for(let e of t.values())e()}for(let e of document.querySelectorAll(`[data-ui-language]`))e.value=d.language}var _=0;async function ie(e){let t=++_;try{if(!await d.setLanguage(e)||t!==_)return;try{localStorage.setItem(r,d.language)}catch{}window.nixampLanguage?.set(d.language).catch(()=>{})}catch{re()}}async function ae(){let e=a(null,navigator.languages);try{e=a(await window.nixampLanguage?.get()??localStorage.getItem(`nixamp.ui.language`),navigator.languages)}catch{}for(let e of document.querySelectorAll(`[data-ui-language]`))e.replaceChildren(...n.map(e=>{let t=new Option(e.label,e.code);return t.lang=e.code,t.dir=`auto`,t})),e.addEventListener(`change`,()=>{ie(e.value)});ne(document),re(),d.onChange(re),new MutationObserver(e=>{for(let t of e)for(let e of t.addedNodes)e instanceof Element&&ne(e);for(let e of p.keys())e.isConnected||p.delete(e)}).observe(document.body,{childList:!0,subtree:!0}),window.addEventListener(`storage`,e=>{e.key===`nixamp.ui.language`&&d.setLanguage(a(e.newValue,navigator.languages)).catch(()=>{})}),window.nixampLanguage?.subscribe(e=>{e!==d.language&&d.setLanguage(e).catch(()=>{})});try{await d.setLanguage(e)}catch{}}function oe(e){if(!Number.isFinite(e)||e<0)return`--:--`;let t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function se(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function ce(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var le=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function ue(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&le.has(e.slice(n+1).toLowerCase())}function v(){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 de=new WeakMap;function fe(e,t=!0){let n=e.contains(document.activeElement);de.delete(e),t&&e.replaceChildren(),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function y(e,...t){if(document.activeElement===e||!e.contains(document.activeElement)){de.delete(e),e.replaceChildren(...t);return}let n=de.has(e);if(de.set(e,t),n)return;let r=()=>{let t=de.get(e);if(t){if(document.activeElement!==e&&e.contains(document.activeElement)){e.addEventListener(`focusout`,i,{once:!0});return}de.delete(e),e.replaceChildren(...t)}},i=()=>{setTimeout(r,0)};e.addEventListener(`focusout`,i,{once:!0})}var b=new WeakMap,x=new WeakSet;function pe(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?b.set(e,t):b.delete(e),x.has(e))return;x.add(e);let a=()=>{let t=b.get(e);t&&pe(e,t)};e.addEventListener(`focusout`,()=>{setTimeout(a,0)}),e.addEventListener(`toggle`,a,!0)}function me(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 he(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 ge(e,t,n=`Live`){let r=e[t];if(!r){let e=me(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${me(r.title)}`:me(r.title),a=he(r.folder??``),o=he(r.group??``).join(` › `),s=[...o?[o]:[],...a],c=s.filter((e,t)=>t===0||e!==s[t-1]).join(` › `)||r.album,l=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(s.length>0||e.album===r.album));return{title:i,context:c,position:`Playlist · ${l.findIndex(({at:e})=>e===t)+1} of ${l.length}`,fullTitle:c?`${c} › ${i}`:i}}var S=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],_e=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function C(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of _e)if(t.test(e.mimeType))return n}let t=w(e.src);for(let[e,n]of S)if(e.test(t))return n;return`unknown`}function w(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ve(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function ye(e,t){let n=C(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function be(e,t){let n=t.capabilities??ve(),r=ye({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await l(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-DQXeuMAN.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await l(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-tqmB8BfI.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await l(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var xe=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]),Se=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function Ce(e){let t=e.lastIndexOf(`.`);return t>0&&Se.has(e.slice(t+1).toLowerCase())}function T(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&xe.has(e.slice(n+1).toLowerCase())}function E(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function we(e){return e.filter(e=>T(e.name,e.type)).sort((e,t)=>E(Te(e),Te(t))).map(e=>({title:ce(e.name),artist:``,album:Ee(Te(e)),duration:0,url:URL.createObjectURL(e),video:ue(e.name,e.type),objectUrl:!0,...Ce(e.name)?{kind:`mpegts`}:{}}))}function Te(e){return e.webkitRelativePath||e.name}function Ee(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function De(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var Oe=2048;function D(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 O(e,t){return e||t===`hls`||t===`mpegts`}var ke=class{elements;handlers;playBlocked=!1;attached=null;source=``;context=null;analyser=null;output=null;translated=!1;wired=new WeakSet;active;jingle=null;frequencies=new Uint8Array;analysable=!0;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video]){t.addEventListener(`timeupdate`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`loadedmetadata`,()=>{t===this.active&&this.handlers.onTime(t.currentTime,Number.isFinite(t.duration)?t.duration:0)}),t.addEventListener(`ended`,()=>{t===this.active&&this.handlers.onEnded()}),t.addEventListener(`play`,()=>{t===this.active&&this.handlers.onState(!0)}),t.addEventListener(`pause`,()=>{t===this.active&&this.handlers.onState(!1)}),t.addEventListener(`error`,()=>{t===this.active&&this.handlers.onError(Ae(t))});let e=e=>()=>{t===this.active&&this.handlers.onBusy?.(e)};for(let n of[`loadstart`,`waiting`,`stalled`,`seeking`])t.addEventListener(n,e(!0));for(let n of[`playing`,`canplay`,`pause`,`ended`,`error`,`emptied`,`seeked`,`abort`])t.addEventListener(n,e(!1))}}get playing(){return!this.active.paused&&!this.active.ended}get jinglePlaying(){return!!this.jingle&&!this.jingle.paused&&!this.jingle.ended}async playJingle(e){this.jingle!==e&&this.stopJingle(),this.jingle=e,this.ensureGraph(e);try{if(await e.play(),this.context?.state===`suspended`)throw new DOMException(`Audio needs an interaction`,`NotAllowedError`)}catch(t){throw e.pause(),e.currentTime=0,t}}stopJingle(){this.jingle?.pause(),this.jingle=null}get needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(!this.context)try{this.context=new t({sampleRate:48e3})}catch{this.context=new t}if(this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=Oe,this.analyser.smoothingTimeConstant=.6,this.output=this.context.createGain(),this.output.gain.value=+!this.translated,this.analyser.connect(this.output),this.output.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}audioInput(){if(!this.analysable)throw Error(`This source blocks audio access, so its audio cannot be translated here.`);if(this.ensureGraph(this.active),!this.context||!this.analyser)throw Error(`This browser cannot capture player audio.`);return{context:this.context,node:this.analyser}}translatedAudio(e){this.translated=e,this.output&&(this.output.gain.value=+!e)}get mediaKey(){return this.active.currentSrc||this.active.src}get loaded(){return!!(this.active.currentSrc||this.active.src)}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.stopJingle(),this.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:C({src:e.url})),r=O(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||D(e.url)||(this.handlers.readable?.(e.url)??!1);r.crossOrigin=i?`anonymous`:null,r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await be(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}let a=this.active.currentSrc||this.active.src||e.url;this.analysable=i||a.startsWith(`blob:`)||D(a),t&&await this.play()}async play(){this.stopJingle(),this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.stopJingle(),this.playBlocked=!1,this.active.pause()}async resumeAfterInteraction(){this.playBlocked?await this.play():this.playing&&this.context?.state===`suspended`&&await this.context.resume()}stop(){this.stopJingle(),this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function Ae(e){switch(e.error?.code){case MediaError.MEDIA_ERR_ABORTED:return`playback was aborted`;case MediaError.MEDIA_ERR_NETWORK:return`the network dropped mid-track`;case MediaError.MEDIA_ERR_DECODE:return`this browser could not decode that`;case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:return`this browser cannot play that format`;default:return`playback failed`}}function je(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function Me(e,t){return{...t,tracks:t.tracks??e.tracks}}function Ne(e){let t=e.trim();if(t===``)return``;/^https?:\/\//i.test(t)||(t=`http://${t}`);let n;try{n=new URL(t)}catch{return``}let r=n.pathname.replace(/\/+$/,``);return r=r.replace(/\/api(\/.*)?$/,``),`${n.origin}${r}`}function Pe(e,t,n=``){let r=`${e===``?``:Ne(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function Fe(e){let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`http:`&&t.protocol!==`https:`)return null;let n=/^\/api\/channels\/([^/]+)\/?$/.exec(t.pathname),r=/^\/api\/media\/(\d+)\/?$/.exec(t.pathname),i=/^\/api\/live\/?$/.test(t.pathname);if(!n&&!r&&!i)return null;let a=t.searchParams.get(`k`)??``,o=a?`${t.origin}/view/${a}`:t.origin,s=`live`;if(r&&(s=`track:${r[1]}`),n)try{s=`channel:${decodeURIComponent(n[1]??``)}`}catch{s=`channel:${n[1]??``}`}return{view:o,what:s}}function Ie(e){let t=e.trim();if(t===``)return{base:``,key:``};let n;try{n=new URL(/^https?:\/\//i.test(t)?t:`http://${t}`)}catch{return{base:``,key:``}}let r=/^\/(?:admin|view|a|v)\/([^/]+)\/?$/.exec(n.pathname),i=r?.[1]??n.searchParams.get(`k`)??``;return r&&(n.pathname=`/`),n.searchParams.delete(`k`),{base:Ne(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var k=null;function Le(e){if(!e&&k!==null)return k;let t=e??(typeof document>`u`?null:document.createElement(`video`));if(!t)return!1;try{let n=t.canPlayType(`video/mp4; codecs="hvc1.1.6.L93.B0"`)!==``;return e||(k=n),n}catch{return!1}}function Re(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return Pe(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function ze(e){if(typeof e!=`object`||!e)return null;let t=e,n=je(),r=(e,t)=>typeof e==`number`&&Number.isFinite(e)?e:t,i=Array.isArray(t.levels)?t.levels:[],a=Array.isArray(t.tracks)?t.tracks.map(e=>{let t=typeof e==`object`&&e?e:{};return{title:typeof t.title==`string`?t.title:`Untitled`,artist:typeof t.artist==`string`?t.artist:``,album:typeof t.album==`string`?t.album:``,duration:r(t.duration,0),...t.video===!0?{video:!0}:{},...typeof t.group==`string`&&t.group!==``?{group:t.group}:{},...typeof t.folder==`string`&&t.folder!==``?{folder:t.folder}:{},...t.remote===!0?{remote:!0}:{}}}):void 0;return{revision:r(t.revision,0),...a?{tracks:a}:{},trackCount:r(t.trackCount,a?.length??0),index:r(t.index,0),playing:t.playing===!0,position:r(t.position,0),bars:Array.isArray(t.bars)?t.bars.map(e=>r(e,0)):[],levels:[r(i[0],0),r(i[1],0)],silent:t.silent===!0,note:typeof t.note==`string`?t.note:``,root:typeof t.root==`string`?t.root:n.root}}function Be(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var Ve=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return Be(this.base,e)}url(e){let t=Pe(this.base,e,this.key);return this.base===``||this.session===``?t:`${t}${t.includes(`?`)?`&`:`?`}session=${encodeURIComponent(this.session)}`}get shareLink(){return this.base===``?``:this.key===``?this.base:`${this.base}${this.shape}${this.key}`}get connected(){return this.source!==null}connect(e){let{base:t,key:n}=Ie(e);this.close(),this.base=t,this.key=n,this.shape=/\/(?:view|v)\/[^/]+\/?$/.test(e.trim())?`/view/`:`/admin/`,this.lastRevision=-1,this.handlers.onStatus(`connecting`);let r=new EventSource(Pe(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=ze(He(e.data));t&&(t.revision<this.lastRevision||(this.lastRevision=t.revision,this.handlers.onStatus(`live`),this.handlers.onSnapshot(t)))},r.onerror=()=>{this.handlers.onStatus(`error`,`reconnecting…`)}}async send(e){if(this.base===``&&!this.connected)return;let t=await fetch(Pe(this.base,`/api/command`,this.key),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e)});if(!t.ok){this.handlers.onStatus(`error`,`command refused (${t.status})`);return}let n=ze(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=Le()){return Re(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function He(e){try{return JSON.parse(e)}catch{return null}}async function Ue(e,t,n=``){try{let r=await fetch(Pe(e,`/api/state`,n),{signal:t});return r.ok?ze(await r.json()):null}catch{return null}}function We(e){if(!/^https:\/\//i.test(e))return``;let t;try{t=new URL(e).hostname.replace(/^\[|\]$/g,``)}catch{return``}return/^\d{1,3}(\.\d{1,3}){3}$/.test(t)||t.includes(`:`)?`That is an https address for a bare IP, and a certificate is issued for a name — a browser refuses it before it asks anything. Use the server's name instead (the address it printed first), or connect over http.`:``}async function Ge(e,t=``,n){let r;try{r=await fetch(Pe(e,`/api/state`,t),{signal:n})}catch{return``}return r.ok?``:r.status===401?t===``?`That server needs its share link. Paste the whole link — the one with /admin/ or /view/ in it — or sign in as its owner.`:`That share link is not accepted by that server. It may have been restarted, which gives it a new one.`:r.status===403?`That link can listen but not drive this server.`:r.status===429?`That server is asking us to slow down. Try again in a moment.`:``}async function Ke(e,t,n=``){try{let r=await fetch(Pe(e,`/api/health`,n),{signal:t});if(!r.ok)return null;let i=await r.json();return i.name===`nixamp`?i.version??`unknown`:null}catch{return null}}function qe(e,t=globalThis.location?.protocol){return t!==`https:`||!/^http:\/\//i.test(e.trim())?``:`This page is https, and a browser refuses every request from an https page to an http one. Open that address directly, or give the server a certificate: nixamp serve --tls-cert cert.pem --tls-key key.pem.`}var Je=.14,Ye=.02;function Xe(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 Ze(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 Qe(e,t,n=Je){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function $e(e,t,n=Ye){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function et(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 tt(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 nt(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function rt(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??d.language,i)===r.toLocaleDateString(t.locale??d.language,i);return n.toLocaleString(t.locale??d.language,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function it(e,t={}){let n=e.data,r=tt(n.away,n.awayScore),i=tt(n.home,n.homeScore),a=nt(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=rt(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 at=`nixamp.tv`,ot=/\bAFT\w*\b.*\bSilk\b|\bSilk\b.*\bAFT\w*\b|Android ?TV|Google ?TV|SMART-?TV|Tizen|Web0S|WebOS|BRAVIA|CrKey|Roku|Xbox|PlayStation|HbbTV|NetCast|VIDAA|Viera|AppleTV/i;function st(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?A(r):/\bSilk\b/.test(e)&&n===0?!0:ot.test(e):A(i)}function A(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function ct(e){return e?12:100}function lt(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 ut=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,dt=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,j=/\.m3u8(\?.*)?$/i,ft=/\.(m3u|pls)(\?.*)?$/i;function pt(e){try{let t=new URL(e);return dt.test(t.pathname+t.search)}catch{return!1}}function mt(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 ht(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||mt(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(!ut.test(a)&&!dt.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 gt(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 _t(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=gt(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 ft.test(o)?{kind:`list`,url:n.toString(),label:mt(n.toString())}:ut.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:dt.test(o)||j.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var vt=`nixamp.panels`;function yt(){return{order:[],placement:{},collapsed:[],closed:[]}}var bt=/^[a-z][a-z0-9-]{0,63}$/,xt=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function St(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&bt.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Ct(e){if(!e)return yt();let t;try{t=JSON.parse(e)}catch{return yt()}if(!t||typeof t!=`object`||Array.isArray(t))return yt();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))bt.test(e)&&typeof t==`string`&&xt.test(t)&&(r[e]=t);let i=e=>{let t=St(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 wt(e){return JSON.stringify(e)}function Tt(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 Et(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}function Dt(e,t=16e3){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}var Ot=16e3,kt=3e4;function At(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function jt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var Mt=`nixamp.captions`,Nt=`nixamp.captions.native-v2.language`,Pt=[{code:``,label:`Original (auto-detect)`},...n];function Ft(e){try{let t=(e(`nixamp.captions.native-v2.language`)??``).trim().toLowerCase();return Pt.some(e=>e.code===t)?t:``}catch{return``}}function It(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function Lt(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function Rt(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 zt(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 Bt(e){try{return e(Mt)!==`off`}catch{return!0}}function Vt(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString(d.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}function Ht(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 M(e,t){return Object.assign(Error(e),{status:t})}var N=12e3,Ut=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>N}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 M((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 M(`The voice audio was interrupted.`,502);this.failures=0}catch(t){if(e!==this.generation)return;if(!Ht(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`)}},Wt=`data:text/javascript;base64,Ly8gVGhlIHJlbmRlciB0aHJlYWQgY29waWVzIHNtYWxsIG1vbm8gYmxvY2tzLiBBbGwgbmV0d29ya2luZyBzdGF5cyBvZmYgaXQuCmNsYXNzIE5peGFtcEF1ZGlvVGFwIGV4dGVuZHMgQXVkaW9Xb3JrbGV0UHJvY2Vzc29yIHsKICBjb25zdHJ1Y3RvcigpIHsgc3VwZXIoKTsgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOyB9CiAgcHJvY2VzcyhpbnB1dHMpIHsKICAgIGNvbnN0IGNoYW5uZWxzID0gaW5wdXRzWzBdOwogICAgaWYgKCFjaGFubmVscz8ubGVuZ3RoKSByZXR1cm4gdHJ1ZTsKICAgIGZvciAobGV0IGkgPSAwOyBpIDwgY2hhbm5lbHNbMF0ubGVuZ3RoOyBpKyspIHsKICAgICAgbGV0IHZhbHVlID0gMDsKICAgICAgZm9yIChjb25zdCBjaGFubmVsIG9mIGNoYW5uZWxzKSB2YWx1ZSArPSBjaGFubmVsW2ldIHx8IDA7CiAgICAgIHRoaXMuYmxvY2tbdGhpcy5hdCsrXSA9IHZhbHVlIC8gY2hhbm5lbHMubGVuZ3RoOwogICAgICBpZiAodGhpcy5hdCA9PT0gdGhpcy5ibG9jay5sZW5ndGgpIHsKICAgICAgICB0aGlzLnBvcnQucG9zdE1lc3NhZ2UodGhpcy5ibG9jaywgW3RoaXMuYmxvY2suYnVmZmVyXSk7CiAgICAgICAgdGhpcy5ibG9jayA9IG5ldyBGbG9hdDMyQXJyYXkoMjA0OCk7IHRoaXMuYXQgPSAwOwogICAgICB9CiAgICB9CiAgICByZXR1cm4gdHJ1ZTsKICB9Cn0KcmVnaXN0ZXJQcm9jZXNzb3IoIm5peGFtcC1hdWRpby10YXAiLCBOaXhhbXBBdWRpb1RhcCk7Cg==`,P=new WeakMap,Gt=class{take;tap=null;generation=0;constructor(e){this.take=e}async start(e,t,n=5){this.stop();let r=this.generation;if(!e.audioWorklet)throw Error(`Live translation needs a browser with AudioWorklet support on HTTPS.`);if(P.has(e)||P.set(e,e.audioWorklet.addModule(Wt).catch(t=>{throw P.delete(e),t})),await P.get(e),r!==this.generation)return;let i=new AudioWorkletNode(e,`nixamp-audio-tap`);this.tap=i;let a=e.createGain();a.gain.value=0,t.connect(i),i.connect(a),a.connect(e.destination);let o=new Float32Array(e.sampleRate*n),s=0,c=new Float32Array,l=Date.now();i.port.onmessage=t=>{if(r!==this.generation)return;let i=0,a=t.data;for(;i<a.length;){let t=Math.min(o.length-s,a.length-i);if(o.set(a.subarray(i,i+t),s),s+=t,i+=t,s!==o.length)continue;let r=new Float32Array(16e3*n),u=e.sampleRate/16e3;for(let e=0;e<r.length;e++){let t=Math.floor(e*u),n=Math.max(t+1,Math.floor((e+1)*u)),i=0;for(let e=t;e<n;e++)i+=o[e]??0;r[e]=i/(n-t)}l+=n*1e3,Math.abs(Date.now()-l)>1500&&(l=Date.now(),c=new Float32Array);let d=new Float32Array(c.length+r.length);d.set(c),d.set(r,c.length),this.take({samples:d,at:l-d.length/16,until:l,freshAt:l-n*1e3}),c=d.slice(-32e3*n),s=0}},this.disconnect=()=>{i.port.onmessage=null,i.port.close(),t.disconnect(i),i.disconnect(),a.disconnect()},await e.resume()}disconnect=null;stop(){this.generation++,this.disconnect?.(),this.disconnect=null,this.tap=null}},F=3,Kt=class e{failed;generation=0;worker=null;node=null;gain=null;input=null;pendingPort=null;cancelStart=null;on=!1;level=1;static loaded=new WeakMap;constructor(e){this.failed=e}async start(t,n){this.stop();let r=this.generation;try{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*F: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*F: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*F: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()}this.gain?.disconnect(),this.worker?.terminate(),this.worker=null,this.node=null,this.gain=null,this.input=null}},qt=class{options;controller=null;clips=new Map;constructor(e){this.options=e}async start(e,t){this.stop();let n=new AbortController;this.controller=n;let r=async()=>{let r=new AbortController,i=setTimeout(()=>r.abort(),12e3),a=await(this.options.fetcher??fetch)(`/api/v1/speech/shared`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,language:t}),signal:AbortSignal.any([n.signal,r.signal])}).finally(()=>clearTimeout(i));if(!a.ok||!a.body)throw M((await a.json().catch(()=>({}))).error||`Live translation is unavailable.`,a.status);return a.body},i=await r();if(this.controller!==n){await i.cancel();return}this.consume(i,n,r)}clearClips(){for(let e of this.clips.values())if(!e.ended)try{e.controller.error(new DOMException(`Playback stopped`,`AbortError`))}catch{}this.clips.clear()}stop(){this.controller?.abort(),this.controller=null,this.clearClips()}audio(e){let t=this.clips.get(e);if(!t||t.taken)throw M(`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(!Ht(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(M(`Live audio connection timed out.`,503)),a()},25e3)})]).finally(()=>clearTimeout(e));if(t.signal.aborted)return;if(o)throw M(`Live translation disconnected.`,503);i+=r.decode(s,{stream:!0});let c;for(;(c=i.indexOf(`
|
|
2
|
-
|
|
3
|
-
`))>=0;){let e=i.slice(0,c);i=i.slice(c+2),e.startsWith(`data: `)&&this.event(JSON.parse(e.slice(6)))}if(i.length>128e3)throw Error(`Invalid live audio response.`)}}finally{t.signal.removeEventListener(`abort`,a),await n.cancel().catch(()=>{}),n.releaseLock()}}event(e){if(e.type===`error`)throw M(e.error,e.retryable?503:400);if(e.type===`status`){this.options.status(`Live translated audio · ${e.listeners} ${e.listeners===1?`listener`:`listeners`}`);return}let t=`nixamp-shared:${e.id}`;if(e.type===`line`){for(let[e,t]of this.clips)t.ended&&(t.taken||Date.now()-t.until>12e3)&&this.clips.delete(e);for(;this.clips.size>=24;){let e=this.clips.entries().next().value;e[1].ended||e[1].controller.error(M(`Catching up with live audio…`,503)),this.clips.delete(e[0])}let n,r=new ReadableStream({start:e=>{n=e},cancel:()=>{let e=this.clips.get(t);e&&(e.ended=!0),this.clips.delete(t)}});this.clips.set(t,{stream:r,controller:n,bytes:0,ended:!1,taken:!1,until:e.line.until}),this.options.line(e.line,t);return}let n=this.clips.get(t);if(!n||n.ended)return;if(e.type===`end`){n.ended=!0,n.controller.close();return}let r=Uint8Array.from(atob(e.data),e=>e.charCodeAt(0));if(n.bytes+=r.length,n.bytes>2097152)throw Error(`The live audio segment was too large.`);n.controller.enqueue(r)}},I=e=>new Intl.NumberFormat(d.language,{style:`currency`,currency:`USD`,maximumFractionDigits:2}).format(e/1e6),L=e=>document.getElementById(e),Jt=class{options;access=null;account=``;opener=null;order=``;requestKey=``;selected=``;timer=null;loading=!1;problem=``;checking=!1;dialog=L(`translation-purchase`);plan=L(`translation-plan`);coin=L(`translation-coin`);buy=L(`translation-checkout`);note=L(`translation-purchase-note`);checkoutLink=L(`translation-checkout-link`);constructor(e){this.options=e,L(`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})}),L(`translation-sign-in`).addEventListener(`click`,()=>this.dialog.close()),this.plan.addEventListener(`change`,()=>this.describe()),this.buy.addEventListener(`click`,()=>void this.purchase()),L(`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=`$`,g(e,`title`,()=>f(`Buy translated audio`)),g(e,`aria-label`,()=>f(`Buy translated audio`)),e.setAttribute(`aria-haspopup`,`dialog`),e.setAttribute(`aria-controls`,`translation-purchase`),e.dataset.translationBuy=``,e.addEventListener(`click`,()=>this.open(e)),e}open(e){this.opener=e,this.dialog.open||this.dialog.showModal(),this.status(``),this.refresh().then(()=>{this.order&&this.dialog.open&&this.check()})}async refresh(){let e=this.options.account();this.problem=``,this.account!==e&&(this.account=e,this.access=null,this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0);try{let t=await fetch(`/api/v1/translation-passes`,{signal:AbortSignal.timeout(15e3)}),n=await t.json();if(this.account!==e||this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Purchases are unavailable.`);this.access=n;let r=this.access.coins??[];[...this.coin.options].map(e=>e.value).join()!==r.join()&&document.activeElement!==this.coin&&this.coin.replaceChildren(...r.map(e=>new Option(e.replaceAll(`_`,` · `),e)));let i=this.access.plans??[];this.plan.options.length||this.plan.replaceChildren(...i.map(e=>{let t=new Option(``,e.id);return h(t,()=>`${e.name} · ${I(e.priceCents*1e4)}`),t})),this.describe();let a=this.access,o=()=>a.required?`${f(`Audio credit`)}: ${I(a.balanceMicros)}${a.expires?` · ${new Date(a.expires).toLocaleString(d.language)}`:``}`:``,s=this.access.free,c=()=>a.required&&s?d.language===`en`?`${s.remaining} of ${s.limit} free sessions left today${s.activeUntil?` · free session active`:``}`:`${f(`Free sessions`)}: ${d.number(s.remaining)}/${d.number(s.limit)}${s.activeUntil?` · ✓`:``}`:``;h(L(`translation-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),h(L(`translation-purchase-balance`),()=>[c(),o()].filter(Boolean).join(` · `)),h(L(`translation-free-description`),()=>s?`Each account gets ${s.limit} free sessions a day, shared across paid panels and upgrades. Each lasts while you listen, within daily usage limits. Reconnect within ${s.reconnectSeconds} seconds to keep the same session. Resets at ${new Date(s.resets).toLocaleString(d.language)} (midnight UTC). Free time is used before purchased credit.`:``),L(`translation-sign-in`).hidden=!!e,this.buy.disabled=!e||!this.access.available||this.loading,!this.access.available&&this.dialog.open&&this.status(this.access.required?`Checkout is temporarily unavailable. Free sessions and existing credit still work.`:`This server sponsors translated audio; no purchase is required.`);let l=new URLSearchParams(location.search).get(`translation_order`),u=this.access.orders?.find(e=>e.id===l||e.id===this.order)??this.access.orders?.[0];u&&!this.order&&(this.order=u.id,this.link(u.url)),l&&!this.order&&/^[a-f0-9-]{36}$/i.test(l)&&e&&(this.order=l,this.check()),this.options.changed(),this.order&&!this.dialog.open&&!this.checking&&this.check()}catch(e){this.problem=e instanceof Error?e.message:`Audio credit could not be checked. Use Buy to retry.`,this.dialog.open&&this.status(this.problem),this.options.changed()}}describe(){let e=this.access?.plans.find(e=>e.id===this.plan.value);if(!e)return;let t=Math.floor(e.priceCents/100/((.66/60+.05)*5));L(`translation-plan-description`).textContent=`${I(e.priceCents*1e4)} credit. Expires ${e.days===1?`24 hours`:`${e.days} days`} after payment. About ${t} minutes at 1,000 spoken characters/minute; usage varies. No automatic renewal.`}link(e){if(!/^https:\/\/coinpayportal\.com\/pay\/[a-f0-9-]{36}$/i.test(e))throw Error(`Invalid checkout address.`);this.checkoutLink.href=e,this.checkoutLink.hidden=!1,L(`translation-check-payment`).hidden=!1}async purchase(){if(this.loading||!this.account)return;let e=this.account,t=`${this.plan.value}|${this.coin.value}`;(!this.requestKey||this.selected!==t)&&(this.requestKey=crypto.randomUUID(),this.selected=t),this.loading=!0,this.buy.disabled=!0,this.status(`Preparing secure checkout…`);try{let t=await fetch(`/api/v1/translation-passes/checkout`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({plan:this.plan.value,coin:this.coin.value,requestKey:this.requestKey}),signal:AbortSignal.timeout(2e4)}),n=await t.json();if(this.options.account()!==e)return;if(!t.ok)throw Error(n.error||`Checkout could not be opened.`);this.order=n.id,this.link(n.url),this.status(`Open secure checkout to pay. Your video keeps playing in this tab. Credit appears after payment confirmation.`),this.poll()}catch(e){this.status(e instanceof Error?e.message:`Checkout could not be opened.`)}finally{this.loading=!1,this.buy.disabled=!this.account||!this.access?.available}}poll(){this.timer&&clearTimeout(this.timer),this.dialog.open&&this.order&&(this.timer=setTimeout(()=>void this.check(),5e3))}async check(){if(!this.order||!this.account||this.checking)return;this.checking=!0;let e=this.order,t=this.account;try{let n=await fetch(`/api/v1/translation-passes/orders/${encodeURIComponent(e)}`,{signal:AbortSignal.timeout(2e4)}),r=await n.json();if(this.account!==t||this.order!==e)return;if(!n.ok)throw Error(r.error||`Payment status could not be checked.`);if(r.status===`paid`){this.order=``,this.requestKey=``,this.checkoutLink.hidden=!0,L(`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}}},Yt=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}},Xt=class{options;tracker=new Yt;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 M(i.error||`Audio translation is unavailable.`,r.status);return i}async run(e){this.running=e;try{for(;this.pending&&e===this.generation;){let t=this.pending;this.pending=null;try{if(Date.now()-t.until>12e3)continue;let n=new AbortController;this.controller=n;let r=AbortSignal.any([n.signal,AbortSignal.timeout(12e3)]),i=this.options.speakers(),a=this.options.language(),o=await this.json(i?`/api/v1/speech/speakers`:`/api/v1/speech/transcribe?live=1`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Uint8Array(Dt(i?t.samples:t.samples.slice(-8e4)))},r);if(e!==this.generation)return;this.recognitionFailures=0;let s=o.language,c=[];if(i){let e=this.tracker.reconcile(o.turns??[],t.at,this.options.voices()),n=this.committedUntil??t.freshAt,r=o.turns??[];for(let[i,a]of r.entries()){let o=e.get(a.speaker),l=a.words.filter(e=>t.at+(e.start+e.end)*500>=n&&(t.at+e.end*1e3<=t.until-100||/[.!?。!?]$/.test(e.text))),u=[],d=()=>{u.length&&(c.push({channel:this.options.channel(),at:t.at+u[0].start*1e3,until:t.at+u.at(-1).end*1e3,text:u.map(e=>e.text).join(` `).trim(),language:s,speaker:o.id,voiceProfile:a.profile}),u=[])};for(let e of l)u.length&&e.start-u.at(-1).end>=.45&&d(),u.push(e),(/[.!?。!?]$/.test(e.text)||u.map(e=>e.text).join(` `).length>=400)&&d();u.length&&(i<r.length-1||t.until-(t.at+u.at(-1).end*1e3)>=350||t.until-(t.at+u[0].start*1e3)>=3e3)&&d()}}else o.text&&(c=[{channel:this.options.channel(),at:t.freshAt,until:t.until,text:o.text,language:s}]);if(!c.length)continue;this.committedUntil=Math.max(this.committedUntil??t.freshAt,...c.map(e=>e.until)),this.translations=this.translations.filter(e=>Date.now()-e.until<=12e3).slice(-11),this.translations.push({lines:c,language:s,target:a,until:t.until}),this.translating===null&&this.translate(this.generation)}catch(t){if(e!==this.generation)return;if(!Ht(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 M(`The audio language could not be detected. Waiting for clearer speech.`,502);let e=await this.json(`/api/v1/translate?live=1`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({texts:n.map(e=>e.text),from:r,to:i})},AbortSignal.any([o.signal,AbortSignal.timeout(12e3)]));if(e.texts.length!==n.length||e.texts.some(e=>!e.trim()))throw M(`Translation omitted a phrase. Waiting for the next phrase.`,502);n=n.map((t,n)=>({...t,original:t.text,sourceLanguage:r,language:i,text:e.texts[n]}))}if(e!==this.generation)return;if(Date.now()-a>12e3)continue;this.translationFailures=0,this.options.lines(n.flatMap(e=>Zt(e))),this.options.status(i?`${r} → ${i} · live translation`:`Original audio language: ${r||`detecting…`}`)}catch(t){if(e!==this.generation)return;if(!Ht(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 Zt(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 Qt=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,$t=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,en=/\s+(?:vs\.?|v\.?|at|@)\s+/i,tn=/^(?: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 nn(e){let t=e.replace($t,``).replace($t,``).trim().split(en);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!tn.test(t)})}function rn(e){let t=String(e??``).trim();return t===``?!1:nn(t.replace(Qt,``))||nn(t)}var an=`nixamp.remote`,on=`nixamp.defaultServer`,sn=`nixamp.volume`,cn=`nixamp.listenHere`,ln=1e4,un=!1;function R(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function dn(){let e=new URLSearchParams(location.search).get(`embed`)===`1`;document.body.classList.toggle(`classroom-embed`,e);let t=null;try{t=localStorage.getItem(at)}catch{}let n=st(navigator.userAgent,location.search,navigator.maxTouchPoints,t);if(document.body.classList.toggle(`tv`,n),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(at,n?`1`:`0`)}catch{}let r=document.getElementById(`tv-toggle`);r&&(h(r,()=>n?`TV mode: on`:f(`TV mode`)),r.title=n?`Back to the ordinary layout: lists with their own scrollbars, smaller type.`:`For a television: bigger type, lists a page at a time, and nothing to scroll but the page.`,r.addEventListener(`click`,()=>{try{localStorage.setItem(at,n?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let i=ct(n),a={status:R(`status`),source:R(`source`),install:R(`install`),video:R(`video`),audio:R(`audio`),title:R(`title-line`),album:R(`album-line`),meta:R(`meta-line`),metaBlurb:R(`meta-blurb`),liveLine:R(`live-line`),downloadNow:R(`download-now`),wayInHere:R(`way-in-here`),embed:R(`embed`),embedFrame:R(`embed-frame`),linkForm:R(`link-form`),linkUrl:R(`link-url`),linkServer:R(`link-server`),linkGoLive:R(`link-go-live`),goLiveNow:R(`go-live-now`),elapsed:R(`elapsed`),total:R(`total`),seek:R(`seek`),fullscreen:R(`fullscreen`),copyNow:R(`copy-now`),canvas:R(`spectrum`),glyphs:R(`glyphs`),levels:R(`levels`),playlist:R(`playlist`),playlistPager:R(`playlist-pager`),crumbs:R(`crumbs`),filter:R(`filter`),playlistTitle:R(`playlist-panel`),note:R(`note`),linkNote:R(`link-note`),logList:R(`log-list`),files:R(`files`),folder:R(`folder`),remoteUrl:R(`remote-url`),remoteForm:R(`remote-form`),remoteState:R(`remote-state`),disconnect:R(`disconnect`),browse:R(`browse`),panelsToggle:R(`panels-toggle`),panelsPanel:R(`panels-panel`),panelsList:R(`panels-list`),panelsReset:R(`panels-reset`),accountForm:R(`account-form`),accountEmail:R(`account-email`),accountPassword:R(`account-password`),accountSubmit:R(`account-submit`),accountToggle:R(`account-toggle`),accountProviders:R(`account-providers`),accountPanel:R(`account-panel`),accountElsewhere:R(`account-elsewhere`),welcome:R(`welcome`),welcomeCreate:R(`welcome-create`),welcomeBrowse:R(`welcome-browse`),welcomeHide:R(`welcome-hide`),accountSignOut:R(`account-signout`),accountNote:R(`account-note`),personaForm:R(`persona-form`),personaHandle:R(`persona-handle`),personaVoice:R(`persona-voice`),personaProfile:R(`persona-profile`),personaNote:R(`persona-note`),adminPanel:R(`admin-panel`),adminNote:R(`admin-note`),adminSaid:R(`admin-said`),adminConnections:R(`admin-connections`),publishPanel:R(`publish-panel`),publishNote:R(`publish-note`),publishList:R(`publish-list`),adminRestream:R(`admin-restream`),adminReplace:R(`admin-replace`),adminSource:R(`admin-source`),adminName:R(`admin-name`),adminAdd:R(`admin-add`),homeNote:R(`home-note`),loadHome:R(`load-home`),directory:R(`directory`),recentNote:R(`recent-note`),recentList:R(`recent-list`),followingNote:R(`following-note`),followingList:R(`following-list`),serversPanel:R(`servers-panel`),serversNote:R(`servers-note`),serversList:R(`servers-list`),favoritesPanel:R(`favorites-panel`),favoritesNote:R(`favorites-note`),favoritesList:R(`favorites-list`),favHere:R(`fav-here`),partiesPanel:R(`parties-panel`),partiesNote:R(`parties-note`),partiesList:R(`parties-list`),partyForm:R(`party-form`),partyCode:R(`party-code`),partyJoin:R(`party-join`),connectionsNote:R(`connections-note`),connectionsList:R(`connections-list`),catalogsPanel:R(`catalogs-panel`),catalogsNote:R(`catalogs-note`),catalogsForm:R(`catalogs-form`),catalogSource:R(`catalog-source`),catalogName:R(`catalog-name`),catalogsList:R(`catalogs-list`),catalogsCrumbs:R(`catalogs-crumbs`),catalogsFilter:R(`catalogs-filter`),catalogsEntries:R(`catalogs-entries`),notifyPanel:R(`notify-panel`),notifyNote:R(`notify-note`),notifyWeb:R(`notify-web`),notifyEmail:R(`notify-email`),notifySms:R(`notify-sms`),notifyPhone:R(`notify-phone`),notifyPhoneForm:R(`notify-phone-form`),notifyPhoneNote:R(`notify-phone-note`),directoryNote:R(`directory-note`),directoryList:R(`directory-list`),sharePanel:R(`share-panel`),trollboxPanel:R(`trollbox-panel`),trollboxNote:R(`trollbox-note`),trollboxList:R(`trollbox-list`),trollboxForm:R(`trollbox-form`),trollboxInput:R(`trollbox-input`),trollboxMic:R(`trollbox-mic`),trollboxEdit:R(`trollbox-edit`),trollboxEditLabel:R(`trollbox-edit-label`),transcriptPanel:R(`transcript-panel`),transcriptNote:R(`transcript-note`),transcriptOn:R(`transcript-on`),transcriptLanguage:R(`transcript-language`),transcriptAudio:R(`transcript-audio`),transcriptVoiceSettings:R(`transcript-voice-settings`),transcriptBackground:R(`transcript-background`),transcriptBackgroundLevel:R(`transcript-background-level`),transcriptBackgroundValue:R(`transcript-background-value`),transcriptAudioNote:R(`transcript-audio-note`),transcriptSpeakers:R(`transcript-speakers`),transcriptList:R(`transcript-list`),subtitle:R(`subtitle`),shareNote:R(`share-note`),shareLink:R(`share-link`),shareCopy:R(`share-copy`),sharePhone:R(`share-phone`),shareSend:R(`share-send`),liveControls:R(`live-controls`),goLive:R(`go-live`),stopLive:R(`stop-live`),shareTo:R(`share-to`),listenOnly:R(`listen-only`),listenHere:R(`listen-here`),volume:R(`volume`),prev:R(`prev`),playPause:R(`play-pause`),transport:R(`transport`),stop:R(`stop`),next:R(`next`),shareNow:R(`share-now`)},o={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>`},s=(e,t)=>{e.innerHTML=o[t]},c=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,l=`local`,u=``,p=[],m=``,ee=!0,te=``;function ne(e){try{return new URL(e).origin}catch{return e}}let re=!1,_=``,ie=0,ae=new Map,ce=e=>ae.get(H(e))??null;function le(e,t){let n=n=>{re=n,_=``,a.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),a.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,s(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`,s(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:G?`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 ue=``,v=[],de=0,b=je(),x=`idle`,he=``,S=`Pick files, or connect to a nixamp running somewhere else.`,_e=!1,C=-1,w=null;function ve(e){return e?/^https?:\/\//i.test(e)?e:P.url(e):``}let ye=0,be=0,xe=!1,Se=()=>!N.needsInteraction&&(be>0||xe);async function Ce(e){be+=1,z();try{return await e()}finally{--be,z()}}let T=null,E=null,Te=``,Ee=null,Oe=``,D=null,O=null,Ae=0;function Ne(){a.embed.hidden||(a.embedFrame.src=`about:blank`),a.embed.hidden=!0}let k=null,Le=``,Re=null;function ze(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Le=i,Re&&clearTimeout(Re),Re=null,!r){if(k?.key===i)return;k=null}if(l!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(P.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Le!==i)return;k={key:i,match:r.match??null},z();let a=k.match;a?.kind===`fixture`&&nt(a)!==`post`&&(Re=setTimeout(()=>{Re=null,!(Le!==i||N.source===``&&!w)&&ze(e,t,n,!0)},6e4))}).catch(()=>void 0)}let Be=!1,He=``,Je=``,Ye=null,tt=``,rt=``,ot=``,A=Array(24).fill(0),ut=Array(24).fill(0),dt=[],j=()=>l===`remote`&&!a.listenHere.checked,ft=()=>l===`remote`&&!a.adminPanel.hidden,mt=!1,gt=()=>ft()||l===`remote`&&mt;function bt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:a.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function xt(){if(l!==`remote`||D)return null;if(T?.catalog&&T.entry)return{kind:`entry`,catalog:T.catalog,entry:T.entry};if(w)return{kind:`channel`,id:w.id,name:w.name};let e=b.tracks[I()];return e&&(N.source!==``||j())?{kind:`track`,index:I(),name:se(e)}:null}async function St(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;S=`Putting ${n} on the air…`,z();try{let r=``,i=``,a=!0;{let t=e.kind===`track`?`/api/tracks/${e.index}/live`:e.kind===`entry`?`/api/catalogs/${encodeURIComponent(e.catalog.id)}/entries/${encodeURIComponent(e.entry.id)}/live`:`/api/channels/${encodeURIComponent(e.id)}/keep`,o=await fetch(P.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){S=s.error??`${n} would not go on the air.`,z();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(ft()&&(Be?await fetch(P.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await ho(!0)),await Ga(),$(),i!==``&&w?.id!==i){let t=e.kind===`entry`?{kind:`channel`,catalog:e.catalog,entry:{id:e.entry.id,title:e.entry.title,group:e.entry.group??``,live:e.entry.live??!0,...e.entry.logo?{logo:e.entry.logo}:{}}}:void 0;await to({id:i,name:n,video:a},!0,t)}let o=co(r),s=He?` Call ${Je||`the line`} and key ${He} to talk about it.`:``;o===``?S=`${n} is on the air and you are watching it.${s}`:(await so(o,t,`✓`),S=`${n} is on the air and you are watching it. Link copied.${s}`),z()}catch{S=`could not reach the server`,z()}finally{t.disabled=!1}}function Ht(e,t=`Join party`){s(e,t===`Join party`?`party`:`live`);let n=document.createTextNode(``);h(n,()=>` ${f(t)}`),e.append(n),g(e,`title`,()=>f(t===`Join party`?`Join live`:t))}Ht(a.partyJoin);function M(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,s(n,`live`),n.title=`Go live with ${t}: on the air for everyone, listed, link copied`,n.setAttribute(`aria-label`,`Go live with ${t}`),n.addEventListener(`click`,t=>{t.stopPropagation(),St(e(),n)}),n}let N=new ke({audio:a.audio,video:a.video},{readable:e=>P.owns(e),onTime:(e,t)=>{let n=v[de];l===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),z()},onEnded:()=>{no()||Vn()||l===`remote`&&C<0&&!j()||hn(1)},onState:()=>z(),onBusy:e=>{xe!==e&&(xe=e,z())},onError:e=>{if(!no()&&!(Ae!==0&&Date.now()-Ae<2e3)){if(O&&e===`this browser cannot play that format`){let e=O.url;if(O=null,Ae=Date.now(),gt()){S=`That site will not let a page play it directly; going live with it on ${u||`the server`} instead.`,z(),a.linkUrl.value=e,Gn();return}S=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,z();return}S=e,z(),Qa()}}}),Wt=()=>j()&&!N.jinglePlaying,P=new Ve({onSnapshot:e=>{let t=e.tracks!==void 0||b.index!==e.index;if(b=Me(b,e),_.startsWith(`track:`)&&b.tracks.length>0){let e=Number(_.slice(6));if(_=``,Number.isInteger(e)&&e>=0&&e<b.tracks.length){let t=ie;pn(e).then(()=>{t>0&&(N.seek(t),setTimeout(()=>N.seek(t),600))})}}Wt()&&(A=e.bars.length>0?e.bars:A,ut=$e(ut,A)),z(),t&&E&&Xa(E)},onStatus:(e,t)=>{x=e,he=t??``,z()}}),F=()=>l===`remote`?b.tracks.length:v.length,I=()=>l===`remote`?j()||C<0?b.index:Math.min(C,Math.max(0,b.tracks.length-1)):de,L=()=>{let e=E?.server.nowPlaying||`Live`;return(!Ee||Ee.tracks!==b.tracks||Ee.index!==b.index||Ee.fallback!==e)&&(Ee={tracks:b.tracks,index:b.index,fallback:e,value:ge(b.tracks,b.index,e)}),Ee.value},Yt=()=>l===`remote`&&!w&&T?.kind===`live`,Zt=()=>Yt()?L().fullTitle:Qt(),Qt=()=>{if(w)return w.name;if(D)return D.label;if(Yt())return L().title;let e=l===`remote`?b.tracks[I()]:v[I()];return e?se(e):f(`Nothing loaded.`)},$t=()=>{if(w)return`live on this server`;if(D)return`playing here, in this browser`;if(Yt()){let{context:e,position:t}=L();return[e,t,`live on ${u||`this server`}`].filter(Boolean).join(` · `)}return(l===`remote`?b.tracks[I()]:v[I()])?.album||`—`};function en(){if(l!==`remote`||w===null&&T?.kind!==`live`){a.liveLine.hidden=!0,a.liveLine.replaceChildren(),delete a.liveLine.dataset.drawn;return}let e=u||`this server`,t=w?w.name:L().fullTitle,n=[w?`Live on ${e}: `:`Live from ${e}, now playing: `,go(t)],r=w?E?.channels.find(e=>e.id===w?.id)?.code??``:Be?He:``;r&&n.push(`. To talk about it, call `,go(Je||`the line`),` and key `,go(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);a.liveLine.dataset.drawn!==i&&(a.liveLine.dataset.drawn=i,a.liveLine.hidden=!1,a.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let tn=()=>j()?b.tracks[I()]?.duration??0:N.duration,nn=()=>j()?b.position:N.position,dn=()=>j()?b.playing:N.playing;async function fn(e){if(l===`remote`){if(j()){await P.send({type:`play`,index:e});return}await pn(e);return}let t=v[e];t&&(de=e,w=null,T={kind:`file`},await Ce(()=>N.load(t,!0)),In(t.video),Ln(),z())}async function pn(e){let t=b.tracks[e];t&&(C=e,w=null,T={kind:`file`},ze(t.title,`auto`),await Ce(()=>N.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:P.media(e,0),video:t.video===!0,objectUrl:!1},!0)),In(t.video===!0),Ln())}async function mn(){if(N.needsInteraction){await N.play(),z();return}if(j()){await P.send({type:`toggle`});return}F()!==0&&(N.playing?N.pause():N.position>0?await N.play():await fn(I()),z())}async function hn(e){let t=F();if(t!==0){if(j()){await P.send({type:e>0?`next`:`prev`});return}await fn((I()+e+t)%t)}}async function gn(){if(Ne(),D=null,O=null,j()){await P.send({type:`stop`});return}w=null,T=null,N.stop(),A=Array(24).fill(0),ut=[...A],z()}let _n=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,vn=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],yn=``;function bn(){let e=[],t=``,n=null,r=w?E?.channels.find(e=>e.id===w?.id):void 0;w&&r?.ended&&Oe!==w.id&&(Oe=w.id,Tr(`${w.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let i=N.source===``&&!w&&!(j()&&b.tracks[I()]);if(!i){w&&r?.ended?e.push(`ENDED`):w?e.push(T?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):T?.kind===`vod`?e.push(`ON DEMAND`):T?.kind===`live`?e.push(`LIVE`):l===`remote`&&j()?e.push(`ON THE SERVER`):e.push(`FILE`),!a.video.hidden&&a.video.videoWidth>0?e.push(`${a.video.videoWidth}×${a.video.videoHeight}`):a.video.hidden?e.push(`audio`):e.push(`video`),r?(e.push(r.via===`pull`?`${r.listeners} watching`:`${r.listeners} listening · over ${r.via}`),r.startedAt>0&&e.push(`on air ${oe(Math.max(0,(Date.now()-r.startedAt)/1e3))}`),r.redials&&e.push(`redialled ${r.redials}×`),ft()&&r.error&&e.push(r.error)):l===`remote`&&!w?(b.tracks[I()]&&F()>0&&e.push(`${Yt()?`library track`:`track`} ${I()+1} of ${F()}`),j()&&E&&e.push(`${E.server.playing?`playing`:`stopped`} on ${u||`the server`}`)):l===`local`&&F()>0&&e.push(`track ${I()+1} of ${F()}`),T?.catalog!==void 0&&(T.kind===`channel`?w!==null:T.kind===`vod`&&N.source!==``)&&T?.catalog&&(e.push(T.entry?.group?`${T.catalog.name} › ${T.entry.group}`:T.catalog.name),t=T.entry?.logo??``),t===``&&w&&(t=ve(r?.art??w.art));let i=k?.key===Le?k.match:null;if(i?.kind===`fixture`)n=it(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(w&&T?.link){let t=``;try{t=new URL(T.link.url).hostname.replace(/^www\./,``)}catch{}e.push(T.link.extractor&&T.link.extractor!==`direct`&&T.link.extractor!==`generic`?`${T.link.extractor} · ${t}`:t||`link`)}Be&&He&&j()&&!w&&T?.kind!==`live`&&e.push(Je?`☎ ${Je} · key ${He}`:`☎ code ${He}`)}let o=k?.key===Le?k.match:null,s=!i&&!n&&o?.summary?o.summary:``,c=`${t}|${n?`${n.away.logo}|${n.home.logo}|${n.text}`:``}|${e.join(`|`)}|${s}`;if(c===yn)return;yn=c,a.meta.hidden=e.length===0,a.metaBlurb.textContent=s,a.metaBlurb.hidden=s===``;let d=[];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)),d.push(e)}if(t!==``&&/^(https?:\/\/|\/api\/)/.test(t)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&t===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=t,e.addEventListener(`error`,()=>{e.hidden=!0}),d.push(e)}for(let t of e){let e=document.createElement(`span`);e.className=n?.state===`in`&&t===n.status?`meta-chip chip-live`:`meta-chip`,e.textContent=t,d.push(e)}a.meta.replaceChildren(...d)}function z(){let e=F(),t=dn(),n=Se();h(a.status,()=>f(n?`LOADING`:t?`▶ PLAYING`:`■ STOPPED`)),a.status.dataset.playing=n?`loading`:String(t),h(a.title,()=>Qt()),a.title.classList.toggle(`with-context`,Yt()),a.album.classList.toggle(`with-context`,Yt()),(Yt()||w)&&Ln(),en(),bn(),a.goLiveNow.hidden=!gt()||xt()===null;let r=t?`${Zt()} · ${c}`:c;document.title!==r&&(document.title=r),a.copyNow.hidden=N.source===``,a.shareNow.hidden=Mi()===``,fi(),wi(),a.downloadNow.hidden=!(w&&T?.link?.download),Un(),a.album.textContent=$t();let i=nn(),o=tn();a.elapsed.textContent=oe(i),a.total.textContent=o>0?oe(o):`--:--`,_e||(a.seek.value=String(o>0?Math.round(i/o*1e3):0),a.seek.disabled=o<=0||j()),a.playPause.textContent=t?`❚❚`:`▶`,g(a.playPause,`aria-label`,()=>f(t?`Pause`:`Play`)),g(a.seek,`aria-valuetext`,()=>`${oe(N.position)} ${d.language===`en`?`of`:`/`} ${oe(N.duration)}`),g(a.volume,`aria-valuetext`,()=>d.number(Number(a.volume.value)/100,{style:`percent`})),g(a.playlistTitle,`data-title`,()=>l===`remote`?`Files on ${u||`this server`} (${e.toLocaleString(d.language)})`:`${f(`Playlist`)} (${d.number(e)})`),h(a.source,()=>l===`remote`?`connected · ${u||P.address.replace(/^https?:\/\//,``)||`—`}`:v.length>0?`local · ${v.length} files`:f(`no source`)),Fn(),h(a.remoteState,()=>l===`remote`?`${x}${he?` — ${he}`:``}`:f(`not connected`)),a.remoteState.dataset.status=l===`remote`?x:`idle`,a.disconnect.hidden=l!==`remote`;let s=N.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:l===`remote`&&b.note!==``?b.note:S;a.note.textContent=s,a.note.hidden=s===``,a.linkNote.textContent=s,a.linkNote.hidden=s===``,Tr(s),kn(),a.glyphs.textContent=A.map(vn).join(``);let[p,m]=Wt()?b.levels:N.levels();a.levels.textContent=_n(p,m)}let xn=``,B=``,Sn=0;function Cn(e){fe(a.playlist),B=e,Sn=0,xn=``,kn()}function wn(e,t,n,r,i){if(a.playlistPager.hidden=n<=1,n<=1){a.playlistPager.replaceChildren();return}let o=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{fe(a.playlist),Sn=t,xn=``,kn()}),i},s=document.createElement(`span`);s.className=`pager-where`,h(s,()=>`${r+1}–${i} of ${e.toLocaleString(d.language)}`),a.playlistPager.replaceChildren(o(`‹ Previous`,t-1,`The page before this one`),s,o(`Next ›`,t+1,`The page after this one`))}function Tn(e){if(a.crumbs.hidden=!e,!e)return;let t=B===``?[]:B.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`,()=>Cn(t)),r},r=[n(`All files`,``,t.length===0)],i=``;t.forEach((e,a)=>{i=i===``?e:`${i}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,r.push(o,n(e,i,a===t.length-1))}),a.crumbs.replaceChildren(...r)}function En(e,t){let n=document.createElement(`li`);n.className=`folder`;let r=document.createElement(`span`);r.className=`name`,r.textContent=`${e}/`;let i=document.createElement(`span`);i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Open folder ${e}, ${t} files`),a.append(r,i),n.replaceChildren(a),a.addEventListener(`click`,t=>{t.stopPropagation(),Cn(B===``?e:`${B}/${e}`)}),n}let Dn=null,On=``;function kn(){let e=l===`remote`?b.tracks:v,t=`${l}:${B}:${a.filter.value}:${Sn}:${gt()}:${a.adminPanel.hidden}`;if(xn&&Dn===e&&On===t){An();return}Dn=e,On=t;let n=l===`remote`?b.tracks.map(e=>({name:se(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):v.map(e=>({name:se(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=a.filter.value.trim().toLowerCase(),o=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),c=e=>r!==``||B===``||e===B||e.startsWith(`${B}/`),u=e=>r!==``||e===B,d=e=>{let t=B===``?e:e.slice(B.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of o){if(!c(e.folder)||u(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=o.filter(e=>u(e.folder)&&c(e.folder)),m=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),h=lt(m.length+p.length,Sn,i);Sn=h.page;let g=m.slice(h.from,h.to),ee=p.slice(Math.max(0,h.from-m.length),Math.max(0,h.to-m.length)),te=`${l}:${B}:${r}:${h.page}/${i}:${m.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==xn){xn=te,Tn(r===``&&(m.length>0||B!==``)),wn(m.length+p.length,h.page,h.pages,h.from,h.to);let e=[];for(let[t,n]of g)e.push(En(t,n));let t=``,n=p.some(e=>e.group!==``);for(let r of ee){r.group!==t&&(n||r.group!==``)&&(t=r.group,e.push(jn(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=document.createElement(`span`);o.className=`name`,o.textContent=r.name;let c=document.createElement(`span`);c.className=`time`,c.textContent=r.seconds>0?oe(r.seconds):`--:--`;let u=document.createElement(`button`);if(u.type=`button`,u.className=`row-main`,u.setAttribute(`aria-label`,`Play ${r.name}${r.seconds>0?`, ${oe(r.seconds)}`:``}`),u.append(a,o,c),i.append(u),l===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,s(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${r.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),so(co(`track:${r.index}`,C===r.index?N.position:0),e,`✓`)}),i.append(e),gt()&&i.append(M(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}e.push(i)}y(a.playlist,...e)}An()}function An(){let e=I(),t=dn();for(let n of Array.from(a.playlist.children)){let r=n,i=Number(r.dataset.index),a=Number.isInteger(i)&&i===e;r.classList.toggle(`selected`,a),r.classList.toggle(`playing`,a&&t),a?r.setAttribute(`aria-current`,`true`):r.removeAttribute(`aria-current`)}}function jn(e){let t=document.createElement(`li`);t.className=`group`;let n=document.createElement(`span`);if(n.className=`group-name`,n.textContent=e===``?`This server's library`:e,t.append(n),e!==``&&!a.adminPanel.hidden){let n=document.createElement(`button`);n.type=`button`,n.className=`group-remove`,n.textContent=`×`,n.title=`Remove ${e} from the playlist`,n.setAttribute(`aria-label`,`Remove ${e} from the playlist`),n.addEventListener(`click`,t=>{t.stopPropagation(),Mn(e)}),t.append(n)}return t}async function Mn(e){try{let t=await fetch(P.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();V(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}}function Nn(){let e=a.canvas,t=Math.min(2,globalThis.devicePixelRatio||1),n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);n>0&&r>0&&(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);if(Wt())ut=$e(ut,A);else{let e=N.read();e.length>0&&(dt.length!==25&&(dt=Xe(24,e.length)),A=Qe(A,Ze(e,dt)),ut=$e(ut,A))}if(i){let t=getComputedStyle(document.documentElement);et(i,{width:e.width,height:e.height},A,ut,{bar:t.getPropertyValue(`--green`).trim()||`#4af689`,peak:t.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(dn()||N.jinglePlaying){a.glyphs.textContent=A.map(vn).join(``);let[e,t]=Wt()?b.levels:N.levels();a.levels.textContent=_n(e,t)}if(dn()){a.elapsed.textContent=oe(nn());let e=tn();!_e&&e>0&&(a.seek.value=String(Math.round(nn()/e*1e3)))}requestAnimationFrame(Nn)}let Pn=``;function Fn(){if(l!==`remote`){a.wayInHere.hidden=!0,Pn=``;return}let e=ft()&&!re,t=ue||P.address,n=e?null:ce(P.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===Pn)return;Pn=r;let[i,o]=le({name:u||`this server`,view:t,admin:n});i.hidden=!e,o.hidden=e,a.wayInHere.replaceChildren(i,o),a.wayInHere.hidden=!1}function In(e){a.video.hidden=!e,a.fullscreen.hidden=!e,Ne(),D=null,O=null}function Ln(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=w?ve(E?.channels.find(e=>e.id===w?.id)?.art??w.art):``,t=JSON.stringify([Qt(),$t(),e]);t!==Te&&(Te=t,navigator.mediaSession.metadata=new MediaMetadata({title:Qt(),album:$t(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void mn()),navigator.mediaSession.setActionHandler(`pause`,()=>void mn()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void hn(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void hn(-1)))}document.addEventListener(`click`,()=>{N.resumeAfterInteraction().catch(()=>{})}),a.filter.addEventListener(`input`,()=>{Sn=0,xn=``,kn()}),a.playlist.addEventListener(`keydown`,e=>{if(e.key!==`Enter`&&e.key!==` `)return;let t=e.target?.closest(`li.row, li.folder`);t&&t===e.target&&(e.preventDefault(),t.click())}),a.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&fn(n)}),a.fullscreen.addEventListener(`click`,()=>{let e=a.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),a.prev.addEventListener(`click`,()=>void hn(-1)),a.next.addEventListener(`click`,()=>void hn(1)),a.stop.addEventListener(`click`,()=>void gn()),a.playPause.addEventListener(`click`,()=>void mn());async function Rn(e){let t=_t(e,bt());if(!t){if(!gt()){S=l===`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.`,z();return}await Hn(e);return}if(w=null,N.stop(),t.kind===`embed`){T={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},In(!1),a.embedFrame.src=t.src,a.embed.hidden=!1,D={url:e,label:t.label,kind:`embed`},S=`Playing ${t.label} here, in this browser.`,z();return}if(t.kind===`list`){await zn(e,t.label);return}T={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await Ce(()=>N.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),In(t.video),D={url:e,label:t.label,kind:`direct`},S=`Playing ${t.label} here, in this browser.`,z()}async function zn(e,t){S=`Reading ${t}…`,z();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){S=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,z();return}let r=ht(n,e);if(r.entries.length===0){S=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,z();return}O={url:e,title:r.title||t,entries:r.entries,at:0},await Bn()}async function Bn(){let e=O,t=e?.entries[e.at];if(!e||!t)return;let n=pt(t.url);T={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await Ce(()=>N.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),O!==null&&(In(n),D={url:e.url,label:e.title,kind:`direct`},O=e,S=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,z())}function Vn(){let e=O;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,Bn(),!0)}async function Hn(e){if(l!==`remote`){S=`Pick a server to go live on, or connect to one, to put a link on the air.`,z();return}S=`Asking ${u||`the server`} to fetch ${e}…`,z(),await Ce(async()=>{let t,n={};try{t=await fetch(P.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!t.ok||!n.channel){S=n.error??`that link would not play.`;return}try{await fetch(P.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await to({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&&(S=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),z()}a.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.linkUrl.value.trim();t!==``&&Rn(t)});function Un(){let e=l===`remote`?P.address:``,t=p.filter(t=>ne(t.url)!==ne(e)),n=JSON.stringify({here:e,name:u,carries:ee,others:t});if(n===m||document.activeElement===a.linkServer)return;m=n;let r=[];if(e!==``&&ee){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${u||e}`,r.push(t)}else{let e=document.createElement(`option`);e.value=``,e.textContent=`go live on…`,r.push(e)}for(let e of t){let t=document.createElement(`option`);t.value=e.url,t.textContent=e.name,r.push(t)}a.linkServer.replaceChildren(...r),a.linkServer.value=e!==``&&!ee&&t[0]?t[0].url:``,a.linkServer.hidden=t.length===0}async function Wn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;p=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Un()}catch{}}async function Gn(){let e=a.linkUrl.value.trim()||D?.url||``;if(e===``){S=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,z();return}let t=a.linkServer.value;if(t!==``&&(l!==`remote`||ne(t)!==ne(P.address))){let n=p.find(e=>e.url===t)?.name??t;te=e,S=`Connecting to ${n} to go live with it…`,z(),Kn(t);return}if(l!==`remote`){S=p.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.`,z();return}if(!ee){S=`${u||`This server`} has no ffmpeg, so it cannot carry a link.`+(p.length>0?` Pick a server to go live on, beside the link.`:``),z();return}if(!gt()){S=`Sign in to nixamp.com to go live here, or use the server's control link.`,z();return}await Hn(e)}function Kn(e){let t=a.linkUrl.value.trim();re=!0,_=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit(),a.linkUrl.value=t}a.linkGoLive.addEventListener(`click`,()=>{Gn()}),a.linkServer.addEventListener(`change`,()=>{let e=a.linkServer.value;e!==``&&Kn(e)}),a.downloadNow.addEventListener(`click`,()=>{let e=T?.link;if(!e||l!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(P.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),S=`Fetching it through the server; your browser will save it when it arrives.`,z()}),a.goLiveNow.addEventListener(`click`,()=>{let e=xt();e&&St(e,a.goLiveNow)}),a.seek.addEventListener(`input`,()=>{_e=!0}),a.seek.addEventListener(`change`,()=>{let e=tn();e>0&&N.seek(Number(a.seek.value)/1e3*e),_e=!1}),a.volume.addEventListener(`input`,()=>{let e=Number(a.volume.value)/100;N.volume=e;try{localStorage.setItem(sn,String(e))}catch{}});let qn=e=>{e.addEventListener(`change`,()=>{let t=we(Array.from(e.files??[]));if(t.length===0){S=`Nothing playable in that selection.`,z();return}De(v),v=t,de=0,l=`local`,P.close(),Ya(!1),S=``,fn(0)})};qn(a.files),qn(a.folder),a.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.remoteUrl.value,{base:n,key:r}=Ie(t);if(n===``){S=`That is not an address.`,z();return}(async()=>{x=`connecting`,z();let e=qe(n);if(e){x=`error`,he=e,S=e,te=``,l=`local`,z();return}if(await Ke(n,void 0,r)===null){x=`error`;let e=We(n);he=e?`needs the server's name`:`not answering`,S=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,te=``,l=`local`,z();return}let i=await Ge(n,r);if(i){x=`error`,he=i,S=i,te=``,l=`local`,z();return}l=`remote`,S=``;try{localStorage.setItem(an,t.trim())}catch{}P.connect(t),Ya(!0),Gi(),ar(),Ga(),z()})()});let Jn=``,Yn=null,Xn=async(e=!1)=>{a.directory.hidden=!1,e||(a.directoryNote.textContent=`Looking for live streams…`,y(a.directoryList)),Yn||=setInterval(()=>{!a.directory.hidden&&document.visibilityState===`visible`&&Xn(!0)},ln);let t;try{let n=await fetch(`/api/directory`);if(!n.ok)throw Error(String(n.status));let r=await n.json();t=r.streams??[],p=t.map(e=>({name:e.name,url:e.url})),Un();let i=JSON.stringify({streams:t.map(({...e})=>{let{updatedAt:t,startedAt:n,...r}=e;return r}),recent:r.recent??[],me:G});if(e&&i===Jn)return;Jn=i,cr(r.recent??[])}catch{e||(a.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(y(a.directoryList),t.length===0){a.directoryNote.textContent=`Nobody is streaming right now.`;return}a.directoryNote.textContent=`${t.length} ${t.length===1?`server is`:`servers are`} on. Connect to one to browse its files and watch what is live on it. No account needed.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`;let o=[`${e.tracks.toLocaleString(d.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}`),i.textContent=o.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ce(e.url),c=(t,n=``)=>{re=t,_=n,a.remoteUrl.value=t?e.url:s??e.url,a.directory.hidden=!0,a.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 s=document.createElement(`button`);s.type=`button`,s.className=`button`,Ht(s),s.title=`Join live: ${t} on ${e.name}`,s.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,s),l.append(n)}let[u,f]=le({name:e.name,view:e.url,admin:s},()=>{a.directory.hidden=!0});if(t.append(n,u,f),G&&t.append(Cr(e.url,e.name)),e.ownerId&&G&&e.ownerId!==G&&t.append(aa(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&G&&e.ownerId===G){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Take off the list`,n.addEventListener(`click`,t=>{t.stopPropagation(),n.disabled=!0,(async()=>{try{let t=await fetch(`/api/directory?id=${encodeURIComponent(e.id)}`,{method:`DELETE`}),n=await t.json().catch(()=>({}));a.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{a.directoryNote.textContent=`could not reach the directory`}finally{await Xn()}})()}),t.append(n)}a.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!a.directory.hidden&&Xn(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),Xn()}let Zn=null,Qn=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,$n=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,er=``,tr=``,nr=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===er)return;er=t,a.adminConnections.replaceChildren();let n=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,n.append(t)}a.adminConnections.append(n);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let n=[[t.address,``],[Qn(t.network),`network-${t.network}`],[$n(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,r]of n){let n=document.createElement(`td`);n.textContent=t,r&&(n.className=r),e.append(n)}a.adminConnections.append(e)}};function V(e){a.adminSaid.textContent=e,a.adminSaid.hidden=e===``}let rr=async()=>{try{let e=await fetch(P.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),n=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,r=t.active??0;a.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,nr(t.connections??[]),ir(t.publish??[],(t.channels??[]).map(e=>e.id)),mo(t.home??``,t.root??``),$()}catch{a.adminNote.textContent=`lost touch with the server`}};function ir(e,t){a.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===tr)return;if(tr=n,e.length===0){y(a.publishList);return}let r=e.length-t.length;a.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,y(a.publishList,...e.map(e=>{let n=t.includes(e.id),r=document.createElement(`li`);n&&(r.className=`in-use`);let i=document.createElement(`span`);i.className=`slot`,i.textContent=n?`${e.id} · live`:e.id;let a=document.createElement(`input`);a.type=`text`,a.readOnly=!0,a.value=e.url,a.setAttribute(`aria-label`,`RTMP URL for ${e.id}`);let o=document.createElement(`button`);return o.type=`button`,o.className=`ghost`,h(o,()=>f(`Copy`)),o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let ar=async()=>{if(l!==`remote`){a.adminPanel.hidden=!0,a.publishPanel.hidden=!0,Zn&&clearInterval(Zn),Zn=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(P.url(`/api/admin`));if(i.ok){let a=await i.json();e=a.allowed===!0,t=a.as??null,n=a.claimed===!0,r=a.member===!0}}catch{e=!1}let i=e||r;if(re&&(e=!1),mt=i&&!e,a.adminPanel.hidden=!e,Wa(e),te!==``){let e=te;te=``,gt()?Hn(e):(S=`Sign in to nixamp.com to go live here.`,z())}if(Zn&&clearInterval(Zn),Zn=null,$(),Gi(),Ga(),a.listenOnly.hidden=e,!e){a.listenOnly.textContent=n?`This is a listen-only link: you can hear this server but not change what it plays. Use its control link — the first one it printed — or sign in as its owner.`:`This is a listen-only link: you can hear this server but not change what it plays. Use its control link, the first one it printed.`;return}a.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,rr(),Zn=setInterval(()=>void rr(),2e3)};function or(e,t,n){let r=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;V(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(P.url(`/api/channels/${encodeURIComponent(r)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...n===void 0?{source:e}:{at:n},...t?{name:t}:{}})}),o=await i.json();if(!i.ok){V(o.error??`that did not work`);return}V(`${o.channel?.name||t||e} is on the air.`),a.adminSource.value=``,a.adminName.value=``,Ga(),$()}catch{V(`could not reach the server`)}})()}a.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=a.adminSource.value.trim();t&&or(t,a.adminName.value.trim())}),a.adminAdd.addEventListener(`click`,()=>{let e=a.adminSource.value.trim();if(!e)return;V(`Reading ${e}…`);let t=a.adminReplace.checked,n=a.adminName.value.trim();(async()=>{try{let r=await fetch(P.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...n?{name:n}:{},...t?{replace:!0}:{}})}),i=await r.json();V(r.ok?t?`Now serving ${e}.`:i.added===0?`Everything there was already in the playlist.`:`Added ${i.added??0} tracks from ${e}.`:i.error??`that did not work`),r.ok&&(a.adminSource.value=``,a.adminName.value=``,Ga(),$())}catch{V(`could not reach the server`)}})()});let sr=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`},cr=e=>{let t=[],n=G?e.filter(e=>e.ownerId&&e.ownerId!==G):[];if(a.recentNote.hidden=n.length===0,n.length===0){y(a.recentList);return}for(let e of n){let n=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${sr(e.endedAt)}`:`ended ${sr(e.endedAt)}`,r.append(i,a),n.append(r,aa(e.ownerId,e.name)),t.push(n)}y(a.recentList,...t)},lr=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 ur(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?`▶ ${lr(e.party.positionNow)}`:`❚❚ ${lr(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`,Ht(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=`⋯`,g(c,`aria-label`,()=>`${f(`Show more`)}: ${e.event.title}`),s.append(c,o),t.append(n,a,s),t}let dr=[],fr=[],pr=!1,mr=null,hr=``;function gr(){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=l===`remote`&&E?ne(P.address):``;for(let e of dr){let r=ne(e.url);if(!r||r===n)continue;let i=[],o=(t,n)=>{let o=document.createElement(`li`);o.dataset.liveKey=`${r}:${t}`,o.className=`party-row`;let s=document.createElement(`span`);s.className=`party-name`,s.textContent=n,s.title=n;let c=document.createElement(`button`);c.type=`button`,Ht(c),g(c,`aria-label`,()=>`${f(`Join party`)}: ${n} · ${e.name}`),c.addEventListener(`click`,()=>{re=!0,_=t,a.remoteUrl.value=e.url,a.remoteForm.requestSubmit()}),o.append(s,c),i.push(o)};e.playing!==!1&&e.nowPlaying&&o(`live`,me(e.nowPlaying));for(let t of e.channels??[]){let n=e.lineup?.find(e=>e.name===t);o(`channel:${n?.id??t}`,t)}t(r,e.name,i)}n&&E&&t(n,E.server.name||u||n,Za(E));for(let e of fr){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=ur(e);i.dataset.liveKey=`party:${e.event.id}`,t(n,r,[i])}let r=new Map([...a.partiesList.children].map(e=>[e.dataset.liveKey,e])),i=[];for(let[t,n]of e){let e=r.get(t);if(!e){e=document.createElement(`li`),e.dataset.liveKey=t,e.className=`party-server`;let n=document.createElement(`h3`),r=document.createElement(`ul`);r.className=`party-rows`,e.append(n,r)}let a=e.querySelector(`h3`);a.textContent!==n.name&&(a.textContent=n.name),pe(e.querySelector(`ul`),n.rows),i.push(e)}pe(a.partiesList,i),a.partiesNote.hidden=e.size>0,e.size||h(a.partiesNote,()=>f(pr?`No parties live right now.`:`Loading…`))}async function _r(){if(e||(hr!==G&&(mr?.abort(),mr=null,fr=[],hr=G,gr()),mr))return;let t=new AbortController;mr=t;let n=G,r=setTimeout(()=>t.abort(),8e3),i=async e=>{let n=await fetch(e,{signal:t.signal,cache:`no-store`});return{ok:n.ok,status:n.status,body:n.ok?await n.json():null}};try{let[e,r]=await Promise.allSettled([i(`/api/directory`),n?i(`/api/v1/watch-parties`):Promise.resolve(null)]);if(mr!==t||n!==G||t.signal.aborted)return;e.status===`fulfilled`&&e.value.ok&&(dr=e.value.body.streams??[],pr=!0),r.status===`fulfilled`&&r.value&&(r.value.ok?(fr=r.value.body.parties??[],pr=!0):[401,403].includes(r.value.status)&&(fr=[])),gr(),!pr&&!E&&h(a.partiesNote,()=>f(`Could not refresh parties.`))}finally{clearTimeout(r),mr===t&&(mr=null)}}a.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){S=n.error??`No party found with that invite code.`,z();return}a.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{S=`Could not look up that party. Try again.`,z()}})()});async function vr(){if(!G){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];a.connectionsNote.hidden=t.length===0,a.connectionsList.hidden=t.length===0,y(a.connectionsList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.clientName;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.scope.split(` `).filter(Boolean).join(`, `),n.append(r,i);let a=document.createElement(`button`);return a.type=`button`,a.className=`ghost`,h(a,()=>f(`Disconnect`)),a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await vr()})()}),t.append(n,a),t}))}catch{a.connectionsNote.hidden=!0,a.connectionsList.hidden=!0}}let yr=new Set,H=e=>{try{return new URL(e).origin}catch{return e}},br=e=>[...yr].some(t=>H(t)===H(e));async function xr(){if(!G){yr=new Set,a.favoritesPanel.hidden=!0,wr();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){a.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];yr=new Set(t.map(e=>e.url)),a.favoritesPanel.hidden=t.length===0,a.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,y(a.favoritesList,...t.map(e=>{let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`server-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||e.url.replace(/^https?:\/\//,``);let i=document.createElement(`span`);return i.className=e.live?`detail live`:`detail`,i.textContent=e.live?[`● on now`,e.nowPlaying?`playing ${e.nowPlaying}`:``,e.channels.length>0?`live: ${e.channels.join(`, `)}`:``].filter(Boolean).join(` · `):`not on right now`,n.append(r,i),t.append(n,...le({name:e.name||e.url,view:e.url,admin:ce(e.url)}),Cr(e.url,e.name)),t}))}catch{a.favoritesPanel.hidden=!0}wr()}async function Sr(e,t,n){try{if(!(n?await fetch(`/api/v1/favorites`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,name:t})}):await fetch(`/api/v1/favorites?url=${encodeURIComponent(e)}`,{method:`DELETE`})).ok){S=n?`Could not save that favourite.`:`Could not remove that favourite.`,z();return}}catch{S=`could not reach nixamp.com`,z();return}if(n)yr.add(e);else for(let t of[...yr])H(t)===H(e)&&yr.delete(t);await xr()}function Cr(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=br(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=[...yr].find(t=>H(t)===H(e))??e;Sr(br(e)?i:e,t,!br(e)).then(r)}),n}function wr(){let e=l===`remote`?P.shareLink:``;if(a.favHere.hidden=!(G&&e),a.favHere.hidden)return;let t=br(e);a.favHere.textContent=t?`♥`:`♡`,a.favHere.dataset.on=t?`yes`:`no`,a.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,a.favHere.setAttribute(`aria-label`,a.favHere.title)}s(a.copyNow,`copy`),a.copyNow.addEventListener(`click`,()=>{so(N.source,a.copyNow,`✓`)});function Tr(e){if(e===``||e===ot)return;ot=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),h(n,()=>r.toLocaleTimeString(d.language,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`}));let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),a.logList.prepend(t);a.logList.children.length>100;)a.logList.lastElementChild?.remove()}let Er=3e3,U=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Dr=``,Or=``,kr=null,Ar=!1,jr=new Set,Mr=``,Nr=null,Pr=!1,Fr=Bt(e=>localStorage.getItem(e)),W=Ft(e=>localStorage.getItem(e)),Ir=new Set,Lr=new Set,Rr=null,zr=``,Br=``,G=``,Vr=(()=>{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()}`}})(),Hr=null,K=!1,Ur=``,Wr=!1,Gr=!1,Kr=``,qr=0,Jr=!1,Yr=!1;try{a.transcriptBackground.checked=localStorage.getItem(`nixamp.backgroundSound`)!==`off`}catch{}let Xr=new Kt(()=>{Yr=!0,Jr&&(a.transcriptAudioNote.textContent=`Translated audio · background sound unavailable on this device`)}),Zr=()=>{let e=Number(a.transcriptBackgroundLevel.value);Xr.setLevel(e/100),a.transcriptBackgroundValue.value=`${e}%`,g(a.transcriptBackgroundLevel,`aria-valuetext`,()=>d.number(e/100,{style:`percent`})),a.transcriptBackgroundLevel.disabled=!a.transcriptBackground.checked};try{let e=localStorage.getItem(`nixamp.backgroundLevel`);e!==null&&Number.isFinite(Number(e))&&(a.transcriptBackgroundLevel.value=e)}catch{}Zr(),a.transcriptBackgroundLevel.addEventListener(`input`,()=>{Zr();try{localStorage.setItem(`nixamp.backgroundLevel`,a.transcriptBackgroundLevel.value)}catch{}});let q=new Jt({account:()=>U===``?G:``,changed:()=>ki()});R(`translation-buy-tools`).append(q.button()),q.refresh();let Qr=new qt({reconnecting:()=>J.reset(),line:(e,t)=>{oi=0,si.push(e),Di(),J.push(e,t,0)},status:e=>{a.transcriptAudioNote.textContent=e},failed:e=>{Ur=e,Br=e,K=!1,a.transcriptAudio.checked=!1,J.disable(),ti(),a.transcriptAudioNote.textContent=`${e} Original audio restored.`,q.refresh()}}),J=new Ut({fetcher:((e,t)=>String(e).startsWith(`nixamp-shared:`)?Promise.resolve(Qr.audio(String(e))):fetch(e,t)),playing:()=>N.playing,volume:()=>N.volume,active:e=>{Jr=e,N.translatedAudio(e),Xr.active(e&&N.playing&&a.transcriptBackground.checked)},status:e=>{a.transcriptAudioNote.textContent=e+(Yr&&Jr?` · background unavailable`:``)},failed:()=>{Br=a.transcriptAudioNote.textContent||`Translated audio stopped.`,K=!1,a.transcriptAudio.checked=!1,ti()},authorization:async(e,t)=>{if(t.channel.startsWith(`dub-`))return new Headers;if(!G||U!==``)throw Error(`Sign in on nixamp.com to enable translated audio.`);if(!Hr||Hr.channel!==t.channel||Hr.expires<Date.now()+2e4||Hr.remaining<t.text.length){let n=await fetch(`/api/v1/speech/grant`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({channel:t.channel}),signal:e}),r=await n.json();if(!n.ok||!r.token||!r.expires)throw Error(r.error||`Sign in to enable translated audio.`);Hr={channel:t.channel,token:r.token,expires:r.expires,remaining:2e3}}return Hr.remaining-=t.text.length,{authorization:`Bearer ${Hr.token}`}}}),$r=new Xt({fetcher:(e,t)=>{let n=new Headers(t?.headers);return String(e).includes(`/speech/speakers`)&&n.set(`x-nixamp-translation-session`,Vr),fetch(e,{...t,headers:n})},language:()=>W,speakers:()=>a.transcriptAudio.checked,voices:()=>Rr?.voices??[],channel:()=>Vr,status:e=>{!Wr&&!K&&(Ur=e),a.transcriptNote.textContent=e},failed:()=>{K=!1,a.transcriptAudio.checked=!1,J.disable(),ti()},lines:e=>{oi=0,si.push(...e),Di(),ri(),a.transcriptAudio.checked&&J.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:W,channel:Vr,speaker:e.speaker,voice:$r.tracker.speakers.get(e.speaker??``)?.voice??`auto`})}})))}}),ei=new Gt(e=>{Wr&&N.playing&&$r.push(e)});function ti(){qr++,Wr=!1,Gr=!1,Kr=``,ei.stop(),$r.reset(),Qr.stop(),Xr.stop(),J.reset(),y(a.transcriptSpeakers)}async function ni(){if((Wr||Gr)&&Kr===N.mediaKey)return;ti();let e=qr;Gr=!0,Kr=N.mediaKey;try{if(!G||U!==``)throw Error(`Sign in on nixamp.com to transcribe or translate this audio.`);let t=N.audioInput();if(Yr=!1,a.transcriptAudio.checked&&a.transcriptBackground.checked&&Xr.start(t.context,t.node).then(t=>{t&&e===qr&&Xr.active(Jr&&N.playing&&a.transcriptBackground.checked)}),a.transcriptAudio.checked&&l===`remote`&&w)await Qr.start(ji(),W),q.refresh();else{if(a.transcriptAudio.checked&&await q.startSession(Vr),e!==qr)return;await ei.start(t.context,t.node,a.transcriptAudio.checked?2:5)}if(e!==qr)return;Wr=!0,K=!0,oi=0,li??=setInterval(Di,250),a.transcriptNote.textContent=a.transcriptAudio.checked?`Listening for speech and speaker changes…`:`Listening in the original audio language…`}catch(t){if(e!==qr)return;K=!1,a.transcriptAudio.checked=!1,J.disable(),ti(),Ur=t instanceof Error?t.message:`This audio could not be captured.`,a.transcriptNote.textContent=Ur}finally{e===qr&&(Gr=!1)}}function ri(){let e=[...$r.tracker.speakers.values()].slice(-32),t=new Set(e.map(e=>e.id));for(let t of e){if(a.transcriptSpeakers.querySelector(`[data-speaker="${t.id}"]`))continue;let e=document.createElement(`label`);e.className=`transcript-switch`,e.dataset.speaker=t.id;let n=document.createElement(`span`),r=t.id.split(`-`)[1];h(n,()=>`${f(`Speaker`)} ${r} `),e.append(n);let i=document.createElement(`select`);i.className=`transcript-language`,g(i,`aria-label`,()=>`${f(`Speaker voices`)}: ${r}`);for(let e of Rr?.voices??[])i.append(new Option(e.name,e.id));i.value=t.voice,i.addEventListener(`change`,()=>{t.voice=i.value,J.reset()}),e.append(i),a.transcriptSpeakers.append(e)}a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked;for(let e of a.transcriptSpeakers.querySelectorAll(`[data-speaker]`))!t.has(e.dataset.speaker??``)&&!e.contains(document.activeElement)&&e.remove()}for(let e of[a.audio,a.video]){for(let t of[`pause`,`ended`,`seeking`,`emptied`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&ti()});for(let t of[`playing`,`seeked`])e.addEventListener(t,()=>{e===(N.showingVideo?a.video:a.audio)&&K&&Fr&&N.playing&&ni()});e.addEventListener(`volumechange`,()=>{J.setVolume()})}let ii=``,ai=null,oi=Lt(6,!1),si=[],ci=[],li=null;function ui(){if(l!==`remote`)return null;let{base:e}=Ie(lo());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=w?w.id:T?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function di(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${U}/api/v1/trollbox?${n.toString()}`}function fi(){let e=ui(),t=e?`${e.server}|${e.channel}`:``;t!==Dr&&(Dr=t,Or=``,jr.clear(),a.trollboxList.replaceChildren(),kr&&clearTimeout(kr),kr=null,a.trollboxPanel.hidden=e===null,a.trollboxForm.hidden=!0,_i(!1),e&&(h(a.trollboxNote,()=>`The room for ${Qt()||e.channel}. Loading…`),mi()))}function pi(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);h(n,()=>Number.isNaN(r.getTime())?``:r.toLocaleTimeString(d.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 mi(){let e=ui(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Dr&&!Ar){Ar=!0;try{let n=await fetch(di(e,Or)),r=await n.json().catch(()=>({}));if(t!==Dr)return;if(!n.ok){a.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!jr.has(e.id));for(let e of i)jr.add(e.id),a.trollboxList.append(pi(e)),Or=e.createdAt;for(;a.trollboxList.children.length>200;)a.trollboxList.firstElementChild?.remove();let o=r.you??``,s=Mr!==o;Mr=o,s&&(Hr=null,ki()),a.trollboxForm.hidden=o===``,a.trollboxEditLabel.hidden=o===``||!hi,o===``&&_i(!1),h(a.trollboxNote,()=>o===``?U===``?`The room for ${Qt()||e.channel}. Sign in to say something.`:`The room for ${Qt()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${o} in the room for ${Qt()||e.channel}.`)}catch{t===Dr&&(a.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Ar=!1,t===Dr&&(kr=setTimeout(()=>{document.visibilityState===`visible`?mi():kr=setTimeout(()=>void mi(),Er)},Er))}}}a.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=ui(),n=a.trollboxInput.value.trim();t&&n!==``&&(a.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${U}/api/v1/trollbox`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({server:t.server,channel:t.channel,body:n})}),r=await e.json().catch(()=>({}));if(!e.ok||!r.message){a.trollboxNote.textContent=r.error??`that did not send`;return}a.trollboxInput.value=``,jr.has(r.message.id)||(jr.add(r.message.id),a.trollboxList.append(pi(r.message)),Or=r.message.createdAt)}catch{a.trollboxNote.textContent=`The trollbox is not answering.`}finally{a.trollboxInput.disabled=!1}})())});let hi=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,gi=hi?At(e=>MediaRecorder.isTypeSupported(e)):``;a.trollboxMic.hidden=!hi;function Y(e){a.trollboxNote.textContent=e,Tr(e)}function _i(e){let t=Nr;if(!t)return;Nr=null,clearTimeout(t.stop),clearInterval(t.tick),a.trollboxMic.setAttribute(`aria-pressed`,`false`),a.trollboxMic.textContent=`🎤`;let n=new Promise(e=>{t.recorder.addEventListener(`stop`,()=>e(),{once:!0})});t.recorder.state!==`inactive`&&t.recorder.stop();for(let e of t.stream.getTracks())e.stop();e&&n.then(()=>yi(new Blob(t.chunks,{type:t.recorder.mimeType||gi||`audio/webm`}),t.startedAt))}async function vi(){if(Nr||Pr||Mr===``||!ui())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){Y(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,gi?{mimeType:gi}:{})}catch{for(let t of e.getTracks())t.stop();Y(`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();Nr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>_i(!0),kt),tick:setInterval(()=>{a.trollboxMic.textContent=jt(r,Date.now())},500)},t.start(250),a.trollboxMic.setAttribute(`aria-pressed`,`true`),a.trollboxMic.textContent=jt(r,r),Y(`Listening. Tap the mic again when you have said it (${Math.round(kt/1e3)} s at most).`)}async function yi(e,t){let n=ui();if(n&&Mr!==``){if(Date.now()-t<400||e.size===0){Y(`That was too short to hear. Tap, say it, then tap again.`);return}Pr=!0,a.trollboxMic.disabled=!0,a.trollboxMic.textContent=`…`,Y(`Hearing you…`);try{let t=new AudioContext,r;try{r=await t.decodeAudioData(await e.arrayBuffer())}finally{t.close()}let i=new OfflineAudioContext(1,Math.max(1,Math.ceil(r.duration*Ot)),Ot),o=i.createBufferSource();o.buffer=r,o.connect(i.destination),o.start();let s=Dt((await i.startRendering()).getChannelData(0),Ot),c=a.trollboxEdit.checked,l=new URLSearchParams(c?{}:{server:n.server,channel:n.channel}),u=navigator.language.slice(0,2).toLowerCase();/^[a-z]{2}$/.test(u)&&l.set(`language`,u);let d=await fetch(`${U}/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){Y(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){Y(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=a.trollboxInput.value.trimEnd();a.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),Y(`Heard: “${p}”. Send it, or fix it first.`);return}ui()&&!jr.has(f.message.id)&&(jr.add(f.message.id),a.trollboxList.append(pi(f.message)),Or=f.message.createdAt),Y(`Said: “${f.message.body}”`)}catch{Y(`That recording could not be read here.`)}finally{Pr=!1,a.trollboxMic.disabled=!1,a.trollboxMic.textContent=`🎤`}}}a.trollboxMic.addEventListener(`click`,()=>{Nr?_i(!0):vi()});try{a.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}a.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,a.trollboxEdit.checked?`on`:`off`)}catch{}Y(a.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function bi(){try{let e=await fetch(`${U}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`Could not read your profile.`;return}a.personaHandle.value=t.chosen?t.handle??``:``,g(a.personaHandle,`placeholder`,()=>t.handle||f(`handle`)),a.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,a.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;a.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${xi(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${xi(t.voice??``)}${n}.`}catch{a.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function xi(e){return e===`female`?`in a woman's voice`:e===`male`?`in a man's voice`:e.includes(`.`)?`in the voice ${e}`:`in whichever voice your profile says, or one picked for you`}a.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.personaHandle.value.trim(),n={voice:a.personaVoice.value,profile:a.personaProfile.value.trim()};t!==``&&(n.handle=t),a.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${U}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){a.personaNote.textContent=t.error??`that did not save`;return}await bi()}catch{a.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Nr&&_i(!0)});function Si(){return l===`remote`&&w?{id:w.id,name:w.name,hls:w.video&&bt()}:N.loaded||D?{id:Vr,name:Qt()||`This audio`,hls:!1}:null}function Ci(){ti(),Hr=null,Ir.clear(),Lr.clear(),ai?.close(),ai=null,li&&clearInterval(li),li=null,si=[],ci=[],a.transcriptList.replaceChildren(),a.subtitle.hidden=!0,a.subtitle.textContent=``}function wi(){let e=Si(),t=`${e?.id??``}|${N.mediaKey}|${Fr}|${W}|${a.transcriptAudio.checked}|${K}|${G}`;if(t!==ii){if(ii=t,Ci(),a.transcriptPanel.hidden=!1,a.transcriptOn.checked=Fr&&(!!w||K||a.transcriptAudio.checked),a.transcriptLanguage.options.length===0)for(let e of Pt){let t=new Option(e.label,e.code);e.code&&(t.lang=e.code),h(t,()=>e.code?e.label:f(`Original (auto-detect)`)),a.transcriptLanguage.append(t)}if(a.transcriptLanguage.value=W,ki(),Ai(),!e){a.transcriptNote.textContent=`Play something to see its captions.`;return}if(!Fr){a.transcriptNote.textContent=`Captions are off.`;return}if(Ur){a.transcriptNote.textContent=Ur;return}a.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,a.transcriptAudio.checked||K?N.playing?ni():a.transcriptNote.textContent=`Press Play to start listening.`:l===`remote`&&w?Ti(e,t):a.transcriptNote.textContent=`Turn on captions to transcribe this audio.`}}async function Ti(e,t){let n=6,r=W?`?language=${encodeURIComponent(W)}`:``;try{let i=await fetch(P.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),o=await i.json().catch(()=>({}));if(t!==ii)return;if(!i.ok){a.transcriptNote.textContent=o.error??`This server is not captioning.`;return}if(o.recognitionRevision!==`native-v2`){G&&U===``?(K=!0,wi()):a.transcriptNote.textContent=`This broadcaster needs an update for native captions. Sign in to transcribe the audio on this device.`;return}n=o.backlog??n}catch{t===ii&&(a.transcriptNote.textContent=`The server did not answer about captions.`);return}oi=Lt(n,e.hls);let i=new EventSource(P.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));ai=i;let o=(e,t=!1)=>{for(let n of e){if(!n||typeof n.text!=`string`||!Number.isFinite(n.at)||!Number.isFinite(n.until))continue;let e=`${n.at}|${n.language}`;Ir.has(e)||(Ir.add(e),Ir.size>600&&Ir.delete(Ir.values().next().value),si.push(n),t&&a.transcriptAudio.checked&&Lr.add(n))}};i.addEventListener(`hello`,r=>{if(t!==ii)return;let i=JSON.parse(r.data);oi=Lt(i.backlog??n,e.hls),o(i.lines??[]);let s=Pt.find(e=>e.code===i.language)?.label??i.language,c=Pt.find(e=>e.code===W)?.label??W;if(a.transcriptNote.textContent=i.error?`Captions unavailable: ${i.error}`:W?`${s||`Detected audio`} → ${c}`:`Original audio · ${s||`detecting language…`}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${U||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,a.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,n=>{if(t!==ii)return;let r=JSON.parse(n.data);o([r],!0);let i=r.sourceLanguage??(r.original===void 0?r.language:``),s=Pt.find(e=>e.code===i)?.label??i,c=Pt.find(e=>e.code===W)?.label??W;a.transcriptNote.textContent=W?`${e.name} · ${s||`Detected audio`} → ${c}`:`${e.name} · Original audio language: ${s||`detecting…`}`}),i.addEventListener(`error`,()=>{t===ii&&i.readyState===EventSource.CLOSED&&(a.transcriptNote.textContent=`Captions stopped; the server went away.`)}),li=setInterval(Di,250)}function Ei(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),h(n,()=>Vt(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=It(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 Di(){let e=Date.now(),{ready:t,still:n}=Rt(si,e,oi);si=n;for(let e of t)if(ci.push(e),a.transcriptList.append(Ei(e)),Lr.delete(e)&&a.transcriptAudio.checked&&W){let t=new URLSearchParams({at:String(e.at),language:W,voice:`auto`});J.push(e,P.url(`/api/channels/${encodeURIComponent(e.channel)}/voice?${t}`),oi)}for(;ci.length>200;)ci.shift();for(;a.transcriptList.children.length>200;)a.transcriptList.firstElementChild?.remove();let r=zt(ci,e,oi),i=a.transcriptList.children,o=r?ci.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===o);let s=N.playing&&r!==null&&!a.video.hidden&&a.video.offsetHeight>0;a.subtitle.hidden=!s,s&&r&&(a.subtitle.textContent!==r.text&&(a.subtitle.textContent=r.text),a.subtitle.style.top=`${a.video.offsetTop+a.video.offsetHeight-a.subtitle.offsetHeight-10}px`)}a.transcriptOn.addEventListener(`change`,()=>{Fr=a.transcriptOn.checked,K=Fr&&(!w||a.transcriptAudio.checked),Fr||(a.transcriptAudio.checked=!1,J.disable());try{localStorage.setItem(Mt,Fr?`on`:`off`)}catch{}wi()}),a.transcriptLanguage.addEventListener(`change`,()=>{Ur=``,Br=``,W=Ft(()=>a.transcriptLanguage.value),!W&&a.transcriptAudio.checked&&(a.transcriptAudio.checked=!1,K=!1,J.disable());try{W?localStorage.setItem(Nt,W):localStorage.removeItem(Nt)}catch{}wi()});function Oi(){if(W)return W;let e=navigator.language.split(`-`)[0]||`en`;return Pt.some(t=>t.code===e)&&Rr?.languages.includes(e)?e:`en`}function ki(){let e=G!==``&&U===``,t=e&&q.loaded()&&!!Si()&&!!Rr?.languages.includes(Oi());a.transcriptAudio.disabled=!t,a.transcriptVoiceSettings.contains(document.activeElement)||(a.transcriptVoiceSettings.hidden=!a.transcriptAudio.checked),t?a.transcriptAudio.checked||h(a.transcriptAudioNote,()=>Br||f(`Original audio.`)):(a.transcriptAudio.checked=!1,J.disable(),a.transcriptAudioNote.textContent=e?Si()?q.loaded()?Br||(Rr?`Audio translation is unavailable for this language.`:`Loading voices…`):q.loadingMessage():`Play something to translate its audio.`:`Sign in to translate audio.`)}async function Ai(){if(!G||U!==``)return;let e=`/api/v1/speech/voices`;if(zr!==e){zr=e,Rr=null,Br=``,ki();try{let t=await fetch(e,{signal:AbortSignal.timeout(1e4)}),n=await t.json();if(zr!==e)return;if(!t.ok)throw Error(n.error||`Translated audio is unavailable on this server.`);if(!Array.isArray(n.voices)||!Array.isArray(n.languages))throw Error(`This server needs an update for translated audio.`);Rr=n}catch(t){if(zr!==e)return;Br=t instanceof Error?t.message:`Translated audio is unavailable.`}ki()}}a.transcriptBackground.addEventListener(`change`,()=>{Zr();try{localStorage.setItem(`nixamp.backgroundSound`,a.transcriptBackground.checked?`on`:`off`)}catch{}if(Xr.stop(),Yr=!1,a.transcriptBackground.checked&&a.transcriptAudio.checked&&N.playing){let e=qr,t=N.audioInput();Xr.start(t.context,t.node).then(t=>{t&&e===qr&&Xr.active(Jr&&N.playing&&a.transcriptBackground.checked)})}}),a.transcriptAudio.addEventListener(`change`,()=>{if(Ur=``,Br=``,Lr.clear(),a.transcriptAudio.checked&&!q.ready()){a.transcriptAudio.checked=!1,q.open(a.transcriptAudio);return}if(a.transcriptAudio.checked){W=Oi();try{localStorage.setItem(Nt,W)}catch{}Fr=!0,K=!0,J.enable()}else K=!1,J.disable();wi()});function ji(){if(D)return D.url;if(l!==`remote`)return``;let{base:e,key:t}=Ie(lo());if(e===``)return``;if(w)return Pe(e,`/api/channels/${encodeURIComponent(w.id)}`,t);if(T?.kind===`live`)return Pe(e,`/api/live`,t);if(N.source===``)return``;try{let n=new URL(N.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Mi(){let e=ji();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}a.shareNow.addEventListener(`click`,()=>{let e=Mi();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${Zt()} on nixamp`,url:e}).catch(()=>void 0);return}so(e,a.shareNow,`Copied`)}),a.favHere.addEventListener(`click`,()=>{let e=lo()||P.shareLink;if(!e)return;let t=[...yr].find(t=>H(t)===H(e))??e;Sr(br(e)?t:e,u||P.address,!br(e)).then(wr)});let Ni=n?i:200,Pi=[],X=null,Z=null,Fi=``,Ii=[],Li=0,Ri=null,zi=0,Bi=null,Vi=null,Hi=new Map;function Ui(e,t){zi++,Bi?.abort(),Ri&&clearTimeout(Ri),Ri=null,fe(a.catalogsList),fe(a.catalogsEntries),X=e,Z=t,Fi=``,a.catalogsFilter.value=``,Ii=[],Li=0,a.catalogsEntries.setAttribute(`aria-busy`,`false`),qi(),e&&t!==null&&Qi(0)}function Wi(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 Gi(){let e=P.url(`/api/catalogs`);if(Vi?.url===e)return Vi.promise;let t=Ki(e).finally(()=>{Vi?.promise===t&&(Vi=null)});return Vi={url:e,promise:t},t}async function Ki(e){if(l!==`remote`){a.catalogsPanel.hidden=!0;return}let t;try{t=await fetch(e)}catch{e===P.url(`/api/catalogs`)&&(a.catalogsPanel.hidden=!0);return}if(l===`remote`&&e===P.url(`/api/catalogs`)){if(!t.ok){a.catalogsPanel.hidden=!0;return}Pi=(await t.json().catch(()=>({}))).catalogs??[],X&&=Pi.find(e=>e.id===X?.id)??null,X||(Z=null),a.catalogsPanel.hidden=!1,qi()}}function qi(){let e=!a.adminPanel.hidden;a.catalogsForm.hidden=!e;let t=Pi.reduce((e,t)=>e+t.live,0),n=Pi.reduce((e,t)=>e+t.vod,0);a.catalogsNote.textContent=Pi.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Pi.length} ${Pi.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,Ji();let r=X!==null&&Z!==null;if(a.catalogsList.hidden=r,a.catalogsFilter.hidden=!r,a.catalogsEntries.hidden=!r,r){$i();return}if(X){Xi(X);return}y(a.catalogsList,...Pi.map(t=>Yi(t,e)))}function Ji(){let e=X!==null;if(a.catalogsCrumbs.hidden=!e,!e)return;let t=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,t),r},n=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},r=[t(`All catalogs`,()=>Ui(null,null),!1),n(),t(X?.name??``,()=>Ui(X,null),Z===null)];Z!==null&&r.push(n(),t(Z===``?`All groups`:Z,()=>void 0,!0)),a.catalogsCrumbs.replaceChildren(...r)}function Yi(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`,h(a,()=>[`${e.entries.toLocaleString(d.language)} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString(d.language)} live`,`${e.vod.toLocaleString(d.language)} on demand`,`refreshed ${Wi(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`,()=>{Ui(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`,()=>{ta(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,h(r,()=>f(`Remove`)),r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&na(e)}),n.append(t,r)}return n}async function Xi(e){let t=P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`),n=`${t}:${e.refreshedAt}:${e.entries}`,r;a.catalogsList.setAttribute(`aria-busy`,`true`);try{let e=Hi.get(n);e||(Hi.size>=20&&Hi.delete(Hi.keys().next().value),e=fetch(t).then(async e=>{if(!e.ok)throw Error(String(e.status));return(await e.json()).groups??[]}),Hi.set(n,e)),r=await e}catch{if(Hi.delete(n),X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`),S=`Could not read the groups in ${e.name}.`,z();return}if(X?.id!==e.id||Z!==null||t!==P.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`))return;a.catalogsList.setAttribute(`aria-busy`,`false`);let i=[Zi(`All groups`,``,e.entries,e.live,e.vod),...r.map(e=>Zi(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];y(a.catalogsList,...i)}function Zi(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`,h(c,()=>`${n.toLocaleString(d.language)} · ${r.toLocaleString(d.language)} live · ${i.toLocaleString(d.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`,()=>{Ui(X,t)}),a.append(o,l),a}async function Qi(e){let t=X,n=Z;if(!t||n===null)return;let r=++zi;Bi?.abort();let i=new AbortController;Bi=i;let o=P.url(`/api/catalogs`);a.catalogsEntries.setAttribute(`aria-busy`,`true`);let s=new URLSearchParams({group:n,q:Fi,offset:String(e),limit:String(Ni)}),c;try{let e=await fetch(P.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${s}`),{signal:i.signal});if(!e.ok)throw Error(String(e.status));c=await e.json()}catch{if(i.signal.aborted||r!==zi)return;a.catalogsEntries.setAttribute(`aria-busy`,`false`),S=`Could not read ${t.name}.`,$i(),z();return}r===zi&&X?.id===t.id&&Z===n&&o===P.url(`/api/catalogs`)&&(a.catalogsEntries.setAttribute(`aria-busy`,`false`),Li=c.total??0,Ii=e===0?c.entries??[]:[...Ii,...c.entries??[]],$i())}function $i(){let e=X;if(!e)return;let t=Ii.map(t=>{let n=document.createElement(`li`);n.className=`row`;let r=document.createElement(`span`);r.className=`name`,r.textContent=t.title;let i=document.createElement(`span`);i.className=t.live?`catalog-tag catalog-live`:`catalog-tag`,i.textContent=t.live?`LIVE`:t.duration>0?oe(t.duration):`VOD`;let a=document.createElement(`button`);if(a.type=`button`,a.className=`row-main`,a.setAttribute(`aria-label`,`Play ${t.title}`),a.append(r,i),n.append(a),a.addEventListener(`click`,()=>{ea(e,t,n)}),!t.live){let r=document.createElement(`button`);r.type=`button`,r.className=`row-copy`,s(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`;so(P.url(i),r,`✓`)}),n.append(r)}return gt()&&n.append(M(()=>({kind:`entry`,catalog:{id:e.id,name:e.name},entry:t}),t.title)),n});if(Ii.length===0){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`span`);n.className=`group-name`,n.textContent=Fi?`Nothing called "${Fi}" here.`:`Nothing in this group.`,e.append(n),t.push(e)}else if(Ii.length<Li){let e=document.createElement(`li`);e.className=`group`;let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,h(n,()=>`Show more (${Ii.length.toLocaleString(d.language)} of ${Li.toLocaleString(d.language)})`),n.addEventListener(`click`,e=>{e.stopPropagation(),fe(a.catalogsEntries,!1),n.disabled=!0,Qi(Ii.length)}),e.append(n),t.push(e)}y(a.catalogsEntries,...t)}async function ea(e,t,n){n?.classList.add(`loading`),S=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await Ce(async()=>{let n,i={};try{n=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{S=`could not reach the server`;return}if(!n.ok){S=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await to({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){w=null,C=-1,T={kind:`vod`,...r},ze(a,`title`),await N.load({title:a,artist:``,album:``,duration:0,url:P.url(i.url),video:!0,objectUrl:!1},!0),In(!0),S=`Playing ${a}.`;return}S=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),z()}}async function ta(e){V(`Reading ${e.name} again…`);try{let t=await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));V(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString(d.language)} entries.`:n.error??`that did not work`)}catch{V(`could not reach the server`)}Gi()}async function na(e){try{V((await fetch(P.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{V(`could not reach the server`)}X?.id===e.id&&(X=null,Z=null),Gi()}a.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.catalogSource.value.trim(),n=a.catalogName.value.trim();t&&(async()=>{V(`Reading ${n||t}…`);try{let e=await fetch(P.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:n})}),r=await e.json().catch(()=>({}));if(!e.ok){V(r.error??`that did not work`);return}V(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString(d.language)} entries.`),a.catalogSource.value=``,a.catalogName.value=``}catch{V(`could not reach the server`)}Gi()})()}),a.catalogsFilter.addEventListener(`input`,()=>{zi++,Bi?.abort(),Ri&&clearTimeout(Ri),Ri=setTimeout(()=>{Ri=null,Fi=a.catalogsFilter.value.trim(),Qi(0)},250)});let ra=async()=>{y(a.serversList);try{let e=await fetch(`/api/v1/servers`);if(!e.ok){a.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];ae=new Map(t.map(e=>[H(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),a.serversPanel.hidden=!1,a.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Arriving signed in, this page connects to your default one, or the first that answers; a link you arrive with goes live there.`;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.url,n.append(r,i);let o=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=le({name:e.name,view:o,admin:o});Ke(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),s.disabled=!0,c.disabled=!0,s.title=c.title=`That machine is not answering. Start nixamp on it.`});let l=ba()===H(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`,()=>{xa(l?``:H(e.url)),ra()});let d=document.createElement(`button`);d.type=`button`,d.className=`ghost`,d.textContent=`Forget`,d.addEventListener(`click`,()=>{(async()=>{d.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await ra()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),a.serversList.append(t)}}catch{a.serversPanel.hidden=!0}},ia=async()=>{y(a.followingList);try{let e=await fetch(`/api/v1/follows`);if(!e.ok){a.followingNote.hidden=!0;return}let t=(await e.json()).following??[];a.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),n=document.createElement(`span`);n.className=`recent-label`;let r=document.createElement(`span`);r.className=`name`,r.textContent=e.name||`a nixamp`;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.live?`live now`:`not streaming`,n.append(r,i);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,h(o,()=>f(`Unfollow`)),o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),a.followingList.children.length===0&&(a.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(n,o),a.followingList.append(t)}}catch{a.followingNote.hidden=!0}},aa=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,h(n,()=>f(`Follow`)),n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{h(n,()=>e?`Following`:f(`Follow`)),n.dataset.following=e?`yes`:`no`};return(async()=>{try{let t=await fetch(`/api/v1/follows/${encodeURIComponent(e)}`);t.ok&&r((await t.json()).following===!0)}catch{}})(),n.addEventListener(`click`,()=>{(async()=>{let t=n.dataset.following===`yes`;n.disabled=!0;try{(await fetch(`/api/v1/follows/${encodeURIComponent(e)}`,{method:t?`DELETE`:`PUT`,headers:{"content-type":`application/json`},body:t?void 0:`{}`})).ok&&(r(!t),ia())}catch{}finally{n.disabled=!1}})()}),n},oa=e=>{let t=(e+`=`.repeat((4-e.length%4)%4)).replace(/-/g,`+`).replace(/_/g,`/`),n=atob(t),r=new Uint8Array(new ArrayBuffer(n.length));for(let e=0;e<n.length;e+=1)r[e]=n.charCodeAt(e);return r},sa=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,ca=async()=>{if(!sa())return a.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return a.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return a.notifyNote.textContent=`Not allowed, so nothing will be sent here.`,!1;try{let e=await navigator.serviceWorker.ready,{publicKey:t}=await(await fetch(`/api/v1/notify/key`)).json();if(!t)return a.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let n=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:oa(t)}),r=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n.toJSON())});if(!r.ok)throw Error(String(r.status));return a.notifyNote.textContent=`This device will be told.`,!0}catch{return a.notifyNote.textContent=`Could not set this device up.`,!1}},la=async()=>{try{let e=await(await navigator.serviceWorker.ready).pushManager.getSubscription();if(!e)return;await fetch(`/api/v1/notify/subscribe?endpoint=${encodeURIComponent(e.endpoint)}`,{method:`DELETE`}),await e.unsubscribe()}catch{}},ua=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),n=await t.json();a.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(a.notifyPhone.value=n.phone)}catch{a.notifyPhoneNote.textContent=`could not reach nixamp.com`}},da=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();a.notifyEmail.checked=t.wantsEmail!==!1,a.notifySms.checked=t.wantsSms===!0,a.notifyPhone.value=t.phone??``;let n=sa()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;a.notifyWeb.checked=t.wantsWeb!==!1&&n,a.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};a.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(a.notifyWeb.checked){let e=await ca();a.notifyWeb.checked=e,await ua({wantsWeb:e});return}await la(),await ua({wantsWeb:!1}),a.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),a.notifyEmail.addEventListener(`change`,()=>{ua({wantsEmail:a.notifyEmail.checked})}),a.notifySms.addEventListener(`change`,()=>{(async()=>{if(a.notifySms.checked&&!a.notifyPhone.value.trim()){a.notifyPhoneNote.textContent=`Add a phone number first.`,a.notifySms.checked=!1;return}await ua({wantsSms:a.notifySms.checked})})()}),a.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),ua({phone:a.notifyPhone.value.trim()})});let fa=!1,pa=!1,ma=`nixamp.welcome`,ha=()=>{let e=!1;try{e=localStorage.getItem(ma)===`hidden`}catch{}a.welcome.hidden=!pa||G!==``||e},ga=e=>{let t=e!==null;q.refresh(),zr=``,Hr=null,t||(K=!1,a.transcriptAudio.checked=!1,J.disable(),ti()),wi(),a.notifyPanel.hidden=!t,t?(da(),ia(),ra()):(a.serversPanel.hidden=!0,a.followingNote.hidden=!0,y(a.followingList),a.recentNote.hidden=!0,a.recentList.replaceChildren()),a.accountForm.hidden=t,a.accountProviders.hidden=t||a.accountProviders.childElementCount===0,a.accountSignOut.hidden=!t,a.personaForm.hidden=!t,a.personaNote.hidden=!t,t&&bi(),a.accountNote.textContent=t?`Signed in as ${e}.`:fa?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,h(a.accountSubmit,()=>f(fa?`Create account`:`Sign in`)),h(a.accountToggle,()=>fa?`I have one`:f(`Create one`)),a.accountPassword.autocomplete=fa?`new-password`:`current-password`,ha()},_a=async()=>{let e=[];pa=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(pa=!0,e=(await t.json()).providers??[])}catch{}a.accountProviders.replaceChildren(),a.accountProviders.hidden=e.length===0,a.accountPanel.hidden=!pa,a.accountElsewhere.hidden=pa,ha();for(let t of e){let e=document.createElement(`a`);e.className=`button`,e.href=`/api/v1/${encodeURIComponent(t.id)}/oauth/start`,e.textContent=`Continue with ${t.name}`,a.accountProviders.append(e)}},va=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();G=e.ok?t.account?.id??``:``,ga(e.ok?t.account?.email??`you`:null)}catch{G=``,ga(null)}if(P.session=``,G!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));P.session=e.ok&&typeof t.token==`string`?t.token:``}catch{P.session=``}l===`remote`&&ar()}xr(),_r(),vr(),Sa();let e=await ya();if(rt!==``){let t=rt;rt=``,e?_=`golive:${t}`:Rn(t)}};async function ya(){if(G===``||l===`remote`||tt!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=ba(),n=[...e].sort((e,n)=>Number(H(n.url)===t)-Number(H(e.url)===t));for(let e of n)if(await Ke(e.url,void 0,e.key)!==null)return l!==`remote`&&(re=!1,_=``,a.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,S=`Connecting to ${e.name}, your server…`,z(),a.remoteForm.requestSubmit(),!0);return!1}function ba(){try{return localStorage.getItem(on)??``}catch{return``}}function xa(e){try{e===``?localStorage.removeItem(on):localStorage.setItem(on,e)}catch{}}function Sa(){if(tt===``)return;let e=tt;tt=``,a.remoteUrl.value=e,a.remoteForm.requestSubmit()}a.accountToggle.addEventListener(`click`,()=>{fa=!fa,ga(null)}),a.welcomeCreate.addEventListener(`click`,()=>{fa=!0,ga(null),a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),a.accountEmail.focus({preventScroll:!0})}),a.welcomeBrowse.addEventListener(`click`,()=>{a.directory.hidden?a.browse.click():a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(ma,`hidden`)}catch{}a.welcome.hidden=!0}),a.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=a.accountEmail.value.trim(),n=a.accountPassword.value;(async()=>{a.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${fa?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){a.accountNote.textContent=r.error??`that did not work`;return}G=r.account?.id??``,a.accountPassword.value=``,ga(r.account?.email??t),ar(),Sa()}catch{a.accountNote.textContent=`could not reach nixamp.com`}finally{a.accountSubmit.disabled=!1}})()}),a.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}G=``,ga(null),_r(),P.close(),C=-1,l=`local`,x=`idle`,he=``,a.remoteUrl.value=``,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,a.listenOnly.hidden=!0,Ya(!1);try{localStorage.removeItem(an)}catch{}S=`Signed out, and disconnected from the server.`,ar(),z()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(tt=t,_=e.get(`play`)??``,ie=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t,S=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(a.linkUrl.value=n,t!==``&&_===``?_=`link:${n}`:t===``&&(rt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=Fe(r);t?(tt=t.view,_=t.what,ie=Math.max(0,Number(e.get(`t`)??`0`)||0),a.remoteUrl.value=t.view,S=`Opening the stream you were sent…`):(a.linkUrl.value=r,rt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Ca=[`zone-top`,`zone-main`],wa=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,Ta=e=>e.parentElement&&Ca.includes(e.parentElement.id)?e.parentElement:null,Ea=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Da=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>wa(e)&&Ta(e)!==null),Oa=e=>e.dataset.title??e.id,ka=new Map,Aa=Da().map((e,t)=>(ka.set(e.id,{zone:Ta(e)?.id??``,col:Ea(e),index:t}),e.id)),Q=yt();try{Q=Ct(localStorage.getItem(vt))}catch{}let ja=()=>Q.order.length>0||Object.keys(Q.placement).length>0;function Ma(){Q.order=Da().map(e=>e.id);try{localStorage.setItem(vt,wt(Q))}catch{}}function Na(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 Pa(){if(e)return;for(let e of Da()){let t=Q.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Ca.includes(i.id)&&Na(e,i,r===`a`||r===`b`?r:``)}let t=Tt(Da().map(e=>e.id),Q.order);for(let e of Ca){let n=document.getElementById(e);if(!n)continue;let r=[...n.children].filter(wa),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 Da())e.toggleAttribute(`data-collapsed`,Q.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Q.closed.includes(e.id))}function Fa(e,t){e.toggleAttribute(`data-collapsed`,t),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-closed`))),e.querySelector(`.panel-tools [aria-expanded]`)?.setAttribute(`aria-expanded`,String(!t)),Q.collapsed=Et(Q.collapsed,e.id,t),Ma(),Ha()}function Ia(e,t){let n=e.contains(document.activeElement);e.toggleAttribute(`data-closed`,t),e===a.panelsPanel&&t&&(e.hidePopover?.(),e.hidden=!0),e===a.panelsPanel&&a.panelsToggle.setAttribute(`aria-expanded`,String(!t&&!e.hidden&&!e.hasAttribute(`data-collapsed`))),e===a.partiesPanel&&!t&&_r(),t&&n&&a.panelsToggle.focus({preventScroll:!0}),Q.closed=Et(Q.closed,e.id,t),Ma(),Ha()}function La(e,t,n){let r=Ta(t);r&&e!==t&&(Na(e,r,Ea(t)),n?t.after(e):t.before(e),Q.placement[e.id]=`${r.id}:${Ea(t)}`,Ma(),Ha())}let Ra=null,za=()=>{for(let e of Da())e.classList.remove(`drop-before`,`drop-after`)},Ba=(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 Va(){for(let e of Da()){let t=Oa(e);e.setAttribute(`aria-label`,t);let n=e.querySelector(`:scope > .panel-heading`);if(n||(n=document.createElement(`h2`),n.className=`panel-heading`,e.prepend(n)),n.textContent!==t&&(n.textContent=t),e.querySelector(`:scope > .panel-tools`))continue;let r=document.createElement(`span`);r.className=`panel-tools`;let i=Ba(`≡`,`Move ${Oa(e)}: Alt plus Up or Down, or drag`,()=>void 0);i.addEventListener(`keydown`,t=>{if(!t.altKey||![`ArrowUp`,`ArrowDown`].includes(t.key))return;t.preventDefault(),t.stopPropagation();let n=Da().filter(t=>Ta(t)===Ta(e)&&Ea(t)===Ea(e)),r=n[n.indexOf(e)+(t.key===`ArrowUp`?-1:1)];r&&(La(e,r,t.key===`ArrowDown`),i.focus({preventScroll:!0}))}),i.classList.add(`grip`),i.draggable=!0,i.addEventListener(`dragstart`,t=>{Ra=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),i.addEventListener(`dragend`,()=>{Ra=null,e.classList.remove(`dragging`),za()});let a=Ba(`▁`,`Shade ${Oa(e)} to its title`,()=>Fa(e,!e.hasAttribute(`data-collapsed`)));a.setAttribute(`aria-expanded`,String(!e.hasAttribute(`data-collapsed`)));let o=Ba(`✕`,`Hide ${Oa(e)}; the Panels list turns it back on`,()=>Ia(e,!0));e.id===`transcript-panel`&&r.append(q.button()),r.append(i,a,o),e.prepend(r),e.addEventListener(`dragover`,t=>{if(!Ra||Ra===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;za(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Ra||Ra===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);za(),La(Ra,e,n)})}}function Ha(){if(a.panelsPanel.hidden||a.panelsList.contains(document.activeElement))return;let e=Da().filter(e=>e!==a.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,g(i,`aria-label`,()=>`${Oa(e)} on`),i.addEventListener(`change`,()=>Ia(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,h(a,()=>Oa(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?`nothing to show right now`:``,t.append(r,o),t});a.panelsList.replaceChildren(...e)}function Ua(){Q=yt();for(let e of Aa){let t=document.getElementById(e),n=ka.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(Na(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Q.order=[...Aa],Pa(),Q=yt();try{localStorage.removeItem(vt)}catch{}Ha()}function Wa(e){if(!e||ja())return;let t=Ta(a.adminPanel);if(!t)return;let n=[...t.children].filter(wa).find(e=>Ea(e)===Ea(a.adminPanel));n&&n!==a.adminPanel&&n.before(a.adminPanel),a.adminPanel.removeAttribute(`data-collapsed`),a.adminPanel.removeAttribute(`data-closed`)}a.panelsToggle.addEventListener(`click`,e=>{e.preventDefault();let t=a.panelsPanel.hidden||a.panelsPanel.hasAttribute(`data-closed`)||a.panelsPanel.hasAttribute(`data-collapsed`);a.panelsPanel.hidden=!t,a.panelsToggle.setAttribute(`aria-expanded`,String(t)),t?(a.panelsPanel.hasAttribute(`data-closed`)&&Ia(a.panelsPanel,!1),a.panelsPanel.hasAttribute(`data-collapsed`)&&Fa(a.panelsPanel,!1),Ha(),a.panelsPanel.showPopover?.(),a.panelsList.querySelector(`input`)?.focus({preventScroll:!0})):a.panelsPanel.hidePopover?.()}),a.panelsPanel.addEventListener(`toggle`,()=>{let e=a.panelsPanel.matches(`:popover-open`);a.panelsToggle.setAttribute(`aria-expanded`,String(e&&!a.panelsPanel.hasAttribute(`data-collapsed`))),e||(a.panelsPanel.hidden=!0)}),a.panelsPanel.addEventListener(`keydown`,e=>{e.key===`Escape`&&typeof a.panelsPanel.hidePopover!=`function`&&(a.panelsPanel.hidden=!0,a.panelsToggle.setAttribute(`aria-expanded`,`false`),a.panelsToggle.focus({preventScroll:!0}))}),a.panelsReset.addEventListener(`click`,Ua),new MutationObserver(()=>{Va(),Ha()}).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Va(),Pa(),_a(),va(),ar(),Wn(),a.browse.addEventListener(`click`,()=>{if(!a.directory.hidden){a.directory.hidden=!0;return}Xn(),a.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),a.disconnect.addEventListener(`click`,()=>{P.close(),a.listenOnly.hidden=!0,C=-1,a.sharePanel.hidden=!0,a.publishPanel.hidden=!0,a.adminPanel.hidden=!0,a.catalogsPanel.hidden=!0,g(a.catalogsPanel,`data-title`,()=>f(`Catalogs on this server`)),u=``,ue=``,wr(),Ya(!1),l=`local`,x=`idle`,he=``,z()});async function Ga(){if(l!==`remote`||P.shareLink===``){a.sharePanel.hidden=!0;return}a.sharePanel.hidden=!1;let e=lo(),t=globalThis.location.origin;a.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,a.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,a.sharePhone.hidden=!0,a.shareSend.hidden=!0,a.liveControls.hidden=!0;let n=``;try{let e=await fetch(`/api/directory`);e.ok&&(n=(await e.json()).callIn??``)}catch{}let r=null;try{let n=await fetch(P.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ue=r.url,a.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(Be=r.live,He=r.live?r.code:``,Je=n,a.liveControls.hidden=a.adminPanel.hidden||!r.possible,a.goLive.hidden=r.live,a.stopLive.hidden=!r.live,a.sharePhone.hidden=!1,!r.live){a.sharePhone.textContent=r.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!n){a.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,a.shareSend.hidden=!1;return}a.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),go(n),document.createTextNode(` and key `),go(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),a.shareSend.hidden=!1}}let Ka=null,qa=null,Ja=0,Ya=e=>{Ka&&clearInterval(Ka),Ka=null,Ja+=1,qa?.abort(),qa=null,E=null,gr(),e&&($(),Ka=setInterval(()=>{document.visibilityState===`visible`&&$()},2e3))};async function $(){if(l!==`remote`||qa)return;let e=new AbortController;qa=e;let t=Ja,n=P.url(`/api/streams`),r=setTimeout(()=>e.abort(),8e3);try{let r=await fetch(n,{signal:e.signal,cache:`no-store`});if(!r.ok)return;let i=await r.json();if(e.signal.aborted||t!==Ja||l!==`remote`||n!==P.url(`/api/streams`))return;ee=i.server.carries!==!1,i.server.name&&i.server.name!==u&&(u=i.server.name,a.catalogsPanel.setAttribute(`data-title`,`Catalogs on ${u}`),wr()),E=i,uo(i),z(),Xa(i)}catch{}finally{clearTimeout(r),qa===e&&(qa=null)}}function Xa(e){gr()}function Za(e){let t=L(),n=e.restreams??[],r=[],i=e.server.playing,o=!a.adminPanel.hidden;i&&r.push(fo({key:`live`,title:me(e.server.nowPlaying)||e.server.name,detail:[i?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${me(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:i?`Join party`:o?`Start the stream`:`Nothing playing`,onPlay:()=>{if(i){eo(e.server.nowPlaying);return}o&&$a()},link:e.server.live?e.server.url:``,...i?{page:co(`live`)}:{},direct:i?P.url(`/api/live`):``}));for(let e of n)r.push(fo({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:()=>{fn(e.at)},link:``,direct:P.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=P.url(`/api/channels/${encodeURIComponent(t.id)}`),i=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&i.push(`☎ ${t.code}`),t.redials&&i.push(`redialled ${t.redials}×`),o&&t.error&&i.push(t.error),r.push(fo({key:`channel:${t.id}`,title:t.name,detail:i.join(` · `),onPlay:()=>{to({id:t.id,name:t.name,video:e,art:t.art})},link:n,page:co(`channel:${t.id}`),direct:n,onRestart:o&&t.via===`pull`?()=>{io(t.id,t.name)}:void 0,onStop:o||mt&&G!==``&&t.startedBy===G?()=>{oo(t.id,t.name)}:void 0,onRename:o||mt&&G!==``&&t.startedBy===G?()=>{ao(t.id,t.name)}:void 0}))}return r}async function Qa(){if(l===`remote`)try{if((await fetch(P.media(I(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;S=G===``?`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.`,G===``&&a.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),z()}catch{}}async function $a(){V(`Starting the stream on the server…`);try{await P.send({type:`play`,index:Math.max(0,I())})}catch{V(`could not reach the server`);return}await eo(b.tracks[I()]?.title??``),V(`Playing to the room. Anybody with the view link sees this.`),await $()}async function eo(e){C=-1,w=null,T={kind:`live`},ze(e,`auto`),await Ce(()=>N.load({title:e||`Live`,artist:``,album:``,duration:0,url:P.url(`/api/live`),video:!0,objectUrl:!1},!0)),In(!0),S=`Watching what this server is playing. Everyone here sees the same thing.`,z()}async function to(e,t=!0,n){C=-1,w=e,t&&(ye=0),t&&(T=n??{kind:`channel`}),t&&ze(e.name,T?.link||rn(e.name)?`auto`:`channel`);let r=e.video&&bt();await Ce(()=>N.load({title:e.name,artist:``,album:``,duration:0,url:P.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),In(e.video),w===e&&(S=`Watching ${e.name}, live on this server.`),z()}function no(){let e=w;return e?Ye?!0:ye>=5?(S=`${e.name} stopped, and did not come back.`,w=null,T=null,z(),!0):(ye+=1,S=`${e.name} started over; rejoining…`,z(),Ye=setTimeout(()=>{Ye=null,w===e&&to(e,!1)},2e3),!0):!1}function ro(e){a.partiesNote.hidden=!1,a.partiesNote.textContent=e,V(e)}async function io(e,t){ro(`Restarting ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));ro(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{ro(`could not reach the server`)}$()}async function ao(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){ro(`Renaming ${t}…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));ro(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{ro(`could not reach the server`)}w?.id===e&&(w={...w,name:r}),$(),z()}}async function oo(e,t){ro(`Taking ${t} off the air…`);try{let n=await fetch(P.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));ro(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{ro(`could not reach the server`)}w?.id===e&&(w=null,N.stop()),$()}async function so(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{S=e,z();return}n===`✓`||n===`✓`?s(t,`check`):h(t,()=>f(n)),setTimeout(()=>{t.innerHTML=r},1200)}function co(e,t=0){let n=lo();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 lo(){if(ue!==``)return ue;let e=l===`remote`?P.shareLink:``;return/\/admin\//.test(e)?``:e}function uo(e){if(_===``)return;let t=_;if(t===`live`){_=``,e.server.playing?eo(e.server.nowPlaying):(S=`Nothing is playing on this server right now.`,z());return}if(t.startsWith(`link:`)){_=``,Rn(t.slice(5));return}if(t.startsWith(`golive:`)){_=``,a.linkUrl.value=t.slice(7),ar().then(()=>Gn());return}if(t.startsWith(`track:`)){_=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&fn(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&&(_=``,to({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function fo(e){let t=document.createElement(`li`);t.className=`party-row`,t.dataset.liveKey=`${ne(P.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`,Ht(o,e.playLabel??`Join party`),o.addEventListener(`click`,e.onPlay),a.append(o);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,s(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};(e.link||e.page)&&a.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;so(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{so(e.direct??``,t,`✓`)})),e.onRestart&&a.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(c(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(c(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),n.className=`party-name`,n.title=`${e.title} · ${e.detail}`,i.hidden=!0,g(o,`aria-label`,()=>`${f(e.playLabel??`Join party`)}: ${e.title}`);let l=document.createElement(`details`);l.className=`party-actions`;let u=document.createElement(`summary`);return u.textContent=`⋯`,g(u,`aria-label`,()=>`${f(`Show more`)}: ${e.title}`),a.removeChild(o),l.append(u,a),t.append(n,o),a.childElementCount&&t.append(l),t}let po=``;function mo(e,t){po=e;let n=e!==``&&t===e;a.loadHome.hidden=e===``,a.homeNote.hidden=e===``,e!==``&&(a.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,a.loadHome.disabled=!1)}a.loadHome.addEventListener(`click`,()=>{po!==``&&(a.loadHome.disabled=!0,V(`Reading this server's files…`),(async()=>{try{let e=await fetch(P.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:po})}),t=await e.json();V(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{V(`could not reach the server`)}finally{a.loadHome.disabled=!1}})())});let ho=async e=>{a.goLive.disabled=!0,a.stopLive.disabled=!0,a.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(P.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();a.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${n.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:n.error??`that did not work`}catch{a.shareNote.textContent=`could not reach the server`}finally{a.goLive.disabled=!1,a.stopLive.disabled=!1,await Ga()}};a.goLive.addEventListener(`click`,()=>void ho(!0)),a.stopLive.addEventListener(`click`,()=>void ho(!1));function go(e){let t=document.createElement(`b`);return t.textContent=e,t}a.shareCopy.addEventListener(`click`,()=>{a.shareLink.select(),navigator.clipboard?.writeText(a.shareLink.value).then(()=>{a.shareNote.textContent=`Copied. Send it to anybody.`},()=>{a.shareNote.textContent=`Copy it from the box above.`})}),a.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=a.shareTo.value.trim();t!==``&&(async()=>{a.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:lo()})}),n=await e.json();a.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(a.shareTo.value=``)}catch{a.shareNote.textContent=`could not send that`}})()}),a.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(cn,a.listenHere.checked?`1`:`0`)}catch{}l===`remote`&&(async()=>{a.listenHere.checked?(await P.send({type:`stop`}),await pn(b.index)):(N.stop(),C=-1),z()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)&&!t?.closest(`input, textarea, select, button, a, [contenteditable], [role=button]`)&&t===a.transport)switch(e.key){case` `:e.preventDefault(),mn();return;case`s`:gn();return;case`n`:case`ArrowRight`:hn(1);return;case`p`:case`ArrowLeft`:hn(-1);return;case`ArrowDown`:e.preventDefault(),fn(Math.min(F()-1,I()+1));return;case`ArrowUp`:e.preventDefault(),fn(Math.max(0,I()-1));return}});let _o=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),_o=e,a.install.hidden=!1}),a.install.addEventListener(`click`,()=>{_o?.prompt(),_o=null,a.install.hidden=!0});try{let e=localStorage.getItem(sn);e!==null&&(a.volume.value=String(Math.round(Number(e)*100)),N.volume=Number(e));let t=localStorage.getItem(an);t&&(a.remoteUrl.value=t),localStorage.getItem(cn)===`0`&&(a.listenHere.checked=!1)}catch{}(async()=>{if(a.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Ke(e)===null)return;let t=await Ue(e);t&&t.trackCount!==0&&(a.remoteUrl.value=e,l=`remote`,S=``,P.connect(e),Ya(!0),Gi(),z())})(),_r();let vo=()=>{document.visibilityState===`visible`&&!a.partiesPanel.hasAttribute(`data-closed`)&&_r()},yo=setInterval(vo,2e3);document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&(_r(),$())}),globalThis.addEventListener(`pagehide`,()=>{clearInterval(yo),Ka&&clearInterval(Ka),mr?.abort(),qa?.abort(),mr=null,qa=null,Ja+=1}),globalThis.addEventListener(`pageshow`,e=>{e.persisted&&(clearInterval(yo),yo=setInterval(vo,2e3),vo(),l===`remote`&&Ya(!0))}),(()=>{if(un||tt!==``)return;let e=()=>N.source!==``||N.playing||Se()||w!==null,t=async()=>{try{let e=await(await fetch(`/jingles/index.json`)).json();if(Array.isArray(e)&&e.length>0){let t=e[Math.floor(Math.random()*e.length)];if(typeof t==`string`)return`/jingles/${t}`}}catch{}return``},n=new Audio;n.volume=.7;let r=()=>{un=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||N.playJingle(n).catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,N.playJingle(n).then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),z(),requestAnimationFrame(Nn)}dn(),ae(),v(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{l as t};
|