Files
dsantillan d5cf0d8d64
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 se ordena: pestañas, buscador, y listas de diez con "Mostrar más"
La pantalla era una sola columna —radio, después podcasts, después listas— y tres
listas de veinte filas es una pantalla por la que se baja buscando lo que ya sabías
que querías. Ahora pregunta primero: **Radio | Podcasts | Listas**, una lista a la
vez, **diez filas** y un **"Mostrar más"** que dice cuántas esconde. Nada queda fuera
de alcance y nada más está en pantalla mientras decidís: el subtítulo también dice qué
estás mirando en vez de hablar siempre de listas.

El **buscador** busca lo que tengas abierto y en el origen, no en la página: `jazz`
le pregunta al directorio de emisoras y `crimen` al de podcasts de Apple —filtrado,
como siempre, a español, y pasando por **la misma** función de filtro que una
categoría, porque un segundo camino más barato al catálogo es como se pierde una
regla—. Con menos de dos letras no se busca ni se pide nada: una letra coincide con
todo y sería una petición por tecla para una respuesta inservible.

La búsqueda de emisoras **ordena por lo que se buscó**: el directorio coincide con
subcadenas en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS -
DANCE & DJ MIX RADIO" —real, con "techno" entre sus etiquetas— por delante de toda
emisora llamada Techno Algo. El nombre pesa antes que la popularidad y a igual peso
gana el nombre más corto; los canales de SomaFM y los mixes de Paradise que coinciden
van primero, porque no tienen publicidad y su stream ya se sabe que funciona. La
búsqueda del directorio va con `is_https=true`, cacheada por consulta.

`lib/paging.js` es puro y tiene test porque tiene un borde fácil de equivocar en un
componente: una lista que se encoge —una búsqueda nueva, una emisora desmarcada— no
puede dejar el tamaño de página pasado del final, que se ve como "Mostrar más" que no
hace nada.

Verificado contra los directorios reales: `radio?q=jazz` → Sonic Universe (SomaFM) y
después Jazz 24; `radio?q=miami` → Miami Beach Radio, 105 Miami; `podcasts?q=crimen`
→ 20 programas en español (es, es-ar) y `q=entrenamiento en casa` → 3; `?q=j` no
busca. `relevance` y `rankStations` se comprobaron por mutación: sacar el orden hace
fallar el test que lo mira de punta a punta.
2026-09-23 21:24:50 -04:00

412 lines
20 KiB
JavaScript

/* 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;
/** How many curated channels a search may answer with before the directory takes over. */
const MAX_CURATED_HITS = 5;
/* 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 []; }
});
}
/**
* A name search across everything this module knows: the curated channels, the Paradise mixes, and
* the directory's thousands.
*
* The curated sources are matched **locally** (they are already in memory, and a match there is a
* better answer than anything the directory can return: no advertising, and a stream that is known
* to work), and the directory is asked by name. Money is what orders the directory's answer — by
* how many people actually listen — so the first rows of "jazz" are jazz stations people use rather
* than whatever was registered most recently.
*
* Like the genre list, a station here arrives with its stream URL already resolved: iOS only allows
* audio to start inside the tap, so waiting for a round trip first is a press that does nothing.
*/
export async function searchStations(query, { fetchImpl = fetch } = {}) {
const q = normQuery(query);
if (!q) return [];
const [channels, directory] = await Promise.all([
somaChannels({ fetchImpl }),
rbSearch(q, { fetchImpl })
]);
const hits = channels.filter(c => matches(c, q)).slice(0, MAX_CURATED_HITS);
// `somaChannels()` already answers with station rows (name, genre, detail, `pls`), so they only
// need their stream resolved here — `somaStation` is for a *raw* channel from the JSON.
const picks = (await Promise.all(
hits.map(async st => ({ ...st, url: await streamFor(st, { fetchImpl }) }))
)).filter(st => st && st.url);
const paradise = PARADISE.filter(p => matches({ title: p.name, genre: p.detail, description: '' }, q))
.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 = rankStations(directory.filter(st => !seen.has(st.id)), q);
return [...picks, ...paradise, ...rest].slice(0, MAX_STATIONS);
}
/* How well a station's *name* answers the query, 0 (it is the name) to 4 (it is somewhere in there).
*
* The directory's search matches substrings anywhere, so a query like "techno" comes back with
* "# TOP 100 CLUB CHARTS - DANCE & DJ MIX RADIO" — a real station, with "techno" somewhere in its
* tags — ahead of every station actually called Techno Something. Ordering by this before the
* directory's own popularity is the difference between a search that looks broken and one that
* looks clever. */
export function relevance(station, q) {
const name = String(station?.name || '').toLowerCase().trim();
if (!name) return 4;
if (name === q) return 0;
if (name.startsWith(q + ' ') || name.startsWith(q + ':') || name.startsWith(q + ' -')) return 1;
if (name.startsWith(q)) return 2;
const word = new RegExp('(^|[^a-z0-9])' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9]|$)');
if (word.test(name)) return 3;
return 4;
}
/** The directory's matches, best answer first: relevance, then the shorter name, then as it came. */
export function rankStations(list, q) {
return [...(Array.isArray(list) ? list : [])]
.map((st, i) => ({ st, i, r: relevance(st, q) }))
.sort((a, b) => a.r - b.r || String(a.st.name).length - String(b.st.name).length || a.i - b.i)
.map(e => e.st);
}
/** One query, normalised: trimmed, lower-cased, and short enough to be a search rather than a wall. */
export function normQuery(query) {
const q = String(query == null ? '' : query).replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 60);
// One letter is not a search: it matches everything and costs the directory a request to say so.
return q.length < 2 ? '' : q;
}
/** Whether a curated channel or mix matches the query, by name, genre or description. */
export function matches(entry, q) {
const hay = [entry?.title, entry?.name, entry?.genre, entry?.description].filter(Boolean).join(' ').toLowerCase();
return hay.includes(q);
}
/** The directory, searched by name. Cached per query: a search is the same answer for everybody. */
export async function rbSearch(q, { fetchImpl = fetch } = {}) {
return cached('rb:q:' + q, CACHE_MS, async () => {
const params = new URLSearchParams({
name: q, limit: '30', hidebroken: 'true', order: 'clickcount', reverse: 'true', is_https: 'true'
});
const text = await get(`https://all.api.radio-browser.info/json/stations/search?${params}`, { 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;
}