Radio: estaciones en vivo mientras entrenás
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s

Música tiene una sección **Radio**: estaciones en vivo por género (Workout/Rave,
Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica),
sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de
radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js.

Tres decisiones que no se ven en la pantalla y son las que hacen que funcione:

- **El audio no pasa por el servidor.** La api entrega la lista y después no ve un
  byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias.
- **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar
  audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el
  play() es un botón que no hace nada, sin error en ninguna parte.
- **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de
  un componente se desmonta con él, y eso es la música cortándose al cambiar de
  pantalla — justo lo que no puede pasar en medio de una serie.

Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y
parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y
las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y
Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de
inventar una pista.

api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id`
reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el
caso de la fila en Music.test.jsx guardan lo demás.

También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado
es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now
(con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md.
This commit is contained in:
dsantillan committed 2026-09-23 20:38:19 -04:00
1 parent e1d28f971d
commit 48cf976635
22 files changed
+1662 -15

No files matched your search

+40
View File
@@ -21,6 +21,7 @@ import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
import { verifyError } from './verify-error.js';
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js';
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
import { genreList, stationsFor, nowPlaying } from './radio.js';
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
import {
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
@@ -133,6 +134,21 @@ function writeVitals(uid, doc) { atomicWrite(vitalsFile(uid), JSON.stringify(doc
/** What a sync is answered with: how much is in the profile now, not just what just arrived. */
const wantRaw = req => new URL(req.url, 'http://x').searchParams.get('raw') === '1';
/* One station, rebuilt from the query string rather than trusted as an object.
*
* The client only ever sends back what it was given, but "only ever" is not a security property:
* what comes back is a source and an id, and the id is used to build a URL this process fetches.
* So the shape is checked here — a known source, a plain id — and the URL for a SomaFM channel is
* rebuilt from the allowlisted host rather than taken from the request. */
function stationFromQuery(q) {
const src = String(q.get('src') || '');
const id = String(q.get('id') || '');
if (!/^[a-z0-9_-]{1,40}$/i.test(id)) return null;
if (src === 'soma') return { src, id };
if (src === 'paradise') return { src, id };
return null;
}
const storedCounts = doc => ({
metrics: doc ? Object.keys(doc.metrics || {}).length : 0,
days: doc ? Object.values(doc.metrics || {}).reduce((n, m) => n + Object.keys(m.days || {}).length, 0) : 0,
@@ -1261,6 +1277,30 @@ const routes = {
json(res, 200, { ok: true, meta: parseMusicPage(html) });
},
/* ---------- radio ----------
*
* Two routes, both session-gated, and neither proxies audio: the list — every station with the
* stream URL already resolved, so a tap can call `play()` inside the gesture iOS demands — and
* what is playing on the stations that publish it. The audio itself goes from the phone straight to the
* station — this server's part is the list, and a session requirement is what stops it becoming
* an open gateway someone else's page can borrow. */
'GET /api/radio': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const key = new URL(req.url, 'http://x').searchParams.get('genre') || '';
const { genre, stations } = await stationsFor(key);
json(res, 200, { ok: true, genres: genreList(), genre: genre.key, label: genre.label, stations });
},
'GET /api/radio/now': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const q = new URL(req.url, 'http://x').searchParams;
const station = stationFromQuery(q);
if (!station) return json(res, 400, { error: 'no such station' });
json(res, 200, { ok: true, now: await nowPlaying(station) });
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
'POST /api/push/subscribe': async (req, res) => {