nixamp 0.56.0 → 0.57.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/channels.d.ts +20 -0
  2. package/dist/channels.js +24 -0
  3. package/dist/label-profiles.js +2 -2
  4. package/dist/library.d.ts +6 -0
  5. package/dist/library.js +11 -0
  6. package/dist/oauth.d.ts +36 -3
  7. package/dist/oauth.js +107 -7
  8. package/dist/playlist-input.d.ts +32 -7
  9. package/dist/playlist-input.js +20 -2
  10. package/dist/server.js +16 -6
  11. package/dist/station-routes.d.ts +1 -0
  12. package/dist/station-routes.js +23 -5
  13. package/dist/station-runner.d.ts +48 -0
  14. package/dist/station-runner.js +208 -4
  15. package/dist/stations.d.ts +14 -0
  16. package/dist/stations.js +11 -0
  17. package/package.json +1 -1
  18. package/src/channels.ts +30 -0
  19. package/src/label-profiles.ts +2 -2
  20. package/src/library.ts +14 -0
  21. package/src/oauth.ts +119 -6
  22. package/src/playlist-input.ts +46 -5
  23. package/src/server.ts +18 -5
  24. package/src/station-routes.ts +23 -6
  25. package/src/station-runner.ts +205 -4
  26. package/src/stations.ts +15 -0
  27. package/web/dist/assets/{ar-CwZJb_gN.js → ar-HteUbQ_m.js} +1 -1
  28. package/web/dist/assets/{cs-BQeUHU5U.js → cs-CjN_4DAJ.js} +1 -1
  29. package/web/dist/assets/{da-B9gLGX-j.js → da-CzsSXVfk.js} +1 -1
  30. package/web/dist/assets/{de-BtKJqMyc.js → de-D7zVt1UT.js} +1 -1
  31. package/web/dist/assets/{es-xCZPNIQ8.js → es-D8duNQiq.js} +1 -1
  32. package/web/dist/assets/{fi-Bs6hJxj9.js → fi-CSKCYE5E.js} +1 -1
  33. package/web/dist/assets/{fr-Db3viYEV.js → fr-DnjuIwaN.js} +1 -1
  34. package/web/dist/assets/{hi-BEO0uXMK.js → hi-ByZe82O5.js} +1 -1
  35. package/web/dist/assets/{hu-DddOFPOR.js → hu-B3iwlAuW.js} +1 -1
  36. package/web/dist/assets/{id-Ca4dDDtC.js → id-B58CS7rH.js} +1 -1
  37. package/web/dist/assets/{it-B9cFkgz7.js → it-CaVLbop_.js} +1 -1
  38. package/web/dist/assets/{main-CHubaPAu.js → main-yTRNIxIl.js} +2 -2
  39. package/web/dist/assets/{nl-kUxjpAwG.js → nl-Dk0ss8Tf.js} +1 -1
  40. package/web/dist/assets/{radio-CtAne8M1.css → radio-Cmg6GPN2.css} +1 -1
  41. package/web/dist/assets/{radio-yD_-qpS7.js → radio-DV3h4YZS.js} +1 -1
  42. package/web/dist/assets/{ru-BE9Sxy3t.js → ru-CGuA41ji.js} +1 -1
  43. package/web/dist/assets/{station-DxBlD6Yl.js → station-D6sd4DqP.js} +1 -1
  44. package/web/dist/assets/{sv-Cp6BIRXI.js → sv-B309Td6Z.js} +1 -1
  45. package/web/dist/assets/{uk-DavLH9cs.js → uk-CCCKvR-U.js} +1 -1
  46. package/web/dist/assets/{vi-eAlsSX6P.js → vi-DfVTbK_t.js} +1 -1
  47. package/web/dist/assets/{zh-D2Y8KIQG.js → zh-BU9_CD0f.js} +1 -1
  48. package/web/dist/index.html +1 -1
  49. package/web/dist/radio.html +2 -2
  50. package/web/dist/station.html +1 -1
  51. package/web/dist/sw.js +22 -22
package/src/oauth.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  * address, and both are asked. Without that check, anyone who can add an
17
17
  * unverified address at a provider could claim somebody else's nixamp account.
18
18
  */
19
- import { randomBytes } from "node:crypto";
19
+ import { createHash, randomBytes } from "node:crypto";
20
20
  import type { Account } from "./accounts.ts";
