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

+222
View File
@@ -0,0 +1,222 @@
/* The radio sources, tested without a network: everything here is a filter or a parse, and the
filters are the point. A station that cannot be played is worse than no station — a row that does
nothing when tapped, on a screen whose whole job is to make sound.
The three rules that are load-bearing: HTTPS (an http stream is blocked by the browser on an
https page, silently), no HLS (Chrome and Android need a library, and this project does not add
one for a station), and nothing fetched from a host that is not on our own list. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
GENRES, genreList, genreOf, PARADISE, parsePls, pickPlaylist, somaStation, rbStations,
nowFrom, allowedHost, get, streamFor, stationsFor, nowPlaying, RADIO_HOSTS, clearRadioCache
} from '../radio.js';
const pls = 'https://api.somafm.com/beatblender.pls';
const channel = (over = {}) => ({
id: 'beatblender', title: 'Beat Blender', genre: 'electronic',
description: 'A late night blend of deep-house and downtempo chill.',
playlists: [
{ url: pls, format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/beatblender130.pls', format: 'aac', quality: 'highest' }
],
...over
});
test('the genres the screen offers are the ones a person asked for', () => {
const keys = genreList().map(g => g.key);
for (const want of ['workout', 'techno', 'rnb', 'latin', 'hiphop', 'reggae', 'chill', 'jazz', 'rock', 'electronic']) {
assert.ok(keys.includes(want), want + ' is offered');
}
// Every genre names at least one SomaFM channel or one tag: a chip that shows nothing is a chip
// that should not be there.
for (const g of GENRES) assert.ok(g.soma.length + g.tags.length > 0, g.key + ' has a source');
assert.equal(genreOf('nope'), null);
assert.equal(genreOf('rnb').label, 'R&B / Soul');
});
test('a .pls gives the stream, and anything else gives nothing', () => {
const text = [
'[playlist]', 'numberofentries=2',
'File1=https://ice2.somafm.com/beatblender-128-mp3',
'Title1=SomaFM: Beat Blender', 'Length1=-1',
'File2=https://ice6.somafm.com/beatblender-128-mp3',
'Version=2'
].join('\n');
assert.equal(parsePls(text), 'https://ice2.somafm.com/beatblender-128-mp3', 'the first mirror');
// An http stream would be blocked by the browser on an https page, so it is not a stream here.
assert.equal(parsePls('[playlist]\nFile1=http://ice2.somafm.com/x'), null);
assert.equal(parsePls('<html>nope</html>'), null);
assert.equal(parsePls(null), null);
assert.equal(parsePls(''), null);
});
test('the playlist chosen is the best one that plays everywhere', () => {
assert.equal(pickPlaylist(channel()), pls, 'mp3 highest wins over aac highest');
assert.equal(pickPlaylist(channel({ playlists: [
{ url: 'https://api.somafm.com/x256.pls', format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/x.pls', format: 'mp3', quality: 'high' }
] })), 'https://api.somafm.com/x256.pls');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'https://api.somafm.com/x130.pls', format: 'aac', quality: 'highest' }] })),
'https://api.somafm.com/x130.pls', 'aac is the fallback, not nothing');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'http://api.somafm.com/x.pls', format: 'mp3' }] })), null);
assert.equal(pickPlaylist(channel({ playlists: [] })), null);
});
test('a SomaFM channel becomes a station, and a broken one does not', () => {
const s = somaStation(channel());
assert.equal(s.src, 'soma');
assert.equal(s.id, 'beatblender');
assert.equal(s.pls, pls);
assert.equal(s.detail, 'A late night blend of deep-house and downtempo chill.');
assert.equal(somaStation(channel({ id: '' })), null);
assert.equal(somaStation(channel({ title: ' ' })), null);
assert.equal(somaStation(channel({ playlists: [] })), null);
assert.equal(somaStation(null), null);
});
test('the directory is filtered down to what can be played', () => {
const rows = [
{ stationuuid: 'a', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3', bitrate: 192, country: 'Germany', tags: 'techno,dance' },
{ stationuuid: 'b', name: 'Plain HTTP', url_resolved: 'http://x.example/stream', codec: 'MP3' },
{ stationuuid: 'c', name: 'HLS only', url_resolved: 'https://x.example/live.m3u8', codec: 'AAC' },
{ stationuuid: 'd', name: 'Unknown codec', url_resolved: 'https://x.example/wm', codec: 'WMAL' },
{ stationuuid: 'e', name: 'Wild', url_resolved: 'https://x.example/wm2' },
{ stationuuid: 'f', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3' },
{ stationuuid: 'g', name: ' ', url_resolved: 'https://x.example/blank', codec: 'MP3' },
{ stationuuid: 'h', name: 'AAC+ Latin', url_resolved: 'https://y.example/aac', codec: 'AAC+', bitrate: 64, country: 'Colombia' }
];
const out = rbStations(rows);
// "Wild" has no codec at all, and that is kept on purpose: a blank codec means the directory did
// not say, which is common, rather than that the station is unplayable. The ones it *does* name
// and that no browser plays (WMAL), and the HLS ones, are the ones dropped.
assert.deepEqual(out.map(s => s.name), ['Techno One', 'Wild', 'AAC+ Latin'], 'only what is known to be unplayable is dropped');
assert.equal(out[0].detail, 'Germany · MP3 · 192 kbps');
assert.equal(out[0].genre, 'techno, dance');
assert.equal(out[2].detail, 'Colombia · AAC+ · 64 kbps');
assert.equal(rbStations('nope').length, 0);
assert.equal(rbStations([{ name: 'no url' }]).length, 0);
});
test('what is playing is read from the two stations that publish it, and invented for nobody', () => {
assert.deepEqual(nowFrom('soma', { songs: [{ title: 'Cuban Nights', artist: 'Miguel Migs', albumArt: 'https://cdn.example/a.jpg' }] }),
{ artist: 'Miguel Migs', title: 'Cuban Nights', cover: 'https://cdn.example/a.jpg' });
assert.deepEqual(nowFrom('paradise', { artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' }),
{ artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' });
// No song playing, no cover, or a source that publishes nothing: null, never a placeholder.
assert.equal(nowFrom('soma', { songs: [] }), null);
assert.equal(nowFrom('soma', null), null);
assert.equal(nowFrom('rb', { title: 'x' }), null);
assert.equal(nowFrom('paradise', {}), null);
const noArt = nowFrom('soma', { songs: [{ title: 'x' }] });
assert.equal(noArt.artist, null);
assert.equal(noArt.cover, null);
});
test('only our own hosts may be fetched, over https', () => {
assert.equal(allowedHost('https://somafm.com/channels.json'), true);
assert.equal(allowedHost('https://api.somafm.com/beatblender.pls'), true);
assert.equal(allowedHost('https://all.api.radio-browser.info/json/stations'), true);
assert.equal(allowedHost('https://api.radioparadise.com/api/now_playing?chan=0'), true);
// The stream hosts are reached by the browser, never by this process — so they are not here.
assert.equal(allowedHost('https://ice2.somafm.com/beatblender-128-mp3'), false);
assert.equal(allowedHost('http://somafm.com/channels.json'), false, 'https only');
assert.equal(allowedHost('https://evil.example/somafm.com'), false);
assert.equal(allowedHost('https://somafm.com.evil.example/x'), false);
assert.equal(allowedHost('not a url'), false);
assert.equal(allowedHost('https://somafm.com/', ['example.com']), false, 'the list is the argument');
assert.ok(RADIO_HOSTS.every(h => h === h.toLowerCase()));
});
/* The gate itself, and the one test that can see it: `get` is the only place this module makes an
outgoing call, so an off-list URL must die there — not at a caller that might forget. */
test('get refuses an off-list url without calling fetch at all', async () => {
let calls = 0;
const fetchImpl = async () => { calls++; return { ok: true, text: async () => 'x' }; };
for (const url of ['https://evil.example/x', 'http://somafm.com/channels.json', 'https://somafm.com.evil.example/x', 'not a url']) {
assert.equal(await get(url, { fetchImpl }), null, url);
}
assert.equal(calls, 0, 'nothing left this process');
// ...and an on-list one does go out, so the test above is not passing because get never works.
assert.equal(await get('https://somafm.com/channels.json', { fetchImpl }), 'x');
assert.equal(calls, 1);
});
test('resolving a stream never fetches anything outside the allowlist', async () => {
clearRadioCache();
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('evil')) throw new Error('should not be called');
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/beatblender-128-mp3\n' };
};
const url = await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl });
assert.equal(url, 'https://ice2.somafm.com/beatblender-128-mp3');
assert.deepEqual(calls, [pls]);
// Cached: a second press does not ask SomaFM again.
assert.equal(await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl }), url);
assert.equal(calls.length, 1);
// A directory station carries its own stream: nothing is fetched, and an http one is refused.
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), 'https://y.example/aac');
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'http://y.example/aac' }, { fetchImpl }), null);
assert.equal(await streamFor(null, { fetchImpl }), null);
// A SomaFM station whose playlist points off the list is refused rather than followed.
assert.equal(await streamFor({ src: 'soma', id: 'x', pls: 'https://evil.example/x.pls' }, { fetchImpl }), null);
assert.equal(calls.length, 1);
});
test('a genre list puts the curated channels first and the directory last', async () => {
clearRadioCache();
const fetchImpl = async (url) => {
const u = String(url);
if (u.includes('channels.json')) {
return { ok: true, text: async () => JSON.stringify({ channels: [
channel(), channel({ id: 'bossa', title: 'Bossa Beyond' }), channel({ id: 'reggae', title: 'Heavyweight Reggae' })
] }) };
}
if (u.includes('api.somafm.com')) {
// The channel's own playlist, which is what turns a channel into something playable.
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/x-128-mp3\n' };
}
if (u.includes('radio-browser')) {
return { ok: true, text: async () => JSON.stringify([
{ stationuuid: 'z1', name: 'Salsa Dura', url_resolved: 'https://z.example/salsa', codec: 'MP3', country: 'Colombia', tags: 'salsa' },
{ stationuuid: 'z2', name: 'Dead', url_resolved: 'http://z.example/dead', codec: 'MP3' }
]) };
}
return { ok: false, text: async () => '' };
};
// The curated channels come back with their stream already resolved (`fetchImpl` answers the
// `.pls` above), and a channel whose stream cannot be resolved is not listed at all.
const { genre, stations } = await stationsFor('latin', { fetchImpl });
assert.equal(genre.key, 'latin');
const names = stations.map(s => s.name);
// The no-advertising stations first — that is what the order is for.
assert.deepEqual(names.slice(0, 3), ['Bossa Beyond', 'Heavyweight Reggae', 'Radio Paradise · Global']);
assert.ok(names.includes('Salsa Dura'), 'and the directory fills in the genres SomaFM does not carry');
assert.ok(stations.every(s => /^https:\/\//.test(s.url || '')), 'every row can be played when it is tapped');
assert.equal(names.includes('Dead'), false);
// An unknown genre falls back to the first one rather than showing a blank screen.
const fallback = await stationsFor('nope', { fetchImpl });
assert.equal(fallback.genre.key, 'workout');
});
test('what is playing is asked for at the right address, per source', async () => {
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('somafm')) return { ok: true, text: async () => JSON.stringify({ songs: [{ title: 'T', artist: 'A' }] }) };
return { ok: true, text: async () => JSON.stringify({ title: 'Paradise Song', artist: 'PR' }) };
};
const soma = await nowPlaying({ src: 'soma', id: 'beatblender' }, { fetchImpl });
assert.equal(soma.title, 'T');
assert.match(calls[0], /somafm\.com\/songs\/beatblender\.json/);
const para = await nowPlaying({ src: 'paradise', id: 'rock' }, { fetchImpl });
assert.equal(para.artist, 'PR');
assert.match(calls[1], /chan=2/, 'the third mix is chan=2');
// A directory station publishes nothing, so nothing is asked and nothing is shown.
assert.equal(await nowPlaying({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), null);
assert.equal(calls.length, 2);
assert.equal(PARADISE.length, 4);
});
+82
View File
@@ -0,0 +1,82 @@
/* The two radio routes, against the real server: who may call them, and what `/now` agrees to look
up. What a genre actually returns is api/test/radio.test.js, which owns the directory logic and
stubs the network — this file is the guards, because a guard is exactly the thing that quietly
stops guarding.
The second one matters more than it looks. `/api/radio/now` takes a source and an id *from the
request* and uses them to build a URL this process then fetches; if the source stopped being
checked, the api container (which sits on the owner's own network) would become a request proxy
for anyone holding a session. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
function mintSession(uid, sv = 0) {
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
const freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
async function startServer(t) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-radio-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_r', name: 'One', created: '2026-01-01T00:00:00.000Z' }], creds: [], subs: [], invites: [] }));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
});
const h = { api: `http://127.0.0.1:${port}`, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
test('the station list needs a session', async t => {
const h = await startServer(t);
// Not an open station directory: the list is what this instance's owner pays attention to, and
// the audio itself never passes through here.
const r = await fetch(`${h.api}/api/radio`);
assert.equal(r.status, 401);
});
test('what is playing needs a session too', async t => {
const h = await startServer(t);
const r = await fetch(`${h.api}/api/radio/now?src=soma&id=beatblender`);
assert.equal(r.status, 401);
});
test('a station that is not one of the two known sources is refused, unfetched', async t => {
const h = await startServer(t);
for (const q of [
'src=http://127.0.0.1:3000&id=health', // a source that is not one of ours
'src=soma', // no id at all
'src=soma&id=' + encodeURIComponent('../../x'),// an id that would walk out of the path
'src=soma&id=' + encodeURIComponent('a b c'),
'id=beatblender' // no source
]) {
const r = await fetch(`${h.api}/api/radio/now?${q}`, { headers: cookie('u_r') });
assert.equal(r.status, 400, `${q} should be refused`);
assert.match((await r.json()).error, /no such station/);
}
});