Música se ordena: pestañas, buscador, y listas de diez con "Mostrar má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

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.
This commit is contained in:
dsantillan committed 2026-09-23 21:24:50 -04:00
1 parent 22654c61fc
commit d5cf0d8d64
16 files changed
+845 -81

No files matched your search

+106 -1
View File
@@ -9,7 +9,8 @@ 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
nowFrom, allowedHost, get, streamFor, stationsFor, nowPlaying, RADIO_HOSTS, clearRadioCache,
searchStations, rbSearch, normQuery, relevance, rankStations
} from '../radio.js';
const pls = 'https://api.somafm.com/beatblender.pls';
@@ -220,3 +221,107 @@ test('what is playing is asked for at the right address, per source', async () =
assert.equal(calls.length, 2);
assert.equal(PARADISE.length, 4);
});
/* ---------- search ---------- */
test('a query has to be a query: trimmed, lowered, and at least two characters', () => {
assert.equal(normQuery(' Jazz '), 'jazz');
assert.equal(normQuery('Deep HOUSE'), 'deep house');
assert.equal(normQuery('j'), '', 'one letter matches everything and costs a request to say so');
assert.equal(normQuery(''), '');
assert.equal(normQuery(null), '');
assert.equal(normQuery('x'.repeat(200)).length, 60, 'a wall of text is truncated, not refused');
});
test('the best answer to "techno" is a station called Techno Something', () => {
// The directory matches substrings anywhere, so a chart station with "techno" in its tags used to
// come back ahead of every station actually named after the genre. This is the ordering that fixes
// it: the name is the answer, and where in the name it appears is the ranking.
assert.equal(relevance({ name: 'Techno' }, 'techno'), 0);
assert.equal(relevance({ name: 'Techno: Live' }, 'techno'), 1);
assert.equal(relevance({ name: 'TechnoFM' }, 'techno'), 2);
assert.equal(relevance({ name: 'Radio Techno Club' }, 'techno'), 3);
assert.equal(relevance({ name: '# TOP 100 CLUB CHARTS - DANCE & DJ MIX' }, 'techno'), 4);
assert.equal(relevance({ name: '' }, 'techno'), 4);
const ranked = rankStations([
{ name: 'Radio Techno Club' },
{ name: '# TOP 100 CLUB CHARTS' },
{ name: 'Techno' },
{ name: 'TechnoFM' }
], 'techno').map(s => s.name);
assert.deepEqual(ranked, ['Techno', 'TechnoFM', 'Radio Techno Club', '# TOP 100 CLUB CHARTS']);
// Ties fall back to the shorter name, then to the order the directory gave: a 90-character
// marketing string is noise next to "Jazz 24".
assert.deepEqual(rankStations([{ name: 'Jazz FM 106.9 Yerevan Radio Station' }, { name: 'Jazz 24' }], 'jazz').map(s => s.name),
['Jazz 24', 'Jazz FM 106.9 Yerevan Radio Station']);
assert.deepEqual(rankStations(null, 'jazz'), []);
});
test('a search asks the directory by name, https only, and the curated channels come first', async () => {
clearRadioCache();
const asked = [];
const fetchImpl = async (url) => {
asked.push(url);
if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({
channels: [
channel({
id: 'sonicuniverse', title: 'Sonic Universe', genre: 'jazz',
playlists: [{ url: 'https://api.somafm.com/sonicuniverse.pls', format: 'mp3', quality: 'highest' }]
}),
channel({ id: 'beatblender', title: 'Beat Blender', genre: 'electronic' }) // not a jazz hit
]
}) };
// As the directory answers: the noisy name first — which is exactly the problem the ranking
// exists for. It matches "jazz" inside a marketing string; "Jazz 24" starts with it.
if (url.includes('/stations/search')) return { ok: true, text: async () => JSON.stringify([
{ name: 'Smooth Jazz Worldwide Radio Charts Network', codec: 'MP3', country: 'Germany', url_resolved: 'https://x/noisy', stationuuid: 'a' },
{ name: 'Jazz 24', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'b' },
{ name: 'Jazz 24 dup', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'c' },
{ name: 'Jazz FM', codec: 'MP3', country: 'United Kingdom', url_resolved: 'http://x/jazzfm', stationuuid: 'd' }
]) };
if (url.includes('sonicuniverse.pls')) return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/sonicuniverse-128-mp3' };
return { ok: false, status: 404, text: async () => '' };
};
const stations = await searchStations('jazz', { fetchImpl });
// The curated channel is the first answer: no advertising, and a stream known to work.
assert.equal(stations[0].src, 'soma');
assert.equal(stations[0].id, 'sonicuniverse');
assert.equal(stations[0].url, 'https://ice2.somafm.com/sonicuniverse-128-mp3');
const search = asked.find(u => u.includes('/stations/search'));
assert.ok(search, 'the directory was asked');
const q = new URL(search).searchParams;
assert.equal(q.get('name'), 'jazz');
assert.equal(q.get('hidebroken'), 'true');
assert.equal(q.get('is_https'), 'true', 'an http stream is a row the browser will refuse to play');
assert.equal(q.get('order'), 'clickcount', 'ordered by what people actually listen to');
// The http station never makes it, the duplicate never makes it, the noisy name does not outrank
// the station actually called Jazz, and nothing from the directory outranks the curated channel.
assert.deepEqual(stations.map(s => s.name), ['Sonic Universe', 'Jazz 24', 'Smooth Jazz Worldwide Radio Charts Network']);
assert.ok(stations.every(s => /^https:\/\//.test(s.url)));
});
test('a one-letter search answers nothing and asks nobody', async () => {
clearRadioCache();
let called = 0;
const fetchImpl = async () => { called++; return { ok: true, text: async () => '[]' } };
assert.deepEqual(await searchStations('j', { fetchImpl }), []);
assert.deepEqual(await searchStations(' ', { fetchImpl }), []);
assert.equal(called, 0);
});
test('the same query twice is one request to the directory', async () => {
clearRadioCache();
let called = 0;
const fetchImpl = async url => {
if (url.includes('/stations/search')) { called++; return { ok: true, text: async () => JSON.stringify([{ name: 'Jazz', codec: 'MP3', url_resolved: 'https://x/1', stationuuid: 'a' }]) } }
if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({ channels: [] }) };
return { ok: false, status: 404, text: async () => '' };
};
await rbSearch('jazz', { fetchImpl });
await rbSearch('jazz', { fetchImpl });
assert.equal(called, 1);
});