nixamp 0.24.2 → 0.25.1

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.
Files changed (40) hide show
  1. package/README.md +38 -0
  2. package/dist/captions.d.ts +12 -0
  3. package/dist/captions.js +29 -2
  4. package/dist/hash.d.ts +12 -0
  5. package/dist/hash.js +139 -0
  6. package/dist/main.js +27 -3
  7. package/dist/mcp.d.ts +3 -0
  8. package/dist/mcp.js +49 -1
  9. package/dist/media-index.d.ts +67 -0
  10. package/dist/media-index.js +114 -0
  11. package/dist/media-local.d.ts +43 -0
  12. package/dist/media-local.js +88 -0
  13. package/dist/media-page.d.ts +18 -0
  14. package/dist/media-page.js +146 -0
  15. package/dist/media.d.ts +145 -0
  16. package/dist/media.js +364 -0
  17. package/dist/server.d.ts +3 -0
  18. package/dist/server.js +186 -1
  19. package/dist/transcribe.js +20 -0
  20. package/dist/transcript-client.d.ts +19 -0
  21. package/dist/transcript-client.js +24 -0
  22. package/package.json +1 -1
  23. package/src/captions.ts +32 -2
  24. package/src/hash.ts +139 -0
  25. package/src/main.ts +27 -3
  26. package/src/mcp.ts +49 -1
  27. package/src/media-index.ts +145 -0
  28. package/src/media-local.ts +117 -0
  29. package/src/media-page.ts +159 -0
  30. package/src/media.ts +433 -0
  31. package/src/server.ts +178 -1
  32. package/src/transcribe.ts +17 -0
  33. package/src/transcript-client.ts +34 -0
  34. package/web/dist/assets/{hls-3VKVEQE3-B3PGV4wK.js → hls-3VKVEQE3-GlzSYi0P.js} +1 -1
  35. package/web/dist/assets/index-DJHHB_63.js +1 -0
  36. package/web/dist/assets/{mpegts-CtxeYR5-.js → mpegts-KIbyW_RL.js} +1 -1
  37. package/web/dist/assets/{mpegts-LO6RVLD6-CBHUeoME.js → mpegts-LO6RVLD6-Fs_vbGcB.js} +1 -1
  38. package/web/dist/index.html +1 -1
  39. package/web/dist/sw.js +5 -5
  40. package/web/dist/assets/index-DOOjAq1w.js +0 -1
package/src/server.ts CHANGED
@@ -94,6 +94,10 @@ import {
94
94
  Transcripts, fileFingerprint, formatOf, idFrom, languageCode, linesFrom, mediaOfLive, mediaOfUrl, toSrt, toText, toVtt, transcriptIdOf, wire,
95
95
  } from "./transcripts.ts";
96
96
  import { handleMessage as mcpMessage } from "./mcp.ts";
97
+ import { Media, factsFromRequest, holderFrom, mediaId, openFileListing, openFileOf, type MediaRecord } from "./media.ts";
98
+ import { mediaPage, type PageTranscript } from "./media-page.ts";
99
+ import { describeFile, refreshChanged } from "./media-local.ts";
100
+ import { WATCH_EVERY_MS, remember, watchOnce } from "./media-index.ts";
97
101
  import { Outro } from "./outro.ts";
98
102
  import { Profiles, Voices, spokenLine, spokenVoiceFor } from "./voices.ts";
99
103
  import { confirm, DEFAULT_DIRECTORY, Publisher } from "./publish.ts";
@@ -1747,6 +1751,8 @@ export interface HandlerOptions {
1747
1751
  transcripts?: Transcripts;
1748
1752
  /** Stored transcripts translated, as jobs. */
1749
1753
  translations?: StoredTranslations;
1754
+ /** The record of every file nixamp has met, by its SHA-256: nixamp.com/hash/<id>. */
1755
+ records?: Media;
1750
1756
  /** nixamp.com's address, for the tools reached over /mcp to call. */
1751
1757
  site?: string;
1752
1758
  /** Other people's OpenProfiles, for the voice their lines are read in. */
@@ -2892,6 +2898,134 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
2892
2898
  return;
2893
2899
  }
2894
2900
 