21
21
  import type { DeviceGrants } from "./device.ts";
22
22
  import type { Queryable } from "./follows.ts";
@@ -33,6 +33,8 @@ export interface Provider {
33
33
  scope: string;
34
34
  /** Turn the provider's access token into an address it stands behind. */
35
35
  identify(accessToken: string, send: typeof fetch): Promise<Identity | null>;
36
+ /** OAuth 2.1: the round trip carries a PKCE S256 challenge and the exchange its verifier. */
37
+ pkce?: boolean;
36
38
  }
37
39
 
38
40
  /** Who the provider says this is. `subject` is stable when an address is not. */
@@ -40,6 +42,43 @@ export interface Identity {
40
42
  provider: string;
41
43
  subject: string;
42
44
  email: string;
45
+ /**
46
+ * Whether the provider verified the address. Absent means yes (GitHub and
47
+ * Google are only asked for verified ones). An unverified one never links
48
+ * to an existing account and is never the new account's address.
49
+ */
50
+ verified?: boolean;
51
+ }
52
+
53
+ /**
54
+ * CoinPay (coinpayportal.com), the house identity: OAuth 2.1, authorization
55
+ * code with PKCE S256 and a client secret. CoinPay does not verify the
56
+ * address it reports, so a CoinPay identity is matched by its `sub` only.
57
+ */
58
+ export function coinpayProvider(clientId: string, clientSecret: string, base = "https://coinpayportal.com"): Provider {
59
+ return {
60
+ id: "coinpay",
61
+ name: "CoinPay",
62
+ clientId,
63
+ clientSecret,
64
+ authorizeUrl: `${base}/api/oauth/authorize`,
65
+ tokenUrl: `${base}/api/oauth/token`,
66
+ scope: "openid profile email",
67
+ pkce: true,
68
+ async identify(accessToken, send) {
69
+ const who = await readJson(await send(`${base}/api/oauth/userinfo`, { headers: { authorization: `Bearer ${accessToken}`, ...AGENT } }));
70
+ const subject = typeof who["sub"] === "string" ? who["sub"] : "";
71
+ if (!subject) return null;
72
+ const email = typeof who["email"] === "string" ? who["email"].toLowerCase() : "";
73
+ return { provider: "coinpay", subject, email, verified: who["email_verified"] === true };
74
+ },
75
+ };
76
+ }
77
+
78
+ /** A PKCE pair: the verifier kept here, the S256 challenge sent with the browser. */
79
+ export function pkcePair(): { verifier: string; challenge: string } {
80
+ const verifier = randomBytes(32).toString("base64url");
81
+ return { verifier, challenge: createHash("sha256").update(verifier).digest("base64url") };
43
82
  }
44
83
 
45
84
  const AGENT = { "user-agent": "nixamp" };
@@ -114,6 +153,9 @@ export function providersFrom(env: Record<string, string | undefined>): Provider
114
153
  if (env["GOOGLE_CLIENT_ID"] && env["GOOGLE_CLIENT_SECRET"]) {
115
154
  found.push(googleProvider(env["GOOGLE_CLIENT_ID"], env["GOOGLE_CLIENT_SECRET"]));
116
155
  }
156
+ if (env["COINPAY_OAUTH_CLIENT_ID"] && env["COINPAY_OAUTH_CLIENT_SECRET"]) {
157
+ found.push(coinpayProvider(env["COINPAY_OAUTH_CLIENT_ID"], env["COINPAY_OAUTH_CLIENT_SECRET"], env["COINPAY_OAUTH_BASE"] || undefined));
158
+ }
117
159
  return found;
118
160
  }
119
161
 
@@ -122,13 +164,17 @@ export function redirectUri(site: string, provider: Provider): string {
122
164
  }
123
165
 
124
166
  /** Where to send the browser. `state` is the only thing standing between this and CSRF. */
