nixamp 0.9.6 → 0.9.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.d.ts CHANGED
@@ -17,6 +17,7 @@ import { Catalogs } from "./catalogs.ts";
17
17
  import { Names } from "./names.ts";
18
18
  import { Certs } from "./certs.ts";
19
19
  import { type Throttle } from "@profullstack/throttle";
20
+ import { type Notification } from "./notify.ts";
20
21
  import { type Tools, type Track } from "./audio.ts";
21
22
  import { type Command, type RemoteTrack, type Snapshot } from "./protocol.ts";
22
23
  export declare const SERVE_BAND_COUNT = 24;
@@ -536,6 +537,17 @@ export interface HandlerOptions {
536
537
  follows?: Follows;
537
538
  /** The servers an account hearted. nixamp.com only, like follows. */
538
539
  favorites?: Favorites;
540
+ /**
541
+ * How an invite is sent: by email, by text, and the site the watch link is
542
+ * built on. nixamp.com only; a personal nixamp has no mail to send from.
543
+ */
544
+ invites?: {
545
+ email?: (to: string, note: Notification) => Promise<boolean>;
546
+ sms?: {
547
+ send(to: string, text: string): Promise<boolean>;
548
+ };
549
+ site: string;
550
+ };
539
551
  /** Names under `<handle>.<zone>` for an account's servers. nixamp.com only. */
540
552
  names?: Names;
541
553
  /** One wildcard certificate per handle, issued and renewed here. nixamp.com only. */
package/dist/server.js CHANGED
@@ -47,6 +47,7 @@ import { forbiddenLibrary, readLibrary } from "./library.js";
47
47
  import { createThrottle, presentedCredential } from "@profullstack/throttle";
48
48
  import { Durable } from "./durable.js";
49
49
  import { notifyAll, resendEmail, webPush } from "./notify.js";
50
+ import { inviteSubject, inviteText, isEmail, isPhone, watchLink } from "./invite.js";
50
51
  import { confirm, DEFAULT_DIRECTORY, Publisher } from "./publish.js";
51
52
  import { applyRemoteConfig, createPaywall, FREE_LISTENERS, paywallFromEnv, } from "./paywall.js";
52
53
  import { isRemote, playsInBrowser, sourceLabel } from "./sources.js";
@@ -1066,6 +1067,80 @@ export function createHandler(engine, options) {
1066
1067
  json(response, 202, { status: "issuing", host });
1067
1068
  return;
1068
1069
  }
1070
+ // --- an invite: "so-and-so is streaming", by text or by email ------------
1071
+ //
1072
+ // The page had a Send button and nothing answered it: the message was
1073
+ // written (invite.ts) and never given a route. Sending needs an account,
1074
+ // because a text costs money and lands on somebody's phone, and the link
1075
+ // sent is always the listen link -- an admin link handed out by mistake
1076
+ // would hand out the server.
1077
+ if (path === "/api/v1/invite" && options.invites && options.accounts) {
1078
+ if (request.method !== "POST") {
1079
+ json(response, 405, { error: "POST only" });
1080
+ return;
1081
+ }
1082
+ const me = await options.accounts.whoIs(tokenFrom(request.headers));
1083
+ if (me === null) {
1084
+ json(response, 401, { error: "sign in to send an invite" });
1085
+ return;
1086
+ }
1087
+ let body = {};
1088
+ try {
1089
+ body = JSON.parse(await readBody(request));
1090
+ }
1091
+ catch {
1092
+ json(response, 400, { error: "bad JSON" });
1093
+ return;
1094
+ }
1095
+ const to = String(body.to ?? "").trim();
1096
+ const stream = String(body.stream ?? "").trim();
1097
+ const byEmail = isEmail(to);
1098
+ const bySms = !byEmail && isPhone(to);
1099
+ if (!byEmail && !bySms) {
1100
+ json(response, 400, { error: "give a phone number or an email address" });
1101
+ return;
1102
+ }
1103
+ let origin = "";
1104
+ try {
1105
+ origin = new URL(stream).origin;
1106
+ }
1107
+ catch {
1108
+ json(response, 400, { error: "that is not a stream link" });
1109
+ return;
1110
+ }
1111
+ // What the directory knows about this server names it and gives the
1112
+ // listen link and the phone code. An unlisted server is still sendable,
1113
+ // as long as the link given is not the one that drives it.
1114
+ const listed = options.directory?.list().find((one) => {
1115
+ try {
1116
+ return new URL(one.url).origin === origin;
1117
+ }
1118
+ catch {
1119
+ return false;
1120
+ }
1121
+ });
1122
+ const link = listed?.url ?? stream;
1123
+ if (/\/admin\//.test(link) || /[?&]k=/.test(link) && !listed) {
1124
+ json(response, 400, { error: "send the view link, not the admin link" });
1125
+ return;
1126
+ }
1127
+ const invite = {
1128
+ name: listed?.name ?? new URL(link).hostname,
1129
+ link: watchLink(link, options.invites.site),
1130
+ phone: listed ? CALL_IN_NUMBER : "",
1131
+ code: listed?.code ?? "",
1132
+ };
1133
+ const sender = byEmail ? options.invites.email : options.invites.sms;
1134
+ if (!sender) {
1135
+ json(response, 503, { error: byEmail ? "this site cannot send email yet" : "this site cannot send texts yet" });
1136
+ return;
1137
+ }
1138
+ const ok = byEmail
1139
+ ? await options.invites.email(to, { title: inviteSubject(invite), body: inviteText(invite), url: invite.link })
1140
+ : await options.invites.sms.send(to, inviteText(invite));
1141
+ json(response, ok ? 200 : 502, ok ? { sent: to } : { error: "the message did not go" });
1142
+ return;
1143
+ }
1069
1144
  // Favourites: the servers you hearted, kept against your account. Reading
1070
1145
  // the directory and listening need no account; remembering where you
1071
1146
  // listened does, because there has to be somebody to remember it for.
@@ -3266,6 +3341,8 @@ export async function serve(argv, version = "0.1.0") {
3266
3341
  // a guess with an Authorization header buys itself the bigger budget.
3267
3342
  { path: "/api/v1/auth/", limit: 20, credential: false },
3268
3343
  { path: "/api/v1/dns/", limit: 30 },
3344
+ // A text costs money and lands on a phone: ten a minute is plenty.
3345
+ { path: "/api/v1/invite", limit: 10 },
3269
3346
  { path: "/api/v1/dns", limit: 30 },
3270
3347
  { path: "/api/v1/certs", limit: 30 },
3271
3348
  { path: "/api/health", open: true },
@@ -3538,6 +3615,33 @@ export async function serve(argv, version = "0.1.0") {
3538
3615
  ...(directory ? { directory } : {}),
3539
3616
  ...(follows ? { follows, vapidPublicKey } : {}),
3540
3617
  ...(favorites ? { favorites } : {}),
3618
+ // Invites go out the same way follow notifications do, and only from a
3619
+ // site that has somebody to send them for.
3620
+ ...(pool
3621
+ ? {
3622
+ invites: {
3623
+ site: (process.env["NIXAMP_SITE"] ?? DEFAULT_DIRECTORY).replace(/\/+$/, ""),
3624
+ ...(process.env["RESEND_API_KEY"]
3625
+ ? {
3626
+ email: resendEmail({
3627
+ apiKey: process.env["RESEND_API_KEY"],
3628
+ from: process.env["NIXAMP_MAIL_FROM"] ?? "nixamp <notifications@nixamp.com>",
3629
+ onEvent: (message) => console.log(message),
3630
+ }),
3631
+ }
3632
+ : {}),
3633
+ ...(process.env["TELNYX_API_KEY"] && process.env["PARTYLINE_SMS_FROM"]
3634
+ ? {
3635
+ sms: telnyxSms({
3636
+ apiKey: process.env["TELNYX_API_KEY"],
3637
+ from: process.env["PARTYLINE_SMS_FROM"],
3638
+ onEvent: (message) => console.log(message),
3639
+ }),
3640
+ }
3641
+ : {}),
3642
+ },
3643
+ }
3644
+ : {}),
3541
3645
  ...(names ? { names } : {}),
3542
3646
  ...(certs ? { certs } : {}),
3543
3647
  dnsZone: zoneName,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nixamp",
3
- "version": "0.9.6",
3
+ "version": "0.9.7",
4
4
  "description": "It really whips the terminal's ass. A Winamp-shaped audio player for your terminal.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/server.ts CHANGED
@@ -64,6 +64,7 @@ import { forbiddenLibrary, readLibrary } from "./library.ts";
64
64
  import { createThrottle, presentedCredential, type Throttle } from "@profullstack/throttle";
65
65
  import { Durable } from "./durable.ts";
66
66
  import { notifyAll, resendEmail, webPush, type Notification } from "./notify.ts";
67
+ import { inviteSubject, inviteText, isEmail, isPhone, watchLink } from "./invite.ts";
67
68
  import { confirm, DEFAULT_DIRECTORY, Publisher } from "./publish.ts";
68
69
  import {
69
70
  applyRemoteConfig,
@@ -1225,6 +1226,15 @@ export interface HandlerOptions {
1225
1226
  follows?: Follows;
1226
1227
  /** The servers an account hearted. nixamp.com only, like follows. */
1227
1228
  favorites?: Favorites;
1229
+ /**
1230
+ * How an invite is sent: by email, by text, and the site the watch link is
1231
+ * built on. nixamp.com only; a personal nixamp has no mail to send from.
1232
+ */
1233
+ invites?: {
1234
+ email?: (to: string, note: Notification) => Promise<boolean>;
1235
+ sms?: { send(to: string, text: string): Promise<boolean> };
1236
+ site: string;
1237
+ };
1228
1238
  /** Names under `<handle>.<zone>` for an account's servers. nixamp.com only. */
1229
1239
  names?: Names;
1230
1240
  /** One wildcard certificate per handle, issued and renewed here. nixamp.com only. */
@@ -1431,6 +1441,78 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
1431
1441
  return;
1432
1442
  }
1433
1443
 
1444
+ // --- an invite: "so-and-so is streaming", by text or by email ------------
1445
+ //
1446
+ // The page had a Send button and nothing answered it: the message was
1447
+ // written (invite.ts) and never given a route. Sending needs an account,
1448
+ // because a text costs money and lands on somebody's phone, and the link
1449
+ // sent is always the listen link -- an admin link handed out by mistake
1450
+ // would hand out the server.
1451
+ if (path === "/api/v1/invite" && options.invites && options.accounts) {
1452
+ if (request.method !== "POST") {
1453
+ json(response, 405, { error: "POST only" });
1454
+ return;
1455
+ }
1456
+ const me = await options.accounts.whoIs(tokenFrom(request.headers));
1457
+ if (me === null) {
1458
+ json(response, 401, { error: "sign in to send an invite" });
1459
+ return;
1460
+ }
1461
+ let body: { to?: unknown; stream?: unknown } = {};
1462
+ try {
1463
+ body = JSON.parse(await readBody(request)) as typeof body;
1464
+ } catch {
1465
+ json(response, 400, { error: "bad JSON" });
1466
+ return;
1467
+ }
1468
+ const to = String(body.to ?? "").trim();
1469
+ const stream = String(body.stream ?? "").trim();
1470
+ const byEmail = isEmail(to);
1471
+ const bySms = !byEmail && isPhone(to);
1472
+ if (!byEmail && !bySms) {
1473
+ json(response, 400, { error: "give a phone number or an email address" });
1474
+ return;
1475
+ }
1476
+ let origin = "";
1477
+ try {
1478
+ origin = new URL(stream).origin;
1479
+ } catch {
1480
+ json(response, 400, { error: "that is not a stream link" });
1481
+ return;
1482
+ }
1483
+ // What the directory knows about this server names it and gives the
1484
+ // listen link and the phone code. An unlisted server is still sendable,
1485
+ // as long as the link given is not the one that drives it.
1486
+ const listed = options.directory?.list().find((one) => {
1487
+ try {
1488
+ return new URL(one.url).origin === origin;
1489
+ } catch {
1490
+ return false;
1491
+ }
1492
+ });
1493
+ const link = listed?.url ?? stream;
1494
+ if (/\/admin\//.test(link) || /[?&]k=/.test(link) && !listed) {
1495
+ json(response, 400, { error: "send the view link, not the admin link" });
1496
+ return;
1497
+ }
1498
+ const invite = {
1499
+ name: listed?.name ?? new URL(link).hostname,
1500
+ link: watchLink(link, options.invites.site),
1501
+ phone: listed ? CALL_IN_NUMBER : "",
1502
+ code: listed?.code ?? "",
1503
+ };
1504
+ const sender = byEmail ? options.invites.email : options.invites.sms;
1505
+ if (!sender) {
1506
+ json(response, 503, { error: byEmail ? "this site cannot send email yet" : "this site cannot send texts yet" });
1507
+ return;
1508
+ }
1509
+ const ok = byEmail
1510
+ ? await options.invites.email!(to, { title: inviteSubject(invite), body: inviteText(invite), url: invite.link })
1511
+ : await options.invites.sms!.send(to, inviteText(invite));
1512
+ json(response, ok ? 200 : 502, ok ? { sent: to } : { error: "the message did not go" });
1513
+ return;
1514
+ }
1515
+
1434
1516
  // Favourites: the servers you hearted, kept against your account. Reading
1435
1517
  // the directory and listening need no account; remembering where you
1436
1518
  // listened does, because there has to be somebody to remember it for.
@@ -3780,6 +3862,8 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
3780
3862
  // a guess with an Authorization header buys itself the bigger budget.
3781
3863
  { path: "/api/v1/auth/", limit: 20, credential: false },
3782
3864
  { path: "/api/v1/dns/", limit: 30 },
3865
+ // A text costs money and lands on a phone: ten a minute is plenty.
3866
+ { path: "/api/v1/invite", limit: 10 },
3783
3867
  { path: "/api/v1/dns", limit: 30 },
3784
3868
  { path: "/api/v1/certs", limit: 30 },
3785
3869
  { path: "/api/health", open: true },
@@ -4068,6 +4152,33 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
4068
4152
  ...(directory ? { directory } : {}),
4069
4153
  ...(follows ? { follows, vapidPublicKey } : {}),
4070
4154
  ...(favorites ? { favorites } : {}),
4155
+ // Invites go out the same way follow notifications do, and only from a
4156
+ // site that has somebody to send them for.
4157
+ ...(pool
4158
+ ? {
4159
+ invites: {
4160
+ site: (process.env["NIXAMP_SITE"] ?? DEFAULT_DIRECTORY).replace(/\/+$/, ""),
4161
+ ...(process.env["RESEND_API_KEY"]
4162
+ ? {
4163
+ email: resendEmail({
4164
+ apiKey: process.env["RESEND_API_KEY"],
4165
+ from: process.env["NIXAMP_MAIL_FROM"] ?? "nixamp <notifications@nixamp.com>",
4166
+ onEvent: (message) => console.log(message),
4167
+ }),
4168
+ }
4169
+ : {}),
4170
+ ...(process.env["TELNYX_API_KEY"] && process.env["PARTYLINE_SMS_FROM"]
4171
+ ? {
4172
+ sms: telnyxSms({
4173
+ apiKey: process.env["TELNYX_API_KEY"],
4174
+ from: process.env["PARTYLINE_SMS_FROM"],
4175
+ onEvent: (message) => console.log(message),
4176
+ }),
4177
+ }
4178
+ : {}),
4179
+ },
4180
+ }
4181
+ : {}),
4071
4182
  ...(names ? { names } : {}),
4072
4183
  ...(certs ? { certs } : {}),
4073
4184
  dnsZone: zoneName,
@@ -1 +1 @@
1
- import{t as e}from"./index-BGIa9JsR.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-Cn1xz1VT.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`]);function i(e,t=``){if(t.startsWith(`video/`))return!0;if(t.startsWith(`audio/`))return!1;let n=e.lastIndexOf(`.`);return n>0&&r.has(e.slice(n+1).toLowerCase())}var a=`modulepreload`,o=function(e){return`/`+e},s={},c=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),c=i?.nonce||i?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function u(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=l(t.map(t=>{if(t=o(t,n),t=u(t),t in s)return;s[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:a,r||(i.as=`script`),i.crossOrigin=``,i.href=t,c&&i.setAttribute(`nonce`,c),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},l=[[/\.m3u8$/i,`hls`],[/\.(ts|mts|m2ts|mpegts)$/i,`mpegts`],[/\.(mp3|m4a|aac|oga|ogg|opus|wav|flac)$/i,`audio`],[/\.(mp4|m4v|webm|mov|ogv)$/i,`mp4`]],u=[[/mpegurl/i,`hls`],[/mp2t|mpeg-?ts/i,`mpegts`],[/^audio\//i,`audio`],[/^video\//i,`mp4`]];function d(e){if(e.kind)return e.kind;if(e.mimeType){for(let[t,n]of u)if(t.test(e.mimeType))return n}let t=f(e.src);for(let[e,n]of l)if(e.test(t))return n;return`unknown`}function f(e){try{return new URL(e,`https://placeholder.invalid`).pathname}catch{return e.split(/[?#]/)[0]??e}}function p(e=globalThis,t=null){let n=e.MediaSource!==void 0,r=!1;try{let e=t??(typeof document>`u`?null:document.createElement(`video`));r=e?e.canPlayType(`application/vnd.apple.mpegurl`)!==``||e.canPlayType(`application/x-mpegURL`)!==``:!1}catch{r=!1}return{mediaSource:n,nativeHls:r}}function m(e,t){let n=d(e);switch(n){case`hls`:return t.mediaSource?{engine:`hls`,kind:n}:t.nativeHls?{engine:`native`,kind:n}:{engine:`native`,kind:n,unplayable:`This browser cannot play HLS streams.`};case`mpegts`:return t.mediaSource?{engine:`mpegts`,kind:n}:{engine:`mpegts`,kind:n,unplayable:`This browser cannot play transport streams.`};default:return{engine:`native`,kind:n}}}async function h(e,t){let n=t.capabilities??p(),r=m({src:t.src,...t.kind?{kind:t.kind}:{},...t.mimeType?{mimeType:t.mimeType}:{}},n),i=()=>void 0,a={media:e,src:t.src,isTv:t.isTv??!1,live:t.live??r.kind===`mpegts`,onError:t.onError??i,onNotice:t.onNotice??i,...t.onReady?{onReady:t.onReady}:{}};if(r.unplayable)return t.onError?.(r.unplayable),{destroy:i,engine:r.engine,kind:r.kind,levels:()=>[],unplayable:r.unplayable};let o,s=t.engines?.[r.engine];if(s)o=await s(a);else if(r.engine===`hls`){let{createHlsEngine:e}=await c(async()=>{let{createHlsEngine:e}=await import(`./hls-3VKVEQE3-D83F7MHN.js`);return{createHlsEngine:e}},[]);o=await e(a)}else if(r.engine===`mpegts`){let{createMpegtsEngine:e}=await c(async()=>{let{createMpegtsEngine:e}=await import(`./mpegts-LO6RVLD6-C7akmB6x.js`);return{createMpegtsEngine:e}},[]);o=await e(a,{withCredentials:t.withCredentials??!1,unplayableAdvice:t.unplayableAdvice??``})}else{let{createNativeEngine:e}=await c(async()=>{let{createNativeEngine:e}=await import(`./native-C7JTKWJH-BUyIoj0P.js`);return{createNativeEngine:e}},[]);o=await e(a)}return{destroy:()=>{o.destroy()},engine:r.engine,kind:r.kind,levels:o.levels,...o.setLevel?{setLevel:o.setLevel}:{},...o.currentLevel?{currentLevel:o.currentLevel}:{}}}var g=new Set([`mp3`,`flac`,`ogg`,`oga`,`opus`,`m4a`,`aac`,`wav`,`wma`,`aiff`,`aif`,`alac`,`mp4`,`webm`,`mkv`,`mov`,`m4v`,`ogv`]);function _(e,t=``){if(t.startsWith(`audio/`)||t.startsWith(`video/`))return!0;let n=e.lastIndexOf(`.`);return n>0&&g.has(e.slice(n+1).toLowerCase())}function v(e,t){return e.localeCompare(t,void 0,{numeric:!0,sensitivity:`base`})}function ee(e){return e.filter(e=>_(e.name,e.type)).sort((e,t)=>v(y(e),y(t))).map(e=>({title:n(e.name),artist:``,album:b(y(e)),duration:0,url:URL.createObjectURL(e),video:i(e.name,e.type),objectUrl:!0}))}function y(e){return e.webkitRelativePath||e.name}function b(e){let t=e.split(`/`);return t.length>1?t[t.length-2]:``}function te(e){for(let t of e)t.objectUrl&&URL.revokeObjectURL(t.url)}var ne=2048;function re(e,t){return e||t===`hls`||t===`mpegts`}var ie=class{elements;handlers;attached=null;source=``;context=null;analyser=null;wired=new WeakSet;active;frequencies=new Uint8Array;constructor(e,t){this.elements=e,this.handlers=t,this.active=e.audio;for(let t of[e.audio,e.video])t.crossOrigin=`anonymous`,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))})}get playing(){return!this.active.paused&&!this.active.ended}get position(){return this.active.currentTime}get duration(){return Number.isFinite(this.active.duration)?this.active.duration:0}get showingVideo(){return this.active===this.elements.video}ensureGraph(e){let t=globalThis.AudioContext??globalThis.webkitAudioContext;if(t){if(this.context??=new t,this.analyser||(this.analyser=this.context.createAnalyser(),this.analyser.fftSize=ne,this.analyser.smoothingTimeConstant=.6,this.analyser.connect(this.context.destination),this.frequencies=new Uint8Array(this.analyser.frequencyBinCount)),!this.wired.has(e))try{this.context.createMediaElementSource(e).connect(this.analyser),this.wired.add(e)}catch{this.wired.add(e)}this.context.resume()}}read(){return this.analyser&&this.analyser.getByteFrequencyData(this.frequencies),this.frequencies}levels(){if(!this.analyser)return[0,0];let e=this.read(),t=0;for(let n of e)t+=n;let n=e.length===0?0:t/e.length/255;return[Math.min(1,n*2.2),Math.min(1,n*2.2)]}async load(e,t){this.source=e.objectUrl?``:e.url;let n=e.objectUrl?e.video?`mp4`:`audio`:d({src:e.url}),r=re(e.video,n)?this.elements.video:this.elements.audio;r!==this.active&&(this.active.pause(),this.active.removeAttribute(`src`),this.active.load(),this.active=r),this.attached?.destroy(),this.attached=null;try{this.attached=await h(this.active,{src:e.url,kind:n,unplayableAdvice:`VLC or mpv will play it; nixamp can only hand it to your browser.`,onError:e=>this.handlers.onError(e),onNotice:e=>{e&&this.handlers.onError(e)}})}catch(e){this.handlers.onError(e instanceof Error?e.message:`that would not play`);return}t&&await this.play()}async play(){this.ensureGraph(this.active);try{await this.active.play()}catch(e){this.handlers.onError(e instanceof Error?e.message:`playback was refused`)}}pause(){this.active.pause()}stop(){this.active.pause(),this.active.currentTime=0,this.source=``,this.attached?.destroy(),this.attached=null}seek(e){Number.isFinite(e)&&(this.active.currentTime=Math.max(0,e))}set volume(e){this.elements.audio.volume=e,this.elements.video.volume=e}get volume(){return this.active.volume}};function 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 ae(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function oe(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 se(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)}}function ce(e,t,n=0,r=``){return C(e,n>0?`/api/media/${t}?kbps=${Math.round(n)}`:`/api/media/${t}`,r)}function w(e){if(typeof e!=`object`||!e)return null;let t=e,n=ae(),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}}var le=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;constructor(e){this.handlers=e}get address(){return this.base}url(e){return C(this.base,e,this.key)}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}=se(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=w(T(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=w(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0){return ce(this.base,e,t,this.key)}close(){this.source?.close(),this.source=null}};function T(e){try{return JSON.parse(e)}catch{return null}}async function ue(e,t,n=``){try{let r=await fetch(C(e,`/api/state`,n),{signal:t});return r.ok?w(await r.json()):null}catch{return null}}function de(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 fe(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 pe(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 me(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 E=.14,he=.02;function ge(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 _e(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 ve(e,t,n=E){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function ye(e,t,n=he){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function be(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)})}var xe=`nixamp.remote`,Se=`nixamp.volume`,Ce=`nixamp.listenHere`,we=!1;function D(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function O(){let n={status:D(`status`),source:D(`source`),install:D(`install`),video:D(`video`),audio:D(`audio`),title:D(`title-line`),album:D(`album-line`),elapsed:D(`elapsed`),total:D(`total`),seek:D(`seek`),fullscreen:D(`fullscreen`),copyNow:D(`copy-now`),canvas:D(`spectrum`),glyphs:D(`glyphs`),levels:D(`levels`),playlist:D(`playlist`),crumbs:D(`crumbs`),filter:D(`filter`),playlistTitle:D(`playlist-panel`),note:D(`note`),files:D(`files`),folder:D(`folder`),remoteUrl:D(`remote-url`),remoteForm:D(`remote-form`),remoteState:D(`remote-state`),disconnect:D(`disconnect`),browse:D(`browse`),accountForm:D(`account-form`),accountEmail:D(`account-email`),accountPassword:D(`account-password`),accountSubmit:D(`account-submit`),accountToggle:D(`account-toggle`),accountProviders:D(`account-providers`),accountPanel:D(`account-panel`),accountElsewhere:D(`account-elsewhere`),accountSignOut:D(`account-signout`),accountNote:D(`account-note`),adminPanel:D(`admin-panel`),adminNote:D(`admin-note`),adminSaid:D(`admin-said`),adminConnections:D(`admin-connections`),publishPanel:D(`publish-panel`),publishNote:D(`publish-note`),publishList:D(`publish-list`),adminRestream:D(`admin-restream`),adminReplace:D(`admin-replace`),adminSource:D(`admin-source`),adminName:D(`admin-name`),adminAdd:D(`admin-add`),homeNote:D(`home-note`),loadHome:D(`load-home`),directory:D(`directory`),recentNote:D(`recent-note`),recentList:D(`recent-list`),followingNote:D(`following-note`),followingList:D(`following-list`),serversPanel:D(`servers-panel`),serversNote:D(`servers-note`),serversList:D(`servers-list`),favoritesPanel:D(`favorites-panel`),favoritesNote:D(`favorites-note`),favoritesList:D(`favorites-list`),favHere:D(`fav-here`),catalogsPanel:D(`catalogs-panel`),catalogsNote:D(`catalogs-note`),catalogsForm:D(`catalogs-form`),catalogSource:D(`catalog-source`),catalogName:D(`catalog-name`),catalogsList:D(`catalogs-list`),catalogsCrumbs:D(`catalogs-crumbs`),catalogsFilter:D(`catalogs-filter`),catalogsEntries:D(`catalogs-entries`),notifyPanel:D(`notify-panel`),notifyNote:D(`notify-note`),notifyWeb:D(`notify-web`),notifyEmail:D(`notify-email`),notifySms:D(`notify-sms`),notifyPhone:D(`notify-phone`),notifyPhoneForm:D(`notify-phone-form`),notifyPhoneNote:D(`notify-phone-note`),directoryNote:D(`directory-note`),directoryList:D(`directory-list`),onairPanel:D(`onair-panel`),onairNote:D(`onair-note`),onairList:D(`onair-list`),sharePanel:D(`share-panel`),shareNote:D(`share-note`),shareLink:D(`share-link`),shareCopy:D(`share-copy`),sharePhone:D(`share-phone`),shareSend:D(`share-send`),liveControls:D(`live-controls`),goLive:D(`go-live`),stopLive:D(`stop-live`),shareTo:D(`share-to`),listenOnly:D(`listen-only`),listenHere:D(`listen-here`),volume:D(`volume`),prev:D(`prev`),playPause:D(`play-pause`),stop:D(`stop`),next:D(`next`)},r={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>`},i=(e,t)=>{e.innerHTML=r[t]},a=document.title||`nixamp`,o=`local`,s=``,c=!1,l=``,u=0,d=``,f=[],p=0,m=ae(),h=`idle`,g=``,_=`Pick files, or connect to a nixamp running somewhere else.`,v=!1,y=-1,b=null,ne=0,re=null,x=``,S=Array(24).fill(0),C=Array(24).fill(0),ce=[],w=()=>o===`remote`&&!n.listenHere.checked,T=new ie({audio:n.audio,video:n.video},{onTime:(e,t)=>{let n=f[p];o===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),j()},onEnded:()=>{Lt()||A(1)},onState:()=>j(),onError:e=>{Lt()||(_=e,j(),Nt())}}),E=new le({onSnapshot:e=>{if(m=oe(m,e),l.startsWith(`track:`)&&m.tracks.length>0){let e=Number(l.slice(6));if(l=``,Number.isInteger(e)&&e>=0&&e<m.tracks.length){let t=u;Ae(e).then(()=>{t>0&&(T.seek(t),setTimeout(()=>T.seek(t),600))})}}w()&&(S=e.bars.length>0?e.bars:S,C=ye(C,S)),j()},onStatus:(e,t)=>{h=e,g=t??``,j()}}),he=()=>o===`remote`?m.tracks.length:f.length,O=()=>o===`remote`?w()||y<0?m.index:Math.min(y,Math.max(0,m.tracks.length-1)):p,Te=()=>{if(b)return b.name;let e=o===`remote`?m.tracks[O()]:f[O()];return e?t(e):`Nothing loaded.`},Ee=()=>b?`live on this server`:(o===`remote`?m.tracks[O()]:f[O()])?.album||`—`,De=()=>w()?m.tracks[O()]?.duration??0:T.duration,Oe=()=>w()?m.position:T.position,ke=()=>w()?m.playing:T.playing;async function k(e){if(o===`remote`){if(w()){await E.send({type:`play`,index:e});return}await Ae(e);return}let t=f[e];t&&(p=e,b=null,await T.load(t,!0),P(t.video),He(),j())}async function Ae(e){let t=m.tracks[e];t&&(y=e,b=null,await T.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:E.media(e,0),video:t.video===!0,objectUrl:!1},!0),P(t.video===!0),He())}async function je(){if(w()){await E.send({type:`toggle`});return}he()!==0&&(T.playing?T.pause():T.position>0?await T.play():await k(O()),j())}async function A(e){let t=he();if(t!==0){if(w()){await E.send({type:e>0?`next`:`prev`});return}await k((O()+e+t)%t)}}async function Me(){if(w()){await E.send({type:`stop`});return}b=null,T.stop(),S=Array(24).fill(0),C=[...S],j()}let Ne=(e,t)=>`L${`▮`.repeat(Math.round(e*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)}`,Pe=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))];function j(){let t=he(),r=ke();n.status.textContent=r?`▶ PLAYING`:`■ STOPPED`,n.status.dataset.playing=String(r),n.title.textContent=Te();let i=r?`${Te()} · ${a}`:a;document.title!==i&&(document.title=i),n.copyNow.hidden=T.source===``,n.album.textContent=Ee();let c=Oe(),l=De();n.elapsed.textContent=e(c),n.total.textContent=l>0?e(l):`--:--`,v||(n.seek.value=String(l>0?Math.round(c/l*1e3):0),n.seek.disabled=l<=0||w()),n.playPause.textContent=r?`❚❚`:`▶`,n.playPause.setAttribute(`aria-label`,r?`Pause`:`Play`),n.playlistTitle.dataset.title=o===`remote`?`Files on ${s||`this server`} (${t.toLocaleString()})`:`Playlist (${t})`,n.source.textContent=o===`remote`?`connected · ${s||E.address.replace(/^https?:\/\//,``)||`—`}`:f.length>0?`local · ${f.length} files`:`no source`,n.remoteState.textContent=o===`remote`?`${h}${g?` — ${g}`:``}`:`not connected`,n.remoteState.dataset.status=o===`remote`?h:`idle`,n.disconnect.hidden=o!==`remote`;let u=o===`remote`&&m.note!==``?m.note:_;n.note.textContent=u,n.note.hidden=u===``,Re(),n.glyphs.textContent=S.map(Pe).join(``);let[d,p]=w()?m.levels:T.levels();n.levels.textContent=Ne(d,p)}let M=``,Fe=-1,N=``;function Ie(e){if(n.crumbs.hidden=!e,!e)return;let t=N===``?[]:N.split(`/`),r=(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`,()=>{N=t,M=``,Re()}),r},i=[r(`All files`,``,t.length===0)],a=``;t.forEach((e,n)=>{a=a===``?e:`${a}/${e}`;let o=document.createElement(`span`);o.textContent=`/`,i.push(o,r(e,a,n===t.length-1))}),n.crumbs.replaceChildren(...i)}function Le(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.addEventListener(`click`,()=>{N=N===``?e:`${N}/${e}`,M=``,Re()}),n}function Re(){let r=o===`remote`?m.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):f.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),a=n.filter.value.trim().toLowerCase(),s=r.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>a===``||`${e.folder}/${e.name}`.toLowerCase().includes(a)),c=e=>a!==``||N===``||e===N||e.startsWith(`${N}/`),l=e=>a!==``||e===N,u=e=>{let t=N===``?e:e.slice(N.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},d=new Map;for(let e of s){if(!c(e.folder)||l(e.folder))continue;let t=u(e.folder);t!==``&&d.set(t,(d.get(t)??0)+1)}let p=s.filter(e=>l(e.folder)&&c(e.folder)),h=`${o}:${N}:${a}:${[...d].join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(h!==M){M=h,Ie(a===``&&([...d.keys()].length>0||N!==``));let t=[];for(let[e,n]of[...d].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})))t.push(Le(e,n));let r=``,s=p.some(e=>e.group!==``);for(let n of p){n.group!==r&&(s||n.group!==``)&&(r=n.group,t.push(ze(n.group)));let a=document.createElement(`li`);a.className=`row`,a.dataset.index=String(n.index);let c=document.createElement(`span`);c.className=`n`,c.textContent=String(n.index+1).padStart(2,` `);let l=document.createElement(`span`);l.className=`name`,l.textContent=n.name;let u=document.createElement(`span`);if(u.className=`time`,u.textContent=n.seconds>0?e(n.seconds):`--:--`,a.append(c,l,u),o===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,i(e,`copy`),e.title=`Copy a link that plays this here, from where it is`,e.setAttribute(`aria-label`,`Copy a link that plays ${n.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),Bt(Vt(`track:${n.index}`,y===n.index?T.position:0),e,`✓`)}),a.append(e)}t.push(a)}n.playlist.replaceChildren(...t)}let g=O(),_=ke(),v;for(let e of Array.from(n.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===g;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&_),r&&(v=t)}g!==Fe&&(Fe=g,v?.scrollIntoView({block:`nearest`}))}function ze(e){let t=document.createElement(`li`);t.className=`group`;let r=document.createElement(`span`);if(r.className=`group-name`,r.textContent=e===``?`This server's library`:e,t.append(r),e!==``&&!n.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(),Be(e)}),t.append(n)}return t}async function Be(e){try{let t=await fetch(E.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();I(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{I(`could not reach the server`)}}function Ve(){let t=n.canvas,r=Math.min(2,globalThis.devicePixelRatio||1),i=Math.round(t.clientWidth*r),a=Math.round(t.clientHeight*r);i>0&&a>0&&(t.width!==i||t.height!==a)&&(t.width=i,t.height=a);let o=t.getContext(`2d`);if(w())C=ye(C,S);else{let e=T.read();e.length>0&&(ce.length!==25&&(ce=ge(24,e.length)),S=ve(S,_e(e,ce)),C=ye(C,S))}if(o){let e=getComputedStyle(document.documentElement);be(o,{width:t.width,height:t.height},S,C,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(ke()){n.glyphs.textContent=S.map(Pe).join(``);let[t,r]=w()?m.levels:T.levels();n.levels.textContent=Ne(t,r),n.elapsed.textContent=e(Oe());let i=De();!v&&i>0&&(n.seek.value=String(Math.round(Oe()/i*1e3)))}requestAnimationFrame(Ve)}function P(e){n.video.hidden=!e,n.fullscreen.hidden=!e}function He(){`mediaSession`in navigator&&(navigator.mediaSession.metadata=new MediaMetadata({title:Te(),album:Ee(),artist:`nixamp`,artwork:[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]}),navigator.mediaSession.setActionHandler(`play`,()=>void je()),navigator.mediaSession.setActionHandler(`pause`,()=>void je()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void A(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void A(-1)))}n.filter.addEventListener(`input`,()=>{M=``,Re()}),n.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&k(n)}),n.fullscreen.addEventListener(`click`,()=>{let e=n.video;if(document.fullscreenElement){document.exitFullscreen().catch(()=>{});return}if(typeof e.requestFullscreen==`function`){e.requestFullscreen().catch(()=>{e.webkitEnterFullscreen?.()});return}e.webkitEnterFullscreen?.()}),n.prev.addEventListener(`click`,()=>void A(-1)),n.next.addEventListener(`click`,()=>void A(1)),n.stop.addEventListener(`click`,()=>void Me()),n.playPause.addEventListener(`click`,()=>void je()),n.seek.addEventListener(`input`,()=>{v=!0}),n.seek.addEventListener(`change`,()=>{let e=De();e>0&&T.seek(Number(n.seek.value)/1e3*e),v=!1}),n.volume.addEventListener(`input`,()=>{let e=Number(n.volume.value)/100;T.volume=e;try{localStorage.setItem(Se,String(e))}catch{}});let Ue=e=>{e.addEventListener(`change`,()=>{let t=ee(Array.from(e.files??[]));if(t.length===0){_=`Nothing playable in that selection.`,j();return}te(f),f=t,p=0,o=`local`,E.close(),_=``,k(0)})};Ue(n.files),Ue(n.folder),n.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=n.remoteUrl.value,{base:r,key:i}=se(t);if(r===``){_=`That is not an address.`,j();return}(async()=>{h=`connecting`,j();let e=me(r);if(e){h=`error`,g=e,_=e,o=`local`,j();return}if(await pe(r,void 0,i)===null){h=`error`;let e=de(r);g=e?`needs the server's name`:`not answering`,_=e||`Nothing answered at ${r}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,o=`local`,j();return}let n=await fe(r,i);if(n){h=`error`,g=n,_=n,o=`local`,j();return}o=`remote`,_=``;try{localStorage.setItem(xe,t.trim())}catch{}E.connect(t),Q(),K(),Mt(!0),Qe(),kt(),j()})()});let We=async()=>{n.directory.hidden=!1,n.directoryNote.textContent=`Looking for live streams…`,n.directoryList.replaceChildren();let e;try{let t=await fetch(`/api/directory`);if(!t.ok)throw Error(String(t.status));let n=await t.json();e=n.streams??[],tt(n.recent??[])}catch{n.directoryNote.textContent=`The directory is not answering. Type an address instead.`;return}if(e.length===0){n.directoryNote.textContent=`Nobody is streaming right now.`;return}n.directoryNote.textContent=`${e.length} ${e.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 t of e){let e=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=t.name;let a=document.createElement(`span`);a.className=`detail`;let o=[`${t.tracks.toLocaleString()} files to browse`];if(t.playing!==!1&&t.nowPlaying?o.push(`playing ${t.nowPlaying}`):o.push(`player idle`),t.code&&o.push(t.callers?`☎ ${t.code} · ${t.callers} on the phone`:`☎ ${t.code}`),a.textContent=o.join(` · `),r.append(i,a),t.channels&&t.channels.length>0){let e=document.createElement(`span`);e.className=`detail live`,e.textContent=`● live: ${t.channels.join(`, `)}`,r.append(e)}let s=!!t.admin,l=e=>{c=e,n.remoteUrl.value=e?t.url:t.admin??t.url,n.directory.hidden=!0,n.remoteForm.requestSubmit()},u=document.createElement(`button`);u.type=`button`,u.className=`button`,u.textContent=`Viewer`,u.title=`Browse and watch. Changes nothing on the server.`,u.addEventListener(`click`,()=>l(!0));let d=document.createElement(`button`);if(d.type=`button`,d.className=`button`,d.textContent=`Admin`,d.disabled=!s,d.title=s?`Drive this server: what plays, what is live, what is on it.`:X?`You do not administer this server.`:`Sign in as this server's owner to administer it.`,d.addEventListener(`click`,()=>l(!1)),e.append(r,u,d),X&&e.append(it(t.url,t.name)),t.ownerId&&X&&t.ownerId!==X&&e.append(bt(t.ownerId,t.name)),t.ownerId&&X&&t.ownerId===X){let r=document.createElement(`button`);r.type=`button`,r.className=`ghost`,r.textContent=`Take off the list`,r.addEventListener(`click`,e=>{e.stopPropagation(),r.disabled=!0,(async()=>{try{let e=await fetch(`/api/directory?id=${encodeURIComponent(t.id)}`,{method:`DELETE`}),r=await e.json().catch(()=>({}));n.directoryNote.textContent=e.ok?`${t.name} is off the list.`:r.error??`that did not work`}catch{n.directoryNote.textContent=`could not reach the directory`}finally{await We()}})()}),e.append(r)}n.directoryList.append(e)}};if(location.pathname.replace(/\/+$/,``)===`/directory`){document.body.classList.add(`route-directory`);let e=document.getElementById(`directory-back`);e&&(e.hidden=!1),We()}let F=null,Ge=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Ke=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,qe=``,Je=``,Ye=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===qe)return;qe=t,n.adminConnections.replaceChildren();let r=document.createElement(`tr`);for(let e of[`Where`,`Network`,`Kind`,`Client`,`Track`,`Sent`]){let t=document.createElement(`th`);t.textContent=e,r.append(t)}n.adminConnections.append(r);for(let t of e.slice(0,40)){let e=document.createElement(`tr`);t.endedAt!==null&&(e.className=`ended`);let r=[[t.address,``],[Ge(t.network),`network-${t.network}`],[Ke(t.kind),``],[t.agent,``],[t.track||`—`,``],[`${Math.round(t.bytes/1024)} KiB`,``]];for(let[t,n]of r){let r=document.createElement(`td`);r.textContent=t,n&&(r.className=n),e.append(r)}n.adminConnections.append(e)}};function I(e){n.adminSaid.textContent=e,n.adminSaid.hidden=e===``}let Xe=async()=>{try{let e=await fetch(E.url(`/api/connections`));if(!e.ok)return;let t=await e.json(),r=(t.connections??[]).filter(e=>e.endedAt===null&&e.kind!==`media`&&e.kind!==`stream`).length,i=t.active??0;n.adminNote.textContent=r===0?`${i} listening now.`:`${i} listening now, and ${r} with the page open.`,Ye(t.connections??[]),Ze(t.publish??[],(t.channels??[]).map(e=>e.id)),Kt(t.home??``,t.root??``),Q()}catch{n.adminNote.textContent=`lost touch with the server`}};function Ze(e,t){n.publishPanel.hidden=e.length===0;let r=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(r===Je)return;if(Je=r,e.length===0){n.publishList.replaceChildren();return}let i=e.length-t.length;n.publishNote.textContent=`Point OBS, Larix or ffmpeg at one of these. One publisher per URL — ${e.length} at once, ${i} free right now.`,n.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 Qe=async()=>{if(o!==`remote`){n.adminPanel.hidden=!0,n.publishPanel.hidden=!0,F&&clearInterval(F),F=null;return}let e=!1,t=null,r=!1;try{let n=await fetch(E.url(`/api/admin`));if(n.ok){let i=await n.json();e=i.allowed===!0,t=i.as??null,r=i.claimed===!0}}catch{e=!1}if(c&&(e=!1),n.adminPanel.hidden=!e,F&&clearInterval(F),F=null,Q(),K(),kt(),n.listenOnly.hidden=e,!e){n.listenOnly.textContent=r?`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}n.adminNote.textContent=t===`owner`?`You own this server.`:`You hold this server's control link.`,Xe(),F=setInterval(()=>void Xe(),2e3)};function $e(e,t,r){let i=(t||e).toLowerCase().replace(/[^a-z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`s${Math.random().toString(16).slice(2,8)}`;I(`Starting ${t||e}…`),(async()=>{try{let a=await fetch(E.url(`/api/channels/${encodeURIComponent(i)}/pull`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({...r===void 0?{source:e}:{at:r},...t?{name:t}:{}})}),o=await a.json();if(!a.ok){I(o.error??`that did not work`);return}I(`${o.channel?.name||t||e} is on the air.`),n.adminSource.value=``,n.adminName.value=``,kt(),Q()}catch{I(`could not reach the server`)}})()}n.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=n.adminSource.value.trim();t&&$e(t,n.adminName.value.trim())}),n.adminAdd.addEventListener(`click`,()=>{let e=n.adminSource.value.trim();if(!e)return;I(`Reading ${e}…`);let t=n.adminReplace.checked,r=n.adminName.value.trim();(async()=>{try{let i=await fetch(E.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:e,...r?{name:r}:{},...t?{replace:!0}:{}})}),a=await i.json();I(i.ok?t?`Now serving ${e}.`:a.added===0?`Everything there was already in the playlist.`:`Added ${a.added??0} tracks from ${e}.`:a.error??`that did not work`),i.ok&&(n.adminSource.value=``,n.adminName.value=``,kt(),Q())}catch{I(`could not reach the server`)}})()});let et=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`},tt=e=>{n.recentList.replaceChildren();let t=X?e.filter(e=>e.ownerId&&e.ownerId!==X):[];if(n.recentNote.hidden=t.length===0,t.length!==0)for(let e of t){let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.nowPlaying?`${e.nowPlaying} · ended ${et(e.endedAt)}`:`ended ${et(e.endedAt)}`,r.append(i,a),t.append(r,bt(e.ownerId,e.name)),n.recentList.append(t)}},L=new Set,R=e=>{try{return new URL(e).origin}catch{return e}},z=e=>[...L].some(t=>R(t)===R(e));async function nt(){if(!X){L=new Set,n.favoritesPanel.hidden=!0,B();return}try{let e=await fetch(`/api/v1/favorites`);if(!e.ok){n.favoritesPanel.hidden=!0;return}let t=(await e.json()).favorites??[];L=new Set(t.map(e=>e.url)),n.favoritesPanel.hidden=t.length===0,n.favoritesNote.textContent=`Servers you hearted. Connect to one, or let it go.`,n.favoritesList.replaceChildren(...t.map(e=>{let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`server-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name||e.url.replace(/^https?:\/\//,``);let a=document.createElement(`span`);a.className=e.live?`detail live`:`detail`,a.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`,r.append(i,a);let o=document.createElement(`button`);return o.type=`button`,o.className=`button`,o.textContent=`Connect`,o.addEventListener(`click`,()=>{n.remoteUrl.value=e.url,n.remoteForm.requestSubmit()}),t.append(r,o,it(e.url,e.name)),t}))}catch{n.favoritesPanel.hidden=!0}B()}async function rt(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){_=n?`Could not save that favourite.`:`Could not remove that favourite.`,j();return}}catch{_=`could not reach nixamp.com`,j();return}if(n)L.add(e);else for(let t of[...L])R(t)===R(e)&&L.delete(t);await nt()}function it(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`heart`;let r=()=>{let t=z(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=[...L].find(t=>R(t)===R(e))??e;rt(z(e)?i:e,t,!z(e)).then(r)}),n}function B(){let e=o===`remote`?E.shareLink:``;if(n.favHere.hidden=!(X&&e),n.favHere.hidden)return;let t=z(e);n.favHere.textContent=t?`♥`:`♡`,n.favHere.dataset.on=t?`yes`:`no`,n.favHere.title=t?`Remove this server from your favourites`:`Add this server to your favourites`,n.favHere.setAttribute(`aria-label`,n.favHere.title)}i(n.copyNow,`copy`),n.copyNow.addEventListener(`click`,()=>{Bt(T.source,n.copyNow,`✓`)}),n.favHere.addEventListener(`click`,()=>{let e=Ht()||E.shareLink;if(!e)return;let t=[...L].find(t=>R(t)===R(e))??e;rt(z(e)?t:e,s||E.address,!z(e)).then(B)});let V=[],H=null,U=null,W=``,G=[],at=0,ot=null,st=0;function ct(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 K(){if(o!==`remote`){n.catalogsPanel.hidden=!0;return}let e;try{e=await fetch(E.url(`/api/catalogs`))}catch{n.catalogsPanel.hidden=!0;return}if(!e.ok){n.catalogsPanel.hidden=!0;return}V=(await e.json().catch(()=>({}))).catalogs??[],H&&=V.find(e=>e.id===H?.id)??null,H||(U=null),n.catalogsPanel.hidden=!1,q()}function q(){let e=!n.adminPanel.hidden;n.catalogsForm.hidden=!e;let t=V.reduce((e,t)=>e+t.live,0),r=V.reduce((e,t)=>e+t.vod,0);n.catalogsNote.textContent=V.length===0?e?`No catalogs yet. Add an m3u list of channels or films.`:`No catalogs yet.`:`${V.length} ${V.length===1?`catalog`:`catalogs`} · ${t} live ${t===1?`channel`:`channels`} · ${r} on demand`,lt();let i=H!==null&&U!==null;if(n.catalogsList.hidden=i,n.catalogsFilter.hidden=!i,n.catalogsEntries.hidden=!i,i){mt();return}if(H){dt(H);return}n.catalogsList.replaceChildren(...V.map(t=>ut(t,e)))}function lt(){let e=H!==null;if(n.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},r=()=>{let e=document.createElement(`span`);return e.textContent=`/`,e},i=[t(`All catalogs`,()=>{H=null,U=null,q()},!1),r(),t(H?.name??``,()=>{U=null,q()},U===null)];U!==null&&i.push(r(),t(U===``?`All groups`:U,()=>void 0,!0)),n.catalogsCrumbs.replaceChildren(...i)}function ut(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 ${ct(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`,()=>{H=e,U=null,q()}),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`,()=>{gt(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?`)&&_t(e)}),n.append(t,r)}return n}async function dt(e){n.catalogsList.replaceChildren();let t=[];try{let n=await fetch(E.url(`/api/catalogs/${encodeURIComponent(e.id)}/groups`));if(!n.ok)throw Error(String(n.status));t=(await n.json()).groups??[]}catch{_=`Could not read the groups in ${e.name}.`,j();return}if(H?.id!==e.id||U!==null)return;let r=[ft(`All groups`,``,e.entries,e.live,e.vod),...t.map(e=>ft(e.name||`(no group)`,e.name,e.count,e.live,e.vod))];n.catalogsList.replaceChildren(...r)}function ft(e,t,r,i,a){let o=document.createElement(`li`),s=document.createElement(`span`);s.className=`server-label`;let c=document.createElement(`span`);c.className=`name`,c.textContent=e;let l=document.createElement(`span`);l.className=`detail`,l.textContent=`${r.toLocaleString()} · ${i.toLocaleString()} live · ${a.toLocaleString()} on demand`,s.append(c,l);let u=document.createElement(`button`);return u.type=`button`,u.className=`button`,u.textContent=`Open`,u.addEventListener(`click`,()=>{U=t,W=``,n.catalogsFilter.value=``,G=[],at=0,q(),pt(0)}),o.append(s,u),o}async function pt(e){let t=H,n=U;if(!t||n===null)return;let r=++st,i=new URLSearchParams({group:n,q:W,offset:String(e),limit:`200`}),a;try{let e=await fetch(E.url(`/api/catalogs/${encodeURIComponent(t.id)}/entries?${i}`));if(!e.ok)throw Error(String(e.status));a=await e.json()}catch{_=`Could not read ${t.name}.`,j();return}r===st&&(at=a.total??0,G=e===0?a.entries??[]:[...G,...a.entries??[]],mt())}function mt(){let t=H;if(!t)return;let r=G.map(n=>{let r=document.createElement(`li`);r.className=`row`;let a=document.createElement(`span`);a.className=`name`,a.textContent=n.title;let o=document.createElement(`span`);if(o.className=n.live?`catalog-tag catalog-live`:`catalog-tag`,o.textContent=n.live?`LIVE`:n.duration>0?e(n.duration):`VOD`,r.append(a,o),!n.live){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,i(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`;Bt(E.url(i),e,`✓`)}),r.append(e)}return r.addEventListener(`click`,()=>{ht(t,n)}),r});if(G.length===0){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`span`);t.className=`group-name`,t.textContent=W?`Nothing called "${W}" here.`:`Nothing in this group.`,e.append(t),r.push(e)}else if(G.length<at){let e=document.createElement(`li`);e.className=`group`;let t=document.createElement(`button`);t.type=`button`,t.className=`ghost`,t.textContent=`Show more (${G.length.toLocaleString()} of ${at.toLocaleString()})`,t.addEventListener(`click`,e=>{e.stopPropagation(),pt(G.length)}),e.append(t),r.push(e)}n.catalogsEntries.replaceChildren(...r)}async function ht(e,t){let n,r={};try{n=await fetch(E.url(`/api/catalogs/${encodeURIComponent(e.id)}/entries/${encodeURIComponent(t.id)}/play`),{method:`POST`}),r=await n.json().catch(()=>({}))}catch{_=`could not reach the server`,j();return}if(!n.ok){_=r.error??`${t.title} would not play.`,j();return}let i=r.name||t.title;if(r.kind===`live`&&r.channel){await It({id:r.channel,name:i,video:!0});return}if(r.kind===`vod`&&r.url){b=null,y=-1,await T.load({title:i,artist:``,album:``,duration:0,url:E.url(r.url),video:!0,objectUrl:!1},!0),P(!0),_=`Playing ${i}.`,j();return}_=`${t.title} would not play.`,j()}async function gt(e){I(`Reading ${e.name} again…`);try{let t=await fetch(E.url(`/api/catalogs/${encodeURIComponent(e.id)}/refresh`),{method:`POST`}),n=await t.json().catch(()=>({}));I(t.ok?`${n.catalog?.name??e.name}: ${(n.catalog?.entries??0).toLocaleString()} entries.`:n.error??`that did not work`)}catch{I(`could not reach the server`)}K()}async function _t(e){try{I((await fetch(E.url(`/api/catalogs/${encodeURIComponent(e.id)}`),{method:`DELETE`})).ok?`${e.name} is off the server.`:`that did not work`)}catch{I(`could not reach the server`)}H?.id===e.id&&(H=null,U=null),K()}n.catalogsForm.addEventListener(`submit`,e=>{e.preventDefault();let t=n.catalogSource.value.trim(),r=n.catalogName.value.trim();t&&(async()=>{I(`Reading ${r||t}…`);try{let e=await fetch(E.url(`/api/catalogs`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:t,name:r})}),i=await e.json().catch(()=>({}));if(!e.ok){I(i.error??`that did not work`);return}I(`${i.catalog?.name??r??t}: ${(i.catalog?.entries??0).toLocaleString()} entries.`),n.catalogSource.value=``,n.catalogName.value=``}catch{I(`could not reach the server`)}K()})()}),n.catalogsFilter.addEventListener(`input`,()=>{ot&&clearTimeout(ot),ot=setTimeout(()=>{ot=null,W=n.catalogsFilter.value.trim(),pt(0)},250)});let vt=async()=>{n.serversList.replaceChildren();try{let e=await fetch(`/api/v1/servers`);if(!e.ok){n.serversPanel.hidden=!0;return}let t=(await e.json()).servers??[];n.serversPanel.hidden=!1,n.serversNote.textContent=t.length===0?"No servers yet. `nixamp server add --here` remembers the one you are running.":`The machines on your account. Open one, or forget it.`;for(let e of t){let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.url,r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`button`,o.textContent=`Open`,o.addEventListener(`click`,()=>{n.remoteUrl.value=e.key?`${e.url}/admin/${e.key}`:e.url,n.remoteForm.requestSubmit()}),pe(e.url).then(n=>{if(n!==null){a.textContent=`${e.url} · ${n}`;return}a.textContent=`${e.url} · not answering`,t.classList.add(`offline`),o.disabled=!0,o.title=`That machine is not answering. Start nixamp on it.`});let s=document.createElement(`button`);s.type=`button`,s.className=`ghost`,s.textContent=`Forget`,s.addEventListener(`click`,()=>{(async()=>{s.disabled=!0;try{await fetch(`/api/v1/servers/${encodeURIComponent(e.id)}`,{method:`DELETE`}),await vt()}catch{s.disabled=!1}})()}),t.append(r,o,s),n.serversList.append(t)}}catch{n.serversPanel.hidden=!0}},yt=async()=>{n.followingList.replaceChildren();try{let e=await fetch(`/api/v1/follows`);if(!e.ok){n.followingNote.hidden=!0;return}let t=(await e.json()).following??[];n.followingNote.hidden=t.length===0;for(let e of t){let t=document.createElement(`li`),r=document.createElement(`span`);r.className=`recent-label`;let i=document.createElement(`span`);i.className=`name`,i.textContent=e.name||`a nixamp`;let a=document.createElement(`span`);a.className=`detail`,a.textContent=e.live?`live now`:`not streaming`,r.append(i,a);let o=document.createElement(`button`);o.type=`button`,o.className=`ghost follow`,o.textContent=`Unfollow`,o.addEventListener(`click`,()=>{(async()=>{o.disabled=!0;try{await fetch(`/api/v1/follows/${encodeURIComponent(e.id)}`,{method:`DELETE`}),t.remove(),n.followingList.children.length===0&&(n.followingNote.hidden=!0)}finally{o.disabled=!1}})()}),t.append(r,o),n.followingList.append(t)}}catch{n.followingNote.hidden=!0}},bt=(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),yt())}catch{}finally{n.disabled=!1}})()}),n},xt=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},St=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,Ct=async()=>{if(!St())return n.notifyNote.textContent=`This browser cannot show notifications.`,!1;if(Notification.permission===`denied`)return n.notifyNote.textContent=`This browser is blocking notifications. Allow them in site settings first.`,!1;if(await Notification.requestPermission()!==`granted`)return n.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 n.notifyNote.textContent=`This server is not set up to send notifications.`,!1;let r=await e.pushManager.getSubscription()??await e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:xt(t)}),i=await fetch(`/api/v1/notify/subscribe`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(r.toJSON())});if(!i.ok)throw Error(String(i.status));return n.notifyNote.textContent=`This device will be told.`,!0}catch{return n.notifyNote.textContent=`Could not set this device up.`,!1}},wt=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{}},J=async e=>{try{let t=await fetch(`/api/v1/notify/prefs`,{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify(e)}),r=await t.json();n.notifyPhoneNote.textContent=t.ok?``:r.error??`that did not save`,t.ok&&typeof r.phone==`string`&&(n.notifyPhone.value=r.phone)}catch{n.notifyPhoneNote.textContent=`could not reach nixamp.com`}},Tt=async()=>{try{let e=await fetch(`/api/v1/notify/prefs`);if(!e.ok)return;let t=await e.json();n.notifyEmail.checked=t.wantsEmail!==!1,n.notifySms.checked=t.wantsSms===!0,n.notifyPhone.value=t.phone??``;let r=St()&&Notification.permission===`granted`?await(await navigator.serviceWorker.ready).pushManager.getSubscription()!==null:!1;n.notifyWeb.checked=t.wantsWeb!==!1&&r,n.notifyNote.textContent=r?`Get told when someone you follow goes live.`:`Turn on “On this device” to be told here.`}catch{}};n.notifyWeb.addEventListener(`change`,()=>{(async()=>{if(n.notifyWeb.checked){let e=await Ct();n.notifyWeb.checked=e,await J({wantsWeb:e});return}await wt(),await J({wantsWeb:!1}),n.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),n.notifyEmail.addEventListener(`change`,()=>{J({wantsEmail:n.notifyEmail.checked})}),n.notifySms.addEventListener(`change`,()=>{(async()=>{if(n.notifySms.checked&&!n.notifyPhone.value.trim()){n.notifyPhoneNote.textContent=`Add a phone number first.`,n.notifySms.checked=!1,n.notifyPhone.focus();return}await J({wantsSms:n.notifySms.checked})})()}),n.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),J({phone:n.notifyPhone.value.trim()})});let Y=!1,X=``,Z=e=>{let t=e!==null;n.notifyPanel.hidden=!t,t?(Tt(),yt(),vt()):(n.serversPanel.hidden=!0,n.followingNote.hidden=!0,n.followingList.replaceChildren(),n.recentNote.hidden=!0,n.recentList.replaceChildren()),n.accountForm.hidden=t,n.accountProviders.hidden=t||n.accountProviders.childElementCount===0,n.accountSignOut.hidden=!t,n.accountNote.textContent=t?`Signed in as ${e}.`:Y?`Create an account on nixamp.com.`:`Listening needs no account. Sign in to keep favourites, follow people, and publish.`,n.accountSubmit.textContent=Y?`Create account`:`Sign in`,n.accountToggle.textContent=Y?`I have one`:`Create one`,n.accountPassword.autocomplete=Y?`new-password`:`current-password`},Et=async()=>{let e=[],t=!1;try{let n=await fetch(`/api/v1/auth/providers`);n.ok&&(t=!0,e=(await n.json()).providers??[])}catch{}n.accountProviders.replaceChildren(),n.accountProviders.hidden=e.length===0,n.accountPanel.hidden=!t,n.accountElsewhere.hidden=t;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}`,n.accountProviders.append(e)}},Dt=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();X=e.ok?t.account?.id??``:``,Z(e.ok?t.account?.email??`you`:null)}catch{X=``,Z(null)}nt(),Ot()};function Ot(){if(x===``)return;let e=x;x=``,n.remoteUrl.value=e,n.remoteForm.requestSubmit()}n.accountToggle.addEventListener(`click`,()=>{Y=!Y,Z(null)}),n.accountForm.addEventListener(`submit`,e=>{e.preventDefault();let t=n.accountEmail.value.trim(),r=n.accountPassword.value;(async()=>{n.accountSubmit.disabled=!0;try{let e=await fetch(`/api/v1/auth/${Y?`signup`:`login`}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:r})}),i=await e.json();if(!e.ok){n.accountNote.textContent=i.error??`that did not work`;return}X=i.account?.id??``,n.accountPassword.value=``,Z(i.account?.email??t),Qe(),Ot()}catch{n.accountNote.textContent=`could not reach nixamp.com`}finally{n.accountSubmit.disabled=!1}})()}),n.accountSignOut.addEventListener(`click`,()=>{(async()=>{try{await fetch(`/api/v1/auth/logout`,{method:`POST`})}catch{}X=``,Z(null),E.close(),y=-1,o=`local`,h=`idle`,g=``,n.remoteUrl.value=``,n.sharePanel.hidden=!0,n.publishPanel.hidden=!0,n.adminPanel.hidden=!0,n.onairPanel.hidden=!0,n.catalogsPanel.hidden=!0,n.listenOnly.hidden=!0,Mt(!1);try{localStorage.removeItem(xe)}catch{}_=`Signed out, and disconnected from the server.`,Qe(),j()})()});try{let e=new URL(globalThis.location.href).searchParams,t=e.get(`url`)??``;t!==``&&(x=t,l=e.get(`play`)??``,u=Math.max(0,Number(e.get(`t`)??`0`)||0),n.remoteUrl.value=t,_=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname))}catch{}Et(),Dt(),Qe(),n.browse.addEventListener(`click`,()=>{if(!n.directory.hidden){n.directory.hidden=!0;return}We(),n.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),n.disconnect.addEventListener(`click`,()=>{E.close(),n.listenOnly.hidden=!0,y=-1,n.sharePanel.hidden=!0,n.publishPanel.hidden=!0,n.adminPanel.hidden=!0,n.onairPanel.hidden=!0,n.onairPanel.dataset.title=`Live on this server`,n.catalogsPanel.hidden=!0,n.catalogsPanel.dataset.title=`Catalogs on this server`,s=``,d=``,B(),Mt(!1),o=`local`,h=`idle`,g=``,j()});async function kt(){if(o!==`remote`||E.shareLink===``){n.sharePanel.hidden=!0;return}n.sharePanel.hidden=!1;let e=Ht(),t=globalThis.location.origin;n.shareLink.value=e===``?``:e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e,n.shareNote.textContent=`Anyone with this link can watch. They sign in once, then it opens.`,n.sharePhone.hidden=!0,n.shareSend.hidden=!0,n.liveControls.hidden=!0;let r=``;try{let e=await fetch(`/api/directory`);e.ok&&(r=(await e.json()).callIn??``)}catch{}let i=null;try{let r=await fetch(E.url(`/api/live/state`));r.ok&&(i=await r.json()),i?.url&&(e=i.url,d=i.url,n.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(i){if(n.liveControls.hidden=n.adminPanel.hidden||!i.possible,n.goLive.hidden=i.live,n.stopLive.hidden=!i.live,n.sharePhone.hidden=!1,!i.live){n.sharePhone.textContent=i.possible?`Not listed, so nobody can find this in the directory. Go live to list it, with a phone number and a code anyone can call.`:`This machine has no address the world can reach, so it cannot be listed.`;return}if(!r){n.sharePhone.textContent=`Listed. The code for the phone line is ${i.code}.`,n.shareSend.hidden=!1;return}n.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),Jt(r),document.createTextNode(` and key `),Jt(i.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),n.shareSend.hidden=!1}}let At=``,jt=null,Mt=e=>{jt&&clearInterval(jt),jt=null,e&&(jt=setInterval(()=>void Q(),6e3))};async function Q(){if(o!==`remote`){n.onairPanel.hidden=!0;return}let e;try{let t=await fetch(E.url(`/api/streams`));if(!t.ok){n.onairPanel.hidden=!0;return}e=await t.json(),e.server.name&&e.server.name!==s&&(s=e.server.name,n.onairPanel.dataset.title=`Live on ${s}`,n.catalogsPanel.dataset.title=`Catalogs on ${s}`,B(),j())}catch{n.onairPanel.hidden=!0;return}n.onairPanel.hidden=!1,Ut(e);let t=`${n.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}`;if(t===At)return;At=t;let r=e.restreams??[],i=e.channels.length+r.length;n.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 a=[],c=e.server.playing,l=!n.adminPanel.hidden;a.push(Wt({title:e.server.name,detail:[c?`playing ${e.server.nowPlaying}`:e.server.nowPlaying?`stopped on ${e.server.nowPlaying}`:`nothing loaded`,`${e.server.tracks} track${e.server.tracks===1?``:`s`}`,e.server.code?`☎ ${e.server.code}`:`not listed`].join(` · `),playLabel:c?`Join live`:l?`Start the stream`:`Nothing playing`,onPlay:()=>{if(c){Ft(e.server.nowPlaying);return}l&&Pt()},link:e.server.live?e.server.url:``,...c?{page:Vt(`live`)}:{},direct:c?E.url(`/api/live`):``}));for(let e of r)a.push(Wt({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{k(e.at)},link:``,direct:E.media(e.at)}));for(let t of e.channels){let e=t.kind!==`audio`,n=E.url(`/api/channels/${encodeURIComponent(t.id)}`),r=[t.via===`pull`?`on the air · ${t.listeners} watching`:`live over ${t.via} · ${t.listeners} listening`];t.redials&&r.push(`redialled ${t.redials}×`),l&&t.error&&r.push(t.error),a.push(Wt({title:t.name,detail:r.join(` · `),onPlay:()=>{It({id:t.id,name:t.name,video:e})},link:n,page:Vt(`channel:${t.id}`),direct:n,onRestart:l&&t.via===`pull`?()=>{Rt(t.id,t.name)}:void 0,onStop:l?()=>{zt(t.id,t.name)}:void 0}))}n.onairList.replaceChildren(...a)}async function Nt(){if(o===`remote`)try{if((await fetch(E.media(O(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;_=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===``&&n.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),j()}catch{}}async function Pt(){I(`Starting the stream on the server…`);try{await E.send({type:`play`,index:Math.max(0,O())})}catch{I(`could not reach the server`);return}await Ft(m.tracks[O()]?.title??``),I(`Playing to the room. Anybody with the view link sees this.`),await Q()}async function Ft(e){y=-1,b=null,await T.load({title:e||`Live`,artist:``,album:``,duration:0,url:E.url(`/api/live`),video:!0,objectUrl:!1},!0),P(!0),_=`Watching what this server is playing. Everyone here sees the same thing.`,j()}async function It(e,t=!0){y=-1,b=e,t&&(ne=0),await T.load({title:e.name,artist:``,album:``,duration:0,url:E.url(`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0),P(e.video),_=`Watching ${e.name}, live on this server.`,j()}function Lt(){let e=b;return e?re?!0:ne>=5?(_=`${e.name} stopped, and did not come back.`,b=null,j(),!0):(ne+=1,_=`${e.name} started over; rejoining…`,j(),re=setTimeout(()=>{re=null,b===e&&It(e,!1)},2e3),!0):!1}function $(e){n.onairNote.textContent=e,I(e)}async function Rt(e,t){$(`Restarting ${t}…`);try{let n=await fetch(E.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`)}At=``,Q()}async function zt(e,t){$(`Taking ${t} off the air…`);try{let n=await fetch(E.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`)}b?.id===e&&(b=null,T.stop()),At=``,Q()}async function Bt(e,t,n=`Copied`){if(!e)return;let r=t.innerHTML;try{await navigator.clipboard.writeText(e)}catch{_=e,j();return}n===`✓`||n===`✓`?i(t,`check`):t.textContent=n,setTimeout(()=>{t.innerHTML=r},1200)}function Vt(e,t=0){let n=Ht();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 Ht(){if(d!==``)return d;let e=o===`remote`?E.shareLink:``;return/\/admin\//.test(e)?``:e}function Ut(e){if(l===``)return;let t=l;if(t===`live`){l=``,e.server.playing?Ft(e.server.nowPlaying):(_=`Nothing is playing on this server right now.`,j());return}let n=t.startsWith(`channel:`)?t.slice(8):``,r=e.channels.find(e=>e.id===n);r&&(l=``,It({id:r.id,name:r.name,video:r.kind!==`audio`}))}function Wt(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 a=document.createElement(`span`);a.className=`detail`,a.textContent=e.detail,n.append(r,a);let o=document.createElement(`span`);o.className=`onair-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`button`,s.textContent=e.playLabel??`Play`,s.addEventListener(`click`,e.onPlay),o.append(s);let c=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`icon`,i(r,e),r.title=t,r.setAttribute(`aria-label`,t),r.addEventListener(`click`,()=>n(r)),r};return(e.link||e.page)&&o.append(c(`link`,`Copy a link that opens this in the player`,t=>{let n=globalThis.location.origin;Bt(e.page??(e.link.startsWith(`https://`)?`${n}/?url=${encodeURIComponent(e.link)}`:e.link),t,`✓`)})),e.direct&&o.append(c(`copy`,`Copy the stream's own URL, for VLC or mpv`,t=>{Bt(e.direct??``,t,`✓`)})),e.onRestart&&o.append(c(`restart`,`Restart: dial the source again`,()=>e.onRestart?.())),e.onStop&&o.append(c(`remove`,`Remove: take it off the air`,()=>e.onStop?.())),t.append(n,o),t}let Gt=``;function Kt(e,t){Gt=e;let r=e!==``&&t===e;n.loadHome.hidden=e===``,n.homeNote.hidden=e===``,e!==``&&(n.homeNote.textContent=r?`This server's own files: ${e}`:`This server's own files are ${e}, and are not in the playlist.`,n.loadHome.disabled=!1)}n.loadHome.addEventListener(`click`,()=>{Gt!==``&&(n.loadHome.disabled=!0,I(`Reading this server's files…`),(async()=>{try{let e=await fetch(E.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:Gt})}),t=await e.json();I(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{I(`could not reach the server`)}finally{n.loadHome.disabled=!1}})())});let qt=async e=>{n.goLive.disabled=!0,n.stopLive.disabled=!0,n.shareNote.textContent=e?`Going live…`:`Taking it off the list…`;try{let t=await fetch(E.url(e?`/api/live/start`:`/api/live/stop`),{method:`POST`}),r=await t.json();n.shareNote.textContent=t.ok?e?`Live. Anyone can call and key ${r.code??``} to talk about it.`:`Taken off the list. The link still works for anybody who has it.`:r.error??`that did not work`}catch{n.shareNote.textContent=`could not reach the server`}finally{n.goLive.disabled=!1,n.stopLive.disabled=!1,await kt()}};n.goLive.addEventListener(`click`,()=>void qt(!0)),n.stopLive.addEventListener(`click`,()=>void qt(!1));function Jt(e){let t=document.createElement(`b`);return t.textContent=e,t}n.shareCopy.addEventListener(`click`,()=>{n.shareLink.select(),navigator.clipboard?.writeText(n.shareLink.value).then(()=>{n.shareNote.textContent=`Copied. Send it to anybody.`},()=>{n.shareNote.textContent=`Copy it from the box above.`})}),n.shareSend.addEventListener(`submit`,e=>{e.preventDefault();let t=n.shareTo.value.trim();t!==``&&(async()=>{n.shareNote.textContent=`Sending…`;try{let e=await fetch(`/api/v1/invite`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({to:t,stream:Ht()})}),r=await e.json();n.shareNote.textContent=e.ok?`Sent to ${r.sent??t}.`:r.error??`that did not send`,e.ok&&(n.shareTo.value=``)}catch{n.shareNote.textContent=`could not send that`}})()}),n.listenHere.addEventListener(`change`,()=>{try{localStorage.setItem(Ce,n.listenHere.checked?`1`:`0`)}catch{}o===`remote`&&(async()=>{n.listenHere.checked?(await E.send({type:`stop`}),await Ae(m.index)):(T.stop(),y=-1),j()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),je();return;case`s`:Me();return;case`n`:case`ArrowRight`:A(1);return;case`p`:case`ArrowLeft`:A(-1);return;case`ArrowDown`:e.preventDefault(),k(Math.min(he()-1,O()+1));return;case`ArrowUp`:e.preventDefault(),k(Math.max(0,O()-1));return}});let Yt=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),Yt=e,n.install.hidden=!1}),n.install.addEventListener(`click`,()=>{Yt?.prompt(),Yt=null,n.install.hidden=!0});try{let e=localStorage.getItem(Se);e!==null&&(n.volume.value=String(Math.round(Number(e)*100)),T.volume=Number(e));let t=localStorage.getItem(xe);t&&(n.remoteUrl.value=t),localStorage.getItem(Ce)===`0`&&(n.listenHere.checked=!1)}catch{}(async()=>{if(n.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await pe(e)===null)return;let t=await ue(e);t&&t.trackCount!==0&&(n.remoteUrl.value=e,o=`remote`,_=``,E.connect(e),j())})(),(()=>{if(we)return;let e=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``},t=new Audio;t.volume=.7;let n=()=>{we=!0},r=()=>{document.removeEventListener(`pointerdown`,r),document.removeEventListener(`keydown`,r),n(),t.play().catch(()=>{})};e().then(e=>{if(e!==``)return t.src=e,t.play().then(n,()=>{document.addEventListener(`pointerdown`,r,{once:!0}),document.addEventListener(`keydown`,r,{once:!0})})})})(),j(),requestAnimationFrame(Ve)}O(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{c as t};