2901
+ /*
2902
+ * One address per file: /hash/<sha256>, the record of the bytes (see
2903
+ * media.ts). As a page for a person, as an OpenFile file object or plain
2904
+ * JSON for a program, and its transcript as subtitles. Reading is open:
2905
+ * the id is the hash of the bytes, and whoever has it has the file.
2906
+ * Keeping (PUT on the API) is signed in, like the ear.
2907
+ */
2908
+ if (path === "/.well-known/openfile.json" && options.records && options.site) {
2909
+ json(response, 200, openFileListing(await options.records.recent(), options.site));
2910
+ return;
2911
+ }
2912
+ if ((path.startsWith("/hash/") || path === "/api/v1/media" || path.startsWith("/api/v1/media/")) && options.records && options.transcripts && options.site) {
2913
+ const media = options.records;
2914
+ const store = options.transcripts;
2915
+ const site = options.site;
2916
+ const viaApi = path.startsWith("/api/v1/media");
2917
+ const tail = viaApi ? path.slice("/api/v1/media".length).replace(/^\//, "") : path.slice("/hash/".length);
2918
+ const parts = /^([^/.]+)(?:\.(openfile\.json|json|srt|vtt|txt))?\/?$/.exec(tail);
2919
+ if (!parts) {
2920
+ json(response, 404, { error: "a file is /hash/<sha256>, with .json, .openfile.json, .srt, .vtt or .txt after it" });
2921
+ return;
2922
+ }
2923
+ let named = "";
2924
+ try {
2925
+ named = decodeURIComponent(parts[1] as string);
2926
+ } catch {
2927
+ json(response, 400, { error: "bad id" });
2928
+ return;
2929
+ }
2930
+ const format = parts[2] ?? "";
2931
+ try {
2932
+ if (request.method === "PUT" && viaApi) {
2933
+ const who = await options.accounts?.whoIs(tokenFrom(request.headers));
2934
+ if (!who) {
2935
+ json(response, 401, { error: "sign in to nixamp.com to keep a file's record" });
2936
+ return;
2937
+ }
2938
+ const id = mediaId(named);
2939
+ if (!id) {
2940
+ json(response, 400, { error: "the id is the file's SHA-256, hex" });
2941
+ return;
2942
+ }
2943
+ let body: { name?: unknown; size?: unknown; contentType?: unknown; updated?: unknown; facts?: unknown; holder?: unknown } = {};
2944
+ try {
2945
+ body = JSON.parse(await readBody(request, 256 * 1024)) as typeof body;
2946
+ } catch {
2947
+ json(response, 400, { error: "bad JSON" });
2948
+ return;
2949
+ }
2950
+ const saved = await media.save({
2951
+ id,
2952
+ ...(typeof body.name === "string" ? { name: body.name.trim() } : {}),
2953
+ ...(typeof body.size === "number" && body.size >= 0 ? { size: Math.floor(body.size) } : {}),
2954
+ ...(typeof body.contentType === "string" ? { contentType: body.contentType.trim().slice(0, 100) } : {}),
2955
+ ...(typeof body.updated === "string" && !Number.isNaN(Date.parse(body.updated)) ? { updated: new Date(body.updated).toISOString() } : {}),
2956
+ facts: factsFromRequest(body.facts),
2957
+ holder: holderFrom(body.holder),
2958
+ by: who.id,
2959
+ });
2960
+ if (!saved) {
2961
+ json(response, 500, { error: "the record was not kept" });
2962
+ return;
2963
+ }
2964
+ json(response, 200, openFileOf(saved, site, saved.facts.fingerprint ? await store.languages(transcriptIdOf(saved.facts.fingerprint)) : []));
2965
+ return;
2966
+ }
2967
+ if (request.method !== "GET") {
2968
+ json(response, 405, { error: "GET the record, or PUT what you know" });
2969
+ return;
2970
+ }
2971
+ // By the SHA-256, by the transcript store's fingerprint, or by a transcript id.
2972
+ let record: MediaRecord | null = null;
2973
+ const hex = mediaId(named);
2974
+ if (hex) record = await media.get(hex);
2975
+ if (!record && /^file:v1:[0-9a-f]{64}$/.test(named)) record = await media.byFingerprint(named);
2976
+ if (!record && hex) {
2977
+ const transcript = await store.get(hex);
2978
+ if (transcript && transcript.kind === "file") record = await media.byFingerprint(transcript.media);
2979
+ }
2980
+ if (!record) {
2981
+ json(response, 404, { error: "nixamp.com does not know that file yet. `nixamp hash FILE` tells it." });
2982
+ return;
2983
+ }
2984
+ const transcriptId = record.facts.fingerprint ? transcriptIdOf(record.facts.fingerprint) : null;
2985
+ const languages = transcriptId ? await store.languages(transcriptId) : [];
2986
+ if (format === "srt" || format === "vtt" || format === "txt") {
2987
+ const language = languageCode(url.searchParams.get("language"));
2988
+ if (language === null) {
2989
+ json(response, 400, { error: "language is a two-letter code" });
2990
+ return;
2991
+ }
2992
+ const transcript = transcriptId ? await store.get(transcriptId, language) : null;
2993
+ if (!transcript) {
2994
+ json(response, 404, { error: language ? `not written down in ${language}` : "not written down yet" });
2995
+ return;
2996
+ }
2997
+ const text = format === "srt" ? toSrt(transcript.lines) : format === "vtt" ? toVtt(transcript.lines) : toText(transcript.lines);
2998
+ const name = (record.name.replace(/\.[^.]+$/, "") || record.id.slice(0, 12)).replace(/[^\w.-]+/g, "_").slice(0, 60);
2999
+ response.writeHead(200, {
3000
+ ...CORS,
3001
+ "content-type": `${format === "vtt" ? "text/vtt" : "text/plain"}; charset=utf-8`,
3002
+ "content-length": Buffer.byteLength(text),
3003
+ "cache-control": "public, max-age=300",
3004
+ "content-disposition": `inline; filename="${name}${transcript.language ? `.${transcript.language}` : ""}.${format}"`,
3005
+ });
3006
+ response.end(text);
3007
+ return;
3008
+ }
3009
+ const descriptor = openFileOf(record, site, languages);
3010
+ const accept = String(request.headers["accept"] ?? "");
3011
+ const wantsJson = viaApi || format === "json" || format === "openfile.json" || (accept.includes("application/json") && !accept.includes("text/html"));
3012
+ if (wantsJson) {
3013
+ json(response, 200, descriptor);
3014
+ return;
3015
+ }
3016
+ const original = transcriptId ? await store.get(transcriptId) : null;
3017
+ const forPage: PageTranscript[] = languages
3018
+ .slice()
3019
+ .sort((a, b) => (a.translatedFrom === null ? -1 : 0) - (b.translatedFrom === null ? -1 : 0))
3020
+ .map((one) => (original && one.language === original.language && one.translatedFrom === null ? { ...one, shown: original.lines } : one));
3021
+ html(response, 200, mediaPage(record, site, forPage));
3022
+ } catch (error) {
3023
+ if (error instanceof SpeechError) json(response, error.status, { error: error.message });
3024
+ else throw error;
3025
+ }
3026
+ return;
3027
+ }
3028
+
2895
3029
  /*
2896
3030
  * Translation: texts in one language, said in another, by a model on
2897
3031
  * this CPU (see translate.ts). Signed in only, like the ear. GET says
@@ -5796,6 +5930,8 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
5796
5930
  // What was heard, kept: where the accounts are, under the media's identity.
5797
5931
  const transcripts = pool ? new Transcripts(pool, (message) => console.log(message)) : undefined;
5798
5932
  const translations = transcripts ? new StoredTranslations(transcripts, translator, (message) => console.log(message)) : undefined;
5933
+ // The record of every file nixamp has met, by its bytes: nixamp.com/hash/<id>.
5934
+ const records = pool ? new Media(pool, (message) => console.log(message)) : undefined;
5799
5935
 
5800
5936
  // nixamp as an OAuth 2.1 authorization server, and the watch parties a
5801
5937
  // client site bridges through it. Both need the same three things -- a
@@ -6005,7 +6141,28 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
6005
6141
  return { ...base, media: mediaOfUrl(pasted), position: info.position };
6006
6142
  }
6007
6143
  try {
6008
- return { ...base, media: fileFingerprint(info.source), position: info.position };
6144
+ const source = info.source;
6145
+ return {
6146
+ ...base,
6147
+ media: fileFingerprint(source),
6148
+ position: info.position,
6149
+ // The file itself, for nixamp.com/hash/<id>: hashed here, once,
6150
+ // with what ffprobe and nichedb said and where it is on the air.
6151
+ describe: async () => {
6152
+ const listen = publishable_ ? shareLink(publishable_.url, listenKey, false) : (options.publicUrl || `http://${options.host}:${options.port}`);
6153
+ const described = await describeFile(source, {
6154
+ tools,
6155
+ enricher: enricher ?? null,
6156
+ holder: { kind: "gateway", url: listen, seenAt: new Date().toISOString(), channel: id, name: streamName },
6157
+ });
6158
+ try {
6159
+ remember(source, { id: described.id, fingerprint: described.fingerprint, size: described.size, mtimeMs: described.mtimeMs });
6160
+ } catch {
6161
+ // The index is a convenience.
6162
+ }
6163
+ return { id: described.id, keep: described.keep };
6164
+ },
6165
+ };
6009
6166
  } catch {
6010
6167
  return null;
6011
6168
  }
@@ -6015,6 +6172,25 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
6015
6172
  },
6016
6173
  })
6017
6174
  : undefined;
6175
+ // The files this machine has told nixamp.com about, looked at again on
6176
+ // their own schedule (media-index.ts): a changed file is a new record.
6177
+ if (tools.carries) {
6178
+ const watch = async (): Promise<void> => {
6179
+ const signed = readSession();
6180
+ if (!signed) return;
6181
+ const counts = await watchOnce({
6182
+ refresh: (file, before) => refreshChanged(signed, file, before, { tools, enricher: enricher ?? null }),
6183
+ onEvent: (message) => console.log(` ${message}`),
6184
+ }).catch((error: unknown) => {
6185
+ console.log(` the media index could not be read: ${(error as Error).message}`);
6186
+ return null;
6187
+ });
6188
+ if (counts && counts.changed > 0) console.log(` ${counts.changed} file(s) changed since nixamp.com last heard of them; told it`);
6189
+ };
6190
+ const watching = setInterval(() => void watch(), WATCH_EVERY_MS);
6191
+ watching.unref?.();
6192
+ setTimeout(() => void watch(), 60_000).unref?.();
6193
+ }
6018
6194
  const owner = new Owner({
6019
6195
  ownerId: options.owner || (session?.token ? await ownerIdOf(session) : ""),
6020
6196
  site: session?.site ?? DEFAULT_DIRECTORY,
@@ -6227,6 +6403,7 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
6227
6403
  ...(translator ? { translator } : {}),
6228
6404
  ...(transcripts ? { transcripts } : {}),
6229
6405
  ...(translations ? { translations } : {}),
6406
+ ...(records ? { records } : {}),
6230
6407
  site: nixampSite,
6231
6408
  // Other people's OpenProfiles, read for the voice a line is spoken in,
6232
6409
  // and the voices to speak in: ElevenLabs when the Telnyx account holds
package/src/transcribe.ts CHANGED
@@ -24,6 +24,8 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
24
  import { basename, extname, join } from "node:path";
25
25
  import { detectTools, type Tools } from "./audio.ts";
26
26
  import { isQuiet } from "./captions.ts";
27
+ import { Enricher } from "./enrich.ts";
28
+ import { describeFile, keepFile } from "./media-local.ts";
27
29
  import { readSession, type Session } from "./session.ts";
28
30
  import { MAX_SECONDS, RATE, isWav, type Segment } from "./speech.ts";
29
31
  import { fetchTranscript, keepLines, type Got, type StoredTranscript } from "./transcript-client.ts";
@@ -430,6 +432,21 @@ export async function transcribe(argv: string[], deps: TranscribeDeps = {}): Pro
430
432
  }
431
433
  const id = transcriptIdOf(media);
432
434
  const title = /^https?:\/\//.test(file) ? file : basename(file, extname(file));
435
+ // A file gets its address at nixamp.com/hash/<sha256> too, with what this
436
+ // machine knows about it, so the transcript has somewhere to hang.
437
+ if (!/^https?:\/\//.test(file) && !deps.fingerprint) {
438
+ void (async () => {
439
+ try {
440
+ const tools = detectTools();
441
+ const described = await describeFile(file, { tools, enricher: new Enricher() });
442
+ const refused = await keepFile(signed, file, described, { fetcher });
443
+ if (refused) console.error(` The file's record was not kept: ${refused}`);
444
+ else console.error(` ${site}/hash/${described.id}`);
445
+ } catch {
446
+ // The transcript is the point; the record is a bonus.
447
+ }
448
+ })();
449
+ }
433
450
  const wanted = (flag(argv, "--translate") ?? "").split(",").map((one) => languageCode(one)).filter((one): one is string => typeof one === "string" && one !== "");
434
451
  if (argv.includes("--translate") && wanted.length === 0) {
435
452
  console.error("nixamp: --translate is one or more two-letter codes, such as de,sv.");
@@ -120,6 +120,40 @@ export async function translateTexts(
120
120
  }
121
121
  }
122
122
 
123
+ /** What a machine tells nixamp.com about a file it has, for the record at /hash/<id>. */
124
+ export interface MediaToKeep {
125
+ name?: string;
126
+ size?: number;
127
+ contentType?: string;
128
+ updated?: string;
129
+ facts?: Record<string, unknown>;
130
+ holder?: { kind?: string; url: string; seenAt?: string; channel?: string; name?: string };
131
+ }
132
+
133
+ /** Keep what is known about a file, by its SHA-256 hex. */
134
+ export async function keepMedia(signed: Signed, id: string, ask: MediaToKeep, fetcher: typeof fetch = fetch): Promise<Got<Record<string, unknown>>> {
135
+ try {
136
+ const response = await fetcher(`${base(signed.site)}/api/v1/media/${encodeURIComponent(id)}`, {
137
+ method: "PUT",
138
+ headers: { authorization: `Bearer ${signed.token}`, "content-type": "application/json" },
139
+ body: JSON.stringify(ask),
140
+ });
141
+ return await asJson(response);
142
+ } catch (error) {
143
+ return unreachable(signed.site, error);
144
+ }
145
+ }
146
+
147
+ /** The record of a file, by id, fingerprint or transcript id. Public: no token needed. */
148
+ export async function fetchMedia(site: string, id: string, fetcher: typeof fetch = fetch): Promise<Got<Record<string, unknown>>> {
149
+ try {
150
+ const response = await fetcher(`${base(site)}/api/v1/media/${encodeURIComponent(id)}`, { headers: { accept: "application/json" } });
151
+ return await asJson(response);
152
+ } catch (error) {
153
+ return unreachable(site, error);
154
+ }
155
+ }
156
+
123
157
  /** Forget some media's transcripts. Only whoever stored them may. */
124
158
  export async function forgetTranscript(signed: Signed, id: string, fetcher: typeof fetch = fetch): Promise<Got<{ ok: true }>> {
125
159
  try {
@@ -1 +1 @@
1
- import{t as e}from"./index-DOOjAq1w.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-DJHHB_63.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())}function a(e){if(!/\.(?:mp4|m4v|mkv|webm|mov|avi|mp3|m4a|flac|ogg|opus|wav|aac)$/i.test(e))return e;let t=(e.split(/[\\/]/).pop()??e).replace(/\.[^.]+$/,``);return t.replace(/^0\d+[_ .-]+(?:\d+[_ .-]+)?/,``).replace(/_+/g,` `).trim()||t}function o(e){if(/^(?:[\\/]|[A-Za-z]:)/.test(e))return[];let t=e.split(/[\\/]/).filter(Boolean);return t.some(e=>e===`..`)?[]:t.filter(e=>e!==`.`).map(e=>e.replace(/_+/g,` `))}function s(e,t,n=`Live`){let r=e[t];if(!r){let e=a(n||`Live`);return{title:e,context:``,position:``,fullTitle:e}}let i=r.artist?`${r.artist} — ${a(r.title)}`:a(r.title),s=o(r.folder??``),c=o(r.group??``).join(` › `),l=[...c?[c]:[],...s],u=l.filter((e,t)=>t===0||e!==l[t-1]).join(` › `)||r.album,d=e.map((e,t)=>({one:e,at:t})).filter(({one:e})=>(e.group??``)===(r.group??``)&&(e.folder??``)===(r.folder??``)&&(l.length>0||e.album===r.album));return{title:i,context:u,position:`Playlist · ${d.findIndex(({at:e})=>e===t)+1} of ${d.length}`,fullTitle:u?`${u} › ${i}`:i}}var c=`modulepreload`,l=function(e){return`/`+e},u={},d=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=l(t,n),t=s(t),t in u)return;u[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`:c,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},f=[[/\.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`]],p=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function m(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of p)if(t.test(e.mimeType))return n}let t=h(e.src);for(let[e,n]of f)if(e.test(t))return n;return`unknown`}function h(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function ee(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 g(e,t){let n=m(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 te(e,t){let n=t.capabilities??ee(),r=g({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 d(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-GlzSYi0P.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await d(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-Fs_vbGcB.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await d(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 _=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`]),v=new Set([`ts`,`m2ts`,`mts`,`m2t`,`trp`,`tp`]);function ne(e){let t=e.lastIndexOf(`.`);return t>0&&v.has(e.slice(t+1).toLowerCase())}function re(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&_.has(e.slice(n+1).toLowerCase())}function ie(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ae(e){return e.filter(e=>re(e.name,e.type)).sort((e,t)=>ie(oe(e),oe(t))).map(e=>({title:n(e.name),artist:``,album:se(oe(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0,...ne(e.name)?{kind:`mpegts`}:{}}))}function oe(e){return e.webkitRelativePath||e.name}function se(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function ce(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var y=2048;function le(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 b(e,t){return e||t===`hls`||t===`mpegts`}var ue=class{elements;handlers;playBlocked=!1;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(x(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 needsInteraction(){return this.playBlocked}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(this.context??=new t,this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=y,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.playBlocked=!1,this.source=e.objectUrl?``:e.url;let n=e.kind??(e.objectUrl?e.video?`mp4`:`audio`:m({src:e.url})),r=b(e.video,n)?this.elements.video:this.elements.audio,i=e.objectUrl||le(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 te(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:`)||le(a),t&&await this.play()}async play(){this.analysable&&this.ensureGraph(this.active),this.playBlocked=!1;try{await this.active.play()}catch(e){if(e instanceof Error&&e.name===`NotAllowedError`){this.playBlocked=!0,this.handlers.onBusy?.(!1),this.handlers.onState(!1);return}this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.playBlocked=!1,this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function x(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 S(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 C(e,t,n=``){let r=`${e===``?``:S(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:S(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}var w=null;function he(e){if(!e&&w!==null)return w;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||(w=n),n}catch{return!1}}function T(e,t,n=0,r=``,i=!1){let a=[...n>0?[`kbps=${Math.round(n)}`]:[],...i?[`hevc=1`]:[]].join(`&`);return C(e,a?`/api/media/${t}?${a}`:`/api/media/${t}`,r)}function E(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 ge(e,t){if(e===``)return!1;try{return new URL(t).origin===new URL(e).origin}catch{return!1}}var _e=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;session=``;constructor(e){this.handlers=e}get address(){return this.base}owns(e){return ge(this.base,e)}url(e){let t=C(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(C(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=E(ve(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(C(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=E(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0,n=he()){return T(this.base,e,t,this.key,n)}close(){this.source?.close(),this.source=null}};function ve(e){try{return JSON.parse(e)}catch{return null}}async function ye(e,t,n=``){try{let r=await fetch(C(e,`/api/state`,n),{signal:t});return r.ok?E(await r.json()):null}catch{return null}}function be(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 xe(e,t=``,n){let r;try{r=await fetch(C(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 Se(e,t,n=``){try{let r=await fetch(C(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 Ce(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 we=.14,Te=.02;function Ee(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 De(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 Oe(e,t,n=we){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function ke(e,t,n=Te){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function Ae(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 je(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 Me(e){let t=String(e.data.state??e.tags?.find(e=>e.startsWith(`state:`))?.slice(6)??``);return t===`in`||t===`post`?t:`pre`}function D(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=je(n.away,n.awayScore),i=je(n.home,n.homeScore),a=Me(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=D(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`,O=/\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!==``?k(r):/\bSilk\b/.test(e)&&n===0?!0:O.test(e):k(i)}function k(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 Re=/\.(mp3|m4a|aac|ogg|oga|opus|flac|wav)(\?.*)?$/i,A=/\.(mp4|m4v|webm|mov|mkv)(\?.*)?$/i,ze=/\.m3u8(\?.*)?$/i,j=/\.(m3u|pls)(\?.*)?$/i;function Be(e){try{let t=new URL(e);return A.test(t.pathname+t.search)}catch{return!1}}function M(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()??``)||M(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(!Re.test(a)&&!A.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 He(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 Ue(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=He(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 j.test(o)?{kind:`list`,url:n.toString(),label:M(n.toString())}:Re.test(o)?{kind:`direct`,url:n.toString(),video:!1,label:s}:A.test(o)||ze.test(o)&&t?{kind:`direct`,url:n.toString(),video:!0,label:s}:null}var We=`nixamp.panels`;function Ge(){return{order:[],placement:{},collapsed:[],closed:[]}}var Ke=/^[a-z][a-z0-9-]{0,63}$/,N=/^[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`&&Ke.test(r)&&!t.has(r)&&(t.add(r),n.push(r));return n}function Je(e){if(!e)return Ge();let t;try{t=JSON.parse(e)}catch{return Ge()}if(!t||typeof t!=`object`||Array.isArray(t))return Ge();let n=t,r={};if(n.placement&&typeof n.placement==`object`)for(let[e,t]of Object.entries(n.placement))Ke.test(e)&&typeof t==`string`&&N.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`,it=`nixamp.captions.language`,at=[{code:``,label:`As spoken`},{code:`en`,label:`English`},{code:`de`,label:`Deutsch`},{code:`sv`,label:`Svenska`},{code:`es`,label:`Español`},{code:`fr`,label:`Français`},{code:`it`,label:`Italiano`},{code:`nl`,label:`Nederlands`},{code:`da`,label:`Dansk`},{code:`fi`,label:`Suomi`},{code:`ru`,label:`Русский`},{code:`uk`,label:`Українська`},{code:`cs`,label:`Čeština`},{code:`hu`,label:`Magyar`},{code:`zh`,label:`中文`},{code:`ar`,label:`العربية`},{code:`hi`,label:`हिन्दी`},{code:`vi`,label:`Tiếng Việt`},{code:`id`,label:`Bahasa Indonesia`}];function ot(e){try{let t=(e(`nixamp.captions.language`)??``).trim().toLowerCase();return at.some(e=>e.code===t)?t:``}catch{return``}}function st(e){return e.original!==void 0&&e.language?`[${e.language}] `:``}function ct(e,t){return(t?Math.max(e,6):Math.max(0,e))*1e3+1500}function lt(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 ut(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 dt(e){try{return e(rt)!==`off`}catch{return!0}}function ft(e){let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}var pt=/^[A-Za-z0-9 .&'-]{1,20}(?::|\s-)\s+/,mt=/(?:\s+|\s*[-|(]\s*)\d{1,2}(?::\d{2})?\s*(?:[ap]\.?m\.?)?(?:\s+[A-Z]{2,4})?\)?\s*$/i,ht=/\s+(?:vs\.?|v\.?|at|@)\s+/i,P=/^(?: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 gt(e){let t=e.replace(mt,``).replace(mt,``).trim().split(ht);return t.length===2&&t.every(e=>{let t=e.trim();return t.length>=2&&t.length<=48&&/[A-Za-z]/.test(t)&&!P.test(t)})}function _t(e){let t=String(e??``).trim();return t===``?!1:gt(t.replace(pt,``))||gt(t)}var vt=`nixamp.remote`,yt=`nixamp.defaultServer`,bt=`nixamp.volume`,xt=`nixamp.listenHere`,St=1e4,Ct=!1;function F(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function wt(){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 o=Ie(r),c={status:F(`status`),source:F(`source`),install:F(`install`),video:F(`video`),audio:F(`audio`),title:F(`title-line`),album:F(`album-line`),meta:F(`meta-line`),metaBlurb:F(`meta-blurb`),liveLine:F(`live-line`),downloadNow:F(`download-now`),wayInHere:F(`way-in-here`),embed:F(`embed`),embedFrame:F(`embed-frame`),linkForm:F(`link-form`),linkUrl:F(`link-url`),linkServer:F(`link-server`),linkGoLive:F(`link-go-live`),goLiveNow:F(`go-live-now`),elapsed:F(`elapsed`),total:F(`total`),seek:F(`seek`),fullscreen:F(`fullscreen`),copyNow:F(`copy-now`),canvas:F(`spectrum`),glyphs:F(`glyphs`),levels:F(`levels`),playlist:F(`playlist`),playlistPager:F(`playlist-pager`),crumbs:F(`crumbs`),filter:F(`filter`),playlistTitle:F(`playlist-panel`),note:F(`note`),linkNote:F(`link-note`),logList:F(`log-list`),files:F(`files`),folder:F(`folder`),remoteUrl:F(`remote-url`),remoteForm:F(`remote-form`),remoteState:F(`remote-state`),disconnect:F(`disconnect`),browse:F(`browse`),panelsToggle:F(`panels-toggle`),panelsPanel:F(`panels-panel`),panelsList:F(`panels-list`),panelsReset:F(`panels-reset`),accountForm:F(`account-form`),accountEmail:F(`account-email`),accountPassword:F(`account-password`),accountSubmit:F(`account-submit`),accountToggle:F(`account-toggle`),accountProviders:F(`account-providers`),accountPanel:F(`account-panel`),accountElsewhere:F(`account-elsewhere`),welcome:F(`welcome`),welcomeCreate:F(`welcome-create`),welcomeBrowse:F(`welcome-browse`),welcomeHide:F(`welcome-hide`),accountSignOut:F(`account-signout`),accountNote:F(`account-note`),personaForm:F(`persona-form`),personaHandle:F(`persona-handle`),personaVoice:F(`persona-voice`),personaProfile:F(`persona-profile`),personaNote:F(`persona-note`),adminPanel:F(`admin-panel`),adminNote:F(`admin-note`),adminSaid:F(`admin-said`),adminConnections:F(`admin-connections`),publishPanel:F(`publish-panel`),publishNote:F(`publish-note`),publishList:F(`publish-list`),adminRestream:F(`admin-restream`),adminReplace:F(`admin-replace`),adminSource:F(`admin-source`),adminName:F(`admin-name`),adminAdd:F(`admin-add`),homeNote:F(`home-note`),loadHome:F(`load-home`),directory:F(`directory`),recentNote:F(`recent-note`),recentList:F(`recent-list`),followingNote:F(`following-note`),followingList:F(`following-list`),serversPanel:F(`servers-panel`),serversNote:F(`servers-note`),serversList:F(`servers-list`),favoritesPanel:F(`favorites-panel`),favoritesNote:F(`favorites-note`),favoritesList:F(`favorites-list`),favHere:F(`fav-here`),partiesPanel:F(`parties-panel`),partiesNote:F(`parties-note`),partiesList:F(`parties-list`),partyForm:F(`party-form`),partyCode:F(`party-code`),partyJoin:F(`party-join`),connectionsNote:F(`connections-note`),connectionsList:F(`connections-list`),catalogsPanel:F(`catalogs-panel`),catalogsNote:F(`catalogs-note`),catalogsForm:F(`catalogs-form`),catalogSource:F(`catalog-source`),catalogName:F(`catalog-name`),catalogsList:F(`catalogs-list`),catalogsCrumbs:F(`catalogs-crumbs`),catalogsFilter:F(`catalogs-filter`),catalogsEntries:F(`catalogs-entries`),notifyPanel:F(`notify-panel`),notifyNote:F(`notify-note`),notifyWeb:F(`notify-web`),notifyEmail:F(`notify-email`),notifySms:F(`notify-sms`),notifyPhone:F(`notify-phone`),notifyPhoneForm:F(`notify-phone-form`),notifyPhoneNote:F(`notify-phone-note`),directoryNote:F(`directory-note`),directoryList:F(`directory-list`),onairPanel:F(`onair-panel`),onairNote:F(`onair-note`),onairList:F(`onair-list`),sharePanel:F(`share-panel`),trollboxPanel:F(`trollbox-panel`),trollboxNote:F(`trollbox-note`),trollboxList:F(`trollbox-list`),trollboxForm:F(`trollbox-form`),trollboxInput:F(`trollbox-input`),trollboxMic:F(`trollbox-mic`),trollboxEdit:F(`trollbox-edit`),trollboxEditLabel:F(`trollbox-edit-label`),transcriptPanel:F(`transcript-panel`),transcriptNote:F(`transcript-note`),transcriptOn:F(`transcript-on`),transcriptLanguage:F(`transcript-language`),transcriptList:F(`transcript-list`),subtitle:F(`subtitle`),shareNote:F(`share-note`),shareLink:F(`share-link`),shareCopy:F(`share-copy`),sharePhone:F(`share-phone`),shareSend:F(`share-send`),liveControls:F(`live-controls`),goLive:F(`go-live`),stopLive:F(`stop-live`),shareTo:F(`share-to`),listenOnly:F(`listen-only`),listenHere:F(`listen-here`),volume:F(`volume`),prev:F(`prev`),playPause:F(`play-pause`),stop:F(`stop`),next:F(`next`),shareNow:F(`share-now`)},l={party:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 21 4-12 8 8Z"/><path d="m7 9 8 8M12 7l1-3M16 10l4-1M16 5l2-2M20 14l1 1M8 4l-1-1"/><circle cx="21" cy="4" r=".5" fill="currentColor"/></svg>`,rename:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>`,eye:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>`,gear:`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1Z"/></svg>`,live:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="2.5"/><path d="M8.5 15.5a5 5 0 0 1 0-7"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M5.6 18.4a9 9 0 0 1 0-12.8"/><path d="M18.4 5.6a9 9 0 0 1 0 12.8"/></svg>`,link:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,copy:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12" rx="2"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/></svg>`,restart:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 3v6h-6"/></svg>`,remove:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>`,check:`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"/></svg>`},u=(e,t)=>{e.innerHTML=l[t]},d=document.querySelector(`meta[name="nixamp-shell-title"]`)?.content||document.title||`nixamp`,f=`local`,p=``,m=[],h=``,ee=!0,g=``;function te(e){try{return new URL(e).origin}catch{return e}}let _=!1,v=``,ne=0,re=new Map,ie=e=>re.get(G(e))??null;function oe(e,t){let n=n=>{_=n,v=``,c.remoteUrl.value=n?e.view:e.admin??e.view,t?.(),c.remoteForm.requestSubmit()},r=document.createElement(`button`);r.type=`button`,r.className=`icon way-in`,u(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`,u(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 se=``,y=[],le=0,b=de(),x=`idle`,S=``,w=`Pick files, or connect to a nixamp running somewhere else.`,he=!1,T=-1,E=null;function ge(e){return e?/^https?:\/\//i.test(e)?e:z.url(e):``}let ve=0,we=0,Te=!1,je=()=>!R.needsInteraction&&(we>0||Te);async function D(e){we+=1,H();try{return await e()}finally{--we,H()}}let O=null,k=null,Re=``,A=null,ze=``,j=null,M=null,He=0;function Ke(){c.embed.hidden||(c.embedFrame.src=`about:blank`),c.embed.hidden=!0}let N=null,qe=``,pt=null;function mt(e,t,n=null,r=!1){let i=`${t}|${e}`;if(qe=i,pt&&clearTimeout(pt),pt=null,!r){if(N?.key===i)return;N=null}if(f!==`remote`||e.trim()===``)return;let a=new URLSearchParams({name:e,kind:t});n&&a.set(`year`,String(n)),fetch(z.url(`/api/enrich?${a}`)).then(e=>e.ok?e.json():{match:null}).then(r=>{if(qe!==i)return;N={key:i,match:r.match??null},H();let a=N.match;a?.kind===`fixture`&&Me(a)!==`post`&&(pt=setTimeout(()=>{pt=null,!(qe!==i||R.source===``&&!E)&&mt(e,t,n,!0)},6e4))}).catch(()=>void 0)}let ht=!1,P=``,gt=``,wt=null,Tt=``,Et=``,Dt=``,I=Array(24).fill(0),Ot=Array(24).fill(0),kt=[],L=()=>f===`remote`&&!c.listenHere.checked,At=()=>f===`remote`&&!c.adminPanel.hidden,jt=!1,Mt=()=>At()||f===`remote`&&jt;function Nt(){try{if(localStorage.getItem(`nixamp.hls`)===`1`)return!0}catch{}return typeof MediaSource<`u`?!1:c.video.canPlayType(`application/vnd.apple.mpegurl`)!==``}function Pt(){if(f!==`remote`||j)return null;if(O?.catalog&&O.entry)return{kind:`entry`,catalog:O.catalog,entry:O.entry};if(E)return{kind:`channel`,id:E.id,name:E.name};let e=b.tracks[B()];return e&&(R.source!==``||L())?{kind:`track`,index:B(),name:t(e)}:null}async function Ft(e,t){t.disabled=!0;let n=e.kind===`entry`?e.entry.title:e.name;w=`Putting ${n} on the air…`,H();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(z.url(t),{method:`POST`}),s=await o.json().catch(()=>({}));if(!o.ok){w=s.error??`${n} would not go on the air.`,H();return}i=e.kind===`channel`?e.id:s.channel??``,a=s.video!==!1,r=`channel:${i}`}if(At()&&(ht?await fetch(z.url(`/api/live/start`),{method:`POST`}).catch(()=>void 0):await ua(!0)),await Wi(),Q(),i!==``&&E?.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 Qi({id:i,name:n,video:a},!0,t)}let o=ia(r),s=P?` Call ${gt||`the line`} and key ${P} to talk about it.`:``;o===``?w=`${n} is on the air and you are watching it.${s}`:(await ra(o,t,`✓`),w=`${n} is on the air and you are watching it. Link copied.${s}`),H()}catch{w=`could not reach the server`,H()}finally{t.disabled=!1}}function It(e,t=`Join party`){u(e,t===`Join party`?`party`:`live`),e.append(document.createTextNode(` ${t}`)),e.title=t===`Join party`?`Join live`:t}It(c.partyJoin);function Lt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`row-copy row-live`,u(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(),Ft(e(),n)}),n}let R=new ue({audio:c.audio,video:c.video},{readable:e=>z.owns(e),onTime:(e,t)=>{let n=y[le];f===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),H()},onEnded:()=>{$i()||xn()||f===`remote`&&T<0&&!L()||Xt(1)},onState:()=>H(),onBusy:e=>{Te!==e&&(Te=e,H())},onError:e=>{if(!$i()&&!(He!==0&&Date.now()-He<2e3)){if(M&&e===`this browser cannot play that format`){let e=M.url;if(M=null,He=Date.now(),Mt()){w=`That site will not let a page play it directly; going live with it on ${p||`the server`} instead.`,H(),c.linkUrl.value=e,Tn();return}w=`That site will not let a page play it directly. Pick a server beside the link and press Go live: the server carries it.`,H();return}w=e,H(),Yi()}}}),z=new _e({onSnapshot:e=>{let t=e.tracks!==void 0||b.index!==e.index;if(b=fe(b,e),v.startsWith(`track:`)&&b.tracks.length>0){let e=Number(v.slice(6));if(v=``,Number.isInteger(e)&&e>=0&&e<b.tracks.length){let t=ne;Jt(e).then(()=>{t>0&&(R.seek(t),setTimeout(()=>R.seek(t),600))})}}L()&&(I=e.bars.length>0?e.bars:I,Ot=ke(Ot,I)),H(),t&&k&&Ji(k)},onStatus:(e,t)=>{x=e,S=t??``,H()}}),Rt=()=>f===`remote`?b.tracks.length:y.length,B=()=>f===`remote`?L()||T<0?b.index:Math.min(T,Math.max(0,b.tracks.length-1)):le,zt=()=>{let e=k?.server.nowPlaying||`Live`;return(!A||A.tracks!==b.tracks||A.index!==b.index||A.fallback!==e)&&(A={tracks:b.tracks,index:b.index,fallback:e,value:s(b.tracks,b.index,e)}),A.value},Bt=()=>f===`remote`&&!E&&O?.kind===`live`,Vt=()=>Bt()?zt().fullTitle:V(),V=()=>{if(E)return E.name;if(j)return j.label;if(Bt())return zt().title;let e=f===`remote`?b.tracks[B()]:y[B()];return e?t(e):`Nothing loaded.`},Ht=()=>{if(E)return`live on this server`;if(j)return`playing here, in this browser`;if(Bt()){let{context:e,position:t}=zt();return[e,t,`live on ${p||`this server`}`].filter(Boolean).join(` · `)}return(f===`remote`?b.tracks[B()]:y[B()])?.album||`—`};function Ut(){if(f!==`remote`||E===null&&O?.kind!==`live`){c.liveLine.hidden=!0,c.liveLine.replaceChildren(),delete c.liveLine.dataset.drawn;return}let e=p||`this server`,t=E?E.name:zt().fullTitle,n=[E?`Live on ${e}: `:`Live from ${e}, now playing: `,da(t)],r=E?k?.channels.find(e=>e.id===E?.id)?.code??``:ht?P:``;r&&n.push(`. To talk about it, call `,da(gt||`the line`),` and key `,da(r),`.`);let i=n.map(e=>typeof e==`string`?e:e.textContent).join(``);c.liveLine.dataset.drawn!==i&&(c.liveLine.dataset.drawn=i,c.liveLine.hidden=!1,c.liveLine.replaceChildren(...n.map(e=>typeof e==`string`?document.createTextNode(e):e)))}let Wt=()=>L()?b.tracks[B()]?.duration??0:R.duration,Gt=()=>L()?b.position:R.position,Kt=()=>L()?b.playing:R.playing;async function qt(e){if(f===`remote`){if(L()){await z.send({type:`play`,index:e});return}await Jt(e);return}let t=y[e];t&&(le=e,E=null,O={kind:`file`},await D(()=>R.load(t,!0)),gn(t.video),_n(),H())}async function Jt(e){let t=b.tracks[e];t&&(T=e,E=null,O={kind:`file`},mt(t.title,`auto`),await D(()=>R.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:z.media(e,0),video:t.video===!0,objectUrl:!1},!0)),gn(t.video===!0),_n())}async function Yt(){if(R.needsInteraction){await R.play(),H();return}if(L()){await z.send({type:`toggle`});return}Rt()!==0&&(R.playing?R.pause():R.position>0?await R.play():await qt(B()),H())}async function Xt(e){let t=Rt();if(t!==0){if(L()){await z.send({type:e>0?`next`:`prev`});return}await qt((B()+e+t)%t)}}async function Zt(){if(Ke(),j=null,M=null,L()){await z.send({type:`stop`});return}E=null,O=null,R.stop(),I=Array(24).fill(0),Ot=[...I],H()}let Qt=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,$t=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))],en=``;function tn(){let t=[],n=``,r=null,i=E?k?.channels.find(e=>e.id===E?.id):void 0;E&&i?.ended&&ze!==E.id&&(ze=E.id,$n(`${E.name} has ended. What is playing is its outro; the room stays open for an hour, then the channel closes.`));let a=R.source===``&&!E&&!(L()&&b.tracks[B()]);if(!a){E&&i?.ended?t.push(`ENDED`):E?t.push(O?.entry?.live===!1?`ON DEMAND · LIVE CHANNEL`:`LIVE`):O?.kind===`vod`?t.push(`ON DEMAND`):O?.kind===`live`?t.push(`LIVE`):f===`remote`&&L()?t.push(`ON THE SERVER`):t.push(`FILE`),!c.video.hidden&&c.video.videoWidth>0?t.push(`${c.video.videoWidth}×${c.video.videoHeight}`):c.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}×`),At()&&i.error&&t.push(i.error)):f===`remote`&&!E?(b.tracks[B()]&&Rt()>0&&t.push(`${Bt()?`library track`:`track`} ${B()+1} of ${Rt()}`),L()&&k&&t.push(`${k.server.playing?`playing`:`stopped`} on ${p||`the server`}`)):f===`local`&&Rt()>0&&t.push(`track ${B()+1} of ${Rt()}`),O?.catalog!==void 0&&(O.kind===`channel`?E!==null:O.kind===`vod`&&R.source!==``)&&O?.catalog&&(t.push(O.entry?.group?`${O.catalog.name} › ${O.entry.group}`:O.catalog.name),n=O.entry?.logo??``),n===``&&E&&(n=ge(i?.art??E.art));let a=N?.key===qe?N.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(E&&O?.link){let e=``;try{e=new URL(O.link.url).hostname.replace(/^www\./,``)}catch{}t.push(O.link.extractor&&O.link.extractor!==`direct`&&O.link.extractor!==`generic`?`${O.link.extractor} · ${e}`:e||`link`)}ht&&P&&L()&&!E&&O?.kind!==`live`&&t.push(gt?`☎ ${gt} · key ${P}`:`☎ code ${P}`)}let o=N?.key===qe?N.match:null,s=!a&&!r&&o?.summary?o.summary:``,l=`${n}|${r?`${r.away.logo}|${r.home.logo}|${r.text}`:``}|${t.join(`|`)}|${s}`;if(l===en)return;en=l,c.meta.hidden=t.length===0,c.metaBlurb.textContent=s,c.metaBlurb.hidden=s===``;let u=[];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)),u.push(e)}if(n!==``&&/^(https?:\/\/|\/api\/)/.test(n)){let e=document.createElement(`img`);e.className=o?.kind===`title`&&n===o.image?`meta-logo meta-poster`:`meta-logo`,e.alt=``,e.src=n,e.addEventListener(`error`,()=>{e.hidden=!0}),u.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,u.push(t)}c.meta.replaceChildren(...u)}function H(){let t=Rt(),n=Kt(),r=je();c.status.textContent=r?`LOADING`:n?`▶ PLAYING`:`■ STOPPED`,c.status.dataset.playing=r?`loading`:String(n),c.title.textContent=V(),c.title.classList.toggle(`with-context`,Bt()),c.album.classList.toggle(`with-context`,Bt()),(Bt()||E)&&_n(),Ut(),tn(),c.goLiveNow.hidden=!Mt()||Pt()===null;let i=n?`${Vt()} · ${d}`:d;document.title!==i&&(document.title=i),c.copyNow.hidden=R.source===``,c.shareNow.hidden=Ir()===``,yr(),jr(),c.downloadNow.hidden=!(E&&O?.link?.download),Cn(),c.album.textContent=Ht();let a=Gt(),o=Wt();c.elapsed.textContent=e(a),c.total.textContent=o>0?e(o):`--:--`,he||(c.seek.value=String(o>0?Math.round(a/o*1e3):0),c.seek.disabled=o<=0||L()),c.playPause.textContent=n?`❚❚`:`▶`,c.playPause.setAttribute(`aria-label`,n?`Pause`:`Play`),c.playlistTitle.dataset.title=f===`remote`?`Files on ${p||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,c.source.textContent=f===`remote`?`connected · ${p||z.address.replace(/^https?:\/\//,``)||`—`}`:y.length>0?`local · ${y.length} files`:`no source`,hn(),c.remoteState.textContent=f===`remote`?`${x}${S?` — ${S}`:``}`:`not connected`,c.remoteState.dataset.status=f===`remote`?x:`idle`,c.disconnect.hidden=f!==`remote`;let s=R.needsInteraction?`Press Play to start playback. Your browser needs a click first.`:f===`remote`&&b.note!==``?b.note:w;c.note.textContent=s,c.note.hidden=s===``,c.linkNote.textContent=s,c.linkNote.hidden=s===``,$n(s),un(),c.glyphs.textContent=I.map($t).join(``);let[l,u]=L()?b.levels:R.levels();c.levels.textContent=Qt(l,u)}let nn=``,rn=-1,U=``,an=0;function on(e){U=e,an=0,nn=``,un()}function sn(e,t,n,r,i){if(c.playlistPager.hidden=n<=1,n<=1){c.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`,()=>{an=t,nn=``,un(),c.playlist.scrollIntoView({block:`nearest`})}),i},o=document.createElement(`span`);o.className=`pager-where`,o.textContent=`${r+1}–${i} of ${e.toLocaleString()}`,c.playlistPager.replaceChildren(a(`‹ Previous`,t-1,`The page before this one`),o,a(`Next ›`,t+1,`The page after this one`))}function cn(e){if(c.crumbs.hidden=!e,!e)return;let t=U===``?[]:U.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`,()=>on(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))}),c.crumbs.replaceChildren(...r)}function ln(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`,()=>on(U===``?e:`${U}/${e}`)),n}function un(){let n=f===`remote`?b.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):y.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),r=c.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)),a=e=>r!==``||U===``||e===U||e.startsWith(`${U}/`),s=e=>r!==``||e===U,l=e=>{let t=U===``?e:e.slice(U.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},d=new Map;for(let e of i){if(!a(e.folder)||s(e.folder))continue;let t=l(e.folder);t!==``&&d.set(t,(d.get(t)??0)+1)}let p=i.filter(e=>s(e.folder)&&a(e.folder)),m=[...d].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})),h=Le(m.length+p.length,an,o);an=h.page;let ee=m.slice(h.from,h.to),g=p.slice(Math.max(0,h.from-m.length),Math.max(0,h.to-m.length)),te=`${f}:${U}:${r}:${h.page}/${o}:${m.join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(te!==nn){nn=te,cn(r===``&&(m.length>0||U!==``)),sn(m.length+p.length,h.page,h.pages,h.from,h.to);let t=[];for(let[e,n]of ee)t.push(ln(e,n));let n=``,i=p.some(e=>e.group!==``);for(let r of g){r.group!==n&&(i||r.group!==``)&&(n=r.group,t.push(dn(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 c=document.createElement(`span`);if(c.className=`time`,c.textContent=r.seconds>0?e(r.seconds):`--:--`,a.append(o,s,c),f===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,u(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(),ra(ia(`track:${r.index}`,T===r.index?R.position:0),e,`✓`)}),a.append(e),Mt()&&a.append(Lt(()=>({kind:`track`,index:r.index,name:r.name}),r.name))}t.push(a)}c.playlist.replaceChildren(...t)}let _=B(),v=Kt(),ne;for(let e of Array.from(c.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===_;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&v),r&&(ne=t)}if(_!==rn){rn=_;let e=p.findIndex(e=>e.index===_);if(e>=0&&!ne){an=Math.floor((m.length+e)/o),nn=``,un();return}ne?.scrollIntoView({block:`nearest`})}}function dn(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!==``&&!c.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(),fn(e)}),t.append(n)}return t}async function fn(e){try{let t=await fetch(z.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();W(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{W(`could not reach the server`)}}function pn(){let t=c.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(L())Ot=ke(Ot,I);else{let e=R.read();e.length>0&&(kt.length!==25&&(kt=Ee(24,e.length)),I=Oe(I,De(e,kt)),Ot=ke(Ot,I))}if(a){let e=getComputedStyle(document.documentElement);Ae(a,{width:t.width,height:t.height},I,Ot,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(Kt()){c.glyphs.textContent=I.map($t).join(``);let[t,n]=L()?b.levels:R.levels();c.levels.textContent=Qt(t,n),c.elapsed.textContent=e(Gt());let r=Wt();!he&&r>0&&(c.seek.value=String(Math.round(Gt()/r*1e3)))}requestAnimationFrame(pn)}let mn=``;function hn(){if(f!==`remote`){c.wayInHere.hidden=!0,mn=``;return}let e=At()&&!_,t=se||z.address,n=e?null:ie(z.address),r=`${t}|${n??``}|${e?`admin`:`view`}`;if(r===mn)return;mn=r;let[i,a]=oe({name:p||`this server`,view:t,admin:n});i.hidden=!e,a.hidden=e,c.wayInHere.replaceChildren(i,a),c.wayInHere.hidden=!1}function gn(e){c.video.hidden=!e,c.fullscreen.hidden=!e,Ke(),j=null,M=null}function _n(){if(!(`mediaSession`in navigator)||typeof MediaMetadata>`u`)return;let e=E?ge(k?.channels.find(e=>e.id===E?.id)?.art??E.art):``,t=JSON.stringify([V(),Ht(),e]);t!==Re&&(Re=t,navigator.mediaSession.metadata=new MediaMetadata({title:V(),album:Ht(),artist:`nixamp`,artwork:e===``?[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]:[{src:e}]}),navigator.mediaSession.setActionHandler(`play`,()=>void Yt()),navigator.mediaSession.setActionHandler(`pause`,()=>void Yt()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void Xt(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void Xt(-1)))}c.filter.addEventListener(`input`,()=>{an=0,nn=``,un()}),c.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())}),c.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&qt(n)}),c.fullscreen.addEventListener(`click`,()=>{let e=c.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),c.prev.addEventListener(`click`,()=>void Xt(-1)),c.next.addEventListener(`click`,()=>void Xt(1)),c.stop.addEventListener(`click`,()=>void Zt()),c.playPause.addEventListener(`click`,()=>void Yt());async function vn(e){let t=Ue(e,Nt());if(!t){if(!Mt()){w=f===`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.`,H();return}await Sn(e);return}if(E=null,R.stop(),t.kind===`embed`){O={kind:`link`,link:{url:e,extractor:t.site,download:!1,live:!1,video:!0}},gn(!1),c.embedFrame.src=t.src,c.embed.hidden=!1,j={url:e,label:t.label,kind:`embed`},w=`Playing ${t.label} here, in this browser.`,H();return}if(t.kind===`list`){await yn(e,t.label);return}O={kind:`link`,link:{url:e,extractor:`direct`,download:!1,live:!1,video:t.video}},await D(()=>R.load({title:t.label,artist:``,album:``,duration:0,url:t.url,video:t.video,objectUrl:!1},!0)),gn(t.video),j={url:e,label:t.label,kind:`direct`},w=`Playing ${t.label} here, in this browser.`,H()}async function yn(e,t){w=`Reading ${t}…`,H();let n=``;try{let t=await fetch(e,{mode:`cors`});if(!t.ok)throw Error(`HTTP ${t.status}`);n=await t.text()}catch(e){w=`That playlist could not be read here (${e.message}). Go live with it instead: the server reads it.`,H();return}let r=Ve(n,e);if(r.entries.length===0){w=`Nothing in that playlist is a file this browser plays. Go live with it instead: the server reads it.`,H();return}M={url:e,title:r.title||t,entries:r.entries,at:0},await bn()}async function bn(){let e=M,t=e?.entries[e.at];if(!e||!t)return;let n=Be(t.url);O={kind:`link`,link:{url:e.url,extractor:`playlist`,download:!1,live:!1,video:n}},await D(()=>R.load({title:t.title,artist:e.title,album:``,duration:0,url:t.url,video:n,objectUrl:!1},!0)),M!==null&&(gn(n),j={url:e.url,label:e.title,kind:`direct`},M=e,w=`Playing ${e.title} here: ${e.at+1} of ${e.entries.length}, ${t.title}.`,H())}function xn(){let e=M;return!e||e.entries.length===0?!1:(e.at=(e.at+1)%e.entries.length,bn(),!0)}async function Sn(e){if(f!==`remote`){w=`Pick a server to go live on, or connect to one, to put a link on the air.`,H();return}w=`Asking ${p||`the server`} to fetch ${e}…`,H(),await D(async()=>{let t,n={};try{t=await fetch(z.url(`/api/links/play`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({url:e,live:!0})}),n=await t.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!t.ok||!n.channel){w=n.error??`that link would not play.`;return}try{await fetch(z.url(`/api/channels/${encodeURIComponent(n.channel)}/keep`),{method:`POST`})}catch{}await Qi({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&&(w=`${n.name||e} is on the air: ${n.entries} entries, played in turn.`)}),H()}c.linkForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.linkUrl.value.trim();t!==``&&vn(t)});function Cn(){let e=f===`remote`?z.address:``,t=m.filter(t=>te(t.url)!==te(e)),n=JSON.stringify({here:e,name:p,carries:ee,others:t});if(n===h)return;h=n;let r=[];if(e!==``&&ee){let t=document.createElement(`option`);t.value=``,t.textContent=`on ${p||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)}c.linkServer.replaceChildren(...r),c.linkServer.value=e!==``&&!ee&&t[0]?t[0].url:``,c.linkServer.hidden=t.length===0}async function wn(){try{let e=await fetch(`/api/directory`);if(!e.ok)return;m=((await e.json()).streams??[]).map(e=>({name:e.name,url:e.url})),Cn()}catch{}}async function Tn(){let e=c.linkUrl.value.trim()||j?.url||``;if(e===``){w=`Paste a link first: a file, an .m3u playlist, an IPTV feed, a YouTube page.`,H();return}let t=c.linkServer.value;if(t!==``&&(f!==`remote`||te(t)!==te(z.address))){let n=m.find(e=>e.url===t)?.name??t;g=e,w=`Connecting to ${n} to go live with it…`,H(),En(t);return}if(f!==`remote`){w=m.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.`,H(),m.length>0&&c.linkServer.focus();return}if(!ee){w=`${p||`This server`} has no ffmpeg, so it cannot carry a link.`+(m.length>0?` Pick a server to go live on, beside the link.`:``),H();return}if(!Mt()){w=`Sign in to nixamp.com to go live here, or use the server's control link.`,H();return}await Sn(e)}function En(e){let t=c.linkUrl.value.trim();_=!0,v=``,c.remoteUrl.value=e,c.remoteForm.requestSubmit(),c.linkUrl.value=t}c.linkGoLive.addEventListener(`click`,()=>{Tn()}),c.linkServer.addEventListener(`change`,()=>{let e=c.linkServer.value;e!==``&&En(e)}),c.downloadNow.addEventListener(`click`,()=>{let e=O?.link;if(!e||f!==`remote`)return;let t=e.video?``:`&audio=1`;globalThis.open(z.url(`/api/links/download?url=${encodeURIComponent(e.url)}${t}`),`_blank`),w=`Fetching it through the server; your browser will save it when it arrives.`,H()}),c.goLiveNow.addEventListener(`click`,()=>{let e=Pt();e&&Ft(e,c.goLiveNow)}),c.seek.addEventListener(`input`,()=>{he=!0}),c.seek.addEventListener(`change`,()=>{let e=Wt();e>0&&R.seek(Number(c.seek.value)/1e3*e),he=!1}),c.volume.addEventListener(`input`,()=>{let e=Number(c.volume.value)/100;R.volume=e;try{localStorage.setItem(bt,String(e))}catch{}});let Dn=e=>{e.addEventListener(`change`,()=>{let t=ae(Array.from(e.files??[]));if(t.length===0){w=`Nothing playable in that selection.`,H();return}ce(y),y=t,le=0,f=`local`,z.close(),w=``,qt(0)})};Dn(c.files),Dn(c.folder),c.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.remoteUrl.value,{base:n,key:r}=me(t);if(n===``){w=`That is not an address.`,H();return}(async()=>{x=`connecting`,H();let e=Ce(n);if(e){x=`error`,S=e,w=e,g=``,f=`local`,H();return}if(await Se(n,void 0,r)===null){x=`error`;let e=be(n);S=e?`needs the server's name`:`not answering`,w=e||`Nothing answered at ${n}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,g=``,f=`local`,H();return}let i=await xe(n,r);if(i){x=`error`,S=i,w=i,g=``,f=`local`,H();return}f=`remote`,w=``;try{localStorage.setItem(vt,t.trim())}catch{}z.connect(t),Q(),Gr(),qi(!0),zn(),Wi(),H()})()});let On=``,kn=null,An=async(e=!1)=>{c.directory.hidden=!1,e||(c.directoryNote.textContent=`Looking for live streams…`,c.directoryList.replaceChildren()),kn||=setInterval(()=>{!c.directory.hidden&&document.visibilityState===`visible`&&An(!0)},St);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??[],m=t.map(e=>({name:e.name,url:e.url})),Cn();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===On)return;On=i,Hn(r.recent??[])}catch{e||(c.directoryNote.textContent=`The directory is not answering. Type an address instead.`);return}if(c.directoryList.replaceChildren(),t.length===0){c.directoryNote.textContent=`Nobody is streaming right now.`;return}c.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 o=e.admin??ie(e.url),s=(t,n=``)=>{_=t,v=n,c.remoteUrl.value=t?e.url:o??e.url,c.directory.hidden=!0,c.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 c=document.createElement(`button`);c.type=`button`,c.className=`button`,It(c),c.title=`Join live: ${t} on ${e.name}`,c.addEventListener(`click`,()=>s(!0,`channel:${t}`)),n.append(r,c),l.append(n)}let[u,d]=oe({name:e.name,view:e.url,admin:o},()=>{c.directory.hidden=!0});if(t.append(n,u,d),X&&t.append(Zn(e.url,e.name)),e.ownerId&&X&&e.ownerId!==X&&t.append(ii(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(()=>({}));c.directoryNote.textContent=t.ok?`${e.name} is off the list.`:n.error??`that did not work`}catch{c.directoryNote.textContent=`could not reach the directory`}finally{await An()}})()}),t.append(n)}c.directoryList.append(t)}};if(document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`visible`&&!c.directory.hidden&&An(!0)}),location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),An()}let jn=null,Mn=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Nn=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,Pn=``,Fn=``,In=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===Pn)return;Pn=t,c.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)}c.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,``],[Mn(t.network),`network-${t.network}`],[Nn(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)}c.adminConnections.append(e)}};function W(e){c.adminSaid.textContent=e,c.adminSaid.hidden=e===``}let Ln=async()=>{try{let e=await fetch(z.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;c.adminNote.textContent=n===0?`${r} listening now.`:`${r} listening now, and ${n} with the page open.`,In(t.connections??[]),Rn(t.publish??[],(t.channels??[]).map(e=>e.id)),la(t.home??``,t.root??``),Q()}catch{c.adminNote.textContent=`lost touch with the server`}};function Rn(e,t){c.publishPanel.hidden=e.length===0;let n=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(n===Fn)return;if(Fn=n,e.length===0){c.publishList.replaceChildren();return}let r=e.length-t.length;c.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${r} free right now.`,c.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 zn=async()=>{if(f!==`remote`){c.adminPanel.hidden=!0,c.publishPanel.hidden=!0,jn&&clearInterval(jn),jn=null;return}let e=!1,t=null,n=!1,r=!1;try{let i=await fetch(z.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(_&&(e=!1),jt=i&&!e,c.adminPanel.hidden=!e,Ui(e),g!==``){let e=g;g=``,Mt()?Sn(e):(w=`Sign in to nixamp.com to go live here.`,H())}if(jn&&clearInterval(jn),jn=null,Q(),Gr(),Wi(),c.listenOnly.hidden=e,!e){c.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}c.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Ln(),jn=setInterval(()=>void Ln(),2e3)};function Bn(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)}`;W(`Starting ${t||e}…`),(async()=>{try{let i=await fetch(z.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){W(a.error??`that did not work`);return}W(`${a.channel?.name||t||e} is on the air.`),c.adminSource.value=``,c.adminName.value=``,Wi(),Q()}catch{W(`could not reach the server`)}})()}c.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=c.adminSource.value.trim();t&&Bn(t,c.adminName.value.trim())}),c.adminAdd.addEventListener(`click`,()=>{let e=c.adminSource.value.trim();if(!e)return;W(`Reading ${e}…`);let t=c.adminReplace.checked,n=c.adminName.value.trim();(async()=>{try{let r=await fetch(z.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();W(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&&(c.adminSource.value=``,c.adminName.value=``,Wi(),Q())}catch{W(`could not reach the server`)}})()});let Vn=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`},Hn=e=>{c.recentList.replaceChildren();let t=X?e.filter(e=>e.ownerId&&e.ownerId!==X):[];if(c.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 ${Vn(e.endedAt)}`:`ended ${Vn(e.endedAt)}`,n.append(r,i),t.append(n,ii(e.ownerId,e.name)),c.recentList.append(t)}},Un=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 Wn(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?`▶ ${Un(e.party.positionNow)}`:`❚❚ ${Un(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`,It(a),a.title=`Join live on the site hosting this party (opens in a new tab)`;let o=document.createElement(`a`);return o.className=`ghost`,o.href=e.links.nixampUrl,o.textContent=`Open room`,t.append(n,a,o),t}async function Gn(){if(!X){c.partiesPanel.hidden=!0;return}try{let e=await fetch(`/api/v1/watch-parties`);if(!e.ok){c.partiesPanel.hidden=!0;return}let t=(await e.json()).parties??[];c.partiesPanel.hidden=!1,c.partiesNote.textContent=t.length===0?`No parties happening right now. Join with an invite code.`:`Join a party on the site hosting the film, or open its room here.`,c.partiesList.replaceChildren(...t.map(Wn))}catch{c.partiesPanel.hidden=!0}}c.partyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.partyCode.value.trim();t!==``&&(async()=>{try{let e=await fetch(`/api/v1/watch-parties/${encodeURIComponent(t)}`),n=await e.json().catch(()=>({}));if(!e.ok){w=n.error??`No party found with that invite code.`,H();return}c.partyCode.value=``,window.location.href=n.links.nixampUrl}catch{w=`Could not look up that party. Try again.`,H()}})()});async function Kn(){if(!X){c.connectionsNote.hidden=!0,c.connectionsList.hidden=!0;return}try{let e=await fetch(`/api/v1/oauth/connections`);if(!e.ok){c.connectionsNote.hidden=!0,c.connectionsList.hidden=!0;return}let t=(await e.json()).connections??[];c.connectionsNote.hidden=t.length===0,c.connectionsList.hidden=t.length===0,c.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 Kn()})()}),t.append(n,a),t}))}catch{c.connectionsNote.hidden=!0,c.connectionsList.hidden=!0}}let qn=new Set,G=e=>{try{return new URL(e).origin}catch{return e}},Jn=e=>[...qn].some(t=>G(t)===G(e));async function Yn(){if(!X){qn=new Set,c.favoritesPanel.hidden=!0,Qn();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){c.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];qn=new Set(t.map(e=>e.url)),c.favoritesPanel.hidden=t.length===0,c.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,c.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:ie(e.url)}),Zn(e.url,e.name)),t}))}catch{c.favoritesPanel.hidden=!0}Qn()}async function Xn(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){w=n?`Could not save that favourite.`:`Could not remove that favourite.`,H();return}}catch{w=`could not reach nixamp.com`,H();return}if(n)qn.add(e);else for(let t of[...qn])G(t)===G(e)&&qn.delete(t);await Yn()}function Zn(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=Jn(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=[...qn].find(t=>G(t)===G(e))??e;Xn(Jn(e)?i:e,t,!Jn(e)).then(r)}),n}function Qn(){let e=f===`remote`?z.shareLink:``;if(c.favHere.hidden=!(X&&e),c.favHere.hidden)return;let t=Jn(e);c.favHere.textContent=t?`♥`:`♡`,c.favHere.dataset.on=t?`yes`:`no`,c.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,c.favHere.setAttribute(`aria-label`,c.favHere.title)}u(c.copyNow,`copy`),c.copyNow.addEventListener(`click`,()=>{ra(R.source,c.copyNow,`✓`)});function $n(e){if(e===``||e===Dt)return;Dt=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),c.logList.prepend(t);c.logList.children.length>100;)c.logList.lastElementChild?.remove()}let er=3e3,tr=/(^|\.)nixamp\.com$/.test(globalThis.location.hostname)?``:`https://nixamp.com`,nr=``,rr=``,ir=null,ar=!1,or=new Set,sr=``,cr=null,lr=!1,ur=dt(e=>localStorage.getItem(e)),K=ot(e=>localStorage.getItem(e)),dr=``,fr=null,pr=ct(6,!1),mr=[],hr=[],gr=null;function _r(){if(f!==`remote`)return null;let{base:e}=me(aa());if(e===``)return null;let t=``;try{t=new URL(e).origin}catch{return null}let n=E?E.id:O?.kind===`live`?`live`:``;return n===``?null:{server:t,channel:n}}function vr(e,t=``){let n=new URLSearchParams({server:e.server,channel:e.channel});return t&&n.set(`after`,t),`${tr}/api/v1/trollbox?${n.toString()}`}function yr(){let e=_r(),t=e?`${e.server}|${e.channel}`:``;t!==nr&&(nr=t,rr=``,or.clear(),c.trollboxList.replaceChildren(),ir&&clearTimeout(ir),ir=null,c.trollboxPanel.hidden=e===null,c.trollboxForm.hidden=!0,wr(!1),e&&(c.trollboxNote.textContent=`The room for ${V()||e.channel}. Loading…`,xr()))}function br(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`);return a.className=`line`,a.textContent=e.body,t.append(n,i,a),t}async function xr(){let e=_r(),t=e?`${e.server}|${e.channel}`:``;if(e&&t===nr&&!ar){ar=!0;try{let n=await fetch(vr(e,rr)),r=await n.json().catch(()=>({}));if(t!==nr)return;if(!n.ok){c.trollboxNote.textContent=r.error??`The trollbox is not answering.`;return}let i=(r.messages??[]).filter(e=>!or.has(e.id));for(let e of i)or.add(e.id),c.trollboxList.append(br(e)),rr=e.createdAt;for(;c.trollboxList.children.length>200;)c.trollboxList.firstElementChild?.remove();i.length>0&&c.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`});let a=r.you??``;sr=a,c.trollboxForm.hidden=a===``,c.trollboxEditLabel.hidden=a===``||!Sr,a===``&&wr(!1),c.trollboxNote.textContent=a===``?tr===``?`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===nr&&(c.trollboxNote.textContent=`The trollbox is not answering.`)}finally{ar=!1,t===nr&&(ir=setTimeout(()=>{document.visibilityState===`visible`?xr():ir=setTimeout(()=>void xr(),er)},er))}}}c.trollboxForm.addEventListener(`submit`,e=>{e.preventDefault();let t=_r(),n=c.trollboxInput.value.trim();t&&n!==``&&(c.trollboxInput.disabled=!0,(async()=>{try{let e=await fetch(`${tr}/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){c.trollboxNote.textContent=r.error??`that did not send`;return}c.trollboxInput.value=``,or.has(r.message.id)||(or.add(r.message.id),c.trollboxList.append(br(r.message)),rr=r.message.createdAt,c.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`}))}catch{c.trollboxNote.textContent=`The trollbox is not answering.`}finally{c.trollboxInput.disabled=!1,c.trollboxInput.focus()}})())});let Sr=typeof MediaRecorder<`u`&&typeof navigator.mediaDevices?.getUserMedia==`function`,Cr=Sr?et(e=>MediaRecorder.isTypeSupported(e)):``;c.trollboxMic.hidden=!Sr;function q(e){c.trollboxNote.textContent=e,$n(e)}function wr(e){let t=cr;if(!t)return;cr=null,clearTimeout(t.stop),clearInterval(t.tick),c.trollboxMic.setAttribute(`aria-pressed`,`false`),c.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(()=>Er(new Blob(t.chunks,{type:t.recorder.mimeType||Cr||`audio/webm`}),t.startedAt))}async function Tr(){if(cr||lr||sr===``||!_r())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,Cr?{mimeType:Cr}:{})}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();cr={recorder:t,stream:e,chunks:n,startedAt:r,stop:setTimeout(()=>wr(!0),$e),tick:setInterval(()=>{c.trollboxMic.textContent=nt(r,Date.now())},500)},t.start(250),c.trollboxMic.setAttribute(`aria-pressed`,`true`),c.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 Er(e,t){let n=_r();if(n&&sr!==``){if(Date.now()-t<400||e.size===0){q(`That was too short to hear. Tap, say it, then tap again.`);return}lr=!0,c.trollboxMic.disabled=!0,c.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 o=tt((await i.startRendering()).getChannelData(0),Qe),s=c.trollboxEdit.checked,l=new URLSearchParams(s?{}:{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(`${tr}/api/v1/speech/transcribe?${l.toString()}`,{method:`POST`,headers:{"content-type":`audio/wav`},body:new Blob([o.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(s||!f.message){let e=c.trollboxInput.value.trimEnd();c.trollboxInput.value=(e===``?p:`${e} ${p}`).slice(0,500),c.trollboxInput.focus(),c.trollboxInput.setSelectionRange(c.trollboxInput.value.length,c.trollboxInput.value.length),q(`Heard: “${p}”. Send it, or fix it first.`);return}_r()&&!or.has(f.message.id)&&(or.add(f.message.id),c.trollboxList.append(br(f.message)),rr=f.message.createdAt,c.trollboxList.lastElementChild?.scrollIntoView({block:`nearest`})),q(`Said: “${f.message.body}”`)}catch{q(`That recording could not be read here.`)}finally{lr=!1,c.trollboxMic.disabled=!1,c.trollboxMic.textContent=`🎤`}}}c.trollboxMic.addEventListener(`click`,()=>{cr?wr(!0):Tr()});try{c.trollboxEdit.checked=localStorage.getItem(`nixamp.dictate.edit`)===`on`}catch{}c.trollboxEdit.addEventListener(`change`,()=>{try{localStorage.setItem(`nixamp.dictate.edit`,c.trollboxEdit.checked?`on`:`off`)}catch{}q(c.trollboxEdit.checked?`A line you say will wait in the box for Send.`:`A line you say goes straight to the room.`)});async function Dr(){try{let e=await fetch(`${tr}/api/v1/me/handle`),t=await e.json().catch(()=>({}));if(!e.ok){c.personaNote.textContent=t.error??`Could not read your profile.`;return}c.personaHandle.value=t.chosen?t.handle??``:``,c.personaHandle.placeholder=t.handle||`handle`,c.personaVoice.value=t.voice===`female`||t.voice===`male`?t.voice:``,c.personaProfile.value=t.profile??``;let n=t.spoken?` (${t.spoken.replace(/^Telnyx\.KokoroTTS\./,`Kokoro `).replace(/^ElevenLabs\./,`ElevenLabs `)})`:``;c.personaNote.textContent=t.chosen?`You are ${t.handle} in every room. On the phone your lines are read ${Or(t.voice??``)}${n}.`:`Rooms call you ${t.handle} until you pick a handle. On the phone your lines are read ${Or(t.voice??``)}${n}.`}catch{c.personaNote.textContent=`Could not reach nixamp.com for your profile.`}}function Or(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`}c.personaForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.personaHandle.value.trim(),n={voice:c.personaVoice.value,profile:c.personaProfile.value.trim()};t!==``&&(n.handle=t),c.personaNote.textContent=`Saving…`,(async()=>{try{let e=await fetch(`${tr}/api/v1/me/handle`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(n)}),t=await e.json().catch(()=>({}));if(!e.ok){c.personaNote.textContent=t.error??`that did not save`;return}await Dr()}catch{c.personaNote.textContent=`Could not reach nixamp.com.`}})()}),document.addEventListener(`visibilitychange`,()=>{document.visibilityState!==`visible`&&cr&&wr(!0)});function kr(){return f!==`remote`||!E?null:{id:E.id,name:E.name,hls:E.video&&Nt()}}function Ar(){fr?.close(),fr=null,gr&&clearInterval(gr),gr=null,mr=[],hr=[],c.transcriptList.replaceChildren(),c.subtitle.hidden=!0,c.subtitle.textContent=``}function jr(){let e=kr(),t=e?`${e.id}|${e.hls}|${ur}|${K}`:``;if(t!==dr){if(dr=t,Ar(),c.transcriptPanel.hidden=e===null,c.transcriptOn.checked=ur,c.transcriptLanguage.options.length===0)for(let e of at)c.transcriptLanguage.append(new Option(e.label,e.code));if(c.transcriptLanguage.value=K,e){if(!ur){c.transcriptNote.textContent=`Captions are off on this device. Turn them on and ${e.name} is written down as it speaks.`;return}c.transcriptNote.textContent=`Asking for ${e.name}'s captions…`,Mr(e,t)}}}async function Mr(e,t){let n=6,r=K?`?language=${encodeURIComponent(K)}`:``;try{let i=await fetch(z.url(`/api/channels/${encodeURIComponent(e.id)}/transcript${r}`)),a=await i.json().catch(()=>({}));if(t!==dr)return;if(!i.ok){c.transcriptNote.textContent=a.error??`This server is not captioning.`;return}n=a.backlog??n}catch{t===dr&&(c.transcriptNote.textContent=`The server did not answer about captions.`);return}pr=ct(n,e.hls);let i=new EventSource(z.url(`/api/channels/${encodeURIComponent(e.id)}/captions${r}`));fr=i;let a=e=>{for(let t of e)t&&typeof t.text==`string`&&Number.isFinite(t.at)&&mr.push(t)};i.addEventListener(`hello`,r=>{if(t!==dr)return;let i=JSON.parse(r.data);pr=ct(i.backlog??n,e.hls),a(i.lines??[]);let o=i.language?` It speaks ${at.find(e=>e.code===i.language)?.label??i.language}.`:``,s=K&&K!==i.language?` Translated to ${at.find(e=>e.code===K)?.label??K} as it goes.`:``,l=i.known?` ${i.known} lines were already written down.`:``;if(c.transcriptNote.textContent=i.error?`Captions for ${e.name} are not coming: ${i.error}`:`What ${e.name} is saying, a few seconds behind the sound.${o}${s}${l}`,!i.error&&i.hash&&/^[0-9a-f]{64}$/.test(i.hash)){let e=document.createElement(`a`);e.href=`${tr||``}/hash/${i.hash}`,e.textContent=`Its page`,e.target=`_blank`,e.rel=`noopener`,c.transcriptNote.append(` `,e,`.`)}}),i.addEventListener(`line`,e=>{t===dr&&a([JSON.parse(e.data)])}),i.addEventListener(`error`,()=>{t===dr&&i.readyState===EventSource.CLOSED&&(c.transcriptNote.textContent=`Captions stopped; the server went away.`)}),gr=setInterval(Pr,250)}function Nr(e){let t=document.createElement(`li`),n=document.createElement(`time`);n.className=`when`,n.dateTime=new Date(e.at).toISOString(),n.textContent=ft(e.at);let r=document.createElement(`span`);r.className=`line`,r.textContent=e.text;let i=st(e);if(i){let a=document.createElement(`span`);a.className=`lang`,a.textContent=i.trim(),e.original&&(r.title=e.original),t.append(n,a,r)}else t.append(n,r);return t}function Pr(){let e=Date.now(),{ready:t,still:n}=lt(mr,e,pr);mr=n;for(let e of t)hr.push(e),c.transcriptList.append(Nr(e));for(;hr.length>200;)hr.shift();for(;c.transcriptList.children.length>200;)c.transcriptList.firstElementChild?.remove();t.length>0&&c.transcriptList.lastElementChild?.scrollIntoView({block:`nearest`});let r=ut(hr,e,pr),i=c.transcriptList.children,a=r?hr.indexOf(r):-1;for(let e=0;e<i.length;e++)i[e]?.classList.toggle(`now`,e===a);let o=r!==null&&!c.video.hidden&&c.video.offsetHeight>0;c.subtitle.hidden=!o,o&&r&&(c.subtitle.textContent!==r.text&&(c.subtitle.textContent=r.text),c.subtitle.style.top=`${c.video.offsetTop+c.video.offsetHeight-c.subtitle.offsetHeight-10}px`)}c.transcriptOn.addEventListener(`change`,()=>{ur=c.transcriptOn.checked;try{localStorage.setItem(rt,ur?`on`:`off`)}catch{}jr()}),c.transcriptLanguage.addEventListener(`change`,()=>{K=ot(()=>c.transcriptLanguage.value);try{K?localStorage.setItem(it,K):localStorage.removeItem(it)}catch{}jr()});function Fr(){if(j)return j.url;if(f!==`remote`)return``;let{base:e,key:t}=me(aa());if(e===``)return``;if(E)return C(e,`/api/channels/${encodeURIComponent(E.id)}`,t);if(O?.kind===`live`)return C(e,`/api/live`,t);if(R.source===``)return``;try{let n=new URL(R.source);return n.origin===new URL(e).origin?(t?n.searchParams.set(`k`,t):n.searchParams.delete(`k`),n.toString()):``}catch{return``}}function Ir(){let e=Fr();return e===``?``:`https://nixamp.com/?play=${encodeURIComponent(e)}`}c.shareNow.addEventListener(`click`,()=>{let e=Ir();if(e===``)return;let t=navigator;if(typeof t.share==`function`){t.share({title:`${Vt()} on nixamp`,url:e}).catch(()=>void 0);return}ra(e,c.shareNow,`Copied`)}),c.favHere.addEventListener(`click`,()=>{let e=aa()||z.shareLink;if(!e)return;let t=[...qn].find(t=>G(t)===G(e))??e;Xn(Jn(e)?t:e,p||z.address,!Jn(e)).then(Qn)});let Lr=r?o:200,Rr=[],J=null,Y=null,zr=``,Br=[],Vr=0,Hr=null,Ur=0;function Wr(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 Gr(){if(f!==`remote`){c.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(z.url(`/api/catalogs`))}catch{c.catalogsPanel.hidden=!0;return}if(!e.ok){c.catalogsPanel.hidden=!0;return}Rr=(await e.json().catch(()=>({}))).catalogs??[],J&&=Rr.find(e=>e.id===J?.id)??null,J||(Y=null),c.catalogsPanel.hidden=!1,Kr()}function Kr(){let e=!c.adminPanel.hidden;c.catalogsForm.hidden=!e;let t=Rr.reduce((e,t)=>e+t.live,0),n=Rr.reduce((e,t)=>e+t.vod,0);c.catalogsNote.textContent=Rr.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${Rr.length} ${Rr.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${n} on demand`,qr();let r=J!==null&&Y!==null;if(c.catalogsList.hidden=r,c.catalogsFilter.hidden=!r,c.catalogsEntries.hidden=!r,r){Qr();return}if(J){Yr(J);return}c.catalogsList.replaceChildren(...Rr.map(t=>Jr(t,e)))}function qr(){let e=J!==null;if(c.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,Kr()},!1),n(),t(J?.name??``,()=>{Y=null,Kr()},Y===null)];Y!==null&&r.push(n(),t(Y===``?`All groups`:Y,()=>void 0,!0)),c.catalogsCrumbs.replaceChildren(...r)}function Jr(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 ${Wr(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,Kr()}),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`,()=>{ei(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?`)&&ti(e)}),n.append(t,r)}return n}async function Yr(e){c.catalogsList.replaceChildren();let t=[];try{let n=await D(()=>fetch(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`)));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{w=`Could not read the groups in ${e.name}.`,H();return}if(J?.id!==e.id||Y!==null)return;let n=[Xr(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>Xr(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];c.catalogsList.replaceChildren(...n)}function Xr(e,t,n,r,i){let a=document.createElement(`li`),o=document.createElement(`span`);o.className=`server-label`;let s=document.createElement(`span`);s.className=`name`,s.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${n.toLocaleString()} · ${r.toLocaleString()} live · ${i.toLocaleString()} on demand`,o.append(s,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{Y=t,zr=``,c.catalogsFilter.value=``,Br=[],Vr=0,Kr(),Zr(0)}),a.append(o,u),a}async function Zr(e){let t=J,n=Y;if(!t||n===null)return;let r=++Ur,i=new URLSearchParams({group:n,q:zr,offset:String(e),limit:String(Lr)}),a;try{let e=await D(()=>fetch(z.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`)));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{w=`Could not read ${t.name}.`,H();return}r===Ur&&(Vr=a.total??0,Br=e===0?a.entries??[]:[...Br,...a.entries??[]],Qr())}function Qr(){let t=J;if(!t)return;let n=Br.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`,u(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`;ra(z.url(i),e,`✓`)}),r.append(e)}return Mt()&&r.append(Lt(()=>({kind:`entry`,catalog:{id:t.id,name:t.name},entry:n}),n.title)),r.addEventListener(`click`,()=>{$r(t,n,r)}),r});if(Br.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=zr?`Nothing called "${zr}" here.`:`Nothing in this group.`,e.append(t),n.push(e)}else if(Br.length<Vr){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${Br.length.toLocaleString()} of ${Vr.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),Zr(Br.length)}),e.append(t),n.push(e)}c.catalogsEntries.replaceChildren(...n)}async function $r(e,t,n){n?.classList.add(`loading`),w=`Starting ${t.title}…`;let r={catalog:{id:e.id,name:e.name},entry:t};try{await D(async()=>{let n,i={};try{n=await fetch(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),i=await n.json().catch(()=>({}))}catch{w=`could not reach the server`;return}if(!n.ok){w=i.error??`${t.title} would not play.`;return}let a=i.name||t.title;if(i.kind===`live`&&i.channel){await Qi({id:i.channel,name:a,video:!0},!0,{kind:`channel`,...r});return}if(i.kind===`vod`&&i.url){E=null,T=-1,O={kind:`vod`,...r},mt(a,`title`),await R.load({title:a,artist:``,album:``,duration:0,url:z.url(i.url),video:!0,objectUrl:!1},!0),gn(!0),w=`Playing ${a}.`;return}w=`${t.title} would not play.`})}finally{n?.classList.remove(`loading`),H()}}async function ei(e){W(`Reading ${e.name} again…`);try{let t=await fetch(z.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));W(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{W(`could not reach the server`)}Gr()}async function ti(e){try{W((await fetch(z.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{W(`could not reach the server`)}J?.id===e.id&&(J=null,Y=null),Gr()}c.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.catalogSource.value.trim(),n=c.catalogName.value.trim();t&&(async()=>{W(`Reading ${n||t}…`);try{let e=await fetch(z.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){W(r.error??`that did not work`);return}W(`${r.catalog?.name??n??t}: ${(r.catalog?.entries??0).toLocaleString()} entries.`),c.catalogSource.value=``,c.catalogName.value=``}catch{W(`could not reach the server`)}Gr()})()}),c.catalogsFilter.addEventListener(`input`,()=>{Hr&&clearTimeout(Hr),Hr=setTimeout(()=>{Hr=null,zr=c.catalogsFilter.value.trim(),Zr(0)},250)});let ni=async()=>{c.serversList.replaceChildren();try{let e=await fetch(`/api/v1/servers`);if(!e.ok){c.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];re=new Map(t.map(e=>[G(e.url),e.key?`${e.url}/admin/${e.key}`:e.url])),c.serversPanel.hidden=!1,c.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,[o,s]=oe({name:e.name,view:a,admin:a});Se(e.url).then(n=>{if(n!==null){i.textContent=`${e.url} · ${n}`;return}i.textContent=`${e.url} · not answering`,t.classList.add(`offline`),o.disabled=!0,s.disabled=!0,o.title=s.title=`That machine is not answering. Start nixamp on it.`});let l=yi()===G(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`,()=>{bi(l?``:G(e.url)),ni()});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 ni()}catch{d.disabled=!1}})()}),t.append(n,o,s,u,d),c.serversList.append(t)}}catch{c.serversPanel.hidden=!0}},ri=async()=>{c.followingList.replaceChildren();try{let e=await fetch(`/api/v1/follows`);if(!e.ok){c.followingNote.hidden=!0;return}let t=(await e.json()).following??[];c.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(),c.followingList.children.length===0&&(c.followingNote.hidden=!0)}finally{a.disabled=!1}})()}),t.append(n,a),c.followingList.append(t)}}catch{c.followingNote.hidden=!0}},ii=(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),ri())}catch{}finally{n.disabled=!1}})()}),n},ai=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},oi=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,si=async()=>{if(!oi())return c.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return c.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return c.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 c.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:ai(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 c.notifyNote.textContent=`This device will be told.`,!0}catch{return c.notifyNote.textContent=`Could not set this device up.`,!1}},ci=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{}},li=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();c.notifyPhoneNote.textContent=t.ok?``:n.error??`that did not save`,t.ok&&typeof n.phone==`string`&&(c.notifyPhone.value=n.phone)}catch{c.notifyPhoneNote.textContent=`could not reach nixamp.com`}},ui=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();c.notifyEmail.checked=t.wantsEmail!==!1,c.notifySms.checked=t.wantsSms===!0,c.notifyPhone.value=t.phone??``;let n=oi()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;c.notifyWeb.checked=t.wantsWeb!==!1&&n,c.notifyNote.textContent=n?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};c.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(c.notifyWeb.checked){let e=await si();c.notifyWeb.checked=e,await li({wantsWeb:e});return}await ci(),await li({wantsWeb:!1}),c.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),c.notifyEmail.addEventListener(`change`,()=>{li({wantsEmail:c.notifyEmail.checked})}),c.notifySms.addEventListener(`change`,()=>{(async()=>{if(c.notifySms.checked&&!c.notifyPhone.value.trim()){c.notifyPhoneNote.textContent=`Add a phone number first.`,c.notifySms.checked=!1,c.notifyPhone.focus();return}await li({wantsSms:c.notifySms.checked})})()}),c.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),li({phone:c.notifyPhone.value.trim()})});let di=!1,X=``,fi=!1,pi=`nixamp.welcome`,mi=()=>{let e=!1;try{e=localStorage.getItem(pi)===`hidden`}catch{}c.welcome.hidden=!fi||X!==``||e},hi=e=>{let t=e!==null;c.notifyPanel.hidden=!t,t?(ui(),ri(),ni()):(c.serversPanel.hidden=!0,c.followingNote.hidden=!0,c.followingList.replaceChildren(),c.recentNote.hidden=!0,c.recentList.replaceChildren()),c.accountForm.hidden=t,c.accountProviders.hidden=t||c.accountProviders.childElementCount===0,c.accountSignOut.hidden=!t,c.personaForm.hidden=!t,c.personaNote.hidden=!t,t&&Dr(),c.accountNote.textContent=t?`Signed in as ${e}.`:di?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,c.accountSubmit.textContent=di?`Create account`:`Sign in`,c.accountToggle.textContent=di?`I have one`:`Create one`,c.accountPassword.autocomplete=di?`new-password`:`current-password`,mi()},gi=async()=>{let e=[];fi=!1;try{let t=await fetch(`/api/v1/auth/providers`);t.ok&&(fi=!0,e=(await t.json()).providers??[])}catch{}c.accountProviders.replaceChildren(),c.accountProviders.hidden=e.length===0,c.accountPanel.hidden=!fi,c.accountElsewhere.hidden=fi,mi();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}`,c.accountProviders.append(e)}},_i=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();X=e.ok?t.account?.id??``:``,hi(e.ok?t.account?.email??`you`:null)}catch{X=``,hi(null)}if(z.session=``,X!==``){try{let e=await fetch(`/api/v1/auth/token`),t=await e.json().catch(()=>({}));z.session=e.ok&&typeof t.token==`string`?t.token:``}catch{z.session=``}f===`remote`&&zn()}Yn(),Gn(),Kn(),xi();let e=await vi();if(Et!==``){let t=Et;Et=``,e?v=`golive:${t}`:vn(t)}};async function vi(){if(X===``||f===`remote`||Tt!==``)return!1;let e=[];try{let t=await fetch(`/api/v1/servers`);if(!t.ok)return!1;e=(await t.json()).servers??[]}catch{return!1}if(e.length===0)return!1;let t=yi(),n=[...e].sort((e,n)=>Number(G(n.url)===t)-Number(G(e.url)===t));for(let e of n)if(await Se(e.url,void 0,e.key)!==null)return f!==`remote`&&(_=!1,v=``,c.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,w=`Connecting to ${e.name}, your server…`,H(),c.remoteForm.requestSubmit(),!0);return!1}function yi(){try{return localStorage.getItem(yt)??``}catch{return``}}function bi(e){try{e===``?localStorage.removeItem(yt):localStorage.setItem(yt,e)}catch{}}function xi(){if(Tt===``)return;let e=Tt;Tt=``,c.remoteUrl.value=e,c.remoteForm.requestSubmit()}c.accountToggle.addEventListener(`click`,()=>{di=!di,hi(null)}),c.welcomeCreate.addEventListener(`click`,()=>{di=!0,hi(null),c.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),c.accountEmail.focus({preventScroll:!0})}),c.welcomeBrowse.addEventListener(`click`,()=>{c.directory.hidden?c.browse.click():c.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),c.welcomeHide.addEventListener(`click`,()=>{try{localStorage.setItem(pi,`hidden`)}catch{}c.welcome.hidden=!0}),c.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=c.accountEmail.value.trim(),n=c.accountPassword.value;(async()=>{c.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${di?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})}),r=await e.json();if(!e.ok){c.accountNote.textContent=r.error??`that did not work`;return}X=r.account?.id??``,c.accountPassword.value=``,hi(r.account?.email??t),zn(),xi()}catch{c.accountNote.textContent=`could not reach nixamp.com`}finally{c.accountSubmit.disabled=!1}})()}),c.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}X=``,hi(null),z.close(),T=-1,f=`local`,x=`idle`,S=``,c.remoteUrl.value=``,c.sharePanel.hidden=!0,c.publishPanel.hidden=!0,c.adminPanel.hidden=!0,c.onairPanel.hidden=!0,c.catalogsPanel.hidden=!0,c.listenOnly.hidden=!0,qi(!1);try{localStorage.removeItem(vt)}catch{}w=`Signed out, and disconnected from the server.`,zn(),H()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(Tt=t,v=e.get(`play`)??``,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),c.remoteUrl.value=t,w=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname));let n=e.get(`link`)??``;n!==``&&(c.linkUrl.value=n,t!==``&&v===``?v=`link:${n}`:t===``&&(Et=n));let r=e.get(`play`)??``;if(t===``&&/^https?:\/\//i.test(r)){let t=pe(r);t?(Tt=t.view,v=t.what,ne=Math.max(0,Number(e.get(`t`)??`0`)||0),c.remoteUrl.value=t.view,w=`Opening the stream you were sent…`):(c.linkUrl.value=r,Et=r),globalThis.history?.replaceState(null,``,globalThis.location.pathname)}}catch{}let Si=[`zone-top`,`zone-main`],Ci=e=>e instanceof HTMLElement&&e.matches(`section.panel`)&&e.id!==``,wi=e=>e.parentElement&&Si.includes(e.parentElement.id)?e.parentElement:null,Ti=e=>e.classList.contains(`col-a`)?`a`:e.classList.contains(`col-b`)?`b`:``,Ei=()=>[...document.querySelectorAll(`section.panel`)].filter(e=>Ci(e)&&wi(e)!==null),Di=e=>e.dataset.title??e.id,Oi=new Map,ki=Ei().map((e,t)=>(Oi.set(e.id,{zone:wi(e)?.id??``,col:Ti(e),index:t}),e.id)),Z=Ge();try{Z=Je(localStorage.getItem(We))}catch{}let Ai=()=>Z.order.length>0||Object.keys(Z.placement).length>0;function ji(){Z.order=Ei().map(e=>e.id);try{localStorage.setItem(We,Ye(Z))}catch{}}function Mi(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 Ni(){for(let e of Ei()){let t=Z.placement[e.id];if(!t)continue;let[n=``,r=``]=t.split(`:`),i=document.getElementById(n);i&&Si.includes(i.id)&&Mi(e,i,r===`a`||r===`b`?r:``)}let e=Xe(Ei().map(e=>e.id),Z.order);for(let t of Si){let n=document.getElementById(t);if(!n)continue;let r=[...n.children].filter(Ci),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 Ei())e.toggleAttribute(`data-collapsed`,Z.collapsed.includes(e.id)),e.toggleAttribute(`data-closed`,Z.closed.includes(e.id))}function Pi(e,t){e.toggleAttribute(`data-collapsed`,t),Z.collapsed=Ze(Z.collapsed,e.id,t),ji(),Vi()}function Fi(e,t){e.toggleAttribute(`data-closed`,t),Z.closed=Ze(Z.closed,e.id,t),ji(),Vi()}function Ii(e,t,n){let r=wi(t);r&&e!==t&&(Mi(e,r,Ti(t)),n?t.after(e):t.before(e),Z.placement[e.id]=`${r.id}:${Ti(t)}`,ji(),Vi())}let Li=null,Ri=()=>{for(let e of Ei())e.classList.remove(`drop-before`,`drop-after`)},zi=(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 Bi(){for(let e of Ei()){if(e.querySelector(`:scope > .panel-tools`))continue;let t=document.createElement(`span`);t.className=`panel-tools`;let n=zi(`≡`,`Move ${Di(e)}: drag it to where it should go`,()=>void 0);n.classList.add(`grip`),n.draggable=!0,n.addEventListener(`dragstart`,t=>{Li=e,e.classList.add(`dragging`),t.dataTransfer?.setData(`text/plain`,e.id),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`)}),n.addEventListener(`dragend`,()=>{Li=null,e.classList.remove(`dragging`),Ri()});let r=zi(`▁`,`Shade ${Di(e)} to its title`,()=>Pi(e,!e.hasAttribute(`data-collapsed`))),i=zi(`✕`,`Hide ${Di(e)}; the Panels list turns it back on`,()=>Fi(e,!0));t.append(n,r,i),e.prepend(t),e.addEventListener(`dragover`,t=>{if(!Li||Li===e)return;t.preventDefault();let n=e.getBoundingClientRect(),r=t.clientY>n.top+n.height/2;Ri(),e.classList.add(r?`drop-after`:`drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drop-before`,`drop-after`)),e.addEventListener(`drop`,t=>{if(!Li||Li===e)return;t.preventDefault();let n=e.classList.contains(`drop-after`);Ri(),Ii(Li,e,n)})}}function Vi(){if(c.panelsPanel.hidden)return;let e=Ei().filter(e=>e!==c.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`,`${Di(e)} on`),i.addEventListener(`change`,()=>Fi(e,!i.checked));let a=document.createElement(`span`);a.className=`name`,a.textContent=Di(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});c.panelsList.replaceChildren(...e)}function Hi(){Z=Ge();for(let e of ki){let t=document.getElementById(e),n=Oi.get(e),r=n?document.getElementById(n.zone):null;t&&n&&r&&(Mi(t,r,n.col),t.removeAttribute(`data-collapsed`),t.removeAttribute(`data-closed`))}Z.order=[...ki],Ni(),Z=Ge();try{localStorage.removeItem(We)}catch{}Vi()}function Ui(e){if(!e||Ai())return;let t=wi(c.adminPanel);if(!t)return;let n=[...t.children].filter(Ci).find(e=>Ti(e)===Ti(c.adminPanel));n&&n!==c.adminPanel&&n.before(c.adminPanel),c.adminPanel.removeAttribute(`data-collapsed`),c.adminPanel.removeAttribute(`data-closed`)}c.panelsToggle.addEventListener(`click`,()=>{let e=c.panelsPanel.hidden;c.panelsPanel.hidden=!e,e&&(c.panelsPanel.hasAttribute(`data-closed`)&&Fi(c.panelsPanel,!1),Vi(),c.panelsPanel.scrollIntoView({behavior:`smooth`,block:`nearest`}))}),c.panelsReset.addEventListener(`click`,Hi),new MutationObserver(()=>Vi()).observe(document.body,{attributes:!0,attributeFilter:[`data-title`,`hidden`],subtree:!0}),Bi(),Ni(),gi(),_i(),zn(),wn(),c.browse.addEventListener(`click`,()=>{if(!c.directory.hidden){c.directory.hidden=!0;return}An(),c.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),c.disconnect.addEventListener(`click`,()=>{z.close(),c.listenOnly.hidden=!0,T=-1,c.sharePanel.hidden=!0,c.publishPanel.hidden=!0,c.adminPanel.hidden=!0,c.onairPanel.hidden=!0,c.onairPanel.dataset.title=`Parties on this server`,c.catalogsPanel.hidden=!0,c.catalogsPanel.dataset.title=`Catalogs on this server`,p=``,se=``,Qn(),qi(!1),f=`local`,x=`idle`,S=``,H()});async function Wi(){if(f!==`remote`||z.shareLink===``){c.sharePanel.hidden=!0;return}c.sharePanel.hidden=!1;let e=aa(),t=globalThis.location.origin;c.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,c.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,c.sharePhone.hidden=!0,c.shareSend.hidden=!0,c.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(z.url(`/api/live/state`));n.ok&&(r=await n.json()),r?.url&&(e=r.url,se=r.url,c.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(r){if(ht=r.live,P=r.live?r.code:``,gt=n,c.liveControls.hidden=c.adminPanel.hidden||!r.possible,c.goLive.hidden=r.live,c.stopLive.hidden=!r.live,c.sharePhone.hidden=!1,!r.live){c.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){c.sharePhone.textContent=`Listed. The code for the phone line is ${r.code}.`,c.shareSend.hidden=!1;return}c.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),da(n),document.createTextNode(` and key `),da(r.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),c.shareSend.hidden=!1}}let Gi=``,Ki=null,qi=e=>{Ki&&clearInterval(Ki),Ki=null,e&&(Ki=setInterval(()=>void Q(),6e3))};async function Q(){if(f!==`remote`){c.onairPanel.hidden=!0;return}let e;try{let t=await fetch(z.url(`/api/streams`));if(!t.ok){c.onairPanel.hidden=!0;return}e=await t.json(),ee=e.server.carries!==!1,e.server.name&&e.server.name!==p&&(p=e.server.name,c.onairPanel.dataset.title=`Parties on ${p}`,c.catalogsPanel.dataset.title=`Catalogs on ${p}`,Qn(),H())}catch{c.onairPanel.hidden=!0;return}c.onairPanel.hidden=!1,k=e,oa(e),H(),Ji(e)}function Ji(e){let t=zt(),n=`${c.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}:${t.fullTitle}:${t.position}`;if(n===Gi)return;Gi=n;let r=e.restreams??[],i=e.channels.length+r.length;c.onairNote.textContent=i===0?`One stream, from this server's own files.`:`${i+1} streams: this server's own files, and ${i} more on it.`;let o=[],s=e.server.playing,l=!c.adminPanel.hidden;o.push(sa({title:e.server.name,detail:[s?`playing ${t.fullTitle}`:e.server.nowPlaying?`stopped on ${a(e.server.nowPlaying)}`:`nothing loaded`,s&&t.position?t.position:`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:s?`Join party`:l?`Start the stream`:`Nothing playing`,onPlay:()=>{if(s){Zi(e.server.nowPlaying);return}l&&Xi()},link:e.server.live?e.server.url:``,...s?{page:ia(`live`)}:{},direct:s?z.url(`/api/live`):``}));for(let e of r)o.push(sa({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{qt(e.at)},link:``,direct:z.media(e.at,0,!0)}));for(let t of e.channels){let e=t.kind!==`audio`,n=z.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}×`),l&&t.error&&r.push(t.error),o.push(sa({title:t.name,detail:r.join(` · `),onPlay:()=>{Qi({id:t.id,name:t.name,video:e,art:t.art})},link:n,page:ia(`channel:${t.id}`),direct:n,onRestart:l&&t.via===`pull`?()=>{ea(t.id,t.name)}:void 0,onStop:l||jt&&X!==``&&t.startedBy===X?()=>{na(t.id,t.name)}:void 0,onRename:l||jt&&X!==``&&t.startedBy===X?()=>{ta(t.id,t.name)}:void 0}))}c.onairList.replaceChildren(...o)}async function Yi(){if(f===`remote`)try{if((await fetch(z.media(B(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;w=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===``&&c.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),H()}catch{}}async function Xi(){W(`Starting the stream on the server…`);try{await z.send({type:`play`,index:Math.max(0,B())})}catch{W(`could not reach the server`);return}await Zi(b.tracks[B()]?.title??``),W(`Playing to the room. Anybody with the view link sees this.`),await Q()}async function Zi(e){T=-1,E=null,O={kind:`live`},mt(e,`auto`),await D(()=>R.load({title:e||`Live`,artist:``,album:``,duration:0,url:z.url(`/api/live`),video:!0,objectUrl:!1},!0)),gn(!0),w=`Watching what this server is playing. Everyone here sees the same thing.`,H()}async function Qi(e,t=!0,n){T=-1,E=e,t&&(ve=0),t&&(O=n??{kind:`channel`}),t&&mt(e.name,O?.link||_t(e.name)?`auto`:`channel`);let r=e.video&&Nt();await D(()=>R.load({title:e.name,artist:``,album:``,duration:0,url:z.url(r?`/api/channels/${encodeURIComponent(e.id)}/hls/index.m3u8`:`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0)),gn(e.video),E===e&&(w=`Watching ${e.name}, live on this server.`),H()}function $i(){let e=E;return e?wt?!0:ve>=5?(w=`${e.name} stopped, and did not come back.`,E=null,O=null,H(),!0):(ve+=1,w=`${e.name} started over; rejoining…`,H(),wt=setTimeout(()=>{wt=null,E===e&&Qi(e,!1)},2e3),!0):!1}function $(e){c.onairNote.textContent=e,W(e)}async function ea(e,t){$(`Restarting ${t}…`);try{let n=await fetch(z.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`)}Gi=``,Q()}async function ta(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(z.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`)}E?.id===e&&(E={...E,name:r}),Gi=``,Q(),H()}}async function na(e,t){$(`Taking ${t} off the air…`);try{let n=await fetch(z.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`)}E?.id===e&&(E=null,R.stop()),Gi=``,Q()}async function ra(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{w=e,H();return}n===`✓`||n===`✓`?u(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function ia(e,t=0){let n=aa();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 aa(){if(se!==``)return se;let e=f===`remote`?z.shareLink:``;return/\/admin\//.test(e)?``:e}function oa(e){if(v===``)return;let t=v;if(t===`live`){v=``,e.server.playing?Zi(e.server.nowPlaying):(w=`Nothing is playing on this server right now.`,H());return}if(t.startsWith(`link:`)){v=``,vn(t.slice(5));return}if(t.startsWith(`golive:`)){v=``,c.linkUrl.value=t.slice(7),zn().then(()=>Tn());return}if(t.startsWith(`track:`)){v=``;let e=Number(t.slice(6));Number.isInteger(e)&&e>=0&&qt(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&&(v=``,Qi({id:r.id,name:r.name,video:r.kind!==`audio`,art:r.art}))}function sa(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`,It(o,e.playLabel??`Join party`),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`,u(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;ra(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=>{ra(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 ca=``;function la(e,t){ca=e;let n=e!==``&&t===e;c.loadHome.hidden=e===``,c.homeNote.hidden=e===``,e!==``&&(c.homeNote.textContent=n?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,c.loadHome.disabled=!1)}c.loadHome.addEventListener(`click`,()=>{ca!==``&&(c.loadHome.disabled=!0,W(`Reading this server's files…`),(async()=>{try{let e=await fetch(z.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:ca})}),t=await e.json();W(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{W(`could not reach the server`)}finally{c.loadHome.disabled=!1}})())});let ua=async e=>{c.goLive.disabled=!0,c.stopLive.disabled=!0,c.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(z.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),n=await t.json();c.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{c.shareNote.textContent=`could not reach the server`}finally{c.goLive.disabled=!1,c.stopLive.disabled=!1,await Wi()}};c.goLive.addEventListener(`click`,()=>void ua(!0)),c.stopLive.addEventListener(`click`,()=>void ua(!1));function da(e){let t=document.createElement(`b`);return t.textContent=e,t}c.shareCopy.addEventListener(`click`,()=>{c.shareLink.select(),navigator.clipboard?.writeText(c.shareLink.value).then(()=>{c.shareNote.textContent=`Copied. Send it to anybody.`},()=>{c.shareNote.textContent=`Copy it from the box above.`})}),c.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=c.shareTo.value.trim();t!==``&&(async()=>{c.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:aa()})}),n=await e.json();c.shareNote.textContent=e.ok?`Sent to ${n.sent??t}.`:n.error??`that did not send`,e.ok&&(c.shareTo.value=``)}catch{c.shareNote.textContent=`could not send that`}})()}),c.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(xt,c.listenHere.checked?`1`:`0`)}catch{}f===`remote`&&(async()=>{c.listenHere.checked?(await z.send({type:`stop`}),await Jt(b.index)):(R.stop(),T=-1),H()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),Yt();return;case`s`:Zt();return;case`n`:case`ArrowRight`:Xt(1);return;case`p`:case`ArrowLeft`:Xt(-1);return;case`ArrowDown`:e.preventDefault(),qt(Math.min(Rt()-1,B()+1));return;case`ArrowUp`:e.preventDefault(),qt(Math.max(0,B()-1));return}});let fa=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),fa=e,c.install.hidden=!1}),c.install.addEventListener(`click`,()=>{fa?.prompt(),fa=null,c.install.hidden=!0});try{let e=localStorage.getItem(bt);e!==null&&(c.volume.value=String(Math.round(Number(e)*100)),R.volume=Number(e));let t=localStorage.getItem(vt);t&&(c.remoteUrl.value=t),localStorage.getItem(xt)===`0`&&(c.listenHere.checked=!1)}catch{}(async()=>{if(c.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await Se(e)===null)return;let t=await ye(e);t&&t.trackCount!==0&&(c.remoteUrl.value=e,f=`remote`,w=``,z.connect(e),H())})(),(()=>{if(Ct||Tt!==``)return;let e=()=>R.source!==``||R.playing||je()||E!==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=()=>{Ct=!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})})})})(),H(),requestAnimationFrame(pn)}wt(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{d as t};