125
- export function authorizeUrl(provider: Provider, site: string, state: string): string {
167
+ export function authorizeUrl(provider: Provider, site: string, state: string, challenge = ""): string {
126
168
  const url = new URL(provider.authorizeUrl);
127
169
  url.searchParams.set("client_id", provider.clientId);
128
170
  url.searchParams.set("redirect_uri", redirectUri(site, provider));
129
171
  url.searchParams.set("response_type", "code");
130
172
  url.searchParams.set("scope", provider.scope);
131
173
  url.searchParams.set("state", state);
174
+ if (challenge) {
175
+ url.searchParams.set("code_challenge", challenge);
176
+ url.searchParams.set("code_challenge_method", "S256");
177
+ }
132
178
  return url.toString();
133
179
  }
134
180
 
@@ -138,6 +184,7 @@ export async function exchangeCode(
138
184
  code: string,
139
185
  site: string,
140
186
  send: typeof fetch = fetch,
187
+ verifier = "",
141
188
  ): Promise<string> {
142
189
  const answer = await send(provider.tokenUrl, {
143
190
  method: "POST",
@@ -154,6 +201,7 @@ export async function exchangeCode(
154
201
  code,
155
202
  redirect_uri: redirectUri(site, provider),
156
203
  grant_type: "authorization_code",
204
+ ...(verifier ? { code_verifier: verifier } : {}),
157
205
  }).toString(),
158
206
  });
159
207
  const body = await readJson(answer);
@@ -208,7 +256,13 @@ export class Identities {
208
256
  }
209
257
 
210
258
  async resolve(identity: Identity): Promise<Account | null> {
211
- if (!identity.subject || !identity.email) return null;
259
+ if (!identity.subject) return null;
260
+ // An address the provider did not verify (CoinPay's) is a hint, not a
261
+ // claim: the account is found by subject alone, and a new one gets an
262
+ // address nobody can own, so purchases kept by email are never reached
263
+ // through it.
264
+ if (identity.verified === false) return this.resolveUnverified(identity);
265
+ if (!identity.email) return null;
212
266
  await this.ensure();
213
267
 
214
268
  // Already linked. The subject is what is matched, not the address: people
@@ -256,6 +310,37 @@ export class Identities {
256
310
  );
257
311
  return account;
258
312
  }
313
+
314
+ /** The account linked to this subject, or a new one whose address is `<provider>-<subject>@<provider>.invalid`. */
315
+ private async resolveUnverified(identity: Identity): Promise<Account | null> {
316
+ await this.ensure();
317
+ const { rows } = await this.db.query(`SELECT user_id, email FROM ${TABLE} WHERE provider = $1 AND subject = $2`, [identity.provider, identity.subject]);
318
+ const linked = rows[0];
319
+ const placeholder = `${identity.provider}-${identity.subject.replace(/[^A-Za-z0-9._-]/g, "").slice(0, 60)}@${identity.provider}.invalid`;
320
+ if (linked) {
321
+ const id = String(linked["user_id"] ?? "");
322
+ return id ? { id, email: String(linked["email"] ?? "") || placeholder } : null;
323
+ }
324
+ const existing = await this.users.getUserByEmail(placeholder);
325
+ const account = existing?.id
326
+ ? { id: existing.id, email: existing.email ?? placeholder }
327
+ : await (async () => {
328
+ const made = await this.users.createUser({
329
+ email: placeholder,
330
+ password: null,
331
+ emailVerified: false,
332
+ profile: { signedUpWith: identity.provider, ...(identity.email ? { providerEmail: identity.email } : {}) },
333
+ });
334
+ return { id: String(made.id ?? ""), email: made.email ?? placeholder };
335
+ })();
336
+ if (!account.id) return null;
337
+ await this.db.query(
338
+ `INSERT INTO ${TABLE} (provider, subject, user_id, email) VALUES ($1, $2, $3, $4)
339
+ ON CONFLICT (provider, subject) DO NOTHING`,
340
+ [identity.provider, identity.subject, account.id, placeholder],
341
+ );
342
+ return account;
343
+ }
259
344
  }
260
345
 
261
346
  // --- the sign-in surface ----------------------------------------------------
