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
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:
1 parent
e1d28f971d
commit
48cf976635
22 files changed
+1662
-15
No files matched your search
+325
@@ -0,0 +1,325 @@
|
||||
/* radio.js — the radio stations the app can play.
|
||||
*
|
||||
* Radio, not files, and that is the whole point: a public stream is made to be listened to — it is
|
||||
* the radio in a car, not a download — so nothing here copies anything, and the audio never passes
|
||||
* through this server. The browser gets a stream URL and plays it straight from the station, which
|
||||
* is why a music library costs this instance no disk and no bandwidth.
|
||||
*
|
||||
* Three sources, each picked for a reason:
|
||||
*
|
||||
* SomaFM listener-supported since 2000, no advertising at all, and a channel list
|
||||
* published as JSON for exactly this kind of use. Their `.pls` gives the direct
|
||||
* stream, so nothing is guessed from a channel id.
|
||||
* Radio Paradise listener-supported, no advertising, four mixes, and a public now-playing API
|
||||
* that even carries the cover of the album.
|
||||
* radio-browser an open-source directory (AGPL) of ~50,000 stations, no key, no account. It is
|
||||
* where the genres SomaFM does not carry come from — salsa, reggaetón, latin
|
||||
* broadcasters — with the honest caveat that those stations are commercial and may
|
||||
* air advertising. The directory has none; the stations are their own business.
|
||||
*
|
||||
* Everything here is a pure function of what is fetched, with `fetch` injected, so the filters —
|
||||
* HTTPS only, MP3/AAC only, no HLS, no dead entries — are testable without a network.
|
||||
*/
|
||||
/* The hosts *this process* is allowed to call, and only these.
|
||||
*
|
||||
* A different list from the music lookup's, because it guards a different thing: that one screens
|
||||
* URLs a signed-in person typed, this one screens the calls this module makes — which are our own
|
||||
* constants plus the community directory. The stream hosts (ice*.somafm.com, the directory's
|
||||
* stations, the Paradise mixes) are never fetched here: they are handed to the browser, which
|
||||
* reaches them directly. That is the point of radio — the audio does not pass through this server. */
|
||||
export const RADIO_HOSTS = Object.freeze([
|
||||
'somafm.com', // the channel list, and what is playing
|
||||
'api.somafm.com', // the .pls that resolves to a stream
|
||||
'api.radioparadise.com', // what is playing, with the cover
|
||||
'all.api.radio-browser.info', // the directory (a load-balanced name, so it is the one to use)
|
||||
'de1.api.radio-browser.info', // the same, pinned, in case the round-robin name is unreachable
|
||||
'nl1.api.radio-browser.info'
|
||||
]);
|
||||
|
||||
/** HTTPS and on the list. Exported because the rule is worth testing on its own. */
|
||||
export function allowedHost(url, hosts = RADIO_HOSTS) {
|
||||
try {
|
||||
const u = new URL(String(url));
|
||||
return u.protocol === 'https:' && hosts.includes(u.hostname.toLowerCase());
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
const UA = 'KuentaGYM (self-hosted)';
|
||||
const TIMEOUT_MS = 12000;
|
||||
const CACHE_MS = 10 * 60 * 1000;
|
||||
const MAX_STATIONS = 40;
|
||||
|
||||
/* The genres, as the chips the screen draws.
|
||||
*
|
||||
* Each one names the SomaFM channels that fit it (curated by hand, because a machine cannot know
|
||||
* that "Seven Inch Soul" is the R&B one) and the radio-browser tags that fill in the rest. A genre
|
||||
* with neither is a chip that shows nothing, so there are none. */
|
||||
export const GENRES = Object.freeze([
|
||||
{ key: 'workout', label: 'Workout / Rave', soma: ['beatblender', 'thetrip', 'cliqhop', 'dubstep', 'defcon'], tags: ['rave', 'dance', 'techno'], paradise: ['main'] },
|
||||
{ key: 'techno', label: 'Techno / House', soma: ['beatblender', 'thetrip', 'lush'], tags: ['techno', 'house', 'deep house'], paradise: [] },
|
||||
{ key: 'rnb', label: 'R&B / Soul', soma: ['7soul', 'fluid'], tags: ['r&b', 'soul', 'funk'], paradise: ['mellow'] },
|
||||
{ key: 'latin', label: 'Latina / Salsa', soma: ['bossa', 'reggae'], tags: ['salsa', 'latin', 'reggaeton', 'bachata'], paradise: ['global'] },
|
||||
{ key: 'hiphop', label: 'Hip-Hop', soma: ['fluid', 'cliqhop'], tags: ['hip hop', 'rap'], paradise: [] },
|
||||
{ key: 'reggae', label: 'Reggae', soma: ['reggae', 'suburbsofgoa'], tags: ['reggae', 'dancehall'], paradise: ['global'] },
|
||||
{ key: 'chill', label: 'Chill / Focus', soma: ['groovesalad', 'dronezone', 'synphaera', 'deepspaceone'], tags: ['chillout', 'ambient', 'lounge'], paradise: ['mellow'] },
|
||||
{ key: 'jazz', label: 'Jazz / Lounge', soma: ['sonicuniverse', 'illstreet', 'secretagent'], tags: ['jazz', 'lounge', 'swing'], paradise: ['mellow'] },
|
||||
{ key: 'rock', label: 'Rock / Indie', soma: ['indiepop', 'poptron', 'metal', 'seventies', 'u80s'], tags: ['rock', 'indie', 'alternative'], paradise: ['main', 'rock'] },
|
||||
{ key: 'electronic', label: 'Electrónica', soma: ['digitalis', 'spacestation', 'vaporwaves', 'u80s'], tags: ['electronic', 'synthwave', 'electro'], paradise: ['main'] }
|
||||
]);
|
||||
export const genreOf = key => GENRES.find(g => g.key === key) || null;
|
||||
|
||||
/** The four Radio Paradise mixes. Fixed URLs: the mixes are the station, and they do not move. */
|
||||
export const PARADISE = Object.freeze([
|
||||
{ id: 'main', name: 'Radio Paradise', detail: 'eclectic rock, no advertising', url: 'https://stream.radioparadise.com/mp3-192' },
|
||||
{ id: 'mellow', name: 'Radio Paradise · Mellow', detail: 'calm mix', url: 'https://stream.radioparadise.com/mellow-192' },
|
||||
{ id: 'rock', name: 'Radio Paradise · Rock', detail: 'harder mix', url: 'https://stream.radioparadise.com/rock-192' },
|
||||
{ id: 'global', name: 'Radio Paradise · Global', detail: 'world mix', url: 'https://stream.radioparadise.com/global-192' }
|
||||
]);
|
||||
|
||||
/* ---------- a small polite cache ----------
|
||||
*
|
||||
* radio-browser is a community service run on donations and SomaFM is listener-supported: neither
|
||||
* should see a request per tap. Everything fetched here is cached for ten minutes, which is also
|
||||
* what makes switching genres on the screen feel instant the second time. */
|
||||
const cache = new Map();
|
||||
function cached(key, ttl, produce) {
|
||||
const hit = cache.get(key);
|
||||
if (hit && Date.now() - hit.at < ttl) return hit.value;
|
||||
return produce().then(value => {
|
||||
if (value != null) cache.set(key, { at: Date.now(), value });
|
||||
return value;
|
||||
});
|
||||
}
|
||||
export const clearRadioCache = () => cache.clear();
|
||||
|
||||
/** One GET, allowlisted, with a timeout, returning text or null. Never throws at the caller. */
|
||||
export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {} } = {}) {
|
||||
// The gate: every outgoing call in this module goes through here, so the allowlist is one rule in
|
||||
// one place rather than a check each caller has to remember.
|
||||
if (!allowedHost(url)) return null;
|
||||
try {
|
||||
const r = await fetchImpl(url, {
|
||||
headers: { 'User-Agent': UA, ...headers },
|
||||
signal: AbortSignal.timeout(timeoutMs)
|
||||
});
|
||||
if (!r.ok) return null;
|
||||
return await r.text();
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
/* ---------- SomaFM ---------- */
|
||||
|
||||
/**
|
||||
* The stream inside a `.pls`. SomaFM publishes one playlist per channel and format, with several
|
||||
* mirrors of the same stream; the first entry is the canonical one. Reading it is what makes this
|
||||
* work for every channel without guessing a bitrate into a URL.
|
||||
*/
|
||||
export function parsePls(text) {
|
||||
if (typeof text !== 'string') return null;
|
||||
const line = text.split(/\r?\n/).find(l => /^\s*file1\s*=/i.test(l));
|
||||
if (!line) return null;
|
||||
const url = line.slice(line.indexOf('=') + 1).trim();
|
||||
return /^https:\/\//i.test(url) ? url : null;
|
||||
}
|
||||
|
||||
/** The playlist URL for a channel: the best quality it publishes, preferring MP3 (it plays everywhere). */
|
||||
export function pickPlaylist(channel) {
|
||||
const lists = Array.isArray(channel?.playlists) ? channel.playlists : [];
|
||||
const best = lists.filter(p => p && /^https:\/\//i.test(p.url || ''));
|
||||
const order = best.find(p => p.format === 'mp3' && p.quality === 'highest')
|
||||
|| best.find(p => p.format === 'mp3')
|
||||
|| best.find(p => p.format === 'aac' && p.quality === 'highest')
|
||||
|| best.find(p => p.format === 'aac')
|
||||
|| best[0];
|
||||
return order ? order.url : null;
|
||||
}
|
||||
|
||||
/** One SomaFM channel, as a station the screen can list. */
|
||||
export function somaStation(channel) {
|
||||
const id = String(channel?.id || '').trim();
|
||||
const name = String(channel?.title || '').trim();
|
||||
const pls = pickPlaylist(channel);
|
||||
if (!id || !name || !pls) return null;
|
||||
return {
|
||||
src: 'soma',
|
||||
id,
|
||||
name,
|
||||
genre: String(channel.genre || '').trim(),
|
||||
detail: String(channel.description || '').replace(/\s+/g, ' ').trim().slice(0, 160),
|
||||
image: /^https:\/\//i.test(channel.xlimage || channel.largeimage || '') ? (channel.xlimage || channel.largeimage) : null,
|
||||
listeners: Number(channel.listeners) || null,
|
||||
// The `.pls` is resolved into a real stream URL when somebody presses play, not here: forty
|
||||
// channels would be forty requests to list a screen.
|
||||
pls
|
||||
};
|
||||
}
|
||||
|
||||
/** The channel list, cached. */
|
||||
export async function somaChannels({ fetchImpl = fetch } = {}) {
|
||||
return cached('soma:channels', CACHE_MS, async () => {
|
||||
const text = await get('https://somafm.com/channels.json', { fetchImpl });
|
||||
if (!text) return [];
|
||||
try {
|
||||
const data = JSON.parse(text);
|
||||
return (data.channels || []).map(somaStation).filter(Boolean);
|
||||
} catch { return []; }
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- radio-browser ---------- */
|
||||
|
||||
/* The codecs a browser plays natively, without a library: HLS (`.m3u8`) needs one on Chrome and
|
||||
Android, and this project does not add a dependency for a station. */
|
||||
const PLAYABLE = /^(mp3|aac|aac\+|aacp|ogg|opus)$/i;
|
||||
|
||||
/**
|
||||
* Station rows from the directory, filtered to what can actually be played and heard.
|
||||
*
|
||||
* HTTPS is not a preference: the app is served over HTTPS and a browser refuses to play an HTTP
|
||||
* stream from an HTTPS page, so an `http://` row is a station that silently does nothing. The same
|
||||
* argument, one step earlier, for a dead or broken entry.
|
||||
*/
|
||||
export function rbStations(rows) {
|
||||
if (!Array.isArray(rows)) return [];
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const r of rows) {
|
||||
const url = String(r?.url_resolved || r?.url || '').trim();
|
||||
if (!/^https:\/\//i.test(url)) continue;
|
||||
if (/\.m3u8(\?|$)/i.test(url)) continue; // HLS: not without a library
|
||||
const codec = String(r?.codec || '').trim();
|
||||
if (codec && !PLAYABLE.test(codec)) continue;
|
||||
const name = String(r?.name || '').replace(/\s+/g, ' ').trim();
|
||||
if (!name || seen.has(url)) continue;
|
||||
seen.add(url);
|
||||
out.push({
|
||||
src: 'rb',
|
||||
id: String(r.stationuuid || url).slice(0, 60),
|
||||
name: name.slice(0, 80),
|
||||
genre: String(r.tags || '').split(',').slice(0, 3).join(', ').slice(0, 60),
|
||||
detail: [r.country, codec, r.bitrate ? r.bitrate + ' kbps' : null].filter(Boolean).join(' · '),
|
||||
image: /^https:\/\//i.test(r.favicon || '') ? r.favicon : null,
|
||||
url
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The directory's best stations for one tag, cached per tag. */
|
||||
export async function rbByTag(tag, { fetchImpl = fetch } = {}) {
|
||||
const key = 'rb:' + tag;
|
||||
return cached(key, CACHE_MS, async () => {
|
||||
const q = new URLSearchParams({
|
||||
limit: '20', hidebroken: 'true', order: 'clickcount', reverse: 'true'
|
||||
});
|
||||
const text = await get(`https://all.api.radio-browser.info/json/stations/bytagexact/${encodeURIComponent(tag)}?${q}`, { fetchImpl });
|
||||
if (!text) return [];
|
||||
try { return rbStations(JSON.parse(text)); } catch { return []; }
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- the list the screen shows ---------- */
|
||||
|
||||
/**
|
||||
* Every station for a genre: the curated SomaFM channels first (no advertising, and the ones worth
|
||||
* pressing), then Radio Paradise on the genres it fits, then the directory for everything else.
|
||||
*/
|
||||
export async function stationsFor(genreKey, { fetchImpl = fetch } = {}) {
|
||||
const genre = genreOf(genreKey) || GENRES[0];
|
||||
const [channels, ...tagged] = await Promise.all([
|
||||
somaChannels({ fetchImpl }),
|
||||
...genre.tags.map(tag => rbByTag(tag, { fetchImpl }))
|
||||
]);
|
||||
const bySoma = new Map(channels.map(c => [c.id, c]));
|
||||
/* The curated channels get their stream resolved *here*, in the list, for one reason: on iOS
|
||||
`play()` has to be called inside the tap's own task, and waiting for a round trip first is what
|
||||
makes a press do nothing. Five channels per genre, cached for ten minutes, is a cheap price for
|
||||
a play button that always plays. A channel whose stream cannot be resolved is left out rather
|
||||
than listed as a row that does nothing. */
|
||||
const picks = (await Promise.all(
|
||||
genre.soma.map(id => bySoma.get(id)).filter(Boolean).map(async c => ({ ...c, url: await streamFor(c, { fetchImpl }) }))
|
||||
)).filter(c => c.url);
|
||||
// The mixes of Radio Paradise that fit this genre, named per genre rather than offered everywhere:
|
||||
// "Rock" under Chill is a suggestion nobody asked for.
|
||||
const wanted = new Set(genre.paradise || []);
|
||||
const paradise = PARADISE.filter(p => wanted.has(p.id))
|
||||
.map(p => ({ src: 'paradise', id: p.id, name: p.name, genre: p.detail, detail: 'no advertising', image: null, url: p.url }));
|
||||
const seen = new Set(picks.map(p => p.id));
|
||||
const rest = [];
|
||||
for (const list of tagged) {
|
||||
for (const s of list) {
|
||||
if (seen.has(s.id)) continue;
|
||||
seen.add(s.id);
|
||||
rest.push(s);
|
||||
}
|
||||
}
|
||||
return { genre, stations: [...picks, ...paradise, ...rest].slice(0, MAX_STATIONS) };
|
||||
}
|
||||
|
||||
/** The genres the screen offers, with their labels. */
|
||||
export const genreList = () => GENRES.map(g => ({ key: g.key, label: g.label }));
|
||||
|
||||
/* ---------- resolving a station into a stream ---------- */
|
||||
|
||||
/**
|
||||
* The URL to hand an `<audio>` element.
|
||||
*
|
||||
* SomaFM's `.pls` is fetched (and cached) at this point, because that is when it is needed and not
|
||||
* when the list is drawn. Everything else already carries its stream.
|
||||
*/
|
||||
export async function streamFor(station, { fetchImpl = fetch } = {}) {
|
||||
if (!station) return null;
|
||||
if (station.src === 'soma') {
|
||||
if (!station.pls || !allowedHost(station.pls)) return null;
|
||||
return cached('pls:' + station.pls, CACHE_MS, async () => parsePls(await get(station.pls, { fetchImpl })));
|
||||
}
|
||||
const url = String(station.url || '');
|
||||
return /^https:\/\//i.test(url) ? url : null;
|
||||
}
|
||||
|
||||
/* ---------- what is playing ---------- */
|
||||
|
||||
/**
|
||||
* The current track, where the station publishes one.
|
||||
*
|
||||
* Only SomaFM and Radio Paradise do, and the difference is the whole reason they are first in each
|
||||
* genre: a station that says what it is playing is a station you can trust with your ears. Anything
|
||||
* else — the directory's thousands — gets no line, rather than an invented one.
|
||||
*/
|
||||
export function nowFrom(src, data) {
|
||||
if (src === 'soma') {
|
||||
const song = (data && Array.isArray(data.songs) && data.songs[0]) || null;
|
||||
if (!song || !song.title) return null;
|
||||
return {
|
||||
artist: String(song.artist || '').trim().slice(0, 80) || null,
|
||||
title: String(song.title).trim().slice(0, 120),
|
||||
cover: /^https:\/\//i.test(song.albumArt || '') ? song.albumArt : null
|
||||
};
|
||||
}
|
||||
if (src === 'paradise') {
|
||||
if (!data || !data.title) return null;
|
||||
return {
|
||||
artist: String(data.artist || '').trim().slice(0, 80) || null,
|
||||
title: String(data.title).trim().slice(0, 120),
|
||||
cover: /^https:\/\//i.test(data.cover || '') ? data.cover : null
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Fetches what is playing, for the two sources that publish it. */
|
||||
export async function nowPlaying(station, { fetchImpl = fetch } = {}) {
|
||||
if (!station) return null;
|
||||
if (station.src === 'soma') {
|
||||
const text = await get(`https://somafm.com/songs/${encodeURIComponent(station.id)}.json`, { fetchImpl });
|
||||
if (!text) return null;
|
||||
try { return nowFrom('soma', JSON.parse(text)); } catch { return null; }
|
||||
}
|
||||
if (station.src === 'paradise') {
|
||||
const chan = PARADISE.findIndex(p => p.id === station.id);
|
||||
const text = await get('https://api.radioparadise.com/api/now_playing?chan=' + (chan < 0 ? 0 : chan), { fetchImpl });
|
||||
if (!text) return null;
|
||||
try { return nowFrom('paradise', JSON.parse(text)); } catch { return null; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in new issue
Block a user