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
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:
1 parent
22654c61fc
commit
d5cf0d8d64
16 files changed
+845
-81
No files matched your search
@@ -48,6 +48,8 @@ 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.
|
||||
*
|
||||
@@ -218,6 +220,90 @@ export async function rbByTag(tag, { fetchImpl = fetch } = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ---------- */
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user