@@ -273,6 +358,33 @@ export interface Pending {
273
358
  /** Set when this round trip is approving a terminal rather than a browser. */
274
359
  userCode: string;
275
360
  createdAt: number;
361
+ /** The PKCE verifier, for a provider that takes one. */
362
+ verifier?: string;
363
+ /** Where the browser goes once signed in (a path here, or an allowed site); "/" by default. */
364
+ redirect?: string;
365
+ }
366
+
367
+ /** The sites a sign-in may return to: NIXAMP_SIGNIN_RETURN_HOSTS, else the ones that send people here. */
368
+ export function signInReturnHosts(env: Record<string, string | undefined> = process.env): string[] {
369
+ const set = (env["NIXAMP_SIGNIN_RETURN_HOSTS"] ?? "").split(",").map((one) => one.trim().toLowerCase()).filter(Boolean);
370
+ return set.length ? set : ["live.streaming", "live.streaming.pit.world", "bittorrented.com", "backtoschool.help"];
371
+ }
372
+
373
+ /**
374
+ * Where a sign-in may send the browser afterwards: a path on this site, or a
375
+ * page on one of the sites that send people here to sign in (live.streaming).
376
+ * Anything else is "/", so a sign-in link cannot be made to bounce elsewhere.
377
+ */
378
+ export function safeRedirect(value: unknown, allowedHosts: string[] = []): string {
379
+ if (typeof value !== "string" || value === "") return "/";
380
+ if (value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\")) return value.slice(0, 500);
381
+ try {
382
+ const url = new URL(value);
383
+ if (url.protocol === "https:" && allowedHosts.includes(url.hostname)) return url.href.slice(0, 500);
384
+ } catch {
385
+ // not a URL
386
+ }
387
+ return "/";
276
388
  }
277
389
 
278
390
  /** A state is only ever open for the length of one sign-in. */
@@ -298,11 +410,12 @@ export class SignIn {
298
410
  }
299
411
 
300
412
  /** Start a round trip, and answer the URL the browser should go to. */
301
- begin(provider: Provider, userCode = ""): string {
413
+ begin(provider: Provider, userCode = "", redirect = "/"): string {
302
414
  this.sweep();
303
415
  const state = randomBytes(24).toString("base64url");
304
- this.states.set(state, { provider: provider.id, userCode, createdAt: this.now() });
305
- return authorizeUrl(provider, this.site, state);
416
+ const pair = provider.pkce ? pkcePair() : null;
417
+ this.states.set(state, { provider: provider.id, userCode, createdAt: this.now(), redirect, ...(pair ? { verifier: pair.verifier } : {}) });
418
+ return authorizeUrl(provider, this.site, state, pair?.challenge ?? "");
306
419
  }
307
420
 
308
421
  /** Redeem a state exactly once, so a replayed callback finds nothing. */
@@ -39,7 +39,16 @@ export interface PlaylistInput {
39
39
  * `next` answers a file to play (an advert, an ident) or null for no break
40
40
  * this time. The break is outside the rotation and the station's history.
41
41
  */
42
- breaks?: { everySeconds: number | (() => number); next: () => Promise<string | null> };
42
+ breaks?: {
43
+ everySeconds: number | (() => number);
44
+ next: () => Promise<string | null>;
45
+ /**
46
+ * Seconds of airtime since the last break when this stream opens, asked
47
+ * once per open: a station that slept with nobody listening carries its
48
+ * clock across, so breaks come every so often of time on the air.
49
+ */
50
+ sinceBreak?: () => number;
51
+ };
43
52
  /** Told when an entry is passed over because it would not play. */
44
53
  onFailure?: (event: { at: number; file: string; reason: string }) => void;
45
54
  }
@@ -51,12 +60,26 @@ export interface PlaylistInput {
51
60
  */
52
61
  export const MAX_FAILURES_IN_A_ROW = 5;
53
62
 
63
+ /** An entry that started: where it sits in the stream and in its pass. */
64
+ interface Entry {
65
+ at: number;
66
+ file: string;
67
+ start: number;
68
+ position: number;
69
+ list: readonly string[];
70
+ /** The pass's order and how far into it the next entry is, for resumePoint. */
71
+ order: readonly number[];
72
+ step: number;
73
+ /** Where the break clock stood when it started. */
74
+ lastBreak: number;
75
+ }
76
+
54
77
  /** Decode each file independently; feed one persistent muxer a fixed stream
55
78
  * profile and continuous timestamps. A concat demuxer cannot decode a list
56
79
  * whose input codecs differ. Only one entry is encoded at a time, with pipe
57
80
  * backpressure bounding read-ahead independently of the directory's size. */
58
81
  export class PlaylistInputStream {
59
- private entries: { at: number; file: string; start: number; position: number; list: readonly string[] }[] = [];
82
+ private entries: Entry[] = [];
60
83
  error: Error | null = null;
61
84
  complete = false;
62
85
  /**
@@ -68,7 +91,7 @@ export class PlaylistInputStream {
68
91
  constructor(private readonly options: PlaylistInput) {}
69
92
 
70
93
  /** Every entry that has started, in the order it started, with where it sits in the stream. */
71
- get history(): ReadonlyArray<{ at: number; file: string; start: number; position: number; list: readonly string[] }> {
94
+ get history(): ReadonlyArray<Entry> {
72
95
  return this.entries;
73
96
  }
74
97
 
@@ -84,6 +107,22 @@ export class PlaylistInputStream {
84
107
  : { at: this.options.at, position: this.options.position, list: this.options.files };
85
108
  }
86
109
 
110
+ /**
111
+ * Where to pick up after this point of the stream, for a station that
112
+ * sleeps with nobody listening: the file that is on ("" in a break), the
113
+ * rest of this pass in the order it was going to play, and the seconds
114
+ * of airtime since the last break.
115
+ */
116
+ resumePoint(seconds: number): { file: string; upcoming: string[]; sinceBreak: number } | null {
117
+ const entry = this.entries.findLast(one => seconds >= one.start) ?? this.entries[0];
118
+ if (!entry) return null;
119
+ return {
120
+ file: entry.at >= 0 ? entry.file : "",
121
+ upcoming: entry.order.slice(entry.step).map((index) => entry.list[index]).filter((one): one is string => typeof one === "string"),
122
+ sinceBreak: entry.at < 0 ? 0 : Math.max(0, seconds - entry.lastBreak),
123
+ };
124
+ }
125
+
87
126
  /** The decoder for the entry that is on, so skip() can end it early. */
88
127
  private stopCurrent: (() => void) | null = null;
89
128
  private skipping = false;
@@ -114,7 +153,9 @@ export class PlaylistInputStream {
114
153
  let step = Math.min(Math.max(0, o.at), order.length);
115
154
  let played = 0;
116
155
  let last = "";
117
- let lastBreak = 0;
156
+ // Counted back from 0 by however long it had been, so a clock carried
157
+ // across a sleep comes due when it would have on the air.
158
+ let lastBreak = -Math.max(0, o.breaks?.sinceBreak?.() ?? 0);
118
159
  // A film cut for a break, to be picked up where it stopped.
119
160
  let resume: { at: number; file: string; position: number } | null = null;
120
161
  for (;;) {
@@ -179,7 +220,7 @@ export class PlaylistInputStream {
179
220
  const room = o.video && !isBreak && o.breaks && every > 0 ? every - (offset - lastBreak) : Infinity;
180
221
  const cut = room >= 1 && full - room > 5;
181
222
  const duration = cut ? room : full;
182
- this.entries.push({ at, file, start: offset, position, list: files });
223
+ this.entries.push({ at, file, start: offset, position, list: files, order, step, lastBreak });
183
224
  const hasVideo = Boolean(codecs.video);
184
225
  const extra = o.video && !hasVideo
185
226
  ? ["-f", "lavfi", "-i", `color=c=black:s=${width}x${height}:r=30`]
package/src/server.ts CHANGED
@@ -55,6 +55,8 @@ import {
55
55
  devicePage,
56
56
  exchangeCode,
57
57
  providersFrom,
58
+ safeRedirect,
59
+ signInReturnHosts,
58
60
  signInFailedPage,
59
61
  SignIn,
60
62
  } from "./oauth.ts";
@@ -122,7 +124,7 @@ import { Porkbun, isIPv4, isIPv6, type DnsZone } from "./dns.ts";
122
124
  import { NameError, Names } from "./names.ts";
123
125
  import { AcmeIssuer, Certs } from "./certs.ts";
124
126
  import { claimName, fetchCert, humanizeSource, labelFor, readCertFiles, writeCertFiles } from "./naming.ts";
125
- import { forbiddenLibrary, readConfig, readLibrary, writeConfig } from "./library.ts";
127
+ import { forbiddenLibrary, readConfig, readLibrary, stationIdleSeconds, writeConfig } from "./library.ts";
126
128
  import { createThrottle, presentedCredential, type Throttle } from "@profullstack/throttle";
127
129
  import { Durable } from "./durable.ts";
128
130
  import { notifyAll, resendEmail, webPush, type Notification } from "./notify.ts";
@@ -4927,7 +4929,9 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
4927
4929
  // A terminal can link straight here with the code it is showing, which
4928
4930
  // is one hop shorter than the page for somebody who followed the link.
4929
4931
  const grant = signIn.device.find(url.searchParams.get("device") ?? "");
4930
- response.writeHead(302, { location: signIn.begin(provider, grant?.userCode ?? "") });
4932
+ // Back where the visit was going: a page here, or a site that sends people here to sign in.
4933
+ const redirect = safeRedirect(url.searchParams.get("redirect"), signInReturnHosts());
4934
+ response.writeHead(302, { location: signIn.begin(provider, grant?.userCode ?? "", redirect) });
4931
4935
  response.end();
4932
4936
  return;
4933
4937
  }
@@ -4945,10 +4949,10 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
4945
4949
  return;
4946
4950
  }
4947
4951
 
4948
- const access = await exchangeCode(provider, code, signIn.site).catch(() => "");
4952
+ const access = await exchangeCode(provider, code, signIn.site, fetch, pending.verifier ?? "").catch(() => "");
4949
4953
  const identity = access ? await provider.identify(access, fetch).catch(() => null) : null;
4950
4954
  if (identity === null) {
4951
- html(response, 401, signInFailedPage(`${provider.name} did not confirm a verified email address.`));
4955
+ html(response, 401, signInFailedPage(provider.pkce ? `${provider.name} did not finish the sign-in. Try it again.` : `${provider.name} did not confirm a verified email address.`));
4952
4956
  return;
4953
4957
  }
4954
4958
 
@@ -4971,7 +4975,7 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
4971
4975
 
4972
4976
  response.writeHead(302, {
4973
4977
  "set-cookie": sessionCookie(result.token, secure),
4974
- location: "/",
4978
+ location: pending.redirect || "/",
4975
4979
  });
4976
4980
  response.end();
4977
4981
  return;
@@ -5940,6 +5944,12 @@ export function createHandler(engine: Engine, options: HandlerOptions) {
5940
5944
  return;
5941
5945
  }
5942
5946
 
5947
+ // A station asleep with nobody listening is woken by whoever asks for
5948
+ // its channel here too, and they are held for its first bytes.
5949
+ if ((action === "hls" || action === undefined) && request.method === "GET" && !channels.has(id) && stationOfChannel(id) && options.stations?.runner.isSleeping(stationOfChannel(id))) {
5950
+ await options.stations.runner.awake(stationOfChannel(id));
5951
+ }
5952
+
5943
5953
  // The same channel as HLS: a playlist of short files, which is what
5944
5954
  // Safari on an iPhone plays live -- it will not take the endless MP4
5945
5955
  // below, and spun on it a few times before giving up. Packaged on
@@ -7455,6 +7465,8 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
7455
7465
  onRestart: (id) => stationUsage.restarted(id),
7456
7466
  onFailure: (id) => stationUsage.failed(id),
7457
7467
  artistOf: (file) => trackFor(engine, file)?.artist ?? "",
7468
+ // Nobody listening for this long and a station sleeps until somebody does.
7469
+ idleSeconds: () => stationIdleSeconds(process.env, readConfig()),
7458
7470
  store: stationStore,
7459
7471
  channels,
7460
7472
  pull: async (channelId, name, files, known) =>
@@ -7729,6 +7741,7 @@ export async function serve(argv: string[], version = "0.1.0"): Promise<void> {
7729
7741
  });
7730
7742
  }
7731
7743
  stationRunner.restore();
7744
+ stationRunner.watchIdle();
7732
7745
  // Where each film has got to, written down every so often, so a restart
7733
7746
  // picks it up from about there rather than from the start. Only when it
7734
7747
  // has changed: a server carrying nothing but live television writes
@@ -114,14 +114,16 @@ function nowPlayingFile(ctx: StationContext, station: Station): string {
114
114
 
115
115
  export function publicView(ctx: StationContext, station: Station): PublicStation {
116
116
  const state = ctx.runner.observed(station.id);
117
- const file = state === "live" || state === "recovering" ? nowPlayingFile(ctx, station) : "";
117
+ // Asleep, what it will wake on: the first listener hears that next.
118
+ const asleep = ctx.runner.isSleeping?.(station.id) ?? false;
119
+ const file = asleep ? ctx.runner.nextUp(station.id) : state === "live" || state === "recovering" ? nowPlayingFile(ctx, station) : "";
118
120
  // The tags the player read when it put this file on, else the library's.
119
121
  const track = file ? (ctx.channels.tagsOf(channelOf(station.id), file) ?? ctx.trackFor(file)) : null;
120
122
  // What the channel is carrying wins over the flag: a station made by hand
121
123
  // from films streams video whether or not anyone said so.
122
124
  const video = station.video || ctx.channels.kindOf(channelOf(station.id)) === "video";
123
125
  // How far into the song (or film) on the air, by the encoder's clock, and how long it is.
124
- const position = file ? ctx.channels.info(channelOf(station.id))?.position : undefined;
126
+ const position = file && !asleep ? ctx.channels.info(channelOf(station.id))?.position : undefined;
125
127
  const duration = file && ctx.durationOf ? ctx.durationOf(file) : 0;
126
128
  const progress = typeof position === "number" && duration > 0 ? { position: Math.round(Math.min(position, duration) * 10) / 10, duration: Math.round(duration * 10) / 10 } : null;
127
129
  return {
@@ -161,11 +163,13 @@ export function guideEntries(ctx: StationContext): Array<PublicStation & { page:
161
163
  return [...names].map(([slug, one]) => ({ ...publicView(ctx, one), page: links(ctx, one, base).page, m3u: links(ctx, one, base).m3u, group: guideGroup(one), radio: `${radioBase}/radio/${slug}` }));
162
164
  }
163
165
 
164
- export function ownerView(ctx: StationContext, station: Station): OwnerStation & { links: ReturnType<typeof links>; nowPlaying: string } {
166
+ export function ownerView(ctx: StationContext, station: Station): OwnerStation & { links: ReturnType<typeof links>; nowPlaying: string; sleeping: boolean } {
165
167
  const { failures, idempotencyKey: _key, ...rest } = station;
166
168
  return {
167
169
  ...rest,
168
170
  state: ctx.runner.observed(station.id),
171
+ // On the air with nobody listening: no encoder until somebody does.
172
+ sleeping: ctx.runner.isSleeping?.(station.id) ?? false,
169
173
  excluded: Object.entries(failures).filter(([, count]) => count >= 3).map(([file]) => file),
170
174
  listeners: ctx.runner.listeners(station.id),
171
175
  error: ctx.runner.error(station.id),
@@ -348,18 +352,31 @@ export async function handleStations(
348
352
  return true;
349
353
  }
350
354
  const channelId = channelOf(station.id);
351
- if (!ctx.channels.has(channelId)) {
352
- ctx.json(response, 503, { error: "the station is not on the air", code: "not_live", state: ctx.runner.observed(station.id) });
355
+ // Asleep, a HEAD is told what it would get without waking it.
356
+ if (method === "HEAD" && ctx.runner.isSleeping?.(station.id)) {
357
+ response.writeHead(200, { ...ctx.headers, "content-type": station.video ? "video/mp4" : "audio/mpeg", "cache-control": "no-store" });
358
+ response.end();
353
359
  return true;
354
360
  }
355
361
  // Admitted only within the station's and the server's limits, and the
356
- // month's allowance; refused with what to do about it.
362
+ // month's allowance; refused with what to do about it. Before waking it:
363
+ // a listener turned away is no reason to start the encoder.
357
364
  const refused = method === "GET" && ctx.usage && ctx.limits ? ctx.usage.admit(station.id, ctx.limits) : null;
358
365
  if (refused) {
359
366
  response.writeHead(refused.status, { ...ctx.headers, "content-type": "application/json; charset=utf-8", "retry-after": String(refused.retryAfter) });
360
367
  response.end(JSON.stringify({ error: refused.error, code: refused.code, retryAfter: refused.retryAfter }));
361
368
  return true;
362
369
  }
370
+ // The first listener wakes a sleeping station, and is held until it
371
+ // starts sending, so they hear it begin rather than a stream that ends.
372
+ let closed = false;
373
+ response.once("close", () => { closed = true; });
374
+ await ctx.runner.awake?.(station.id, undefined, () => closed);
375
+ if (closed) return true;
376
+ if (!ctx.channels.has(channelId)) {
377
+ ctx.json(response, 503, { error: "the station is not on the air", code: "not_live", state: ctx.runner.observed(station.id) });
378
+ return true;
379
+ }
363
380
  // Signed in at nixamp.com: no breaks, starting a little behind live so
364
381
  // they can be left out without a gap. Radio only (Channel.listenWithoutBreaks).
365
382
  const pass = url.searchParams.get(PASS_PARAM) ?? "";