nixamp 0.7.35 → 0.7.37
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/audio.js +3 -1
- package/dist/channels.d.ts +71 -2
- package/dist/channels.js +195 -6
- package/dist/rtmp-in.js +4 -0
- package/dist/server.d.ts +11 -1
- package/dist/server.js +81 -11
- package/package.json +1 -1
- package/src/audio.ts +3 -1
- package/src/channels.ts +213 -5
- package/src/rtmp-in.ts +4 -0
- package/src/server.ts +96 -12
- package/web/dist/assets/{hls-3VKVEQE3-DL_mIqWp.js → hls-3VKVEQE3-DbzFtX7t.js} +1 -1
- package/web/dist/assets/index-DGi1TAtn.js +1 -0
- package/web/dist/assets/{index-DDa16PVk.css → index-PhllvN11.css} +1 -1
- package/web/dist/assets/{mpegts-LO6RVLD6-UN1L-F7w.js → mpegts-LO6RVLD6-pqyQjSte.js} +1 -1
- package/web/dist/assets/{mpegts-BowzC-37.js → mpegts-Nijsm5UM.js} +1 -1
- package/web/dist/index.html +2 -2
- package/web/dist/install.sh +29 -2
- package/web/dist/sw.js +6 -6
- package/web/dist/assets/index-C_j8Onbv.js +0 -1
package/src/channels.ts
CHANGED
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
*/
|
|
17
17
|
import { spawn, type ChildProcess } from "node:child_process";
|
|
18
18
|
import { randomBytes } from "node:crypto";
|
|
19
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
20
|
+
import { join } from "node:path";
|
|
19
21
|
import type { Readable } from "node:stream";
|
|
20
22
|
import { Fragments } from "./fragments.ts";
|
|
21
23
|
|
|
@@ -44,12 +46,52 @@ export interface ChannelInfo {
|
|
|
44
46
|
kind?: "audio" | "video";
|
|
45
47
|
/** For a channel we pull ourselves: where from. Never shown to a listener. */
|
|
46
48
|
source?: string;
|
|
49
|
+
/** The last thing ffmpeg complained about, for whoever administers this. */
|
|
50
|
+
error?: string;
|
|
51
|
+
/** How many times the source has been dialled again since it started. */
|
|
52
|
+
redials?: number;
|
|
47
53
|
}
|
|
48
54
|
|
|
49
55
|
/** How long to wait before dialling a dropped source again. */
|
|
50
56
|
export const REDIAL = 2000;
|
|
51
57
|
/** How many times in a row a source may fail without ever sending anything. */
|
|
52
58
|
export const GIVE_UP = 5;
|
|
59
|
+
/**
|
|
60
|
+
* How long a pulled source may say nothing before it is treated as gone.
|
|
61
|
+
*
|
|
62
|
+
* ffmpeg's own reconnect covers a connection that errors. It does not cover
|
|
63
|
+
* one that simply stops sending, and neither does anything else: a television
|
|
64
|
+
* channel that is quiet for half a minute is not being quiet, it is dead.
|
|
65
|
+
*/
|
|
66
|
+
export const STALL = 30_000;
|
|
67
|
+
/** How much of what ffmpeg said to keep, for the last line when it dies. */
|
|
68
|
+
const TAIL = 2000;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Read everything a child says on stderr, keeping only the end of it.
|
|
72
|
+
*
|
|
73
|
+
* This is not optional. A pipe nobody reads fills, at 64 KiB on Linux, and
|
|
74
|
+
* the child then blocks on its next write to it -- every thread it has waits
|
|
75
|
+
* on the one that is stuck, and it produces nothing more, for ever, without
|
|
76
|
+
* exiting. A channel carrying an IPTV transport stream logs a line for every
|
|
77
|
+
* corrupt packet, and over twelve hours that is more than 64 KiB. Measured on
|
|
78
|
+
* the real server: CNN "on the air" with a full stderr socket, its decoder
|
|
79
|
+
* thread asleep in the kernel on that write, its byte count frozen, and a
|
|
80
|
+
* listener handed the opening boxes and then nothing at all.
|
|
81
|
+
*/
|
|
82
|
+
function drain(stream: Readable | null | undefined, keep: (tail: string) => void): void {
|
|
83
|
+
let tail = "";
|
|
84
|
+
stream?.on("data", (chunk: Buffer) => {
|
|
85
|
+
tail = (tail + chunk.toString("utf8")).slice(-TAIL);
|
|
86
|
+
keep(tail);
|
|
87
|
+
});
|
|
88
|
+
stream?.on("error", () => undefined);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The last thing ffmpeg said, which is where it says what went wrong. */
|
|
92
|
+
function lastLine(tail: string): string {
|
|
93
|
+
return tail.trim().split("\n").pop() ?? "";
|
|
94
|
+
}
|
|
53
95
|
|
|
54
96
|
/** A name that can sit in a URL and be read back in a list. */
|
|
55
97
|
export function cleanId(value: unknown, fallback = "main"): string {
|
|
@@ -80,6 +122,10 @@ export class Channel {
|
|
|
80
122
|
private redial: (() => void) | null = null;
|
|
81
123
|
private failures = 0;
|
|
82
124
|
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
125
|
+
/** Fires when a pulled source has said nothing for STALL. */
|
|
126
|
+
private watchdog: ReturnType<typeof setTimeout> | null = null;
|
|
127
|
+
private stall = STALL;
|
|
128
|
+
private stderr = "";
|
|
83
129
|
|
|
84
130
|
constructor(
|
|
85
131
|
readonly info: ChannelInfo,
|
|
@@ -112,6 +158,7 @@ export class Channel {
|
|
|
112
158
|
this.info.bytes += chunk.byteLength;
|
|
113
159
|
this.send(chunk);
|
|
114
160
|
});
|
|
161
|
+
drain(child.stderr, (tail) => { this.stderr = tail; });
|
|
115
162
|
// A publisher that hangs up mid-write breaks the pipe, and an unhandled
|
|
116
163
|
// EPIPE takes the whole server with it.
|
|
117
164
|
child.stdin?.on("error", () => this.close());
|
|
@@ -136,13 +183,15 @@ export class Channel {
|
|
|
136
183
|
* because you looked away, and a room where the picture depends on who is
|
|
137
184
|
* in it is not a room anybody can be invited to.
|
|
138
185
|
*/
|
|
139
|
-
pull(source: string, encode: string[], paced = true): void {
|
|
186
|
+
pull(source: string, encode: string[], paced = true, stall = STALL): void {
|
|
187
|
+
this.stall = stall;
|
|
140
188
|
if (this.info.kind === "video") this.fragments = new Fragments();
|
|
141
189
|
const [command, ...prefix] = this.options.ffmpeg as [string, ...string[]];
|
|
142
190
|
const remote = /^https?:\/\//i.test(source);
|
|
143
191
|
|
|
144
192
|
const dial = (): void => {
|
|
145
193
|
if (this.closing) return;
|
|
194
|
+
this.stderr = "";
|
|
146
195
|
const child = spawn(
|
|
147
196
|
command,
|
|
148
197
|
[
|
|
@@ -153,6 +202,11 @@ export class Channel {
|
|
|
153
202
|
// the first time a CDN hiccups is not a channel anybody can rely
|
|
154
203
|
// on. ffmpeg redials on its own before we have to.
|
|
155
204
|
...(remote ? ["-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5"] : []),
|
|
205
|
+
// A connection that stops answering is an error after this long,
|
|
206
|
+
// and an error is a thing the reconnect above knows what to do
|
|
207
|
+
// with. Without it a silent socket is waited on for ever. In
|
|
208
|
+
// microseconds, as ffmpeg wants it.
|
|
209
|
+
...(remote ? ["-rw_timeout", String(stall * 1000)] : []),
|
|
156
210
|
// Real time, always. A file read as fast as the disk allows is an
|
|
157
211
|
// hour of film in ninety seconds and a room that cannot be in it
|
|
158
212
|
// together; a live source is already paced and loses nothing.
|
|
@@ -165,15 +219,22 @@ export class Channel {
|
|
|
165
219
|
);
|
|
166
220
|
|
|
167
221
|
let sent = false;
|
|
222
|
+
this.child = child;
|
|
223
|
+
this.rearm(child);
|
|
168
224
|
child.stdout?.on("data", (chunk: Buffer) => {
|
|
225
|
+
// An ffmpeg that was replaced can still have a chunk in the pipe.
|
|
226
|
+
if (this.child !== child) return;
|
|
169
227
|
sent = true;
|
|
170
228
|
this.info.bytes += chunk.byteLength;
|
|
229
|
+
this.rearm(child);
|
|
171
230
|
this.emit(chunk);
|
|
172
231
|
});
|
|
173
232
|
child.stdout?.on("error", () => undefined);
|
|
174
|
-
child.
|
|
175
|
-
|
|
176
|
-
|
|
233
|
+
drain(child.stderr, (tail) => { this.stderr = tail; });
|
|
234
|
+
// Only the ffmpeg we are currently running gets to say the source
|
|
235
|
+
// dropped. One that was killed to make way for a restart is not news.
|
|
236
|
+
child.on("error", () => { if (this.child === child) this.dropped(sent); });
|
|
237
|
+
child.on("close", () => { if (this.child === child) this.dropped(sent); });
|
|
177
238
|
};
|
|
178
239
|
|
|
179
240
|
this.redial = dial;
|
|
@@ -181,6 +242,75 @@ export class Channel {
|
|
|
181
242
|
this.options.onStart?.(this.info);
|
|
182
243
|
}
|
|
183
244
|
|
|
245
|
+
/**
|
|
246
|
+
* Start the source over, now.
|
|
247
|
+
*
|
|
248
|
+
* For a pulled channel only: a publisher's stream cannot be dialled again
|
|
249
|
+
* from this end. The current ffmpeg is killed and a new one started at
|
|
250
|
+
* once, with the count of failures cleared -- somebody asking for this has
|
|
251
|
+
* decided the thing is worth another go, and should not inherit the four
|
|
252
|
+
* strikes a dead CDN ran up an hour ago.
|
|
253
|
+
*/
|
|
254
|
+
restart(): boolean {
|
|
255
|
+
const dial = this.redial;
|
|
256
|
+
if (!dial || this.closing) return false;
|
|
257
|
+
if (this.timer) clearTimeout(this.timer);
|
|
258
|
+
this.timer = null;
|
|
259
|
+
if (this.watchdog) clearTimeout(this.watchdog);
|
|
260
|
+
this.watchdog = null;
|
|
261
|
+
this.failures = 0;
|
|
262
|
+
this.info.redials = (this.info.redials ?? 0) + 1;
|
|
263
|
+
this.info.error = undefined;
|
|
264
|
+
const old = this.child;
|
|
265
|
+
this.child = null;
|
|
266
|
+
old?.kill("SIGKILL");
|
|
267
|
+
this.startOver();
|
|
268
|
+
dial();
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* The stream that was is over; the next ffmpeg is a new one.
|
|
274
|
+
*
|
|
275
|
+
* New opening boxes, timestamps from zero again. Whoever was listening
|
|
276
|
+
* cannot follow that mid-picture, and a newcomer must not be handed the old
|
|
277
|
+
* opening boxes in front of the new fragments -- so the header is dropped
|
|
278
|
+
* and the audience is ended, to come back to the stream as it now is. The
|
|
279
|
+
* player rejoins on its own. Done the moment the source is known to be
|
|
280
|
+
* gone, not when the redial happens: somebody joining in between gets the
|
|
281
|
+
* new beginning as it is written, rather than a stale one first.
|
|
282
|
+
*/
|
|
283
|
+
private startOver(): void {
|
|
284
|
+
if (this.info.kind === "video") this.fragments = new Fragments();
|
|
285
|
+
this.hangUp();
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Expect output within STALL, or treat the source as gone and dial again. */
|
|
289
|
+
private rearm(child: ChildProcess): void {
|
|
290
|
+
if (this.watchdog) clearTimeout(this.watchdog);
|
|
291
|
+
this.watchdog = setTimeout(() => {
|
|
292
|
+
this.watchdog = null;
|
|
293
|
+
if (this.child !== child || this.closing) return;
|
|
294
|
+
this.info.error = `no data from the source for ${Math.round(this.stall / 1000)}s`;
|
|
295
|
+
// Its close handler is what dials again.
|
|
296
|
+
child.kill("SIGKILL");
|
|
297
|
+
}, this.stall);
|
|
298
|
+
this.watchdog.unref?.();
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** End everybody listening; the stream they were on is over. */
|
|
302
|
+
private hangUp(): void {
|
|
303
|
+
for (const listener of this.listeners) {
|
|
304
|
+
try {
|
|
305
|
+
listener.end();
|
|
306
|
+
} catch {
|
|
307
|
+
// Gone already.
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
this.listeners.clear();
|
|
311
|
+
this.info.listeners = 0;
|
|
312
|
+
}
|
|
313
|
+
|
|
184
314
|
/**
|
|
185
315
|
* A source that stopped. Try it again, unless it never worked at all.
|
|
186
316
|
*
|
|
@@ -191,11 +321,17 @@ export class Channel {
|
|
|
191
321
|
private dropped(sent: boolean): void {
|
|
192
322
|
if (this.closing || !this.redial) return;
|
|
193
323
|
this.child = null;
|
|
324
|
+
if (this.watchdog) clearTimeout(this.watchdog);
|
|
325
|
+
this.watchdog = null;
|
|
326
|
+
const said = lastLine(this.stderr);
|
|
327
|
+
if (said) this.info.error = said;
|
|
194
328
|
this.failures = sent ? 0 : this.failures + 1;
|
|
195
329
|
if (this.failures >= GIVE_UP) {
|
|
196
330
|
this.close();
|
|
197
331
|
return;
|
|
198
332
|
}
|
|
333
|
+
this.info.redials = (this.info.redials ?? 0) + 1;
|
|
334
|
+
this.startOver();
|
|
199
335
|
const dial = this.redial;
|
|
200
336
|
this.timer = setTimeout(() => {
|
|
201
337
|
this.timer = null;
|
|
@@ -282,6 +418,10 @@ export class Channel {
|
|
|
282
418
|
this.redial = null;
|
|
283
419
|
if (this.timer) clearTimeout(this.timer);
|
|
284
420
|
this.timer = null;
|
|
421
|
+
if (this.watchdog) clearTimeout(this.watchdog);
|
|
422
|
+
this.watchdog = null;
|
|
423
|
+
const said = lastLine(this.stderr);
|
|
424
|
+
if (said && !this.info.error) this.info.error = said;
|
|
285
425
|
const child = this.child;
|
|
286
426
|
this.child = null;
|
|
287
427
|
try {
|
|
@@ -378,6 +518,7 @@ export class Channels {
|
|
|
378
518
|
encode: string[],
|
|
379
519
|
kind: "audio" | "video",
|
|
380
520
|
paced = true,
|
|
521
|
+
stall = STALL,
|
|
381
522
|
): Channel | null {
|
|
382
523
|
if (this.open.has(id)) return null;
|
|
383
524
|
const channel = new Channel(
|
|
@@ -396,10 +537,24 @@ export class Channels {
|
|
|
396
537
|
(gone) => this.open.delete(gone),
|
|
397
538
|
);
|
|
398
539
|
this.open.set(id, channel);
|
|
399
|
-
channel.pull(source, encode, paced);
|
|
540
|
+
channel.pull(source, encode, paced, stall);
|
|
400
541
|
return channel;
|
|
401
542
|
}
|
|
402
543
|
|
|
544
|
+
/**
|
|
545
|
+
* Dial a pulled channel's source again, now. False for a channel that is
|
|
546
|
+
* not there or is not ours to dial: a publisher's stream restarts at the
|
|
547
|
+
* publisher's end.
|
|
548
|
+
*/
|
|
549
|
+
restart(id: string): boolean {
|
|
550
|
+
return this.open.get(id)?.restart() ?? false;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Whether a channel is one we fetch ourselves, and so can start over. */
|
|
554
|
+
pulled(id: string): boolean {
|
|
555
|
+
return this.open.get(id)?.info.via === "pull";
|
|
556
|
+
}
|
|
557
|
+
|
|
403
558
|
/** What a listener should be told this channel is. */
|
|
404
559
|
contentType(id: string): string {
|
|
405
560
|
return this.open.get(id)?.info.kind === "video" ? "video/mp4" : "audio/mpeg";
|
|
@@ -446,6 +601,59 @@ export class Channels {
|
|
|
446
601
|
}
|
|
447
602
|
}
|
|
448
603
|
|
|
604
|
+
/**
|
|
605
|
+
* The channels a server pulls itself, remembered across a restart.
|
|
606
|
+
*
|
|
607
|
+
* A server is restarted to pick up a new version, which is to say often, and
|
|
608
|
+
* every restart used to take CNN off the air until somebody noticed and put
|
|
609
|
+
* it back by hand. A publisher's stream cannot be remembered -- it restarts at
|
|
610
|
+
* the publisher's end -- but a pulled one is a name and a URL, and a name and
|
|
611
|
+
* a URL can be written down.
|
|
612
|
+
*
|
|
613
|
+
* Keyed by port, like the keys, because two servers on one machine are two
|
|
614
|
+
* different line-ups.
|
|
615
|
+
*/
|
|
616
|
+
export interface RememberedChannel {
|
|
617
|
+
id: string;
|
|
618
|
+
name: string;
|
|
619
|
+
source: string;
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const REMEMBERED = "channels.json";
|
|
623
|
+
|
|
624
|
+
export function rememberedChannels(dir: string, port: number): RememberedChannel[] {
|
|
625
|
+
try {
|
|
626
|
+
const all = JSON.parse(readFileSync(join(dir, REMEMBERED), "utf8")) as Record<string, unknown>;
|
|
627
|
+
const list = all[String(port)];
|
|
628
|
+
if (!Array.isArray(list)) return [];
|
|
629
|
+
return list.filter(
|
|
630
|
+
(one): one is RememberedChannel =>
|
|
631
|
+
typeof one === "object" && one !== null &&
|
|
632
|
+
typeof (one as RememberedChannel).id === "string" &&
|
|
633
|
+
typeof (one as RememberedChannel).name === "string" &&
|
|
634
|
+
typeof (one as RememberedChannel).source === "string",
|
|
635
|
+
);
|
|
636
|
+
} catch {
|
|
637
|
+
return [];
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
export function rememberChannels(dir: string, port: number, list: RememberedChannel[]): void {
|
|
642
|
+
let all: Record<string, unknown> = {};
|
|
643
|
+
try {
|
|
644
|
+
all = JSON.parse(readFileSync(join(dir, REMEMBERED), "utf8")) as Record<string, unknown>;
|
|
645
|
+
} catch {
|
|
646
|
+
// First time, or unreadable: start again rather than refuse to remember.
|
|
647
|
+
}
|
|
648
|
+
all[String(port)] = list;
|
|
649
|
+
try {
|
|
650
|
+
mkdirSync(dir, { recursive: true });
|
|
651
|
+
writeFileSync(join(dir, REMEMBERED), JSON.stringify(all, null, 2));
|
|
652
|
+
} catch {
|
|
653
|
+
// A state directory that cannot be written costs a memory, not a stream.
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
|
|
449
657
|
/** A channel id nobody chose, for a publisher that did not name one. */
|
|
450
658
|
export function generatedId(): string {
|
|
451
659
|
return `s${randomBytes(3).toString("hex")}`;
|
package/src/rtmp-in.ts
CHANGED
|
@@ -71,6 +71,10 @@ export class RtmpListeners {
|
|
|
71
71
|
channel?.feed(chunk);
|
|
72
72
|
});
|
|
73
73
|
child.stdout?.on("error", () => child.kill("SIGKILL"));
|
|
74
|
+
// Read and dropped. A pipe nobody reads fills at 64 KiB, and ffmpeg then
|
|
75
|
+
// blocks on its next complaint and stops producing anything -- a
|
|
76
|
+
// publisher whose stream hiccups enough would take the slot down with it.
|
|
77
|
+
child.stderr?.resume();
|
|
74
78
|
child.on("error", () => this.done(slot, child, channel));
|
|
75
79
|
child.on("close", () => this.done(slot, child, channel));
|
|
76
80
|
}
|
package/src/server.ts
CHANGED
|
@@ -26,7 +26,10 @@ import {
|
|
|
26
26
|
redact,
|
|
27
27
|
} from "./broadcast.ts";
|
|
28
28
|
import { Ingest, normaliseFormat } from "./ingest.ts";
|
|
29
|
-
import {
|
|
29
|
+
import {
|
|
30
|
+
Channels, cleanId, generatedId, rememberChannels, rememberedChannels,
|
|
31
|
+
type Channel, type RememberedChannel,
|
|
32
|
+
} from "./channels.ts";
|
|
30
33
|
import { RtmpListeners } from "./rtmp-in.ts";
|
|
31
34
|
import { Accounts, clearedCookie, sessionCookie, tokenFrom } from "./accounts.ts";
|
|
32
35
|
import { anonymousHandle, Handles } from "./handles.ts";
|
|
@@ -908,6 +911,30 @@ export class PlayerEngine implements Engine {
|
|
|
908
911
|
* looking at what is on wants "that album from the web", not every track in
|
|
909
912
|
* it. An entry names where to start, so clicking it plays.
|
|
910
913
|
*/
|
|
914
|
+
/**
|
|
915
|
+
* Probe a source and start carrying it as a channel of its own.
|
|
916
|
+
*
|
|
917
|
+
* Shared by the request that puts one on and the boot that puts remembered
|
|
918
|
+
* ones back, so that both agree on what a source is encoded as. Null when
|
|
919
|
+
* that channel id is already on.
|
|
920
|
+
*/
|
|
921
|
+
export async function pullChannel(
|
|
922
|
+
channels: Channels,
|
|
923
|
+
ffprobe: string[],
|
|
924
|
+
id: string,
|
|
925
|
+
name: string,
|
|
926
|
+
source: string,
|
|
927
|
+
): Promise<Channel | null> {
|
|
928
|
+
const codecs = await codecsOf({ ffmpeg: [], ffprobe, play: null }, source);
|
|
929
|
+
const kind = codecs.video === "" ? "audio" : "video";
|
|
930
|
+
const encode = kind === "video"
|
|
931
|
+
? videoArgs(codecs)
|
|
932
|
+
// No picture in it, so none is invented: MP3 is the thing every browser
|
|
933
|
+
// plays and the thing a listener can join halfway through.
|
|
934
|
+
: ["-vn", "-c:a", "libmp3lame", "-b:a", "192k", "-f", "mp3"];
|
|
935
|
+
return channels.pull(id, name, source, encode, kind);
|
|
936
|
+
}
|
|
937
|
+
|
|
911
938
|
export function liveOnes(engine: Engine): { name: string; at: number; tracks: number }[] {
|
|
912
939
|
const tracks = engine.snapshot().tracks ?? [];
|
|
913
940
|
const found = new Map<string, { name: string; at: number; tracks: number }>();
|
|
@@ -1065,6 +1092,8 @@ export interface HandlerOptions {
|
|
|
1065
1092
|
ingest?: Ingest;
|
|
1066
1093
|
/** Several live streams at once, each with its own audience. */
|
|
1067
1094
|
channels?: Channels;
|
|
1095
|
+
/** Write down the channels this server pulls, so a restart puts them back. */
|
|
1096
|
+
rememberChannels?: (list: RememberedChannel[]) => void;
|
|
1068
1097
|
/** Live audio going out to RTMP. */
|
|
1069
1098
|
broadcaster?: Broadcaster;
|
|
1070
1099
|
/** Where a broadcast should send, and what it should look like. */
|
|
@@ -2173,6 +2202,12 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
2173
2202
|
via: one.via,
|
|
2174
2203
|
listeners: one.listeners,
|
|
2175
2204
|
startedAt: one.startedAt,
|
|
2205
|
+
// Whether it has a picture, so the page puts it in the element
|
|
2206
|
+
// that can show one. Never the source: that is the owner's.
|
|
2207
|
+
kind: one.kind ?? "audio",
|
|
2208
|
+
// How it has been going, for whoever may do something about it.
|
|
2209
|
+
redials: one.redials ?? 0,
|
|
2210
|
+
error: one.error ?? "",
|
|
2176
2211
|
})),
|
|
2177
2212
|
// Anything re-streamed into this server is a live stream too, and was
|
|
2178
2213
|
// sitting in the middle of the playlist among the files -- which is
|
|
@@ -2197,7 +2232,13 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
2197
2232
|
// devices can publish at once, each to their own channel, and a listener
|
|
2198
2233
|
// picks which to hear.
|
|
2199
2234
|
if (path === "/api/channels" && options.channels) {
|
|
2200
|
-
|
|
2235
|
+
// Without the source. Anyone holding the listen link may ask what is
|
|
2236
|
+
// on, and the address a channel is pulled from is the one thing about
|
|
2237
|
+
// it that is not theirs to have.
|
|
2238
|
+
json(response, 200, {
|
|
2239
|
+
channels: options.channels.list().map(({ source: _source, ...shown }) => shown),
|
|
2240
|
+
listeners: options.channels.listeners,
|
|
2241
|
+
});
|
|
2201
2242
|
return;
|
|
2202
2243
|
}
|
|
2203
2244
|
|
|
@@ -2248,6 +2289,15 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
2248
2289
|
// Asked once: the second call would answer false, having just stopped
|
|
2249
2290
|
// the thing it was asking about.
|
|
2250
2291
|
const stopped = channels.stop(id);
|
|
2292
|
+
// Taken off on purpose is forgotten on purpose: it must not come back
|
|
2293
|
+
// at the next restart.
|
|
2294
|
+
if (stopped && options.rememberChannels) {
|
|
2295
|
+
options.rememberChannels(
|
|
2296
|
+
channels.list()
|
|
2297
|
+
.filter((one) => one.via === "pull" && one.source)
|
|
2298
|
+
.map((one) => ({ id: one.id, name: one.name, source: one.source as string })),
|
|
2299
|
+
);
|
|
2300
|
+
}
|
|
2251
2301
|
json(response, stopped ? 200 : 404, { ok: stopped });
|
|
2252
2302
|
return;
|
|
2253
2303
|
}
|
|
@@ -2257,6 +2307,28 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
2257
2307
|
return;
|
|
2258
2308
|
}
|
|
2259
2309
|
|
|
2310
|
+
/**
|
|
2311
|
+
* Dial the source again, now.
|
|
2312
|
+
*
|
|
2313
|
+
* The thing an administrator reaches for when a channel says it is on
|
|
2314
|
+
* the air and shows nobody anything. It is what fixed CNN by hand --
|
|
2315
|
+
* take it off, put it back -- without having to know the source, which
|
|
2316
|
+
* a browser is never told.
|
|
2317
|
+
*/
|
|
2318
|
+
if (action === "restart") {
|
|
2319
|
+
if (!channels.has(id)) {
|
|
2320
|
+
json(response, 404, { error: "nothing is playing on that channel" });
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
if (!channels.pulled(id)) {
|
|
2324
|
+
json(response, 409, { error: "that channel is published into this server; restart it at the publisher" });
|
|
2325
|
+
return;
|
|
2326
|
+
}
|
|
2327
|
+
const restarted = channels.restart(id);
|
|
2328
|
+
json(response, restarted ? 200 : 409, { ok: restarted });
|
|
2329
|
+
return;
|
|
2330
|
+
}
|
|
2331
|
+
|
|
2260
2332
|
/**
|
|
2261
2333
|
* Carry a source of our own, rather than waiting to be sent one.
|
|
2262
2334
|
*
|
|
@@ -2301,20 +2373,20 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
|
|
|
2301
2373
|
return;
|
|
2302
2374
|
}
|
|
2303
2375
|
|
|
2304
|
-
const
|
|
2305
|
-
const codecs = await codecsOf({ ffmpeg: [], ffprobe: probe, play: null }, source);
|
|
2306
|
-
const kind = codecs.video === "" ? "audio" : "video";
|
|
2307
|
-
const encode = kind === "video"
|
|
2308
|
-
? videoArgs(codecs)
|
|
2309
|
-
// No picture in it, so none is invented: MP3 is the thing every
|
|
2310
|
-
// browser plays and the thing a listener can join halfway through.
|
|
2311
|
-
: ["-vn", "-c:a", "libmp3lame", "-b:a", "192k", "-f", "mp3"];
|
|
2312
|
-
|
|
2313
|
-
const channel = channels.pull(wanted, called, source, encode, kind);
|
|
2376
|
+
const channel = await pullChannel(channels, options.ffprobe ?? ["ffprobe"], wanted, called, source);
|
|
2314
2377
|
if (!channel) {
|
|
2315
2378
|
json(response, 409, { error: "that channel is already on" });
|
|
2316
2379
|
return;
|
|
2317
2380
|
}
|
|
2381
|
+
// Written down, so a restart puts it back on the air.
|
|
2382
|
+
if (options.rememberChannels) {
|
|
2383
|
+
options.rememberChannels([
|
|
2384
|
+
...channels.list()
|
|
2385
|
+
.filter((one) => one.via === "pull" && one.source && one.id !== wanted)
|
|
2386
|
+
.map((one) => ({ id: one.id, name: one.name, source: one.source as string })),
|
|
2387
|
+
{ id: wanted, name: called, source },
|
|
2388
|
+
]);
|
|
2389
|
+
}
|
|
2318
2390
|
json(response, 200, { ok: true, channel: channel.info });
|
|
2319
2391
|
return;
|
|
2320
2392
|
}
|
|
@@ -3245,6 +3317,17 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
|
|
|
3245
3317
|
onEnd: (info) => console.log(` "${info.id}" stopped.`),
|
|
3246
3318
|
});
|
|
3247
3319
|
|
|
3320
|
+
// The channels this server was carrying when it was last stopped, put back
|
|
3321
|
+
// on. A server is restarted to pick up a new version, which is often, and
|
|
3322
|
+
// every restart used to take CNN off the air until somebody noticed.
|
|
3323
|
+
const remembering = (list: RememberedChannel[]): void => rememberChannels(stateDir(), options.port, list);
|
|
3324
|
+
for (const one of rememberedChannels(stateDir(), options.port)) {
|
|
3325
|
+
console.log(` Putting "${one.id}" (${one.name}) back on the air.`);
|
|
3326
|
+
void pullChannel(channels, tools.ffprobe, one.id, one.name, one.source).then((channel) => {
|
|
3327
|
+
if (!channel) console.log(` "${one.id}" is already on.`);
|
|
3328
|
+
});
|
|
3329
|
+
}
|
|
3330
|
+
|
|
3248
3331
|
const destinations = parseDestinations(options.rtmp);
|
|
3249
3332
|
const broadcaster = new Broadcaster(tools.ffmpeg);
|
|
3250
3333
|
const ingest = options.ingest
|
|
@@ -3445,6 +3528,7 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
|
|
|
3445
3528
|
media: options.media,
|
|
3446
3529
|
owner,
|
|
3447
3530
|
channels,
|
|
3531
|
+
rememberChannels: remembering,
|
|
3448
3532
|
publishUrls: () => publishUrls,
|
|
3449
3533
|
serverName: options.name || hostname(),
|
|
3450
3534
|
homeSource: root,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./index-
|
|
1
|
+
import{t as e}from"./index-DGi1TAtn.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-DbzFtX7t.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-pqyQjSte.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 x=2048;function S(e,t){return e||t===`hls`||t===`mpegts`}var ne=class{elements;handlers;attached=null;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(C(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=x,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){let n=e.objectUrl?e.video?`mp4`:`audio`:d({src:e.url}),r=S(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.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 C(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 re(){return{revision:0,tracks:[],trackCount:0,index:0,playing:!1,position:0,bars:[],levels:[0,0],silent:!0,note:``,root:``}}function ie(e,t){return{...t,tracks:t.tracks??e.tracks}}function w(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 T(e,t,n=``){let r=`${e===``?``:w(e)}${t.startsWith(`/`)?t:`/${t}`}`;return n?`${r}${r.includes(`?`)?`&`:`?`}k=${encodeURIComponent(n)}`:r}function ae(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:w(`${n.origin}${n.pathname}`),key:decodeURIComponent(i)}}function E(e,t,n=0,r=``){return T(e,n>0?`/api/media/${t}?kbps=${Math.round(n)}`:`/api/media/${t}`,r)}function D(e){if(typeof e!=`object`||!e)return null;let t=e,n=re(),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 oe=class{handlers;source=null;base=``;key=``;shape=`/admin/`;lastRevision=-1;constructor(e){this.handlers=e}get address(){return this.base}url(e){return T(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}=ae(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(T(t,`/api/events`,n));this.source=r,r.onopen=()=>this.handlers.onStatus(`live`),r.onmessage=e=>{let t=D(O(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(T(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=D(await t.json());n&&this.handlers.onSnapshot(n)}media(e,t=0){return E(this.base,e,t,this.key)}close(){this.source?.close(),this.source=null}};function O(e){try{return JSON.parse(e)}catch{return null}}async function se(e,t,n=``){try{let r=await fetch(T(e,`/api/state`,n),{signal:t});return r.ok?D(await r.json()):null}catch{return null}}function ce(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 le(e,t=``,n){let r;try{r=await fetch(T(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 k(e,t,n=``){try{let r=await fetch(T(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 ue(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 A=.14,de=.02;function fe(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 pe(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 me(e,t,n=A){return t.map((t,r)=>{let i=e[r]??0;return t>=i?t:Math.max(t,i-n)})}function j(e,t,n=de){return t.map((t,r)=>Math.max(t,(e[r]??0)-n))}function he(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 M=`nixamp.remote`,ge=`nixamp.volume`,_e=`nixamp.listenHere`,ve=!1;function N(e){let t=document.getElementById(e);if(!t)throw Error(`nixamp: #${e} is missing from the shell`);return t}function P(){let n={status:N(`status`),source:N(`source`),install:N(`install`),video:N(`video`),audio:N(`audio`),title:N(`title-line`),album:N(`album-line`),elapsed:N(`elapsed`),total:N(`total`),seek:N(`seek`),fullscreen:N(`fullscreen`),canvas:N(`spectrum`),glyphs:N(`glyphs`),levels:N(`levels`),playlist:N(`playlist`),crumbs:N(`crumbs`),filter:N(`filter`),playlistTitle:N(`playlist-panel`),note:N(`note`),files:N(`files`),folder:N(`folder`),remoteUrl:N(`remote-url`),remoteForm:N(`remote-form`),remoteState:N(`remote-state`),disconnect:N(`disconnect`),browse:N(`browse`),accountForm:N(`account-form`),accountEmail:N(`account-email`),accountPassword:N(`account-password`),accountSubmit:N(`account-submit`),accountToggle:N(`account-toggle`),accountProviders:N(`account-providers`),accountPanel:N(`account-panel`),accountElsewhere:N(`account-elsewhere`),accountSignOut:N(`account-signout`),accountNote:N(`account-note`),adminPanel:N(`admin-panel`),adminNote:N(`admin-note`),adminSaid:N(`admin-said`),adminConnections:N(`admin-connections`),publishPanel:N(`publish-panel`),publishNote:N(`publish-note`),publishList:N(`publish-list`),adminRestream:N(`admin-restream`),adminReplace:N(`admin-replace`),adminSource:N(`admin-source`),adminName:N(`admin-name`),adminAdd:N(`admin-add`),homeNote:N(`home-note`),loadHome:N(`load-home`),directory:N(`directory`),recentNote:N(`recent-note`),recentList:N(`recent-list`),followingNote:N(`following-note`),followingList:N(`following-list`),serversPanel:N(`servers-panel`),serversNote:N(`servers-note`),serversList:N(`servers-list`),notifyPanel:N(`notify-panel`),notifyNote:N(`notify-note`),notifyWeb:N(`notify-web`),notifyEmail:N(`notify-email`),notifySms:N(`notify-sms`),notifyPhone:N(`notify-phone`),notifyPhoneForm:N(`notify-phone-form`),notifyPhoneNote:N(`notify-phone-note`),directoryNote:N(`directory-note`),directoryList:N(`directory-list`),onairPanel:N(`onair-panel`),onairNote:N(`onair-note`),onairList:N(`onair-list`),sharePanel:N(`share-panel`),shareNote:N(`share-note`),shareLink:N(`share-link`),shareCopy:N(`share-copy`),sharePhone:N(`share-phone`),shareSend:N(`share-send`),liveControls:N(`live-controls`),goLive:N(`go-live`),stopLive:N(`stop-live`),shareTo:N(`share-to`),listenOnly:N(`listen-only`),listenHere:N(`listen-here`),volume:N(`volume`),prev:N(`prev`),playPause:N(`play-pause`),stop:N(`stop`),next:N(`next`)},r=`local`,i=[],a=0,o=re(),s=`idle`,c=``,l=`Pick files, or connect to a nixamp running somewhere else.`,u=!1,d=-1,f=null,p=0,m=null,h=``,g=Array(24).fill(0),_=Array(24).fill(0),v=[],y=()=>r===`remote`&&!n.listenHere.checked,b=new ne({audio:n.audio,video:n.video},{onTime:(e,t)=>{let n=i[a];r===`local`&&n&&t>0&&n.duration!==t&&(n.duration=t),I()},onEnded:()=>{et()||F(1)},onState:()=>I(),onError:e=>{et()||(l=e,I(),Xe())}}),x=new oe({onSnapshot:e=>{o=ie(o,e),y()&&(g=e.bars.length>0?e.bars:g,_=j(_,g)),I()},onStatus:(e,t)=>{s=e,c=t??``,I()}}),S=()=>r===`remote`?o.tracks.length:i.length,C=()=>r===`remote`?y()||d<0?o.index:Math.min(d,Math.max(0,o.tracks.length-1)):a,w=()=>{if(f)return f.name;let e=r===`remote`?o.tracks[C()]:i[C()];return e?t(e):`Nothing loaded.`},T=()=>f?`live on this server`:(r===`remote`?o.tracks[C()]:i[C()])?.album||`—`,E=()=>y()?o.tracks[C()]?.duration??0:b.duration,D=()=>y()?o.position:b.position,O=()=>y()?o.playing:b.playing;async function A(e){if(r===`remote`){if(y()){await x.send({type:`play`,index:e});return}await de(e);return}let t=i[e];t&&(a=e,f=null,await b.load(t,!0),B(t.video),De(),I())}async function de(e){let t=o.tracks[e];t&&(d=e,f=null,await b.load({title:t.title,artist:t.artist,album:t.album,duration:t.duration,url:x.media(e,0),video:t.video===!0,objectUrl:!1},!0),B(t.video===!0),De())}async function P(){if(y()){await x.send({type:`toggle`});return}S()!==0&&(b.playing?b.pause():b.position>0?await b.play():await A(C()),I())}async function F(e){let t=S();if(t!==0){if(y()){await x.send({type:e>0?`next`:`prev`});return}await A((C()+e+t)%t)}}async function ye(){if(y()){await x.send({type:`stop`});return}f=null,b.stop(),g=Array(24).fill(0),_=[...g],I()}let be=e=>`▁▂▃▄▅▆▇█`[Math.max(0,Math.min(7,Math.round(e*7)))];function I(){let t=S(),a=O();n.status.textContent=a?`▶ PLAYING`:`■ STOPPED`,n.status.dataset.playing=String(a),n.title.textContent=w(),n.album.textContent=T();let d=D(),f=E();n.elapsed.textContent=e(d),n.total.textContent=f>0?e(f):`--:--`,u||(n.seek.value=String(f>0?Math.round(d/f*1e3):0),n.seek.disabled=f<=0||y()),n.playPause.textContent=a?`❚❚`:`▶`,n.playPause.setAttribute(`aria-label`,a?`Pause`:`Play`),n.playlistTitle.dataset.title=`Playlist (${t})`,n.source.textContent=r===`remote`?`remote · ${x.address.replace(/^https?:\/\//,``)||`—`}`:i.length>0?`local · ${i.length} files`:`no source`,n.remoteState.textContent=r===`remote`?`${s}${c?` — ${c}`:``}`:`not connected`,n.remoteState.dataset.status=r===`remote`?s:`idle`,n.disconnect.hidden=r!==`remote`;let p=r===`remote`&&o.note!==``?o.note:l;n.note.textContent=p,n.note.hidden=p===``,z(),n.glyphs.textContent=g.map(be).join(``);let[m,h]=y()?o.levels:b.levels();n.levels.textContent=`L${`▮`.repeat(Math.round(m*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(h*6)).padEnd(6,`·`)}`}let L=``,xe=-1,R=``;function Se(e){if(n.crumbs.hidden=!e,!e)return;let t=R===``?[]:R.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`,()=>{R=t,L=``,z()}),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 Ce(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`,()=>{R=R===``?e:`${R}/${e}`,L=``,z()}),n}function z(){let a=r===`remote`?o.tracks.map(e=>({name:t(e),seconds:e.duration,group:e.group??``,folder:e.folder??``,remote:e.remote===!0})):i.map(e=>({name:t(e),seconds:e.duration,group:``,folder:``,remote:!1})),s=n.filter.value.trim().toLowerCase(),c=a.map((e,t)=>({...e,index:t})).filter(e=>!e.remote).filter(e=>s===``||`${e.folder}/${e.name}`.toLowerCase().includes(s)),l=e=>s!==``||R===``||e===R||e.startsWith(`${R}/`),u=e=>s!==``||e===R,d=e=>{let t=R===``?e:e.slice(R.length+1),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)},f=new Map;for(let e of c){if(!l(e.folder)||u(e.folder))continue;let t=d(e.folder);t!==``&&f.set(t,(f.get(t)??0)+1)}let p=c.filter(e=>u(e.folder)&&l(e.folder)),m=`${r}:${R}:${s}:${[...f].join(`,`)}:${p.map(e=>`${e.index}@${e.name}@${e.seconds}@${e.group}`).join(`|`)}`;if(m!==L){L=m,Se(s===``&&([...f.keys()].length>0||R!==``));let t=[];for(let[e,n]of[...f].sort((e,t)=>e[0].localeCompare(t[0],void 0,{numeric:!0})))t.push(Ce(e,n));let i=``,a=p.some(e=>e.group!==``);for(let n of p){n.group!==i&&(a||n.group!==``)&&(i=n.group,t.push(we(n.group)));let o=document.createElement(`li`);o.className=`row`,o.dataset.index=String(n.index);let s=document.createElement(`span`);s.className=`n`,s.textContent=String(n.index+1).padStart(2,` `);let c=document.createElement(`span`);c.className=`name`,c.textContent=n.name;let l=document.createElement(`span`);if(l.className=`time`,l.textContent=n.seconds>0?e(n.seconds):`--:--`,o.append(s,c,l),r===`remote`){let e=document.createElement(`button`);e.type=`button`,e.className=`row-copy`,e.textContent=`⧉`,e.title=`Copy this file's URL`,e.setAttribute(`aria-label`,`Copy the URL of ${n.name}`),e.addEventListener(`click`,t=>{t.stopPropagation(),rt(x.media(n.index),e,`✓`)}),o.append(e)}t.push(o)}n.playlist.replaceChildren(...t)}let h=C(),g=O(),_;for(let e of Array.from(n.playlist.children)){let t=e,n=Number(t.dataset.index),r=Number.isInteger(n)&&n===h;t.classList.toggle(`selected`,r),t.classList.toggle(`playing`,r&&g),r&&(_=t)}h!==xe&&(xe=h,_?.scrollIntoView({block:`nearest`}))}function we(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(),Te(e)}),t.append(n)}return t}async function Te(e){try{let t=await fetch(x.url(`/api/source/remove`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({group:e})}),n=await t.json();U(t.ok?`Removed ${n.removed??0} tracks from ${e}.`:n.error??`that did not work`)}catch{U(`could not reach the server`)}}function Ee(){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 s=t.getContext(`2d`);if(y())_=j(_,g);else{let e=b.read();e.length>0&&(v.length!==25&&(v=fe(24,e.length)),g=me(g,pe(e,v)),_=j(_,g))}if(s){let e=getComputedStyle(document.documentElement);he(s,{width:t.width,height:t.height},g,_,{bar:e.getPropertyValue(`--green`).trim()||`#4af689`,peak:e.getPropertyValue(`--green-dim`).trim()||`#227a4a`,background:`transparent`})}if(O()){n.glyphs.textContent=g.map(be).join(``);let[t,r]=y()?o.levels:b.levels();n.levels.textContent=`L${`▮`.repeat(Math.round(t*6)).padEnd(6,`·`)} R${`▮`.repeat(Math.round(r*6)).padEnd(6,`·`)}`,n.elapsed.textContent=e(D());let i=E();!u&&i>0&&(n.seek.value=String(Math.round(D()/i*1e3)))}requestAnimationFrame(Ee)}function B(e){n.video.hidden=!e,n.fullscreen.hidden=!e}function De(){`mediaSession`in navigator&&(navigator.mediaSession.metadata=new MediaMetadata({title:w(),album:T(),artist:`nixamp`,artwork:[{src:`/icons/icon-512.png`,sizes:`512x512`,type:`image/png`}]}),navigator.mediaSession.setActionHandler(`play`,()=>void P()),navigator.mediaSession.setActionHandler(`pause`,()=>void P()),navigator.mediaSession.setActionHandler(`nexttrack`,()=>void F(1)),navigator.mediaSession.setActionHandler(`previoustrack`,()=>void F(-1)))}n.filter.addEventListener(`input`,()=>{L=``,z()}),n.playlist.addEventListener(`click`,e=>{let t=e.target.closest(`li`),n=Number(t?.dataset.index);Number.isInteger(n)&&A(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 F(-1)),n.next.addEventListener(`click`,()=>void F(1)),n.stop.addEventListener(`click`,()=>void ye()),n.playPause.addEventListener(`click`,()=>void P()),n.seek.addEventListener(`input`,()=>{u=!0}),n.seek.addEventListener(`change`,()=>{let e=E();e>0&&b.seek(Number(n.seek.value)/1e3*e),u=!1}),n.volume.addEventListener(`input`,()=>{let e=Number(n.volume.value)/100;b.volume=e;try{localStorage.setItem(ge,String(e))}catch{}});let Oe=e=>{e.addEventListener(`change`,()=>{let t=ee(Array.from(e.files??[]));if(t.length===0){l=`Nothing playable in that selection.`,I();return}te(i),i=t,a=0,r=`local`,x.close(),l=``,A(0)})};Oe(n.files),Oe(n.folder),n.remoteForm.addEventListener(`submit`,e=>{e.preventDefault();let t=n.remoteUrl.value,{base:i,key:a}=ae(t);if(i===``){l=`That is not an address.`,I();return}(async()=>{s=`connecting`,I();let e=ue(i);if(e){s=`error`,c=e,l=e,r=`local`,I();return}if(await k(i,void 0,a)===null){s=`error`;let e=ce(i);c=e?`needs the server's name`:`not answering`,l=e||`Nothing answered at ${i}. If that is your machine, it is off or nixamp is not running on it; otherwise check the address.`,r=`local`,I();return}let n=await le(i,a);if(n){s=`error`,c=n,l=n,r=`local`,I();return}r=`remote`,l=``;try{localStorage.setItem(M,t.trim())}catch{}x.connect(t),$(),Q(!0),W(),Y(),I()})()});let V=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??[],Re(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} live ${e.length===1?`stream`:`streams`}:`;for(let t of e){let e=document.createElement(`li`),r=document.createElement(`button`);r.type=`button`;let i=document.createElement(`span`);i.className=`name`,i.textContent=t.name;let a=document.createElement(`span`);a.className=`detail`;let o=[t.nowPlaying,`${t.tracks} tracks`].filter(Boolean);if(t.code&&o.push(t.callers?`☎ ${t.code} · ${t.callers} on the phone`:`☎ ${t.code}`),a.textContent=o.join(` · `),r.append(i,a),r.addEventListener(`click`,()=>{n.remoteUrl.value=t.url,n.directory.hidden=!0,n.remoteForm.requestSubmit()}),e.append(r),t.ownerId&&q&&t.ownerId!==q&&e.append(Ve(t.ownerId,t.name)),t.ownerId&&q&&t.ownerId===q){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 V()}})()}),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),V()}let H=null,ke=e=>e===`cgnat`?`mobile or tailscale`:e===`private`?`your network`:e===`local`?`this machine`:e===`public`?`the internet`:e,Ae=e=>e===`events`?`watching the panel`:e===`page`?`opened the page`:e===`media`?`playing a track`:e===`stream`?`listening live`:e,je=``,Me=``,Ne=e=>{let t=e.map(e=>`${e.address}|${e.kind}|${e.track}|${Math.round(e.bytes/4096)}|${e.endedAt}`).join(`~`);if(t===je)return;je=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,``],[ke(t.network),`network-${t.network}`],[Ae(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 U(e){n.adminSaid.textContent=e,n.adminSaid.hidden=e===``}let Pe=async()=>{try{let e=await fetch(x.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.`,Ne(t.connections??[]),Fe(t.publish??[],(t.channels??[]).map(e=>e.id)),ot(t.home??``,t.root??``),$()}catch{n.adminNote.textContent=`lost touch with the server`}};function Fe(e,t){n.publishPanel.hidden=e.length===0;let r=`${e.map(e=>`${e.id}=${e.url}`).join(`~`)}::${t.join(`,`)}`;if(r===Me)return;if(Me=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 W=async()=>{if(r!==`remote`){n.adminPanel.hidden=!0,n.publishPanel.hidden=!0,H&&clearInterval(H),H=null;return}let e=!1,t=null,i=!1;try{let n=await fetch(x.url(`/api/admin`));if(n.ok){let r=await n.json();e=r.allowed===!0,t=r.as??null,i=r.claimed===!0}}catch{e=!1}if(n.adminPanel.hidden=!e,H&&clearInterval(H),H=null,$(),Y(),n.listenOnly.hidden=e,!e){n.listenOnly.textContent=i?`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.`,Pe(),H=setInterval(()=>void Pe(),2e3)};function Ie(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)}`;U(`Starting ${t||e}…`),(async()=>{try{let a=await fetch(x.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){U(o.error??`that did not work`);return}U(`${o.channel?.name||t||e} is on the air.`),n.adminSource.value=``,n.adminName.value=``,Y(),$()}catch{U(`could not reach the server`)}})()}n.adminRestream.addEventListener(`submit`,e=>{e.preventDefault();let t=n.adminSource.value.trim();t&&Ie(t,n.adminName.value.trim())}),n.adminAdd.addEventListener(`click`,()=>{let e=n.adminSource.value.trim();if(!e)return;U(`Reading ${e}…`);let t=n.adminReplace.checked,r=n.adminName.value.trim();(async()=>{try{let i=await fetch(x.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();U(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=``,Y(),$())}catch{U(`could not reach the server`)}})()});let Le=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`},Re=e=>{n.recentList.replaceChildren();let t=q?e.filter(e=>e.ownerId&&e.ownerId!==q):[];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 ${Le(e.endedAt)}`:`ended ${Le(e.endedAt)}`,r.append(i,a),t.append(r,Ve(e.ownerId,e.name)),n.recentList.append(t)}},ze=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()}),k(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 ze()}catch{s.disabled=!1}})()}),t.append(r,o,s),n.serversList.append(t)}}catch{n.serversPanel.hidden=!0}},Be=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}},Ve=(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),Be())}catch{}finally{n.disabled=!1}})()}),n},He=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},Ue=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window,We=async()=>{if(!Ue())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:He(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}},Ge=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{}},G=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`}},Ke=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=Ue()&&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 We();n.notifyWeb.checked=e,await G({wantsWeb:e});return}await Ge(),await G({wantsWeb:!1}),n.notifyNote.textContent=`Turn on “On this device” to be told here.`})()}),n.notifyEmail.addEventListener(`change`,()=>{G({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 G({wantsSms:n.notifySms.checked})})()}),n.notifyPhoneForm.addEventListener(`submit`,e=>{e.preventDefault(),G({phone:n.notifyPhone.value.trim()})});let K=!1,q=``,J=e=>{let t=e!==null;n.notifyPanel.hidden=!t,t?(Ke(),Be(),ze()):(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}.`:K?`Create an account on nixamp.com.`:`Sign in to nixamp.com to publish and get paid.`,n.accountSubmit.textContent=K?`Create account`:`Sign in`,n.accountToggle.textContent=K?`I have one`:`Create one`,n.accountPassword.autocomplete=K?`new-password`:`current-password`},qe=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)}},Je=async()=>{try{let e=await fetch(`/api/v1/auth/me`),t=await e.json();q=e.ok?t.account?.id??``:``,J(e.ok?t.account?.email??`you`:null)}catch{q=``,J(null)}Ye()};function Ye(){if(h===``)return;let e=h;h=``,n.remoteUrl.value=e,n.remoteForm.requestSubmit()}n.accountToggle.addEventListener(`click`,()=>{K=!K,J(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/${K?`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}q=i.account?.id??``,n.accountPassword.value=``,J(i.account?.email??t),W(),Ye()}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{}q=``,J(null),x.close(),d=-1,r=`local`,s=`idle`,c=``,n.remoteUrl.value=``,n.sharePanel.hidden=!0,n.publishPanel.hidden=!0,n.adminPanel.hidden=!0,n.onairPanel.hidden=!0,n.listenOnly.hidden=!0,Q(!1);try{localStorage.removeItem(M)}catch{}l=`Signed out, and disconnected from the server.`,W(),I()})()});try{let e=new URL(globalThis.location.href).searchParams.get(`url`)??``;e!==``&&(h=e,n.remoteUrl.value=e,l=`Opening the stream you were sent…`,globalThis.history?.replaceState(null,``,globalThis.location.pathname))}catch{}qe(),Je(),W(),n.browse.addEventListener(`click`,()=>{if(!n.directory.hidden){n.directory.hidden=!0;return}V(),n.directory.scrollIntoView({behavior:`smooth`,block:`nearest`})}),n.disconnect.addEventListener(`click`,()=>{x.close(),n.listenOnly.hidden=!0,d=-1,n.sharePanel.hidden=!0,n.publishPanel.hidden=!0,n.adminPanel.hidden=!0,n.onairPanel.hidden=!0,Q(!1),r=`local`,s=`idle`,c=``,I()});async function Y(){if(r!==`remote`||x.shareLink===``){n.sharePanel.hidden=!0;return}n.sharePanel.hidden=!1;let e=x.shareLink,t=globalThis.location.origin;n.shareLink.value=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 i=``;try{let e=await fetch(`/api/directory`);e.ok&&(i=(await e.json()).callIn??``)}catch{}let a=null;try{let r=await fetch(x.url(`/api/live/state`));r.ok&&(a=await r.json()),a?.url&&(e=a.url,n.shareLink.value=e.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e)}`:e)}catch{}if(a){if(n.liveControls.hidden=n.adminPanel.hidden||!a.possible,n.goLive.hidden=a.live,n.stopLive.hidden=!a.live,n.sharePhone.hidden=!1,!a.live){n.sharePhone.textContent=a.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(!i){n.sharePhone.textContent=`Listed. The code for the phone line is ${a.code}.`,n.shareSend.hidden=!1;return}n.sharePhone.replaceChildren(document.createTextNode(`To talk about it, call `),ct(i),document.createTextNode(` and key `),ct(a.code),document.createTextNode(`. That is a room with everyone else watching — not the stream itself.`)),n.shareSend.hidden=!1}}let X=``,Z=null,Q=e=>{Z&&clearInterval(Z),Z=null,e&&(Z=setInterval(()=>void $(),6e3))};async function $(){if(r!==`remote`){n.onairPanel.hidden=!0;return}let e;try{let t=await fetch(x.url(`/api/streams`));if(!t.ok){n.onairPanel.hidden=!0;return}e=await t.json()}catch{n.onairPanel.hidden=!0;return}n.onairPanel.hidden=!1;let t=`${n.adminPanel.hidden?`view`:`drive`}:${JSON.stringify(e)}`;if(t===X)return;X=t;let i=e.restreams??[],a=e.channels.length+i.length;n.onairNote.textContent=a===0?`One stream, from this server's own files.`:`${a+1} streams: this server's own files, and ${a} more on it.`;let o=[],s=e.server.playing,c=!n.adminPanel.hidden;o.push(it({title:e.server.name,detail:[s?`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:s?`Join live`:c?`Start the stream`:`Nothing playing`,onPlay:()=>{if(s){Qe(e.server.nowPlaying);return}c&&Ze()},link:e.server.live?e.server.url:``,direct:s?x.url(`/api/live`):``}));for(let e of i)o.push(it({title:e.name,detail:e.tracks===1?`re-streamed from the web`:`re-streamed from the web · ${e.tracks} tracks`,onPlay:()=>{A(e.at)},link:``,direct:x.media(e.at)}));for(let t of e.channels){let e=t.kind!==`audio`,n=x.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}×`),c&&t.error&&r.push(t.error),o.push(it({title:t.name,detail:r.join(` · `),onPlay:()=>{$e({id:t.id,name:t.name,video:e})},link:n,direct:n,onRestart:c&&t.via===`pull`?()=>{tt(t.id,t.name)}:void 0,onStop:c?()=>{nt(t.id,t.name)}:void 0}))}n.onairList.replaceChildren(...o)}async function Xe(){if(r===`remote`)try{if((await fetch(x.media(C(),0),{method:`GET`,headers:{range:`bytes=0-1`}})).status!==402)return;l=q===``?`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.`,q===``&&n.accountPanel.scrollIntoView({behavior:`smooth`,block:`center`}),I()}catch{}}async function Ze(){U(`Starting the stream on the server…`);try{await x.send({type:`play`,index:Math.max(0,C())})}catch{U(`could not reach the server`);return}await Qe(o.tracks[C()]?.title??``),U(`Playing to the room. Anybody with the view link sees this.`),await $()}async function Qe(e){d=-1,f=null,await b.load({title:e||`Live`,artist:``,album:``,duration:0,url:x.url(`/api/live`),video:!0,objectUrl:!1},!0),B(!0),l=`Watching what this server is playing. Everyone here sees the same thing.`,I()}async function $e(e,t=!0){d=-1,f=e,t&&(p=0),await b.load({title:e.name,artist:``,album:``,duration:0,url:x.url(`/api/channels/${encodeURIComponent(e.id)}`),video:e.video,objectUrl:!1},!0),B(e.video),l=`Watching ${e.name}, live on this server.`,I()}function et(){let e=f;return e?m?!0:p>=5?(l=`${e.name} stopped, and did not come back.`,f=null,I(),!0):(p+=1,l=`${e.name} started over; rejoining…`,I(),m=setTimeout(()=>{m=null,f===e&&$e(e,!1)},2e3),!0):!1}async function tt(e,t){U(`Restarting ${t}…`);try{let n=await fetch(x.url(`/api/channels/${encodeURIComponent(e)}/restart`),{method:`POST`}),r=await n.json().catch(()=>({}));U(n.ok?`${t} is dialling its source again.`:r.error??`that did not work`)}catch{U(`could not reach the server`)}X=``,$()}async function nt(e,t){try{U((await fetch(x.url(`/api/channels/${encodeURIComponent(e)}`),{method:`DELETE`})).ok?`${t} is off the air.`:`that did not work`)}catch{U(`could not reach the server`)}f?.id===e&&(f=null,b.stop()),X=``,$()}async function rt(e,t,n=`Copied`){if(!e)return;let r=t.textContent;try{await navigator.clipboard.writeText(e)}catch{l=e,I();return}t.textContent=n,setTimeout(()=>{t.textContent=r},1200)}function it(e){let t=document.createElement(`li`),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(`button`);if(a.type=`button`,a.className=`button`,a.textContent=e.playLabel??`Play`,a.addEventListener(`click`,e.onPlay),t.append(n,a),e.link){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Copy link`,n.title=`A link that opens this in the player`,n.addEventListener(`click`,()=>{let t=globalThis.location.origin;rt(e.link.startsWith(`https://`)?`${t}/?url=${encodeURIComponent(e.link)}`:e.link,n)}),t.append(n)}if(e.direct){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Copy URL`,n.title=`The stream's own address, for VLC or mpv`,n.addEventListener(`click`,()=>{rt(e.direct??``,n)}),t.append(n)}if(e.onRestart){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Restart`,n.title=`Dial the source again`,n.addEventListener(`click`,e.onRestart),t.append(n)}if(e.onStop){let n=document.createElement(`button`);n.type=`button`,n.className=`ghost`,n.textContent=`Remove`,n.title=`Take it off the air`,n.addEventListener(`click`,e.onStop),t.append(n)}return t}let at=``;function ot(e,t){at=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`,()=>{at!==``&&(n.loadHome.disabled=!0,U(`Reading this server's files…`),(async()=>{try{let e=await fetch(x.url(`/api/source`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({source:at})}),t=await e.json();U(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{U(`could not reach the server`)}finally{n.loadHome.disabled=!1}})())});let st=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(x.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 Y()}};n.goLive.addEventListener(`click`,()=>void st(!0)),n.stopLive.addEventListener(`click`,()=>void st(!1));function ct(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:x.shareLink})}),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(_e,n.listenHere.checked?`1`:`0`)}catch{}r===`remote`&&(async()=>{n.listenHere.checked?(await x.send({type:`stop`}),await de(o.index)):(b.stop(),d=-1),I()})()}),document.addEventListener(`keydown`,e=>{let t=e.target;if(!(t&&/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))switch(e.key){case` `:e.preventDefault(),P();return;case`s`:ye();return;case`n`:case`ArrowRight`:F(1);return;case`p`:case`ArrowLeft`:F(-1);return;case`ArrowDown`:e.preventDefault(),A(Math.min(S()-1,C()+1));return;case`ArrowUp`:e.preventDefault(),A(Math.max(0,C()-1));return}});let lt=null;globalThis.addEventListener(`beforeinstallprompt`,e=>{e.preventDefault(),lt=e,n.install.hidden=!1}),n.install.addEventListener(`click`,()=>{lt?.prompt(),lt=null,n.install.hidden=!0});try{let e=localStorage.getItem(ge);e!==null&&(n.volume.value=String(Math.round(Number(e)*100)),b.volume=Number(e));let t=localStorage.getItem(M);t&&(n.remoteUrl.value=t),localStorage.getItem(_e)===`0`&&(n.listenHere.checked=!1)}catch{}(async()=>{if(n.remoteUrl.value!==``)return;let e=globalThis.location.origin;if(await k(e)===null)return;let t=await se(e);t&&t.trackCount!==0&&(n.remoteUrl.value=e,r=`remote`,l=``,x.connect(e),I())})(),(()=>{if(ve)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=()=>{ve=!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})})})})(),I(),requestAnimationFrame(Ee)}P(),`serviceWorker`in navigator&&globalThis.addEventListener(`load`,()=>{navigator.serviceWorker.register(`/sw.js`).catch(()=>{})});export{c as t};
|