nixamp 0.23.4 → 0.23.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -88,6 +88,7 @@ import { Rooms } from "./rooms.ts";
88
88
  import { Trollbox, TrollboxError, fallbackHandle, roomFor } from "./trollbox.ts";
89
89
  import { MAX_BYTES as SPEECH_BYTES, Speech, SpeechError, isWav, languageOf } from "./speech.ts";
90
90
  import { Captions } from "./captions.ts";
91
+ import { Profiles, spokenLine, telnyxVoiceFor, voicesFromEnv } from "./voices.ts";
91
92
  import { confirm, DEFAULT_DIRECTORY, Publisher } from "./publish.ts";
92
93
  import {
93
94
  applyRemoteConfig,
@@ -1733,6 +1734,8 @@ export interface HandlerOptions {
1733
1734
  trollbox?: Trollbox;
1734
1735
  /** Speech to text: a line said out loud, heard here. Needs the optional model. */
1735
1736
  speech?: Speech;
1737
+ /** Other people's OpenProfiles, for the voice their lines are read in. */
1738
+ profiles?: Profiles;
1736
1739
  /** Tickets: a paid pass to one event's room. Absent means every show is free. */
1737
1740
  tickets?: Tickets;
1738
1741
  /**
@@ -2703,6 +2706,33 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
2703
2706
  // Separate from the address on purpose. The address is a credential and
2704
2707
  // a way to reach somebody; publishing it in a directory listing or an
2705
2708
  // invite would be publishing what they log in with.
2709
+ /**
2710
+ * A trollbox line, read aloud to whoever is on the phone in that room.
2711
+ * The room's code comes from the directory (one per channel, one for
2712
+ * the server's own stream), the voice from the author's account or
2713
+ * OpenProfile. Never awaited by the poster: the phone is a side effect
2714
+ * of the chat, and a slow Telnyx must not slow the box.
2715
+ */
2716
+ const readOnThePhone = (where: { server: string; channel: string }, authorId: string, handle: string, body: string): void => {
2717
+ const partyLine = options.partyLine;
2718
+ const listing = (options.directory?.list() ?? []).find((one) => {
2719
+ try {
2720
+ return new URL(one.url).origin === where.server;
2721
+ } catch {
2722
+ return false;
2723
+ }
2724
+ });
2725
+ if (!partyLine || !listing) return;
2726
+ const code = where.channel === "live" || where.channel === "main" ? listing.code : listing.channelCodes[where.channel] ?? "";
2727
+ if (!code || !partyLine.hasCallers(code)) return;
2728
+ void (async () => {
2729
+ const persona = (await options.handles?.persona(authorId)) ?? { handle, voice: "", profile: "" };
2730
+ const profile = persona.profile && options.profiles ? await options.profiles.voiceOf(persona.profile) : null;
2731
+ const voice = telnyxVoiceFor({ userId: authorId, voice: persona.voice, profile }, voicesFromEnv());
2732
+ await partyLine.say(code, spokenLine(handle, body), voice);
2733
+ })().catch(() => undefined);
2734
+ };
2735
+
2706
2736
  /*
2707
2737
  * The trollbox: the chat for one live room, keyed by the server and
2708
2738
  * the channel so every viewer of a stream is in the same box whichever
@@ -2751,6 +2781,7 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
2751
2781
  }
2752
2782
  const handle = (await options.handles?.of(who.id)) || fallbackHandle(who.id);
2753
2783
  const line = await trollbox.post(where, who.id, handle, body.body);
2784
+ readOnThePhone(where, who.id, line.handle, line.body);
2754
2785
  json(response, 201, { message: { id: line.id, handle: line.handle, body: line.body, createdAt: line.createdAt, mine: true } });
2755
2786
  return;
2756
2787
  }
@@ -2819,6 +2850,7 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
2819
2850
  if (where && options.trollbox && heard.text !== "") {
2820
2851
  const handle = (await options.handles?.of(who.id)) || fallbackHandle(who.id);
2821
2852
  const line = await options.trollbox.post(where, who.id, handle, heard.text);
2853
+ readOnThePhone(where, who.id, line.handle, line.body);
2822
2854
  json(response, 201, {
2823
2855
  text: heard.text, seconds: heard.seconds, model: speech.model,
2824
2856
  message: { id: line.id, handle: line.handle, body: line.body, createdAt: line.createdAt, mine: true },
@@ -2841,24 +2873,38 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
2841
2873
  return;
2842
2874
  }
2843
2875
 
2876
+ // The handle, and since 0.23.4 the voice a line is read in on the
2877
+ // phone and the OpenProfile it may be read from. Any of the three may
2878
+ // be sent alone; what is not sent is kept.
2844
2879
  if (request.method === "GET") {
2845
- json(response, 200, { handle: await handles.of(who.id) });
2880
+ const persona = await handles.persona(who.id);
2881
+ json(response, 200, { ...persona, handle: persona.handle || fallbackHandle(who.id), chosen: persona.handle !== "" });
2846
2882
  return;
2847
2883
  }
2848
2884
  if (request.method === "PUT" || request.method === "POST") {
2849
- let body: { handle?: unknown };
2885
+ let body: { handle?: unknown; voice?: unknown; profile?: unknown };
2850
2886
  try {
2851
2887
  body = JSON.parse(await readBody(request)) as typeof body;
2852
2888
  } catch {
2853
2889
  json(response, 400, { error: "bad JSON" });
2854
2890
  return;
2855
2891
  }
2856
- const claimed = await handles.claim(who.id, body.handle);
2857
- if (claimed.error) {
2858
- json(response, 409, { error: claimed.error });
2859
- return;
2892
+ if (body.handle !== undefined) {
2893
+ const claimed = await handles.claim(who.id, body.handle);
2894
+ if (claimed.error) {
2895
+ json(response, 409, { error: claimed.error });
2896
+ return;
2897
+ }
2898
+ }
2899
+ if (body.voice !== undefined || body.profile !== undefined) {
2900
+ const described = await handles.describe(who.id, fallbackHandle(who.id), { voice: body.voice, profile: body.profile });
2901
+ if (described.error) {
2902
+ json(response, 422, { error: described.error });
2903
+ return;
2904
+ }
2860
2905
  }
2861
- json(response, 200, { handle: claimed.handle });
2906
+ const persona = await handles.persona(who.id);
2907
+ json(response, 200, { ...persona, handle: persona.handle || fallbackHandle(who.id), chosen: persona.handle !== "" });
2862
2908
  return;
2863
2909
  }
2864
2910
  json(response, 405, { error: "GET or PUT" });
@@ -5824,6 +5870,8 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
5824
5870
  ...(rooms ? { rooms } : {}),
5825
5871
  ...(trollbox ? { trollbox } : {}),
5826
5872
  ...(speech ? { speech } : {}),
5873
+ // Other people's OpenProfiles, read for the voice a line is spoken in.
5874
+ ...(accounts ? { profiles: new Profiles() } : {}),
5827
5875
  ...(tickets ? { tickets } : {}),
5828
5876
  ...(authServer ? { authServer } : {}),
5829
5877
  ...(parties ? { parties } : {}),
package/src/voices.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * The voice a person's words are read in, on the phone.
3
+ *
4
+ * A trollbox line is text; the party line is a phone call. Reading one into
5
+ * the other needs a voice, and the voice should be theirs as far as a
6
+ * machine can manage: a man's line in a man's voice, a woman's in a woman's,
7
+ * anybody else's in whichever they asked for. Where that comes from, in
8
+ * order: the voice they set on their nixamp account; their OpenProfile
9
+ * (`Voice`, then `Gender`, then `Pronouns`; see logicsrc.com/openprofile);
10
+ * and failing both, one picked from their id, so the same person is always
11
+ * the same voice even when nobody was told which.
12
+ *
13
+ * The voices are Telnyx's Kokoro ones: an open-weights model, no bill beyond
14
+ * the call. ElevenLabs or anything else Telnyx speaks is a configuration
15
+ * away, per sex, because "better" and "paid" are the same word there.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+
19
+ export type VoiceKind = "female" | "male" | "";
20
+
21
+ /** Kokoro, through Telnyx: af_heart is the default woman, am_adam the default man. */
22
+ export const DEFAULT_VOICES: Record<Exclude<VoiceKind, "">, string> = {
23
+ female: "Telnyx.KokoroTTS.af_heart",
24
+ male: "Telnyx.KokoroTTS.am_adam",
25
+ };
26
+
27
+ /** The word a person used for themselves, as a voice: female, male, or nothing to go on. */
28
+ export function voiceKindOf(value: unknown): VoiceKind {
29
+ if (typeof value !== "string") return "";
30
+ const word = value.trim().toLowerCase();
31
+ if (word === "") return "";
32
+ if (/^(f|female|woman|women|girl|she|her|she\/her|fem|feminine|lady)$/.test(word)) return "female";
33
+ if (/^(m|male|man|men|boy|he|him|he\/him|masc|masculine|guy)$/.test(word)) return "male";
34
+ if (/^she\b/.test(word)) return "female";
35
+ if (/^he\b/.test(word)) return "male";
36
+ return "";
37
+ }
38
+
39
+ export interface ProfileVoice {
40
+ /** What the profile said outright, when it did: female, male, or a provider voice id. */
41
+ voice: string;
42
+ gender: string;
43
+ pronouns: string;
44
+ }
45
+
46
+ /**
47
+ * The parts of an OpenProfile.md that say how somebody sounds. The identity
48
+ * block is the bullets under the first `#`; `Gender` may also sit under
49
+ * `## Match`, where the spec put it first. Everything else is ignored.
50
+ */
51
+ export function readProfileVoice(markdown: string): ProfileVoice {
52
+ const found: ProfileVoice = { voice: "", gender: "", pronouns: "" };
53
+ let section = "";
54
+ let started = false;
55
+ for (const raw of markdown.split(/\r?\n/)) {
56
+ const line = raw.trim();
57
+ if (line.startsWith("# ") && !started) {
58
+ started = true;
59
+ continue;
60
+ }
61
+ if (line.startsWith("## ")) {
62
+ section = line.slice(3).trim().toLowerCase();
63
+ continue;
64
+ }
65
+ const inIdentity = started && section === "";
66
+ const inMatch = /^(match|dating|matching|partner|looking for)$/.test(section);
67
+ if (!inIdentity && !inMatch) continue;
68
+ const item = /^[-*]\s+(?:\*\*)?([A-Za-z ]+?)(?:\*\*)?\s*:\s*(.+)$/.exec(line);
69
+ if (!item) continue;
70
+ const key = (item[1] ?? "").trim().toLowerCase();
71
+ const value = (item[2] ?? "").trim();
72
+ if (key === "voice" && !found.voice) found.voice = value;
73
+ if (key === "gender" && !found.gender) found.gender = value;
74
+ if (key === "pronouns" && !found.pronouns) found.pronouns = value;
75
+ }
76
+ return found;
77
+ }
78
+
79
+ /**
80
+ * The Telnyx voice for somebody, from what is known about them. A voice
81
+ * named outright (`ElevenLabs.…`, `Telnyx.KokoroTTS.…`, `Polly.…`) is used
82
+ * as written; a sex picks the configured voice for it; nothing at all
83
+ * picks one by the account id, so it stays the same tomorrow.
84
+ */
85
+ export function telnyxVoiceFor(
86
+ who: { userId: string; voice?: string; profile?: ProfileVoice | null },
87
+ voices: Record<Exclude<VoiceKind, "">, string> = DEFAULT_VOICES,
88
+ ): string {
89
+ const asked = (who.voice ?? "").trim();
90
+ if (asked.includes(".")) return asked;
91
+ const fromProfile = who.profile?.voice.trim() ?? "";
92
+ if (fromProfile.includes(".")) return fromProfile;
93
+ const kind = voiceKindOf(asked) || voiceKindOf(fromProfile) || voiceKindOf(who.profile?.gender) || voiceKindOf(who.profile?.pronouns);
94
+ if (kind) return voices[kind];
95
+ const digit = createHash("sha1").update(who.userId).digest()[0] as number;
96
+ return digit % 2 === 0 ? voices.female : voices.male;
97
+ }
98
+
99
+ /** The voices to use per sex, from the environment when it says so. */
100
+ export function voicesFromEnv(env: NodeJS.ProcessEnv = process.env): Record<Exclude<VoiceKind, "">, string> {
101
+ return {
102
+ female: env["NIXAMP_VOICE_FEMALE"] || DEFAULT_VOICES.female,
103
+ male: env["NIXAMP_VOICE_MALE"] || DEFAULT_VOICES.male,
104
+ };
105
+ }
106
+
107
+ /** What a line sounds like read aloud: who said it, then what. */
108
+ export function spokenLine(handle: string, body: string): string {
109
+ const said = body.replace(/\s+/g, " ").trim();
110
+ return `${handle.replace(/-/g, " ")} says: ${said}`;
111
+ }
112
+
113
+ /**
114
+ * Somebody's OpenProfile, fetched and kept an hour. A profile is read on
115
+ * every line they say, and a line a second is the trollbox's own limit.
116
+ */
117
+ export class Profiles {
118
+ private readonly kept = new Map<string, { at: number; voice: ProfileVoice }>();
119
+
120
+ constructor(
121
+ private readonly fetcher: typeof fetch = fetch,
122
+ private readonly now: () => number = () => Date.now(),
123
+ private readonly ttlMs = 60 * 60 * 1000,
124
+ ) {}
125
+
126
+ async voiceOf(url: string): Promise<ProfileVoice | null> {
127
+ let where: URL;
128
+ try {
129
+ where = new URL(url);
130
+ if (where.protocol !== "https:" && where.protocol !== "http:") return null;
131
+ } catch {
132
+ return null;
133
+ }
134
+ const had = this.kept.get(where.href);
135
+ if (had && this.now() - had.at < this.ttlMs) return had.voice;
136
+ try {
137
+ const response = await this.fetcher(where.href, {
138
+ headers: { accept: "text/markdown, text/plain;q=0.9, */*;q=0.1" },
139
+ signal: AbortSignal.timeout(5000),
140
+ });
141
+ if (!response.ok) return had?.voice ?? null;
142
+ const text = (await response.text()).slice(0, 64 * 1024);
143
+ const voice = readProfileVoice(text);
144
+ this.kept.set(where.href, { at: this.now(), voice });
145
+ if (this.kept.size > 5000) {
146
+ for (const [key, one] of this.kept) if (this.now() - one.at > this.ttlMs) this.kept.delete(key);
147
+ }
148
+ return voice;
149
+ } catch {
150
+ return had?.voice ?? null;
151
+ }
152
+ }
153
+ }
@@ -1 +1 @@
1
- import{t as e}from"./index-CjxlA6ia.js";var t=3;async function n(n){let{media:r,src:i,isTv:a}=n,{default:o}=await e(async()=>{let{default:e}=await import(`./hls-n74Cnh8A.js`);return{default:e}},[]);if(!o.isSupported())return n.onError(`This browser cannot play HLS streams.`),{destroy:()=>void 0,levels:()=>[]};let s=new o({...a?{maxBufferLength:60,maxMaxBufferLength:120,backBufferLength:30,liveSyncDurationCount:4}:{backBufferLength:90},enableWorker:!0}),c=0,l=!1;s.on(o.Events.ERROR,(e,r)=>{if(!l&&r.fatal){if(c>=t){n.onError(`This stream kept failing and has been stopped.`),s.destroy();return}switch(c+=1,r.type){case o.ErrorTypes.NETWORK_ERROR:n.onNotice(`Reconnecting…`),s.startLoad();break;case o.ErrorTypes.MEDIA_ERROR:n.onNotice(`Recovering…`),s.recoverMediaError();break;default:n.onError(`This stream could not be played.`),s.destroy()}}}),s.on(o.Events.MANIFEST_PARSED,()=>{l||(n.onNotice(null),n.onReady?.({live:s.levels.length>0&&!Number.isFinite(r.duration),levels:u()}))}),s.on(o.Events.LEVEL_LOADED,(e,t)=>{l||n.onReady?.({live:t.details.live,levels:u()})}),s.on(o.Events.FRAG_BUFFERED,()=>{l||n.onNotice(null)});function u(){return s.levels.map((e,t)=>({index:t,height:e.height||null,bitrate:e.bitrate||null,label:e.height?`${String(e.height)}p`:`${String(Math.round((e.bitrate||0)/1e3))}k`}))}return s.loadSource(i),s.attachMedia(r),{destroy(){l=!0,s.destroy()},levels:u,setLevel(e){s.currentLevel=e},currentLevel:()=>s.autoLevelEnabled?-1:s.currentLevel}}export{n as createHlsEngine};
1
+ import{t as e}from"./index-zCUbE3U5.js";var t=3;async function n(n){let{media:r,src:i,isTv:a}=n,{default:o}=await e(async()=>{let{default:e}=await import(`./hls-n74Cnh8A.js`);return{default:e}},[]);if(!o.isSupported())return n.onError(`This browser cannot play HLS streams.`),{destroy:()=>void 0,levels:()=>[]};let s=new o({...a?{maxBufferLength:60,maxMaxBufferLength:120,backBufferLength:30,liveSyncDurationCount:4}:{backBufferLength:90},enableWorker:!0}),c=0,l=!1;s.on(o.Events.ERROR,(e,r)=>{if(!l&&r.fatal){if(c>=t){n.onError(`This stream kept failing and has been stopped.`),s.destroy();return}switch(c+=1,r.type){case o.ErrorTypes.NETWORK_ERROR:n.onNotice(`Reconnecting…`),s.startLoad();break;case o.ErrorTypes.MEDIA_ERROR:n.onNotice(`Recovering…`),s.recoverMediaError();break;default:n.onError(`This stream could not be played.`),s.destroy()}}}),s.on(o.Events.MANIFEST_PARSED,()=>{l||(n.onNotice(null),n.onReady?.({live:s.levels.length>0&&!Number.isFinite(r.duration),levels:u()}))}),s.on(o.Events.LEVEL_LOADED,(e,t)=>{l||n.onReady?.({live:t.details.live,levels:u()})}),s.on(o.Events.FRAG_BUFFERED,()=>{l||n.onNotice(null)});function u(){return s.levels.map((e,t)=>({index:t,height:e.height||null,bitrate:e.bitrate||null,label:e.height?`${String(e.height)}p`:`${String(Math.round((e.bitrate||0)/1e3))}k`}))}return s.loadSource(i),s.attachMedia(r),{destroy(){l=!0,s.destroy()},levels:u,setLevel(e){s.currentLevel=e},currentLevel:()=>s.autoLevelEnabled?-1:s.currentLevel}}export{n as createHlsEngine};
@@ -0,0 +1 @@
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)}})();function e(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 t(e){return e.artist?`${e.artist} — ${e.title}`:e.title}function n(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var r=new Set([`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`,`avi`,`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}var a=`modulepreload`,o=function(e){return`/`+e},s={},c=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]`),c=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=o(t,n),t=u(t),t in s)return;s[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`:a,r||(i.as=`script`),i.crossOrigin=``,i.href=t,c&&i.setAttribute(`nonce`,c),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)})},l=[[/\.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`]],u=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function d(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of u)if(t.test(e.mimeType))return n}let t=f(e.src);for(let[e,n]of l)if(e.test(t))return n;return`unknown`}function f(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function p(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 m(e,t){let n=d(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function h(e,t){let n=t.capabilities??p(),r=m({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 c(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-Dq51v8Gv.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await c(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-Dz2Fz7af.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await c(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 ee=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`]),te=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function g(e){let t=e.lastIndexOf(`.`);return t>0&&te.has(e.slice(t+1).toLowerCase())}function ne(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&ee.has(e.slice(n+1).toLowerCase())}function re(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ie(e){return e.filter(e=>ne(e.name,e.type)).sort((e,t)=>re(ae(e),ae(t))).map(e=>({title:n(e.name),artist:``,album:oe(ae(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...g(e.name)?{kind:`mpegts`}:{}}))}function ae(e){return e.webkitRelativePath||e.name}function oe(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function se(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var ce=2048;function _(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 le(e,t){return e||t===`hls`||t===`mpegts`}var ue=class{elements;handlers;attached=null;source=``;context=null;analyser=null;wired=new WeakSet;active;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(v(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 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??=new t,this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=ce,this.analyser.smoothingTimeConstant=.6,this.analyser.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()}}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.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:d({src:e.url})),r=le(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||_(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 h(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:`)||_(a),t&&await this.play()}async play(){this.analysable&&this.ensureGraph(this.active);try{await this.active.play()}catch(e){this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){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 v(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 de(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function fe(e,t){return{...t,tracks:t.tracks??e.tracks}}function y(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 b(e,t,n=``){let r=`${e===``?``:y(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function pe(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 me(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:y(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var x=null;function S(e){if(!e&&x!==null)return x;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||(x=n),n}catch{return!1}}function he(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return b(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function C(e){if(typeof e!=`object`||!e)return null;let t=e,n=de(),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 w(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var ge=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return w(this.base,e)}url(e){let t=b(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}=me(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(b(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=C(_e(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(b(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=C(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=S()){return he(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function _e(e){try{return JSON.parse(e)}catch{return null}}async function ve(e,t,n=``){try{let r=await fetch(b(e,`/api/state`,n),{signal:t});return r.ok?C(await r.json()):null}catch{return null}}function ye(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 be(e,t=``,n){let r;try{r=await fetch(b(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 xe(e,t,n=``){try{let r=await fetch(b(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 Se(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 Ce=.14,we=.02;function Te(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 Ee(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 De(e,t,n=Ce){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function Oe(e,t,n=we){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function ke(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 Ae(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 je(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function Me(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,i)===r.toLocaleDateString(t.locale,i);return n.toLocaleString(t.locale,{...i,...a?{}:{weekday:`short`},hour:`numeric`,minute:`2-digit`})}function Ne(e,t={}){let n=e.data,r=Ae(n.away,n.awayScore),i=Ae(n.home,n.homeScore),a=je(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=Me(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 Pe=`nixamp.tv`,T=/\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 Fe(e,t=``,n=1,r=null){let i=new URLSearchParams(t).get(`tv`);return i===null?r!==null&&r!==``?E(r):/\bSilk\b/.test(e)&&n===0?!0:T.test(e):E(i)}function E(e){return e!==`0`&&e!==`no`&&e!==`off`&&e!==`false`}function Ie(e){return e?12:100}function Le(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 D=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,O=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,k=/\.m3u8(\?.*)?$/i,Re=/\.(m3u|pls)(\?.*)?$/i;function ze(e){try{let t=new URL(e);return O.test(t.pathname+t.search)}catch{return!1}}function Be(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 Ve(e,t){let n=(/^#PLAYLIST:\s*(.+)$/im.exec(e)?.[1]?.replace(/[\u0000-\u001F]/g,` `).trim()??``)||Be(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(!D.test(a)&&!O.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 A(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 He(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=A(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 Re.test(o)?{kind:`list`,url:n.toString(),label:Be(n.toString())}:D.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:O.test(o)||k.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var Ue=`nixamp.panels`;function We(){return{order:[],placement:{},collapsed:[],closed:[]}}var Ge=/^[a-z][a-z0-9-]{0,63}$/,Ke=/^[a-z][a-z0-9-]{0,63}:[ab]?$/;function qe(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let r of e)typeof r==`string`&&Ge.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Je(e){if(!e)return We();let t;try{t=JSON.parse(e)}catch{return We()}if(!t||typeof t!=`object`||Array.isArray(t))return We();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))Ge.test(e)&&typeof t==`string`&&Ke.test(t)&&(r[e]=t);return{order:qe(n.order),placement:r,collapsed:qe(n.collapsed),closed:qe(n.closed)}}function Ye(e){return JSON.stringify(e)}function Xe(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 Ze(e,t,n){let r=e.filter(e=>e!==t);return n?[...r,t]:r}var Qe=16e3,$e=3e4;function et(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/aac`].find(t=>e(t))??``}function tt(e,t=Qe){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function nt(e,t){return`● ${Math.max(0,Math.floor((t-e)/1e3))}s`}var rt=`nixamp.captions`;function it(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function at(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 ot(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 st(e){try{return e(rt)!==`off`}catch{return!0}}function ct(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var lt=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,j=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,ut=/\s+(?:vs\.?|v\.?|at|@)\s+/i,dt=/^(?: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 M(e){let t=e.replace(j,``).replace(j,``).trim().split(ut);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!dt.test(t)})}function ft(e){let t=String(e??``).trim();return t===``?!1:M(t.replace(lt,``))||M(t)}var pt=`nixamp.remote`,mt=`nixamp.defaultServer`,ht=`nixamp.volume`,gt=`nixamp.listenHere`,_t=1e4,vt=!1;function N(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function yt(){let n=null;try{n=localStorage.getItem(Pe)}catch{}let r=Fe(navigator.userAgent,location.search,navigator.maxTouchPoints,n);if(document.body.classList.toggle(`tv`,r),new URLSearchParams(location.search).has(`tv`))try{localStorage.setItem(Pe,r?`1`:`0`)}catch{}let i=document.getElementById(`tv-toggle`);i&&(i.textContent=r?`TV mode: on`:`TV mode`,i.title=r?`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.`,i.addEventListener(`click`,()=>{try{localStorage.setItem(Pe,r?`0`:`1`)}catch{}let e=new URL(location.href);e.searchParams.delete(`tv`),location.replace(e.toString())}));let a=Ie(r),o={status:N(`status`),source:N(`source`),install:N(`install`),video:N(`video`),audio:N(`audio`),title:N(`title-line`),album:N(`album-line`),meta:N(`meta-line`),metaBlurb:N(`meta-blurb`),liveLine:N(`live-line`),downloadNow:N(`download-now`),wayInHere:N(`way-in-here`),embed:N(`embed`),embedFrame:N(`embed-frame`),linkForm:N(`link-form`),linkUrl:N(`link-url`),linkServer:N(`link-server`),linkGoLive:N(`link-go-live`),goLiveNow:N(`go-live-now`),elapsed:N(`elapsed`),total:N(`total`),seek:N(`seek`),fullscreen:N(`fullscreen`),copyNow:N(`copy-now`),canvas:N(`spectrum`),glyphs:N(`glyphs`),levels:N(`levels`),playlist:N(`playlist`),playlistPager:N(`playlist-pager`),crumbs:N(`crumbs`),filter:N(`filter`),playlistTitle:N(`playlist-panel`),note:N(`note`),linkNote:N(`link-note`),logList:N(`log-list`),files:N(`files`),folder:N(`folder`),remoteUrl:N(`remote-url`),remoteForm:N(`remote-form`),remoteState:N(`remote-state`),disconnect:N(`disconnect`),browse:N(`browse`),panelsToggle:N(`panels-toggle`),panelsPanel:N(`panels-panel`),panelsList:N(`panels-list`),panelsReset:N(`panels-reset`),accountForm:N(`account-form`),accountEmail:N(`account-email`),accountPassword:N(`account-password`),accountSubmit:N(`account-submit`),accountToggle:N(`account-toggle`),accountProviders:N(`account-providers`),accountPanel:N(`account-panel`),accountElsewhere:N(`account-elsewhere`),welcome:N(`welcome`),welcomeCreate:N(`welcome-create`),welcomeBrowse:N(`welcome-browse`),welcomeHide:N(`welcome-hide`),accountSignOut:N(`account-signout`),accountNote:N(`account-note`),personaForm:N(`persona-form`),personaHandle:N(`persona-handle`),personaVoice:N(`persona-voice`),personaProfile:N(`persona-profile`),personaNote:N(`persona-note`),adminPanel:N(`admin-panel`),adminNote:N(`admin-note`),adminSaid:N(`admin-said`),adminConnections:N(`admin-connections`),publishPanel:N(`publish-panel`),publishNote:N(`publish-note`),publishList:N(`publish-list`),adminRestream:N(`admin-restream`),adminReplace:N(`admin-replace`),adminSource:N(`admin-source`),adminName:N(`admin-name`),adminAdd:N(`admin-add`),homeNote:N(`home-note`),loadHome:N(`load-home`),directory:N(`directory`),recentNote:N(`recent-note`),recentList:N(`recent-list`),followingNote:N(`following-note`),followingList:N(`following-list`),serversPanel:N(`servers-panel`),serversNote:N(`servers-note`),serversList:N(`servers-list`),favoritesPanel:N(`favorites-panel`),favoritesNote:N(`favorites-note`),favoritesList:N(`favorites-list`),favHere:N(`fav-here`),partiesPanel:N(`parties-panel`),partiesNote:N(`parties-note`),partiesList:N(`parties-list`),partyForm:N(`party-form`),partyCode:N(`party-code`),connectionsNote:N(`connections-note`),connectionsList:N(`connections-list`),catalogsPanel:N(`catalogs-panel`),catalogsNote:N(`catalogs-note`),catalogsForm:N(`catalogs-form`),catalogSource:N(`catalog-source`),catalogName:N(`catalog-name`),catalogsList:N(`catalogs-list`),catalogsCrumbs:N(`catalogs-crumbs`),catalogsFilter:N(`catalogs-filter`),catalogsEntries:N(`catalogs-entries`),notifyPanel:N(`notify-panel`),notifyNote:N(`notify-note`),notifyWeb:N(`notify-web`),notifyEmail:N(`notify-email`),notifySms:N(`notify-sms`),notifyPhone:N(`notify-phone`),notifyPhoneForm:N(`notify-phone-form`),notifyPhoneNote:N(`notify-phone-note`),directoryNote:N(`directory-note`),directoryList:N(`directory-list`),onairPanel:N(`onair-panel`),onairNote:N(`onair-note`),onairList:N(`onair-list`),sharePanel:N(`share-panel`),trollboxPanel:N(`trollbox-panel`),trollboxNote:N(`trollbox-note`),trollboxList:N(`trollbox-list`),trollboxForm:N(`trollbox-form`),trollboxInput:N(`trollbox-input`),trollboxMic:N(`trollbox-mic`),trollboxEdit:N(`trollbox-edit`),trollboxEditLabel:N(`trollbox-edit-label`),transcriptPanel:N(`transcript-panel`),transcriptNote:N(`transcript-note`),transcriptOn:N(`transcript-on`),transcriptList:N(`transcript-list`),subtitle:N(`subtitle`),shareNote:N(`share-note`),shareLink:N(`share-link`),shareCopy:N(`share-copy`),sharePhone:N(`share-phone`),shareSend:N(`share-send`),liveControls:N(`live-controls`),goLive:N(`go-live`),stopLive:N(`stop-live`),shareTo:N(`share-to`),listenOnly:N(`listen-only`),listenHere:N(`listen-here`),volume:N(`volume`),prev:N(`prev`),playPause:N(`play-pause`),stop:N(`stop`),next:N(`next`),shareNow:N(`share-now`)},s={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>`},c=(e,t)=>{e.innerHTML=s[t]},l=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,u=`local`,d=``,f=[],p=``,m=!0,h=``;function ee(e){try{return new URL(e).origin}catch{return e}}let te=!1,g=``,ne=0,re=new Map,ae=e=>re.get(K(e))??null;function oe(e,t){let n=n=>{te=n,g=``,o.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),o.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,c(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`,c(i,`gear`),i.disabled=e.admin===null,i.title=e.admin?`Admin: drive this server. What plays, what is live, what is on it.`:X?`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 ce=``,_=[],le=0,v=de(),y=`idle`,x=``,S=`Pick files, or connect to a nixamp running somewhere else.`,he=!1,C=-1,w=null;function _e(e){return e?/^https?:\/\//i.test(e)?e:R.url(e):``}let Ce=0,we=0,Ae=!1,Me=()=>we>0||Ae;async function T(e){we+=1,U();try{return await e()}finally{--we,U()}}let E=null,D=null,O=null,k=null,Re=0;function Be(){o.embed.hidden||(o.embedFrame.src=`about:blank`),o.embed.hidden=!0}let A=null,Ge=``,Ke=null;function qe(e,t,n=null,r=!1){let i=`${t}|${e}`;if(Ge=i,Ke&&clearTimeout(Ke),Ke=null,!r){if(A?.key===i)return;A=null}if(u!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(R.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(Ge!==i)return;A={key:i,match:r.match??null},U();let a=A.match;a?.kind===`fixture`&&je(a)!==`post`&&(Ke=setTimeout(()=>{Ke=null,!(Ge!==i||L.source===``&&!w)&&qe(e,t,n,!0)},6e4))}).catch(()=>void 0)}let lt=!1,j=``,ut=``,dt=null,M=``,yt=``,bt=``,P=Array(24).fill(0),F=Array(24).fill(0),xt=[],I=()=>u===`remote`&&!o.listenHere.checked,St=()=>u===`remote`&&!o.adminPanel.hidden,Ct=!1,wt=()=>St()||u===`remote`&&Ct;function Tt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:o.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function Et(){if(u!==`remote`||O)return null;if(E?.catalog&&E.entry)return{kind:`entry`,catalog:E.catalog,entry:E.entry};if(w)return{kind:`channel`,id:w.id,name:w.name};let e=v.tracks[B()];return e&&(L.source!==``||I())?{kind:`track`,index:B(),name:t(e)}:null}async function Dt(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;S=`Putting ${n} on the air…`,U();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(R.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){S=s.error??`${n} would not go on the air.`,U();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(St()&&(lt?await fetch(R.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await Zi(!0)),await Mi(),Q(),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 zi({id:i,name:n,video:a},!0,t)}let o=Gi(r),s=j?` Call ${ut||`the line`} and key ${j} to talk about it.`:``;o===``?S=`${n} is on the air and you are watching it.${s}`:(await Wi(o,t,`✓`),S=`${n} is on the air and you are watching it. Link copied.${s}`),U()}catch{S=`could not reach the server`,U()}finally{t.disabled=!1}}function Ot(e,t=`Join live`){c(e,`live`),e.append(document.createTextNode(` ${t}`))}function kt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,c(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(),Dt(e(),n)}),n}let L=new ue({audio:o.audio,video:o.video},{readable:e=>R.owns(e),onTime:(e,t)=>{let n=_[le];u===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),U()},onEnded:()=>{Bi()||cn()||u===`remote`&&C<0&&!I()||Lt(1)},onState:()=>U(),onBusy:e=>{Ae!==e&&(Ae=e,U())},onError:e=>{if(!Bi()&&!(Re!==0&&Date.now()-Re<2e3)){if(k&&e===`this browser cannot play that format`){let e=k.url;if(k=null,Re=Date.now(),wt()){S=`That site will not let a page play it directly; going live with it on ${d||`the server`} instead.`,U(),o.linkUrl.value=e,fn();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.`,U();return}S=e,U(),Ii()}}}),R=new ge({onSnapshot:e=>{if(v=fe(v,e),g.startsWith(`track:`)&&v.tracks.length>0){let e=Number(g.slice(6));if(g=``,Number.isInteger(e)&&e>=0&&e<v.tracks.length){let t=ne;Ft(e).then(()=>{t>0&&(L.seek(t),setTimeout(()=>L.seek(t),600))})}}I()&&(P=e.bars.length>0?e.bars:P,F=Oe(F,P)),U()},onStatus:(e,t)=>{y=e,x=t??``,U()}}),z=()=>u===`remote`?v.tracks.length:_.length,B=()=>u===`remote`?I()||C<0?v.index:Math.min(C,Math.max(0,v.tracks.length-1)):le,V=()=>{if(w)return w.name;if(O)return O.label;let e=u===`remote`?v.tracks[B()]:_[B()];return e?t(e):`Nothing loaded.`},At=()=>w?`live on this server`:O?`playing here, in this browser`:E?.kind===`live`&&u===`remote`?`live on ${d||`this server`}`:(u===`remote`?v.tracks[B()]:_[B()])?.album||`—`;function jt(){if(u!==`remote`||w===null&&E?.kind!==`live`){o.liveLine.hidden=!0,o.liveLine.replaceChildren();return}let e=d||`this server`,t=w?w.name:D?.server.nowPlaying||V(),n=[w?`Live on ${e}: `:`Live from ${e}, now playing: `,Qi(t)],r=w?D?.channels.find(e=>e.id===w?.id)?.code??``:lt?j:``;r&&n.push(`. To talk about it, call `,Qi(ut||`the line`),` and key `,Qi(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);o.liveLine.dataset.drawn!==i&&(o.liveLine.dataset.drawn=i,o.liveLine.hidden=!1,o.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let Mt=()=>I()?v.tracks[B()]?.duration??0:L.duration,Nt=()=>I()?v.position:L.position,Pt=()=>I()?v.playing:L.playing;async function H(e){if(u===`remote`){if(I()){await R.send({type:`play`,index:e});return}await Ft(e);return}let t=_[e];t&&(le=e,w=null,E={kind:`file`},await T(()=>L.load(t,!0)),nn(t.video),rn(),U())}async function Ft(e){let t=v.tracks[e];t&&(C=e,w=null,E={kind:`file`},qe(t.title,`auto`),await T(()=>L.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:R.media(e,0),video:t.video===!0,objectUrl:!1},!0)),nn(t.video===!0),rn())}async function It(){if(I()){await R.send({type:`toggle`});return}z()!==0&&(L.playing?L.pause():L.position>0?await L.play():await H(B()),U())}async function Lt(e){let t=z();if(t!==0){if(I()){await R.send({type:e>0?`next`:`prev`});return}await H((B()+e+t)%t)}}async function Rt(){if(Be(),O=null,k=null,I()){await R.send({type:`stop`});return}w=null,E=null,L.stop(),P=Array(24).fill(0),F=[...P],U()}let zt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Bt=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],Vt=``;function Ht(){let t=[],n=``,r=null,i=w?D?.channels.find(e=>e.id===w?.id):void 0,a=L.source===``&&!w&&!(I()&&v.tracks[B()]);if(!a){w?t.push(E?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):E?.kind===`vod`?t.push(`ON DEMAND`):E?.kind===`live`?t.push(`LIVE`):u===`remote`&&I()?t.push(`ON THE SERVER`):t.push(`FILE`),!o.video.hidden&&o.video.videoWidth>0?t.push(`${o.video.videoWidth}×${o.video.videoHeight}`):o.video.hidden?t.push(`audio`):t.push(`video`),i?(t.push(i.via===`pull`?`${i.listeners} watching`:`${i.listeners} listening · over ${i.via}`),i.startedAt>0&&t.push(`on air ${e(Math.max(0,(Date.now()-i.startedAt)/1e3))}`),i.redials&&t.push(`redialled ${i.redials}×`),St()&&i.error&&t.push(i.error)):u===`remote`&&!w?(v.tracks[B()]&&z()>0&&t.push(`track ${B()+1} of ${z()}`),I()&&D&&t.push(`${D.server.playing?`playing`:`stopped`} on ${d||`the server`}`)):u===`local`&&z()>0&&t.push(`track ${B()+1} of ${z()}`),E?.catalog!==void 0&&(E.kind===`channel`?w!==null:E.kind===`vod`&&L.source!==``)&&E?.catalog&&(t.push(E.entry?.group?`${E.catalog.name} › ${E.entry.group}`:E.catalog.name),n=E.entry?.logo??``),n===``&&w&&(n=_e(i?.art??w.art));let a=A?.key===Ge?A.match:null;if(a?.kind===`fixture`)r=Ne(a),t.unshift(r.status,...r.chips);else if(a){a.image&&(n=a.image);let e=a.data;if(a.kind===`title`){a.year&&t.push(String(a.year));let n=typeof e.rating==`number`?e.rating:null;n&&t.push(`★ ${n.toFixed(1)}`);let r=Array.isArray(e.genres)?e.genres.slice(0,2).map(String):[];r.length&&t.push(r.join(` · `));let i=typeof e.runtimeMin==`number`?e.runtimeMin:0;i&&t.push(`${i} min`)}else if(a.kind===`channel`){let n=typeof e.country==`string`?e.country:``,r=Array.isArray(e.categories)?e.categories.slice(0,2).map(String):[],i=typeof e.network==`string`?e.network:``;n&&t.push(n),r.length&&t.push(r.join(` · `)),i&&t.push(i)}}if(w&&E?.link){let e=``;try{e=new URL(E.link.url).hostname.replace(/^www\./,``)}catch{}t.push(E.link.extractor&&E.link.extractor!==`direct`&&E.link.extractor!==`generic`?`${E.link.extractor} · ${e}`:e||`link`)}lt&&j&&I()&&!w&&E?.kind!==`live`&&t.push(ut?`☎ ${ut} · key ${j}`:`☎ code ${j}`)}let s=A?.key===Ge?A.match:null,c=!a&&!r&&s?.summary?s.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${c}`;if(l===Vt)return;Vt=l,o.meta.hidden=t.length===0,o.metaBlurb.textContent=c,o.metaBlurb.hidden=c===``;let f=[];if(r){let e=document.createElement(`div`);e.className=`meta-score`;let t=(e,t)=>{let n=[],i=document.createElement(`span`);if(i.className=`meta-team`,i.textContent=e.name,n.push(i),r?.state!==`pre`&&e.score!==null){let t=document.createElement(`b`);t.className=`meta-points`,t.textContent=String(e.score),n.push(t)}if(e.logo!==``){let r=document.createElement(`img`);r.className=`meta-team-logo`,r.alt=``,r.src=e.logo,r.addEventListener(`error`,()=>{r.hidden=!0}),t?n.unshift(r):n.push(r)}return n},n=document.createElement(`span`);n.className=`meta-dash`,n.textContent=`–`,e.replaceChildren(...t(r.away,!0),n,...t(r.home,!1)),f.push(e)}if(n!==``&&/^(https?:\/\/|\/api\/)/.test(n)){let e=document.createElement(`img`);e.className=s?.kind===`title`&&n===s.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),f.push(e)}for(let e of t){let t=document.createElement(`span`);t.className=r?.state===`in`&&e===r.status?`meta-chip chip-live`:`meta-chip`,t.textContent=e,f.push(t)}o.meta.replaceChildren(...f)}function U(){let t=z(),n=Pt(),r=Me();o.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,o.status.dataset.playing=r?`loading`:String(n),o.title.textContent=V(),jt(),Ht(),o.goLiveNow.hidden=!wt()||Et()===null;let i=n?`${V()} · ${l}`:l;document.title!==i&&(document.title=i),o.copyNow.hidden=L.source===``,o.shareNow.hidden=wr()===``,or(),yr(),o.downloadNow.hidden=!(w&&E?.link?.download),un(),o.album.textContent=At();let a=Nt(),s=Mt();o.elapsed.textContent=e(a),o.total.textContent=s>0?e(s):`--:--`,he||(o.seek.value=String(s>0?Math.round(a/s*1e3):0),o.seek.disabled=s<=0||I()),o.playPause.textContent=n?`❚❚`:`▶`,o.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),o.playlistTitle.dataset.title=u===`remote`?`Files on ${d||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,o.source.textContent=u===`remote`?`connected · ${d||R.address.replace(/^https?:\/\//,``)||`—`}`:_.length>0?`local · ${_.length} files`:`no source`,tn(),o.remoteState.textContent=u===`remote`?`${y}${x?` — ${x}`:``}`:`not connected`,o.remoteState.dataset.status=u===`remote`?y:`idle`,o.disconnect.hidden=u!==`remote`;let c=u===`remote`&&v.note!==``?v.note:S;o.note.textContent=c,o.note.hidden=c===``,o.linkNote.textContent=c,o.linkNote.hidden=c===``,Bn(c),Xt(),o.glyphs.textContent=P.map(Bt).join(``);let[f,p]=I()?v.levels:L.levels();o.levels.textContent=zt(f,p)}let Ut=``,Wt=-1,W=``,Gt=0;function Kt(e){W=e,Gt=0,Ut=``,Xt()}function qt(e,t,n,r,i){if(o.playlistPager.hidden=n<=1,n<=1){o.playlistPager.replaceChildren();return}let a=(e,t,r)=>{let i=document.createElement(`button`);return i.type=`button`,i.className=`ghost`,i.textContent=e,i.title=r,i.disabled=t<0||t>=n,i.addEventListener(`click`,()=>{Gt=t,Ut=``,Xt(),o.playlist.scrollIntoView({block:`nearest`})}),i},s=document.createElement(`span`);s.className=`pager-where`,s.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,o.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),s,a(`Next ›`,t+1,`The page after this one`))}function Jt(e){if(o.crumbs.hidden=!e,!e)return;let t=W===``?[]:W.split(`/`),n=(e,t,n)=>{if(n){let t=document.createElement(`span`);return t.className=`here`,t.textContent=e,t}let r=document.createElement(`button`);return r.type=`button`,r.textContent=e,r.addEventListener(`click`,()=>Kt(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))}),o.crumbs.replaceChildren(...r)}function Yt(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`);return i.className=`count`,i.textContent=`${t} file${t===1?``:`s`}`,n.append(r,i),n.tabIndex=0,n.addEventListener(`click`,()=>Kt(W===``?e:`${W}/${e}`)),n}function Xt(){let n=u===`remote`?v.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):_.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=o.filter.value.trim().toLowerCase(),i=n.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>r===``||`${e.folder}/${e.name}`.toLowerCase().includes(r)),s=e=>r!==``||W===``||e===W||e.startsWith(`${W}/`),l=e=>r!==``||e===W,d=e=>{let t=W===``?e:e.slice(W.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of i){if(!s(e.folder)||l(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=i.filter(e=>l(e.folder)&&s(e.folder)),m=[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),h=Le(m.length+p.length,Gt,a);Gt=h.page;let ee=m.slice(h.from,h.to),te=p.slice(Math.max(0,h.from-m.length),Math.max(0,h.to-m.length)),g=`${u}:${W}:${r}:${h.page}/${a}:${m.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(g!==Ut){Ut=g,Jt(r===``&&(m.length>0||W!==``)),qt(m.length+p.length,h.page,h.pages,h.from,h.to);let t=[];for(let[e,n]of ee)t.push(Yt(e,n));let n=``,i=p.some(e=>e.group!==``);for(let r of te){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(Zt(r.group)));let a=document.createElement(`li`);a.className=`row`,a.tabIndex=0,a.dataset.index=String(r.index);let o=document.createElement(`span`);o.className=`n`,o.textContent=String(r.index+1).padStart(2,` `);let s=document.createElement(`span`);s.className=`name`,s.textContent=r.name;let l=document.createElement(`span`);if(l.className=`time`,l.textContent=r.seconds>0?e(r.seconds):`--:--`,a.append(o,s,l),u===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(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(),Wi(Gi(`track:${r.index}`,C===r.index?L.position:0),e,`✓`)}),a.append(e),wt()&&a.append(kt(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}o.playlist.replaceChildren(...t)}let ne=B(),re=Pt(),ie;for(let e of Array.from(o.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===ne;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&re),r&&(ie=t)}if(ne!==Wt){Wt=ne;let e=p.findIndex(e=>e.index===ne);if(e>=0&&!ie){Gt=Math.floor((m.length+e)/a),Ut=``,Xt();return}ie?.scrollIntoView({block:`nearest`})}}function Zt(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!==``&&!o.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(),Qt(e)}),t.append(n)}return t}async function Qt(e){try{let t=await fetch(R.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();G(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{G(`could not reach the server`)}}function $t(){let t=o.canvas,n=Math.min(2,globalThis.devicePixelRatio||1),r=Math.round(t.clientWidth*n),i=Math.round(t.clientHeight*n);r>0&&i>0&&(t.width!==r||t.height!==i)&&(t.width=r,t.height=i);let a=t.getContext(`2d`);if(I())F=Oe(F,P);else{let e=L.read();e.length>0&&(xt.length!==25&&(xt=Te(24,e.length)),P=De(P,Ee(e,xt)),F=Oe(F,P))}if(a){let e=getComputedStyle(document.documentElement);ke(a,{width:t.width,height:t.height},P,F,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(Pt()){o.glyphs.textContent=P.map(Bt).join(``);let[t,n]=I()?v.levels:L.levels();o.levels.textContent=zt(t,n),o.elapsed.textContent=e(Nt());let r=Mt();!he&&r>0&&(o.seek.value=String(Math.round(Nt()/r*1e3)))}requestAnimationFrame($t)}let en=``;function tn(){if(u!==`remote`){o.wayInHere.hidden=!0,en=``;return}let e=St()&&!te,t=ce||R.address,n=e?null:ae(R.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===en)return;en=r;let[i,a]=oe({name:d||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,o.wayInHere.replaceChildren(i,a),o.wayInHere.hidden=!1}function nn(e){o.video.hidden=!e,o.fullscreen.hidden=!e,Be(),O=null,k=null}function rn(){if(!(`mediaSession`in navigator))return;let e=w?_e(D?.channels.find(e=>e.id===w?.id)?.art??w.art):``;navigator.mediaSession.metadata=new MediaMetadata({title:V(),album:At(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void It()),navigator.mediaSession.setActionHandler(`pause`,()=>void It()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void Lt(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void Lt(-1))}o.filter.addEventListener(`input`,()=>{Gt=0,Ut=``,Xt()}),o.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())}),o.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&H(n)}),o.fullscreen.addEventListener(`click`,()=>{let e=o.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),o.prev.addEventListener(`click`,()=>void Lt(-1)),o.next.addEventListener(`click`,()=>void Lt(1)),o.stop.addEventListener(`click`,()=>void Rt()),o.playPause.addEventListener(`click`,()=>void It());async function an(e){let t=He(e,Tt());if(!t){if(!wt()){S=u===`remote`?`That link would need this server to fetch it, which is going live with it: sign in to nixamp.com, or use the server's control link. YouTube, Vimeo, SoundCloud and links straight to a file play here.`:`That link would need a server to fetch it: pick one to go live on, or connect to one. YouTube, Vimeo, SoundCloud and links straight to a file play here.`,U();return}await ln(e);return}if(w=null,L.stop(),t.kind===`embed`){E={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},nn(!1),o.embedFrame.src=t.src,o.embed.hidden=!1,O={url:e,label:t.label,kind:`embed`},S=`Playing ${t.label} here, in this browser.`,U();return}if(t.kind===`list`){await on(e,t.label);return}E={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await T(()=>L.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),nn(t.video),O={url:e,label:t.label,kind:`direct`},S=`Playing ${t.label} here, in this browser.`,U()}async function on(e,t){S=`Reading ${t}…`,U();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.`,U();return}let r=Ve(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.`,U();return}k={url:e,title:r.title||t,entries:r.entries,at:0},await sn()}async function sn(){let e=k,t=e?.entries[e.at];if(!e||!t)return;let n=ze(t.url);E={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await T(()=>L.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),k!==null&&(nn(n),O={url:e.url,label:e.title,kind:`direct`},k=e,S=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,U())}function cn(){let e=k;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,sn(),!0)}async function ln(e){if(u!==`remote`){S=`Pick a server to go live on, or connect to one, to put a link on the air.`,U();return}S=`Asking ${d||`the server`} to fetch ${e}…`,U(),await T(async()=>{let t,n={};try{t=await fetch(R.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(R.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await zi({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.`)}),U()}o.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.linkUrl.value.trim();t!==``&&an(t)});function un(){let e=u===`remote`?R.address:``,t=f.filter(t=>ee(t.url)!==ee(e)),n=JSON.stringify({here:e,name:d,carries:m,others:t});if(n===p)return;p=n;let r=[];if(e!==``&&m){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${d||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)}o.linkServer.replaceChildren(...r),o.linkServer.value=e!==``&&!m&&t[0]?t[0].url:``,o.linkServer.hidden=t.length===0}async function dn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;f=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),un()}catch{}}async function fn(){let e=o.linkUrl.value.trim()||O?.url||``;if(e===``){S=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,U();return}let t=o.linkServer.value;if(t!==``&&(u!==`remote`||ee(t)!==ee(R.address))){let n=f.find(e=>e.url===t)?.name??t;h=e,S=`Connecting to ${n} to go live with it…`,U(),pn(t);return}if(u!==`remote`){S=f.length>0?`Pick a server to go live on, beside the link.`:`Connect to a server first: Browse the directory, or paste a server's link in the Server panel.`,U(),f.length>0&&o.linkServer.focus();return}if(!m){S=`${d||`This server`} has no ffmpeg, so it cannot carry a link.`+(f.length>0?` Pick a server to go live on, beside the link.`:``),U();return}if(!wt()){S=`Sign in to nixamp.com to go live here, or use the server's control link.`,U();return}await ln(e)}function pn(e){let t=o.linkUrl.value.trim();te=!0,g=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit(),o.linkUrl.value=t}o.linkGoLive.addEventListener(`click`,()=>{fn()}),o.linkServer.addEventListener(`change`,()=>{let e=o.linkServer.value;e!==``&&pn(e)}),o.downloadNow.addEventListener(`click`,()=>{let e=E?.link;if(!e||u!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(R.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),S=`Fetching it through the server; your browser will save it when it arrives.`,U()}),o.goLiveNow.addEventListener(`click`,()=>{let e=Et();e&&Dt(e,o.goLiveNow)}),o.seek.addEventListener(`input`,()=>{he=!0}),o.seek.addEventListener(`change`,()=>{let e=Mt();e>0&&L.seek(Number(o.seek.value)/1e3*e),he=!1}),o.volume.addEventListener(`input`,()=>{let e=Number(o.volume.value)/100;L.volume=e;try{localStorage.setItem(ht,String(e))}catch{}});let mn=e=>{e.addEventListener(`change`,()=>{let t=ie(Array.from(e.files??[]));if(t.length===0){S=`Nothing playable in that selection.`,U();return}se(_),_=t,le=0,u=`local`,R.close(),S=``,H(0)})};mn(o.files),mn(o.folder),o.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.remoteUrl.value,{base:n,key:r}=me(t);if(n===``){S=`That is not an address.`,U();return}(async()=>{y=`connecting`,U();let e=Se(n);if(e){y=`error`,x=e,S=e,h=``,u=`local`,U();return}if(await xe(n,void 0,r)===null){y=`error`;let e=ye(n);x=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.`,h=``,u=`local`,U();return}let i=await be(n,r);if(i){y=`error`,x=i,S=i,h=``,u=`local`,U();return}u=`remote`,S=``;try{localStorage.setItem(pt,t.trim())}catch{}R.connect(t),Q(),Nr(),Fi(!0),En(),Mi(),U()})()});let hn=``,gn=null,_n=async(e=!1)=>{o.directory.hidden=!1,e||(o.directoryNote.textContent=`Looking for live streams…`,o.directoryList.replaceChildren()),gn||=setInterval(()=>{!o.directory.hidden&&document.visibilityState===`visible`&&_n(!0)},_t);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??[],f=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:X});if(e&&i===hn)return;hn=i,kn(r.recent??[])}catch{e||(o.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(o.directoryList.replaceChildren(),t.length===0){o.directoryNote.textContent=`Nobody is streaming right now.`;return}o.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 a=[`${e.tracks.toLocaleString()} files to browse`];e.playing!==!1&&e.nowPlaying?a.push(`playing ${e.nowPlaying}`):a.push(`player idle`),e.code&&a.push(e.callers?`☎ ${e.code} · ${e.callers} on the phone`:`☎ ${e.code}`),i.textContent=a.join(` · `),i.title=i.textContent,n.append(r,i);let s=e.admin??ae(e.url),c=(t,n=``)=>{te=t,g=n,o.remoteUrl.value=t?e.url:s??e.url,o.directory.hidden=!0,o.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`,Ot(s),s.title=`Join ${t}, live on ${e.name}`,s.addEventListener(`click`,()=>c(!0,`channel:${t}`)),n.append(r,s),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:s},()=>{o.directory.hidden=!0});if(t.append(n,u,d),X&&t.append(Rn(e.url,e.name)),e.ownerId&&X&&e.ownerId!==X&&t.append(Kr(e.ownerId,e.name)),l.childElementCount>0&&t.append(l),e.ownerId&&X&&e.ownerId===X){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(()=>({}));o.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{o.directoryNote.textContent=`could not reach the directory`}finally{await _n()}})()}),t.append(n)}o.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!o.directory.hidden&&_n(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),_n()}let vn=null,yn=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,bn=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,xn=``,Sn=``,Cn=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===xn)return;xn=t,o.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)}o.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,``],[yn(t.network),`network-${t.network}`],[bn(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)}o.adminConnections.append(e)}};function G(e){o.adminSaid.textContent=e,o.adminSaid.hidden=e===``}let wn=async()=>{try{let e=await fetch(R.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;o.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,Cn(t.connections??[]),Tn(t.publish??[],(t.channels??[]).map(e=>e.id)),Xi(t.home??``,t.root??``),Q()}catch{o.adminNote.textContent=`lost touch with the server`}};function Tn(e,t){o.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Sn)return;if(Sn=n,e.length===0){o.publishList.replaceChildren();return}let r=e.length-t.length;o.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,o.publishList.replaceChildren(...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`,o.textContent=`Copy`,o.addEventListener(`click`,()=>{a.select(),navigator.clipboard?.writeText(e.url).catch(()=>{})}),r.append(i,a,o),r}))}let En=async()=>{if(u!==`remote`){o.adminPanel.hidden=!0,o.publishPanel.hidden=!0,vn&&clearInterval(vn),vn=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(R.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(te&&(e=!1),Ct=i&&!e,o.adminPanel.hidden=!e,ji(e),h!==``){let e=h;h=``,wt()?ln(e):(S=`Sign in to nixamp.com to go live here.`,U())}if(vn&&clearInterval(vn),vn=null,Q(),Nr(),Mi(),o.listenOnly.hidden=e,!e){o.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}o.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,wn(),vn=setInterval(()=>void wn(),2e3)};function Dn(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)}`;G(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(R.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}:{}})}),a=await i.json();if(!i.ok){G(a.error??`that did not work`);return}G(`${a.channel?.name||t||e} is on the air.`),o.adminSource.value=``,o.adminName.value=``,Mi(),Q()}catch{G(`could not reach the server`)}})()}o.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=o.adminSource.value.trim();t&&Dn(t,o.adminName.value.trim())}),o.adminAdd.addEventListener(`click`,()=>{let e=o.adminSource.value.trim();if(!e)return;G(`Reading ${e}…`);let t=o.adminReplace.checked,n=o.adminName.value.trim();(async()=>{try{let r=await fetch(R.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();G(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&&(o.adminSource.value=``,o.adminName.value=``,Mi(),Q())}catch{G(`could not reach the server`)}})()});let On=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`},kn=e=>{o.recentList.replaceChildren();let t=X?e.filter(e=>e.ownerId&&e.ownerId!==X):[];if(o.recentNote.hidden=t.length===0,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;let i=document.createElement(`span`);i.className=`detail`,i.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${On(e.endedAt)}`:`ended ${On(e.endedAt)}`,n.append(r,i),t.append(n,Kr(e.ownerId,e.name)),o.recentList.append(t)}},An=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 jn(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?`▶ ${An(e.party.positionNow)}`:`❚❚ ${An(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`,a.textContent=`Watch`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Room`,t.append(n,a,o),t}async function Mn(){if(!X){o.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){o.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];o.partiesPanel.hidden=!1,o.partiesNote.textContent=t.length===0?`No parties on right now. Have a code from a site? Put it in.`:`Parties on now. Watch opens the film where it lives; Room is here.`,o.partiesList.replaceChildren(...t.map(jn))}catch{o.partiesPanel.hidden=!0}}o.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.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 with that code`,U();return}o.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{S=`could not ask about that party`,U()}})()});async function Nn(){if(!X){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];o.connectionsNote.hidden=t.length===0,o.connectionsList.hidden=t.length===0,o.connectionsList.replaceChildren(...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`,a.textContent=`Disconnect`,a.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/oauth/connections/${encodeURIComponent(e.clientId)}`,{method:`DELETE`})}catch{}await Nn()})()}),t.append(n,a),t}))}catch{o.connectionsNote.hidden=!0,o.connectionsList.hidden=!0}}let Pn=new Set,K=e=>{try{return new URL(e).origin}catch{return e}},Fn=e=>[...Pn].some(t=>K(t)===K(e));async function In(){if(!X){Pn=new Set,o.favoritesPanel.hidden=!0,zn();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){o.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];Pn=new Set(t.map(e=>e.url)),o.favoritesPanel.hidden=t.length===0,o.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,o.favoritesList.replaceChildren(...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,...oe({name:e.name||e.url,view:e.url,admin:ae(e.url)}),Rn(e.url,e.name)),t}))}catch{o.favoritesPanel.hidden=!0}zn()}async function Ln(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.`,U();return}}catch{S=`could not reach nixamp.com`,U();return}if(n)Pn.add(e);else for(let t of[...Pn])K(t)===K(e)&&Pn.delete(t);await In()}function Rn(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Fn(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=[...Pn].find(t=>K(t)===K(e))??e;Ln(Fn(e)?i:e,t,!Fn(e)).then(r)}),n}function zn(){let e=u===`remote`?R.shareLink:``;if(o.favHere.hidden=!(X&&e),o.favHere.hidden)return;let t=Fn(e);o.favHere.textContent=t?`♥`:`♡`,o.favHere.dataset.on=t?`yes`:`no`,o.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,o.favHere.setAttribute(`aria-label`,o.favHere.title)}c(o.copyNow,`copy`),o.copyNow.addEventListener(`click`,()=>{Wi(L.source,o.copyNow,`✓`)});function Bn(e){if(e===``||e===bt)return;bt=e;let t=document.createElement(`li`),n=document.createElement(`time`),r=new Date;n.dateTime=r.toISOString(),n.textContent=r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`});let i=document.createElement(`span`);for(i.textContent=e,t.append(n,i),o.logList.prepend(t);o.logList.children.length>100;)o.logList.lastElementChild?.remove()}let Vn=3e3,Hn=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,Un=``,Wn=``,Gn=null,Kn=!1,qn=new Set,Jn=``,Yn=null,Xn=!1,Zn=st(e=>localStorage.getItem(e)),Qn=``,$n=null,er=it(6,!1),tr=[],nr=[],rr=null;function ir(){if(u!==`remote`)return null;let{base:e}=me(Ki());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=w?w.id:E?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function ar(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${Hn}/api/v1/trollbox?${n.toString()}`}function or(){let e=ir(),t=e?`${e.server}|${e.channel}`:``;t!==Un&&(Un=t,Wn=``,qn.clear(),o.trollboxList.replaceChildren(),Gn&&clearTimeout(Gn),Gn=null,o.trollboxPanel.hidden=e===null,o.trollboxForm.hidden=!0,fr(!1),e&&(o.trollboxNote.textContent=`The room for ${V()||e.channel}. Loading…`,cr()))}function sr(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);n.textContent=Number.isNaN(r.getTime())?``:r.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`});let i=document.createElement(`span`);i.className=`who`,i.textContent=e.handle;let a=document.createElement(`span`);if(a.className=`line`,a.textContent=e.body,t.append(n,i,a),e.mine===!0||St()){let n=document.createElement(`button`);n.type=`button`,n.className=`icon-btn`,n.textContent=`✕`,n.title=e.mine===!0?`Take your line down`:`Take this line down`,n.setAttribute(`aria-label`,n.title),n.addEventListener(`click`,()=>{lr(e.id,t)}),t.append(n)}return t}async function cr(){let e=ir(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===Un&&!Kn){Kn=!0;try{let n=await fetch(ar(e,Wn)),r=await n.json().catch(()=>({}));if(t!==Un)return;if(!n.ok){o.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!qn.has(e.id));for(let e of i)qn.add(e.id),o.trollboxList.append(sr(e)),Wn=e.createdAt;for(;o.trollboxList.children.length>200;)o.trollboxList.firstElementChild?.remove();i.length>0&&o.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`});let a=r.you??``;Jn=a,o.trollboxForm.hidden=a===``,o.trollboxEditLabel.hidden=a===``||!ur,a===``&&fr(!1),o.trollboxNote.textContent=a===``?Hn===``?`The room for ${V()||e.channel}. Sign in to say something.`:`The room for ${V()||e.channel}. To say something, open this stream on nixamp.com and sign in.`:`You are ${a} in the room for ${V()||e.channel}.`}catch{t===Un&&(o.trollboxNote.textContent=`The trollbox is not answering.`)}finally{Kn=!1,t===Un&&(Gn=setTimeout(()=>{document.visibilityState===`visible`?cr():Gn=setTimeout(()=>void cr(),Vn)},Vn))}}}async function lr(e,t){let n=ir();if(n)try{let r=await fetch(`${Hn}/api/v1/trollbox/${encodeURIComponent(e)}?${new URLSearchParams(n).toString()}`,{method:`DELETE`});r.ok?t.remove():o.trollboxNote.textContent=(await r.json().catch(()=>({}))).error??`that did not work`}catch{o.trollboxNote.textContent=`The trollbox is not answering.`}}o.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=ir(),n=o.trollboxInput.value.trim();t&&n!==``&&(o.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${Hn}/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){o.trollboxNote.textContent=r.error??`that did not send`;return}o.trollboxInput.value=``,qn.has(r.message.id)||(qn.add(r.message.id),o.trollboxList.append(sr(r.message)),Wn=r.message.createdAt,o.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`}))}catch{o.trollboxNote.textContent=`The trollbox is not answering.`}finally{o.trollboxInput.disabled=!1,o.trollboxInput.focus()}})())});let ur=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,dr=ur?et(e=>MediaRecorder.isTypeSupported(e)):``;o.trollboxMic.hidden=!ur;function q(e){o.trollboxNote.textContent=e,Bn(e)}function fr(e){let t=Yn;if(!t)return;Yn=null,clearTimeout(t.stop),clearInterval(t.tick),o.trollboxMic.setAttribute(`aria-pressed`,`false`),o.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(()=>mr(new Blob(t.chunks,{type:t.recorder.mimeType||dr||`audio/webm`}),t.startedAt))}async function pr(){if(Yn||Xn||Jn===``||!ir())return;let e;try{e=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}})}catch(e){q(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,dr?{mimeType:dr}:{})}catch{for(let t of e.getTracks())t.stop();q(`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();Yn={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>fr(!0),$e),tick:setInterval(()=>{o.trollboxMic.textContent=nt(r,Date.now())},500)},t.start(250),o.trollboxMic.setAttribute(`aria-pressed`,`true`),o.trollboxMic.textContent=nt(r,r),q(`Listening. Tap the mic again when you have said it (${Math.round($e/1e3)} s at most).`)}async function mr(e,t){let n=ir();if(n&&Jn!==``){if(Date.now()-t<400||e.size===0){q(`That was too short to hear. Tap, say it, then tap again.`);return}Xn=!0,o.trollboxMic.disabled=!0,o.trollboxMic.textContent=`…`,q(`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*Qe)),Qe),a=i.createBufferSource();a.buffer=r,a.connect(i.destination),a.start();let s=tt((await i.startRendering()).getChannelData(0),Qe),c=o.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(`${Hn}/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){q(f.error??`nixamp.com could not hear that.`);return}let p=(f.text??``).trim();if(p===``){q(`Heard nothing. Try again, closer to the mic.`);return}if(c||!f.message){let e=o.trollboxInput.value.trimEnd();o.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),o.trollboxInput.focus(),o.trollboxInput.setSelectionRange(o.trollboxInput.value.length,o.trollboxInput.value.length),q(`Heard: “${p}”. Send it, or fix it first.`);return}ir()&&!qn.has(f.message.id)&&(qn.add(f.message.id),o.trollboxList.append(sr(f.message)),Wn=f.message.createdAt,o.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`})),q(`Said: “${f.message.body}”`)}catch{q(`That recording could not be read here.`)}finally{Xn=!1,o.trollboxMic.disabled=!1,o.trollboxMic.textContent=`🎤`}}}o.trollboxMic.addEventListener(`click`,()=>{Yn?fr(!0):pr()});try{o.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}o.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,o.trollboxEdit.checked?`on`:`off`)}catch{}q(o.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function hr(){try{let e=await fetch(`${Hn}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`Could not read your profile.`;return}o.personaHandle.value=t.chosen?t.handle??``:``,o.personaHandle.placeholder=t.handle||`handle`,o.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,o.personaProfile.value=t.profile??``,o.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${gr(t.voice??``)}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${gr(t.voice??``)}.`}catch{o.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function gr(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`}o.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.personaHandle.value.trim(),n={voice:o.personaVoice.value,profile:o.personaProfile.value.trim()};t!==``&&(n.handle=t),o.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${Hn}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){o.personaNote.textContent=t.error??`that did not save`;return}await hr()}catch{o.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&Yn&&fr(!0)});function _r(){return u!==`remote`||!w?null:{id:w.id,name:w.name,hls:w.video&&Tt()}}function vr(){$n?.close(),$n=null,rr&&clearInterval(rr),rr=null,tr=[],nr=[],o.transcriptList.replaceChildren(),o.subtitle.hidden=!0,o.subtitle.textContent=``}function yr(){let e=_r(),t=e?`${e.id}|${e.hls}|${Zn}`:``;if(t!==Qn&&(Qn=t,vr(),o.transcriptPanel.hidden=e===null,o.transcriptOn.checked=Zn,e)){if(!Zn){o.transcriptNote.textContent=`Captions are off on this device. Turn them on and ${e.name} is written down as it speaks.`;return}o.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,br(e,t)}}async function br(e,t){let n=6;try{let r=await fetch(R.url(`/api/channels/${encodeURIComponent(e.id)}/transcript`)),i=await r.json().catch(()=>({}));if(t!==Qn)return;if(!r.ok){o.transcriptNote.textContent=i.error??`This server is not captioning.`;return}n=i.backlog??n}catch{t===Qn&&(o.transcriptNote.textContent=`The server did not answer about captions.`);return}er=it(n,e.hls);let r=new EventSource(R.url(`/api/channels/${encodeURIComponent(e.id)}/captions`));$n=r;let i=e=>{for(let t of e)t&&typeof t.text==`string`&&Number.isFinite(t.at)&&tr.push(t)};r.addEventListener(`hello`,r=>{if(t!==Qn)return;let a=JSON.parse(r.data);er=it(a.backlog??n,e.hls),i(a.lines??[]),o.transcriptNote.textContent=a.error?`Captions for ${e.name} are not coming: ${a.error}`:`What ${e.name} is saying, a few seconds behind the sound.`}),r.addEventListener(`line`,e=>{t===Qn&&i([JSON.parse(e.data)])}),r.addEventListener(`error`,()=>{t===Qn&&r.readyState===EventSource.CLOSED&&(o.transcriptNote.textContent=`Captions stopped; the server went away.`)}),rr=setInterval(Sr,250)}function xr(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),n.textContent=ct(e.at);let r=document.createElement(`span`);return r.className=`line`,r.textContent=e.text,t.append(n,r),t}function Sr(){let e=Date.now(),{ready:t,still:n}=at(tr,e,er);tr=n;for(let e of t)nr.push(e),o.transcriptList.append(xr(e));for(;nr.length>200;)nr.shift();for(;o.transcriptList.children.length>200;)o.transcriptList.firstElementChild?.remove();t.length>0&&o.transcriptList.lastElementChild?.scrollIntoView({block:`nearest`});let r=ot(nr,e,er),i=o.transcriptList.children,a=r?nr.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let s=r!==null&&!o.video.hidden&&o.video.offsetHeight>0;o.subtitle.hidden=!s,s&&r&&(o.subtitle.textContent!==r.text&&(o.subtitle.textContent=r.text),o.subtitle.style.top=`${o.video.offsetTop+o.video.offsetHeight-o.subtitle.offsetHeight-10}px`)}o.transcriptOn.addEventListener(`change`,()=>{Zn=o.transcriptOn.checked;try{localStorage.setItem(rt,Zn?`on`:`off`)}catch{}yr()});function Cr(){if(O)return O.url;if(u!==`remote`)return``;let{base:e,key:t}=me(Ki());if(e===``)return``;if(w)return b(e,`/api/channels/${encodeURIComponent(w.id)}`,t);if(E?.kind===`live`)return b(e,`/api/live`,t);if(L.source===``)return``;try{let n=new URL(L.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function wr(){let e=Cr();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}o.shareNow.addEventListener(`click`,()=>{let e=wr();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${V()} on nixamp`,url:e}).catch(()=>void 0);return}Wi(e,o.shareNow,`Copied`)}),o.favHere.addEventListener(`click`,()=>{let e=Ki()||R.shareLink;if(!e)return;let t=[...Pn].find(t=>K(t)===K(e))??e;Ln(Fn(e)?t:e,d||R.address,!Fn(e)).then(zn)});let Tr=r?a:200,Er=[],J=null,Y=null,Dr=``,Or=[],kr=0,Ar=null,jr=0;function Mr(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`}async function Nr(){if(u!==`remote`){o.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(R.url(`/api/catalogs`))}catch{o.catalogsPanel.hidden=!0;return}if(!e.ok){o.catalogsPanel.hidden=!0;return}Er=(await e.json().catch(()=>({}))).catalogs??[],J&&=Er.find(e=>e.id===J?.id)??null,J||(Y=null),o.catalogsPanel.hidden=!1,Pr()}function Pr(){let e=!o.adminPanel.hidden;o.catalogsForm.hidden=!e;let t=Er.reduce((e,t)=>e+t.live,0),n=Er.reduce((e,t)=>e+t.vod,0);o.catalogsNote.textContent=Er.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Er.length} ${Er.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,Fr();let r=J!==null&&Y!==null;if(o.catalogsList.hidden=r,o.catalogsFilter.hidden=!r,o.catalogsEntries.hidden=!r,r){Br();return}if(J){Lr(J);return}o.catalogsList.replaceChildren(...Er.map(t=>Ir(t,e)))}function Fr(){let e=J!==null;if(o.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`,()=>{J=null,Y=null,Pr()},!1),n(),t(J?.name??``,()=>{Y=null,Pr()},Y===null)];Y!==null&&r.push(n(),t(Y===``?`All groups`:Y,()=>void 0,!0)),o.catalogsCrumbs.replaceChildren(...r)}function Ir(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`,a.textContent=[`${e.entries.toLocaleString()} ${e.entries===1?`entry`:`entries`}`,`${e.live.toLocaleString()} live`,`${e.vod.toLocaleString()} on demand`,`refreshed ${Mr(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.addEventListener(`click`,()=>{J=e,Y=null,Pr()}),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`,()=>{Hr(e)});let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Remove`,r.title=`Take this catalog off the server`,r.addEventListener(`click`,()=>{confirm(`Remove ${e.name} from this server?`)&&Ur(e)}),n.append(t,r)}return n}async function Lr(e){o.catalogsList.replaceChildren();let t=[];try{let n=await T(()=>fetch(R.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{S=`Could not read the groups in ${e.name}.`,U();return}if(J?.id!==e.id||Y!==null)return;let n=[Rr(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Rr(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];o.catalogsList.replaceChildren(...n)}function Rr(e,t,n,r,i){let a=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{Y=t,Dr=``,o.catalogsFilter.value=``,Or=[],kr=0,Pr(),zr(0)}),a.append(s,u),a}async function zr(e){let t=J,n=Y;if(!t||n===null)return;let r=++jr,i=new URLSearchParams({group:n,q:Dr,offset:String(e),limit:String(Tr)}),a;try{let e=await T(()=>fetch(R.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{S=`Could not read ${t.name}.`,U();return}r===jr&&(kr=a.total??0,Or=e===0?a.entries??[]:[...Or,...a.entries??[]],Br())}function Br(){let t=J;if(!t)return;let n=Or.map(n=>{let r=document.createElement(`li`);r.className=`row`;let i=document.createElement(`span`);i.className=`name`,i.textContent=n.title;let a=document.createElement(`span`);if(a.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,a.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(i,a),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,c(e,`copy`),e.title=`Copy this entry's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.title}`),e.addEventListener(`click`,r=>{r.stopPropagation();let i=`/api/catalogs/${encodeURIComponent(t.id)}/entries/${encodeURIComponent(n.id)}/stream`;Wi(R.url(i),e,`✓`)}),r.append(e)}return wt()&&r.append(kt(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{Vr(t,n,r)}),r});if(Or.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=Dr?`Nothing called "${Dr}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(Or.length<kr){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${Or.length.toLocaleString()} of ${kr.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),zr(Or.length)}),e.append(t),n.push(e)}o.catalogsEntries.replaceChildren(...n)}async function Vr(e,t,n){n?.classList.add(`loading`),S=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await T(async()=>{let n,i={};try{n=await fetch(R.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 zi({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){w=null,C=-1,E={kind:`vod`,...r},qe(a,`title`),await L.load({title:a,artist:``,album:``,duration:0,url:R.url(i.url),video:!0,objectUrl:!1},!0),nn(!0),S=`Playing ${a}.`;return}S=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),U()}}async function Hr(e){G(`Reading ${e.name} again…`);try{let t=await fetch(R.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));G(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{G(`could not reach the server`)}Nr()}async function Ur(e){try{G((await fetch(R.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{G(`could not reach the server`)}J?.id===e.id&&(J=null,Y=null),Nr()}o.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.catalogSource.value.trim(),n=o.catalogName.value.trim();t&&(async()=>{G(`Reading ${n||t}…`);try{let e=await fetch(R.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){G(r.error??`that did not work`);return}G(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),o.catalogSource.value=``,o.catalogName.value=``}catch{G(`could not reach the server`)}Nr()})()}),o.catalogsFilter.addEventListener(`input`,()=>{Ar&&clearTimeout(Ar),Ar=setTimeout(()=>{Ar=null,Dr=o.catalogsFilter.value.trim(),zr(0)},250)});let Wr=async()=>{o.serversList.replaceChildren();try{let e=await fetch(`/api/v1/servers`);if(!e.ok){o.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];re=new Map(t.map(e=>[K(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),o.serversPanel.hidden=!1,o.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 a=e.key?`${e.url}/admin/${e.key}`:e.url,[s,c]=oe({name:e.name,view:a,admin:a});xe(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=si()===K(e.url),u=document.createElement(`button`);u.type=`button`,u.className=`ghost`,u.textContent=l?`✓ Default`:`Make default`,u.title=l?`The server this page connects to when you arrive signed in. Press to go back to the first that answers.`:`Connect to this server whenever you arrive signed in`,u.addEventListener(`click`,()=>{ci(l?``:K(e.url)),Wr()});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 Wr()}catch{d.disabled=!1}})()}),t.append(n,s,c,u,d),o.serversList.append(t)}}catch{o.serversPanel.hidden=!0}},Gr=async()=>{o.followingList.replaceChildren();try{let e=await fetch(`/api/v1/follows`);if(!e.ok){o.followingNote.hidden=!0;return}let t=(await e.json()).following??[];o.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 a=document.createElement(`button`);a.type=`button`,a.className=`ghost follow`,a.textContent=`Unfollow`,a.addEventListener(`click`,()=>{(async()=>{a.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),o.followingList.children.length===0&&(o.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),o.followingList.append(t)}}catch{o.followingNote.hidden=!0}},Kr=(e,t)=>{let n=document.createElement(`button`);n.type=`button`,n.className=`ghost follow`,n.textContent=`Follow`,n.setAttribute(`aria-label`,`Follow ${t}`);let r=e=>{n.textContent=e?`Following`:`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),Gr())}catch{}finally{n.disabled=!1}})()}),n},qr=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},Jr=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Yr=async()=>{if(!Jr())return o.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return o.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return o.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 o.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:qr(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 o.notifyNote.textContent=`This device will be told.`,!0}catch{return o.notifyNote.textContent=`Could not set this device up.`,!1}},Xr=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{}},Zr=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();o.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(o.notifyPhone.value=n.phone)}catch{o.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Qr=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();o.notifyEmail.checked=t.wantsEmail!==!1,o.notifySms.checked=t.wantsSms===!0,o.notifyPhone.value=t.phone??``;let n=Jr()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;o.notifyWeb.checked=t.wantsWeb!==!1&&n,o.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};o.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(o.notifyWeb.checked){let e=await Yr();o.notifyWeb.checked=e,await Zr({wantsWeb:e});return}await Xr(),await Zr({wantsWeb:!1}),o.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),o.notifyEmail.addEventListener(`change`,()=>{Zr({wantsEmail:o.notifyEmail.checked})}),o.notifySms.addEventListener(`change`,()=>{(async()=>{if(o.notifySms.checked&&!o.notifyPhone.value.trim()){o.notifyPhoneNote.textContent=`Add a phone number first.`,o.notifySms.checked=!1,o.notifyPhone.focus();return}await Zr({wantsSms:o.notifySms.checked})})()}),o.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),Zr({phone:o.notifyPhone.value.trim()})});let $r=!1,X=``,ei=!1,ti=`nixamp.welcome`,ni=()=>{let e=!1;try{e=localStorage.getItem(ti)===`hidden`}catch{}o.welcome.hidden=!ei||X!==``||e},ri=e=>{let t=e!==null;o.notifyPanel.hidden=!t,t?(Qr(),Gr(),Wr()):(o.serversPanel.hidden=!0,o.followingNote.hidden=!0,o.followingList.replaceChildren(),o.recentNote.hidden=!0,o.recentList.replaceChildren()),o.accountForm.hidden=t,o.accountProviders.hidden=t||o.accountProviders.childElementCount===0,o.accountSignOut.hidden=!t,o.personaForm.hidden=!t,o.personaNote.hidden=!t,t&&hr(),o.accountNote.textContent=t?`Signed in as ${e}.`:$r?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,o.accountSubmit.textContent=$r?`Create account`:`Sign in`,o.accountToggle.textContent=$r?`I have one`:`Create one`,o.accountPassword.autocomplete=$r?`new-password`:`current-password`,ni()},ii=async()=>{let e=[];ei=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(ei=!0,e=(await t.json()).providers??[])}catch{}o.accountProviders.replaceChildren(),o.accountProviders.hidden=e.length===0,o.accountPanel.hidden=!ei,o.accountElsewhere.hidden=ei,ni();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}`,o.accountProviders.append(e)}},ai=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();X=e.ok?t.account?.id??``:``,ri(e.ok?t.account?.email??`you`:null)}catch{X=``,ri(null)}if(R.session=``,X!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));R.session=e.ok&&typeof t.token==`string`?t.token:``}catch{R.session=``}u===`remote`&&En()}In(),Mn(),Nn(),li();let e=await oi();if(yt!==``){let t=yt;yt=``,e?g=`golive:${t}`:an(t)}};async function oi(){if(X===``||u===`remote`||M!==``)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=si(),n=[...e].sort((e,n)=>Number(K(n.url)===t)-Number(K(e.url)===t));for(let e of n)if(await xe(e.url,void 0,e.key)!==null)return u!==`remote`&&(te=!1,g=``,o.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,S=`Connecting to ${e.name}, your server…`,U(),o.remoteForm.requestSubmit(),!0);return!1}function si(){try{return localStorage.getItem(mt)??``}catch{return``}}function ci(e){try{e===``?localStorage.removeItem(mt):localStorage.setItem(mt,e)}catch{}}function li(){if(M===``)return;let e=M;M=``,o.remoteUrl.value=e,o.remoteForm.requestSubmit()}o.accountToggle.addEventListener(`click`,()=>{$r=!$r,ri(null)}),o.welcomeCreate.addEventListener(`click`,()=>{$r=!0,ri(null),o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),o.accountEmail.focus({preventScroll:!0})}),o.welcomeBrowse.addEventListener(`click`,()=>{o.directory.hidden?o.browse.click():o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(ti,`hidden`)}catch{}o.welcome.hidden=!0}),o.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=o.accountEmail.value.trim(),n=o.accountPassword.value;(async()=>{o.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${$r?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){o.accountNote.textContent=r.error??`that did not work`;return}X=r.account?.id??``,o.accountPassword.value=``,ri(r.account?.email??t),En(),li()}catch{o.accountNote.textContent=`could not reach nixamp.com`}finally{o.accountSubmit.disabled=!1}})()}),o.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}X=``,ri(null),R.close(),C=-1,u=`local`,y=`idle`,x=``,o.remoteUrl.value=``,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.catalogsPanel.hidden=!0,o.listenOnly.hidden=!0,Fi(!1);try{localStorage.removeItem(pt)}catch{}S=`Signed out, and disconnected from the server.`,En(),U()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(M=t,g=e.get(`play`)??``,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t,S=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(o.linkUrl.value=n,t!==``&&g===``?g=`link:${n}`:t===``&&(yt=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=pe(r);t?(M=t.view,g=t.what,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),o.remoteUrl.value=t.view,S=`Opening the stream you were sent…`):(o.linkUrl.value=r,yt=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let ui=[`zone-top`,`zone-main`],di=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,fi=e=>e.parentElement&&ui.includes(e.parentElement.id)?e.parentElement:null,pi=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,mi=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>di(e)&&fi(e)!==null),hi=e=>e.dataset.title??e.id,gi=new Map,_i=mi().map((e,t)=>(gi.set(e.id,{zone:fi(e)?.id??``,col:pi(e),index:t}),e.id)),Z=We();try{Z=Je(localStorage.getItem(Ue))}catch{}let vi=()=>Z.order.length>0||Object.keys(Z.placement).length>0;function yi(){Z.order=mi().map(e=>e.id);try{localStorage.setItem(Ue,Ye(Z))}catch{}}function bi(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 xi(){for(let e of mi()){let t=Z.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&ui.includes(i.id)&&bi(e,i,r===`a`||r===`b`?r:``)}let e=Xe(mi().map(e=>e.id),Z.order);for(let t of ui){let n=document.getElementById(t);if(!n)continue;let r=[...n.children].filter(di),i=r.map(e=>{let t=document.createComment(`panel`);return e.before(t),t});r.sort((t,n)=>e.indexOf(t.id)-e.indexOf(n.id)),r.forEach((e,t)=>i[t]?.replaceWith(e))}for(let e of mi())e.toggleAttribute(`data-collapsed`,Z.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Z.closed.includes(e.id))}function Si(e,t){e.toggleAttribute(`data-collapsed`,t),Z.collapsed=Ze(Z.collapsed,e.id,t),yi(),ki()}function Ci(e,t){e.toggleAttribute(`data-closed`,t),Z.closed=Ze(Z.closed,e.id,t),yi(),ki()}function wi(e,t,n){let r=fi(t);r&&e!==t&&(bi(e,r,pi(t)),n?t.after(e):t.before(e),Z.placement[e.id]=`${r.id}:${pi(t)}`,yi(),ki())}let Ti=null,Ei=()=>{for(let e of mi())e.classList.remove(`drop-before`,`drop-after`)},Di=(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 Oi(){for(let e of mi()){if(e.querySelector(`:scope > .panel-tools`))continue;let t=document.createElement(`span`);t.className=`panel-tools`;let n=Di(`≡`,`Move ${hi(e)}: drag it to where it should go`,()=>void 0);n.classList.add(`grip`),n.draggable=!0,n.addEventListener(`dragstart`,t=>{Ti=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),n.addEventListener(`dragend`,()=>{Ti=null,e.classList.remove(`dragging`),Ei()});let r=Di(`▁`,`Shade ${hi(e)} to its title`,()=>Si(e,!e.hasAttribute(`data-collapsed`))),i=Di(`✕`,`Hide ${hi(e)}; the Panels list turns it back on`,()=>Ci(e,!0));t.append(n,r,i),e.prepend(t),e.addEventListener(`dragover`,t=>{if(!Ti||Ti===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;Ei(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Ti||Ti===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);Ei(),wi(Ti,e,n)})}}function ki(){if(o.panelsPanel.hidden)return;let e=mi().filter(e=>e!==o.panelsPanel).map(e=>{let t=document.createElement(`li`),n=e.hasAttribute(`data-closed`);t.classList.toggle(`off`,n);let r=document.createElement(`label`),i=document.createElement(`input`);i.type=`checkbox`,i.checked=!n,i.setAttribute(`aria-label`,`${hi(e)} on`),i.addEventListener(`change`,()=>Ci(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,a.textContent=hi(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});o.panelsList.replaceChildren(...e)}function Ai(){Z=We();for(let e of _i){let t=document.getElementById(e),n=gi.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(bi(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Z.order=[..._i],xi(),Z=We();try{localStorage.removeItem(Ue)}catch{}ki()}function ji(e){if(!e||vi())return;let t=fi(o.adminPanel);if(!t)return;let n=[...t.children].filter(di).find(e=>pi(e)===pi(o.adminPanel));n&&n!==o.adminPanel&&n.before(o.adminPanel),o.adminPanel.removeAttribute(`data-collapsed`),o.adminPanel.removeAttribute(`data-closed`)}o.panelsToggle.addEventListener(`click`,()=>{let e=o.panelsPanel.hidden;o.panelsPanel.hidden=!e,e&&(o.panelsPanel.hasAttribute(`data-closed`)&&Ci(o.panelsPanel,!1),ki(),o.panelsPanel.scrollIntoView({behavior:`smooth`,block:`nearest`}))}),o.panelsReset.addEventListener(`click`,Ai),new MutationObserver(()=>ki()).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Oi(),xi(),ii(),ai(),En(),dn(),o.browse.addEventListener(`click`,()=>{if(!o.directory.hidden){o.directory.hidden=!0;return}_n(),o.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),o.disconnect.addEventListener(`click`,()=>{R.close(),o.listenOnly.hidden=!0,C=-1,o.sharePanel.hidden=!0,o.publishPanel.hidden=!0,o.adminPanel.hidden=!0,o.onairPanel.hidden=!0,o.onairPanel.dataset.title=`Live on this server`,o.catalogsPanel.hidden=!0,o.catalogsPanel.dataset.title=`Catalogs on this server`,d=``,ce=``,zn(),Fi(!1),u=`local`,y=`idle`,x=``,U()});async function Mi(){if(u!==`remote`||R.shareLink===``){o.sharePanel.hidden=!0;return}o.sharePanel.hidden=!1;let e=Ki(),t=globalThis.location.origin;o.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,o.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,o.sharePhone.hidden=!0,o.shareSend.hidden=!0,o.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(R.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,ce=r.url,o.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(lt=r.live,j=r.live?r.code:``,ut=n,o.liveControls.hidden=o.adminPanel.hidden||!r.possible,o.goLive.hidden=r.live,o.stopLive.hidden=!r.live,o.sharePhone.hidden=!1,!r.live){o.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){o.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,o.shareSend.hidden=!1;return}o.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Qi(n),document.createTextNode(` and key `),Qi(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),o.shareSend.hidden=!1}}let Ni=``,Pi=null,Fi=e=>{Pi&&clearInterval(Pi),Pi=null,e&&(Pi=setInterval(()=>void Q(),6e3))};async function Q(){if(u!==`remote`){o.onairPanel.hidden=!0;return}let e;try{let t=await fetch(R.url(`/api/streams`));if(!t.ok){o.onairPanel.hidden=!0;return}e=await t.json(),m=e.server.carries!==!1,e.server.name&&e.server.name!==d&&(d=e.server.name,o.onairPanel.dataset.title=`Live on ${d}`,o.catalogsPanel.dataset.title=`Catalogs on ${d}`,zn(),U())}catch{o.onairPanel.hidden=!0;return}o.onairPanel.hidden=!1,D=e,qi(e);let t=`${o.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}`;if(t===Ni)return;Ni=t;let n=e.restreams??[],r=e.channels.length+n.length;o.onairNote.textContent=r===0?`One stream, from this server's own files.`:`${r+1} streams: this server's own files, and ${r} more on it.`;let i=[],a=e.server.playing,s=!o.adminPanel.hidden;i.push(Ji({title:e.server.name,detail:[a?`playing ${e.server.nowPlaying}`:e.server.nowPlaying?`stopped on ${e.server.nowPlaying}`:`nothing loaded`,`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:a?`Join live`:s?`Start the stream`:`Nothing playing`,onPlay:()=>{if(a){Ri(e.server.nowPlaying);return}s&&Li()},link:e.server.live?e.server.url:``,...a?{page:Gi(`live`)}:{},direct:a?R.url(`/api/live`):``}));for(let e of n)i.push(Ji({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{H(e.at)},link:``,direct:R.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=R.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.code&&r.push(`☎ ${t.code}`),t.redials&&r.push(`redialled ${t.redials}×`),s&&t.error&&r.push(t.error),i.push(Ji({title:t.name,detail:r.join(` · `),onPlay:()=>{zi({id:t.id,name:t.name,video:e,art:t.art})},link:n,page:Gi(`channel:${t.id}`),direct:n,onRestart:s&&t.via===`pull`?()=>{Vi(t.id,t.name)}:void 0,onStop:s||Ct&&X!==``&&t.startedBy===X?()=>{Ui(t.id,t.name)}:void 0,onRename:s||Ct&&X!==``&&t.startedBy===X?()=>{Hi(t.id,t.name)}:void 0}))}o.onairList.replaceChildren(...i)}async function Ii(){if(u===`remote`)try{if((await fetch(R.media(B(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;S=X===``?`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.`,X===``&&o.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),U()}catch{}}async function Li(){G(`Starting the stream on the server…`);try{await R.send({type:`play`,index:Math.max(0,B())})}catch{G(`could not reach the server`);return}await Ri(v.tracks[B()]?.title??``),G(`Playing to the room. Anybody with the view link sees this.`),await Q()}async function Ri(e){C=-1,w=null,E={kind:`live`},qe(e,`auto`),await T(()=>L.load({title:e||`Live`,artist:``,album:``,duration:0,url:R.url(`/api/live`),video:!0,objectUrl:!1},!0)),nn(!0),S=`Watching what this server is playing. Everyone here sees the same thing.`,U()}async function zi(e,t=!0,n){C=-1,w=e,t&&(Ce=0),t&&(E=n??{kind:`channel`}),t&&qe(e.name,E?.link||ft(e.name)?`auto`:`channel`);let r=e.video&&Tt();await T(()=>L.load({title:e.name,artist:``,album:``,duration:0,url:R.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),nn(e.video),w===e&&(S=`Watching ${e.name}, live on this server.`),U()}function Bi(){let e=w;return e?dt?!0:Ce>=5?(S=`${e.name} stopped, and did not come back.`,w=null,E=null,U(),!0):(Ce+=1,S=`${e.name} started over; rejoining…`,U(),dt=setTimeout(()=>{dt=null,w===e&&zi(e,!1)},2e3),!0):!1}function $(e){o.onairNote.textContent=e,G(e)}async function Vi(e,t){$(`Restarting ${t}…`);try{let n=await fetch(R.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}Ni=``,Q()}async function Hi(e,t){let n=globalThis.prompt(`Call ${t}…`,t);if(n===null)return;let r=n.trim();if(r!==``&&r!==t){$(`Renaming ${t}…`);try{let n=await fetch(R.url(`/api/channels/${encodeURIComponent(e)}`),{method:`PATCH`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r})}),i=await n.json().catch(()=>({}));$(n.ok?`${t} is now ${r}.`:i.error??`that did not work`)}catch{$(`could not reach the server`)}w?.id===e&&(w={...w,name:r}),Ni=``,Q(),U()}}async function Ui(e,t){$(`Taking ${t} off the air…`);try{let n=await fetch(R.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`}),r=await n.json().catch(()=>({}));$(n.ok?`${t} is off the air.`:r.error??`that did not work`)}catch{$(`could not reach the server`)}w?.id===e&&(w=null,L.stop()),Ni=``,Q()}async function Wi(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{S=e,U();return}n===`✓`||n===`✓`?c(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function Gi(e,t=0){let n=Ki();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 Ki(){if(ce!==``)return ce;let e=u===`remote`?R.shareLink:``;return/\/admin\//.test(e)?``:e}function qi(e){if(g===``)return;let t=g;if(t===`live`){g=``,e.server.playing?Ri(e.server.nowPlaying):(S=`Nothing is playing on this server right now.`,U());return}if(t.startsWith(`link:`)){g=``,an(t.slice(5));return}if(t.startsWith(`golive:`)){g=``,o.linkUrl.value=t.slice(7),En().then(()=>fn());return}if(t.startsWith(`track:`)){g=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&H(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&&(g=``,zi({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function Ji(e){let t=document.createElement(`li`);t.className=`onair`;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`,Ot(o,e.playLabel??`Join live`),o.addEventListener(`click`,e.onPlay),a.append(o);let s=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,c(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&a.append(s(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Wi(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&a.append(s(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Wi(e.direct??``,t,`✓`)})),e.onRestart&&a.append(s(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onRename&&a.append(s(`rename`,`Rename: call it something better in the directory`,()=>e.onRename?.())),e.onStop&&a.append(s(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,a),t}let Yi=``;function Xi(e,t){Yi=e;let n=e!==``&&t===e;o.loadHome.hidden=e===``,o.homeNote.hidden=e===``,e!==``&&(o.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,o.loadHome.disabled=!1)}o.loadHome.addEventListener(`click`,()=>{Yi!==``&&(o.loadHome.disabled=!0,G(`Reading this server's files…`),(async()=>{try{let e=await fetch(R.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Yi})}),t=await e.json();G(e.ok?t.added===0?`This server's files are already in the playlist.`:`Loaded ${t.added??0} of this server's own files.`:t.error??`that did not work`)}catch{G(`could not reach the server`)}finally{o.loadHome.disabled=!1}})())});let Zi=async e=>{o.goLive.disabled=!0,o.stopLive.disabled=!0,o.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(R.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();o.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{o.shareNote.textContent=`could not reach the server`}finally{o.goLive.disabled=!1,o.stopLive.disabled=!1,await Mi()}};o.goLive.addEventListener(`click`,()=>void Zi(!0)),o.stopLive.addEventListener(`click`,()=>void Zi(!1));function Qi(e){let t=document.createElement(`b`);return t.textContent=e,t}o.shareCopy.addEventListener(`click`,()=>{o.shareLink.select(),navigator.clipboard?.writeText(o.shareLink.value).then(()=>{o.shareNote.textContent=`Copied. Send it to anybody.`},()=>{o.shareNote.textContent=`Copy it from the box above.`})}),o.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=o.shareTo.value.trim();t!==``&&(async()=>{o.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ki()})}),n=await e.json();o.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(o.shareTo.value=``)}catch{o.shareNote.textContent=`could not send that`}})()}),o.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(gt,o.listenHere.checked?`1`:`0`)}catch{}u===`remote`&&(async()=>{o.listenHere.checked?(await R.send({type:`stop`}),await Ft(v.index)):(L.stop(),C=-1),U()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),It();return;case`s`:Rt();return;case`n`:case`ArrowRight`:Lt(1);return;case`p`:case`ArrowLeft`:Lt(-1);return;case`ArrowDown`:e.preventDefault(),H(Math.min(z()-1,B()+1));return;case`ArrowUp`:e.preventDefault(),H(Math.max(0,B()-1));return}});let $i=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),$i=e,o.install.hidden=!1}),o.install.addEventListener(`click`,()=>{$i?.prompt(),$i=null,o.install.hidden=!0});try{let e=localStorage.getItem(ht);e!==null&&(o.volume.value=String(Math.round(Number(e)*100)),L.volume=Number(e));let t=localStorage.getItem(pt);t&&(o.remoteUrl.value=t),localStorage.getItem(gt)===`0`&&(o.listenHere.checked=!1)}catch{}(async()=>{if(o.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await xe(e)===null)return;let t=await ve(e);t&&t.trackCount!==0&&(o.remoteUrl.value=e,u=`remote`,S=``,R.connect(e),U())})(),(()=>{if(vt||M!==``)return;let e=()=>L.source!==``||L.playing||Me()||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=()=>{vt=!0},i=()=>{document.removeEventListener(`pointerdown`,i),document.removeEventListener(`keydown`,i),r(),setTimeout(()=>{e()||n.play().catch(()=>{})},150)};t().then(t=>{if(!(t===``||e()))return n.src=t,n.play().then(r,()=>{document.addEventListener(`pointerdown`,i,{once:!0}),document.addEventListener(`keydown`,i,{once:!0})})})})(),U(),requestAnimationFrame($t)}yt(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{c as t};
@@ -1 +1 @@
1
- import{t as e}from"./index-CjxlA6ia.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-DAbMVJ3m.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};
1
+ import{t as e}from"./index-zCUbE3U5.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-WAX5pHld.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};