diff --git a/CHANGELOG.md b/CHANGELOG.md index f0a5809..2fa3ba4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## Sin publicar — Música se ordena: pestañas, buscador y listas de diez + +La pantalla de Música era una sola columna: la radio, después los podcasts, después las listas. +Tres listas de veinte filas cada una es una pantalla por la que se baja buscando lo que ya sabías +que querías — y lo que querías solía estar abajo. Ahora **pregunta primero**: *Radio | Podcasts | +Listas*, una lista a la vez, **diez filas** y un **"Mostrar más"** que dice cuántas queda +escondiendo. Nada quedó fuera de alcance: todo está a un toque, y nada más está en pantalla mientras +decidís. + +Arriba de las pestañas hay un **buscador** que busca lo que tengas abierto, y busca en el origen, no +en la página: escribir *jazz* le pregunta al directorio de emisoras, y *crimen* al de podcasts de +Apple —filtrado, como siempre, a español—. Las filas que devuelve son las mismas que muestra una +categoría, así que una emisora encontrada buscando se guarda, suena y se cachea igual que una +encontrada navegando. Con menos de dos letras no se busca nada: una letra coincide con todo, y +pedirle al directorio que lo demuestre es una petición por tecla para una respuesta que nadie puede +usar. + +La búsqueda de emisoras **ordena por lo que la persona buscó**: el directorio coincide con subcadenas +en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS - DANCE & DJ MIX RADIO" —una +emisora 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 Radio Paradise que coinciden van primero, porque no tienen publicidad y su stream ya +se sabe que funciona. + +También: la lista de episodios de un programa (hasta cuarenta) se muestra de a diez; y el subtítulo +de la pantalla dice qué estás mirando en vez de hablar siempre de listas. + ## Sin publicar — Podcasts (en español, y que se acuerdan de dónde ibas) Música tiene ahora una sección **Podcasts**: programas por categoría — *Salud y fitness, Deporte, diff --git a/api/openapi.yaml b/api/openapi.yaml index 00d8244..94a6671 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -961,7 +961,18 @@ paths: container sits on the owner's own network and fetches on behalf of whoever asks. An unknown or missing `genre` is not an error: it falls back to the first genre. + + **`?q=` searches instead of browsing**, and it is the same route on purpose: the screen has + one list, and what fills it changes. A query is matched against the curated channels and + Radio Paradise mixes locally, and the directory is asked by name — ordered by how many people + listen, then re-ordered so a station *called* "Jazz 24" comes before one with "jazz" buried + in a forty-character marketing name. A query shorter than two characters is not a search and + answers an empty list without asking anybody. parameters: + - name: q + in: query + schema: { type: string, maxLength: 60 } + description: A name search. Two characters or more; when present, `genre` is ignored. - name: genre in: query schema: @@ -985,8 +996,9 @@ paths: properties: key: { type: string } label: { type: string } - genre: { type: string, description: The genre actually answered with. } - label: { type: string, description: That genre's human label. } + genre: { type: string, description: The genre actually answered with. Absent on a search. } + label: { type: string, description: That genre's human label. Absent on a search. } + query: { type: string, description: Present only on a search — the normalised query that was used. } stations: type: array description: Curated, ad-free picks first, then the directory. At most 40. @@ -1074,6 +1086,13 @@ paths: type: string enum: [fitness, sports, comedy, news, history, truecrime, science, tech, society, business, fiction, education, music, leisure] description: Category key. Missing or unrecognised falls back to `fitness`. + - name: q + in: query + schema: { type: string, maxLength: 80 } + description: >- + A search by name. Two characters or more; when present, `category` is ignored and the + same Spanish-language check runs on the results as on a category's chart entries — a + search is not a second, weaker way into the catalogue. responses: '200': description: The categories for the chips, and the Spanish shows in the one asked for. @@ -1091,8 +1110,9 @@ paths: properties: key: { type: string } label: { type: string, description: Spanish label, like the rest of the show list. } - category: { type: string, description: The category actually answered with. } + category: { type: string, description: The category actually answered with. Absent on a search. } label: { type: string } + query: { type: string, description: Present only on a search — the term that was used. } shows: type: array description: At most 20, Spanish-language only. diff --git a/api/podcasts.js b/api/podcasts.js index c2b210a..c64c35d 100644 --- a/api/podcasts.js +++ b/api/podcasts.js @@ -332,13 +332,22 @@ export async function showsFor(genreKey, { fetchImpl = fetch } = {}) { for (let i = 0; lists.some(l => l[i]); i++) { for (const list of lists) if (list[i]) rows.push(list[i]); } + const { shows, skipped } = await spanishOnly(rows, { fetchImpl }); + return { category, shows, skipped }; +} + +/** + * The Spanish filter, shared by a category list and a search: check each candidate's feed, keep the + * Spanish ones, and count why the others went. + * + * *Why* a show was left out is reported and not just dropped. It used to be `return null` for every + * reason, which made three different things — "not in Spanish", "the feed did not answer", "the pool + * swallowed an unexpected error" — the same observable outcome, so a refactor that accidentally let + * the third one happen looked exactly like the rule working. A count per reason makes each of them a + * fact a test can assert on. + */ +export async function spanishOnly(rows, { fetchImpl = fetch, limit = MAX_SHOWS } = {}) { const seen = new Set(); - /* *Why* a show was left out is reported, not just dropped. - * - * It used to be `return null` for every reason, which made three different things — "not in - * Spanish", "the feed did not answer", "the pool swallowed an unexpected error" — the same - * observable outcome. A refactor that accidentally let the third one happen then looked exactly - * like the rule working. A count per reason makes each of them a fact a test can assert on. */ const skipped = { duplicate: 0, language: 0, unreadable: 0, failed: 0 }; const results = await mapLimit(rows.slice(0, CHECK_LIMIT), POOL, async show => { if (seen.has(show.feed)) return { skip: 'duplicate' }; @@ -355,9 +364,54 @@ export async function showsFor(genreKey, { fetchImpl = fetch } = {}) { if (!r) { skipped.failed++; continue } if (r.skip) { skipped[r.skip]++; continue } shows.push(r.show); - if (shows.length >= MAX_SHOWS) break; + if (shows.length >= limit) break; } - return { category, shows, skipped }; + return { shows, skipped }; +} + +/* ---------- search ---------- */ + +/** + * Shows by name, from the same directory as the categories. + * + * Apple's search endpoint takes the same shape as its charts did in `lookup` — `collectionName`, + * `feedUrl`, `artworkUrl600` — so the rows go straight through `showFrom`, and then through the very + * same Spanish filter as a category list. That sharing is the point: a search is not a second, + * weaker way into the catalogue, and "Spanish only" cannot quietly stop applying to it. + * + * The two storefronts are searched because they publish different podcasts, and the results are + * interleaved so neither country fills the screen. + */ +export async function searchShows(query, { fetchImpl = fetch } = {}) { + const term = normQuery(query); + if (!term) return { query: '', shows: [], skipped: { duplicate: 0, language: 0, unreadable: 0, failed: 0 } }; + const perStore = await Promise.all(STORES.map(country => appleSearch(term, country, { fetchImpl }))); + const lists = perStore.filter(Array.isArray); + const rows = []; + for (let i = 0; lists.some(l => l[i]); i++) { + for (const list of lists) if (list[i]) rows.push(list[i]); + } + const { shows, skipped } = await spanishOnly(rows, { fetchImpl }); + return { query: term, shows, skipped }; +} + +/** One query, normalised: one letter matches everything and costs a request per storefront to say so. */ +export function normQuery(query) { + const q = String(query == null ? '' : query).replace(/\s+/g, ' ').trim().slice(0, 80); + return q.length < 2 ? '' : q; +} + +/** The directory's search for one storefront, cached: the same query is the same answer. */ +export async function appleSearch(term, country, { fetchImpl = fetch } = {}) { + return cached(`search:${country}:${term.toLowerCase()}`, CACHE_MS, async () => { + const params = new URLSearchParams({ media: 'podcast', term, country, limit: String(CHART_LIMIT), lang: 'es' }); + const text = await get(apple('/search?' + params), { fetchImpl }); + if (!text) return []; + try { + const json = JSON.parse(text); + return (json.results || []).map(r => showFrom(r, country)).filter(Boolean); + } catch { return [] } + }); } /* ---------- the feed ---------- */ diff --git a/api/radio.js b/api/radio.js index 412003b..7d3f88c 100644 --- a/api/radio.js +++ b/api/radio.js @@ -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 ---------- */ /** diff --git a/api/server.js b/api/server.js index cf3a383..7afb7e5 100644 --- a/api/server.js +++ b/api/server.js @@ -21,8 +21,8 @@ import { dayReminderPush, restTimerPush, testPush } from './push-messages.js'; import { verifyError } from './verify-error.js'; import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js'; import { hostAllowed, readCapped, parseMusicPage } from './music.js'; -import { genreList, stationsFor, nowPlaying } from './radio.js'; -import { categoryList, showsFor, episodesFor, safeFeedUrl, isSpanish } from './podcasts.js'; +import { genreList, stationsFor, nowPlaying, searchStations, normQuery } from './radio.js'; +import { categoryList, showsFor, searchShows, episodesFor, safeFeedUrl, isSpanish } from './podcasts.js'; import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js'; import { readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost @@ -1290,7 +1290,14 @@ const routes = { 'GET /api/radio': async (req, res) => { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); - const key = new URL(req.url, 'http://x').searchParams.get('genre') || ''; + const q = new URL(req.url, 'http://x').searchParams; + /* `?q=` is a name search and `?genre=` is a browse, and they are the same route on purpose: the + screen has one list, and what fills it changes. A search answers without the genre list + because the chips are already on the client — it does not need to be told again what the + genres are to show results. */ + const query = normQuery(q.get('q')); + if (query) return json(res, 200, { ok: true, query, stations: await searchStations(query) }); + const key = q.get('genre') || ''; const { genre, stations } = await stationsFor(key); json(res, 200, { ok: true, genres: genreList(), genre: genre.key, label: genre.label, stations }); }, @@ -1317,7 +1324,14 @@ const routes = { 'GET /api/podcasts': async (req, res) => { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); - const key = new URL(req.url, 'http://x').searchParams.get('category') || ''; + const q = new URL(req.url, 'http://x').searchParams; + // Same shape as the radio list: `?q=` searches, `?category=` browses, one route for one screen. + const query = normQuery(q.get('q')); + if (query) { + const { shows, skipped } = await searchShows(query); + return json(res, 200, { ok: true, query, shows, skipped }); + } + const key = q.get('category') || ''; const { category, shows, skipped } = await showsFor(key); json(res, 200, { ok: true, categories: categoryList(), category: category.key, label: category.label, shows, skipped }); }, diff --git a/api/test/podcasts.test.js b/api/test/podcasts.test.js index f32eb22..aa20b42 100644 --- a/api/test/podcasts.test.js +++ b/api/test/podcasts.test.js @@ -18,7 +18,7 @@ import { CATEGORIES, STORES, MAX_EPISODES, MAX_SHOWS, categoryList, categoryOf, isSpanish, languageOf, publicHost, safeFeedUrl, parseDuration, decodeEntities, episodeFrom, parseFeed, tagText, tagAttr, get, readCapped, feedLanguage, showsFor, episodesFor, chartEntries, showFrom, mapLimit, - clearPodcastCache + clearPodcastCache, searchShows, appleSearch, normQuery } from '../podcasts.js'; /* A stand-in for `fetch`: a body, a status, and the url it ended at. */ @@ -329,3 +329,85 @@ test('the pool keeps the order and never throws out of itself', async () => { }); assert.deepEqual(out, [2, 4, null, 8, 10]); }); + +/* ---------- search ---------- */ + +test('a query has to be a query here too', () => { + assert.equal(normQuery(' Crimen real '), 'Crimen real', 'the term goes to Apple as typed'); + assert.equal(normQuery('a'), ''); + assert.equal(normQuery(null), ''); + assert.equal(normQuery('x'.repeat(200)).length, 80); +}); + +test('a search is Apple\'s, one request per storefront, Spanish and no key', async () => { + clearPodcastCache(); + const asked = []; + const fetchImpl = async url => { + asked.push(url); + if (url.includes('/search?')) { + const country = new URL(url).searchParams.get('country'); + return res(JSON.stringify({ results: [{ + collectionId: country + '1', + collectionName: 'Crimen ' + country, + artistName: 'Alguien', + artworkUrl600: 'https://img.example.com/x.jpg', + primaryGenreName: 'True Crime', + feedUrl: 'https://feeds.example.com/' + country + }] }), { url }); + } + // Both feeds declare Spanish, except the Mexican one, which declares English. + if (url === 'https://feeds.example.com/es') return res('es-ES', { status: 206, url }); + if (url === 'https://feeds.example.com/mx') return res('en', { status: 206, url }); + return res('', { status: 500, url }); + }; + const { query, shows, skipped } = await searchShows('crimen', { fetchImpl }); + assert.equal(query, 'crimen'); + assert.deepEqual(shows.map(s => s.name), ['Crimen es'], 'only the Spanish one'); + assert.equal(shows[0].lang, 'es-es'); + assert.equal(skipped.language, 1, 'and the other one is counted, not silently missing'); + assert.equal(skipped.failed, 0); + + // One request per storefront, not one per show: `media=podcast`, the storefront, and `lang=es`. + const searches = asked.filter(u => u.includes('/search?')); + assert.equal(searches.length, 2); + const q = new URL(searches[0]).searchParams; + assert.equal(q.get('media'), 'podcast'); + assert.equal(q.get('term'), 'crimen'); + assert.equal(q.get('lang'), 'es'); + assert.deepEqual(searches.map(u => new URL(u).searchParams.get('country')).sort(), ['es', 'mx']); +}); + +test('a search result goes through the same feed rule as a chart entry', async () => { + clearPodcastCache(); + const fetchImpl = async url => { + if (url.includes('/search?')) { + return res(JSON.stringify({ results: [ + { collectionId: '1', collectionName: 'Bueno', feedUrl: 'https://feeds.example.com/a' }, + { collectionId: '2', collectionName: 'Inservible', feedUrl: 'http://feeds.example.com/b' }, + { collectionId: '3', collectionName: 'Privado', feedUrl: 'https://10.0.0.9/c' } + ] }), { url }); + } + return res('es', { status: 206, url }); + }; + const { shows } = await searchShows('algo', { fetchImpl }); + assert.deepEqual(shows.map(s => s.name), ['Bueno'], 'an http feed and a private host are not shows'); +}); + +test('one letter is not a search, and nobody is asked', async () => { + clearPodcastCache(); + let called = 0; + const fetchImpl = async () => { called++; return res('{}') }; + const { shows, query } = await searchShows('c', { fetchImpl }); + assert.deepEqual(shows, []); + assert.equal(query, ''); + assert.equal(called, 0); + // And the storefronts are cached: the same query twice is one request each. + const impl = async url => url.includes('/search?') + ? res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'X', feedUrl: 'https://feeds.example.com/x' }] }), { url }) + : res('es', { status: 206, url }); + let n = 0; + const counting = async (url, ...rest) => { if (url.includes('/search?')) n++; return impl(url, ...rest) }; + await searchShows('comedia', { fetchImpl: counting }); + await searchShows('comedia', { fetchImpl: counting }); + assert.equal(n, 2, 'one per storefront, then cached'); +}); diff --git a/api/test/radio.test.js b/api/test/radio.test.js index 22a7e23..f972b1d 100644 --- a/api/test/radio.test.js +++ b/api/test/radio.test.js @@ -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); +}); diff --git a/docs/PODCASTS.md b/docs/PODCASTS.md index 4eac7b3..24640ef 100644 --- a/docs/PODCASTS.md +++ b/docs/PODCASTS.md @@ -2,7 +2,8 @@ Radio, but the other half of it: episodes, in Spanish, that you can resume. -Open **Música → Podcasts**, pick a category (*Salud y fitness*, *Deporte*, *Comedia*, *Noticias*, +Open **Música → Podcasts** (the middle tab; the screen shows one list at a time, ten shows with a +"show more"), search by name if you know what you are looking for, or pick a category (*Salud y fitness*, *Deporte*, *Comedia*, *Noticias*, *Historia*, *Crímenes reales*, *Ciencia*, *Tecnología*, *Sociedad y cultura*, *Negocios*, *Ficción*, *Educación*, *Música*, *Ocio*), tap a show, tap an episode. It plays across screens, keeps going with the screen locked, and comes back where you left it. @@ -22,6 +23,14 @@ They are opposites in every way that matters to the player, and the difference i A podcast you cannot scrub is a podcast you do not use, which is why the player bar grows a progress hairline and two seek buttons when an episode is playing, and none of that exists for a station. +## A search is not a weaker way in + +Typing in the box above the tabs asks Apple's podcast search, both storefronts, and the results go +through **the same feed check and the same Spanish filter** as a category's chart entries — one +function on the server, used by both, so "Spanish only" cannot quietly stop applying to a search. +That is the shape worth keeping: a second, cheaper path into a catalogue is how a rule like this +gets lost. + ## Spanish only — checked, not assumed The user asked for Spanish, so the app checks, and this is the part worth knowing before trusting a diff --git a/docs/RADIO.md b/docs/RADIO.md index 5dc12ce..bfecc0c 100644 --- a/docs/RADIO.md +++ b/docs/RADIO.md @@ -10,6 +10,13 @@ purpose, the other is what plays while you count reps. ## What is playing +There is also a **search box** above the tabs, and it searches the directory rather than the page +you are looking at: *jazz* is every jazz station radio-browser knows, not the jazz stations that +happened to be in the genre on screen. Results are ordered by the name first — a station *called* +"Jazz 24" comes before one with "jazz" buried in a forty-character marketing name — and then by how +many people listen. The curated channels and mixes that match come first of all: no advertising, and +a stream already known to work. + Chips pick a genre. Ten of them: **Workout / Rave, Techno / House, R&B / Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica**. Each one is a list of **SomaFM** channels (curated by hand — a machine cannot know that *Seven Inch Soul* is the R&B one), the **Radio Paradise** mixes that diff --git a/frontend/src/index.css b/frontend/src/index.css index f2207ea..6efbcef 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1135,6 +1135,10 @@ body.chips-dragging *{cursor:inherit} .mus-rad-go{font-size:17px;color:var(--acc);flex:0 0 auto} .mus-rad-save{color:var(--label-3)} .mus-rad-save .icn{font-size:17px} +/* The screen's three lists, one at a time. The segmented control sits right under the search box and + above everything it switches between, so the screen reads top to bottom: what am I looking at, + which of the three, and then the list. */ +.mus-tabs{margin:2px 0 12px} .mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px} /* The episodes sheet: a show's feed, newest first. Rows are buttons because the whole row plays the diff --git a/frontend/src/lib/paging.js b/frontend/src/lib/paging.js new file mode 100644 index 0000000..ca6c5a5 --- /dev/null +++ b/frontend/src/lib/paging.js @@ -0,0 +1,29 @@ +/* Showing ten of something instead of forty. + * + * The Música screen carries three lists — stations, podcasts, playlists — and a list that renders + * everything is a screen you scroll through looking for the thing you already know you want. Ten + * rows and a "show more" is the house style here (the exercise library and the admin activity log + * both work this way), and it is the reason the screen reads as three small lists rather than one + * long one. + * + * Pure and tested because the arithmetic has an edge that is easy to get wrong in a component: a + * list that *shrinks* — a new search, a station unstarred — must not leave the page size past its + * end, which reads as "show more" doing nothing. */ +export const PAGE = 10 + +/** The first `shown` items. Never more than there are, and never a crash on a missing list. */ +export const visible = (list, shown) => (Array.isArray(list) ? list : []).slice(0, Math.max(0, shown)) + +/** Whether there is anything left to reveal. */ +export const hasMore = (list, shown) => (Array.isArray(list) ? list.length : 0) > Math.max(0, shown) + +/** + * How many to show after "show more". + * + * Clamped to the list: the button is only ever pressed against a list that shrank since it was + * drawn, and growing past the end would leave it on screen doing nothing at all. + */ +export const nextShown = (shown, total, step = PAGE) => Math.min((Number(shown) || 0) + step, Math.max(0, Number(total) || 0)) + +/** How many are hidden — for a button that says how much it is hiding, or nothing at all. */ +export const hiddenCount = (list, shown) => Math.max(0, (Array.isArray(list) ? list.length : 0) - Math.max(0, shown)) diff --git a/frontend/src/lib/paging.test.js b/frontend/src/lib/paging.test.js new file mode 100644 index 0000000..51190fb --- /dev/null +++ b/frontend/src/lib/paging.test.js @@ -0,0 +1,46 @@ +/* Ten at a time, and the edges of that. */ +import { describe, expect, it } from 'vitest' +import { PAGE, visible, hasMore, nextShown, hiddenCount } from './paging.js' + +const list = n => Array.from({ length: n }, (_, i) => i) + +describe('showing a list in pages of ten', () => { + it('shows ten, not everything', () => { + expect(PAGE).toBe(10) + expect(visible(list(40), PAGE)).toHaveLength(10) + expect(visible(list(40), PAGE)[9]).toBe(9) + }) + + it('shows what there is when there is less than a page', () => { + expect(visible(list(4), PAGE)).toEqual([0, 1, 2, 3]) + expect(hasMore(list(4), PAGE)).toBe(false) + }) + + it('says when there is more, and stops saying it at the end', () => { + expect(hasMore(list(11), PAGE)).toBe(true) + expect(hasMore(list(20), 20)).toBe(false) + // The bug this exists for: a list that shrank under a page size that was already past its end. + expect(hasMore([], PAGE)).toBe(false) + expect(hasMore(list(3), 10)).toBe(false) + }) + + it('grows by a page, and never past the end', () => { + expect(nextShown(PAGE, 40)).toBe(20) + expect(nextShown(30, 40)).toBe(40) + // "Show more" on a list that shrank to eight would otherwise leave the button there forever. + expect(nextShown(20, 8)).toBe(8) + }) + + it('counts what it is hiding', () => { + expect(hiddenCount(list(25), PAGE)).toBe(15) + expect(hiddenCount(list(3), PAGE)).toBe(0) + }) + + it('survives a list that is not there yet', () => { + expect(visible(null, PAGE)).toEqual([]) + expect(visible(undefined, PAGE)).toEqual([]) + expect(hasMore(null, PAGE)).toBe(false) + expect(hiddenCount(null, PAGE)).toBe(0) + expect(visible(list(5), null)).toEqual([]) + }) +}) diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 19ff6ee..3b1f767 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1409,6 +1409,15 @@ export default { 'The server is running an older API than this screen: the numbers may not match Apple Health, and the hourly detail and the sync receipt will not appear until the api container is updated.': 'El servidor está corriendo una api más vieja que esta pantalla: los números pueden no coincidir con Apple Health, y el detalle por hora y el recibo del último envío no van a aparecer hasta que se actualice el contenedor de la api.', 'using {0}': 'se usa {0}', // podcasts + 'Live radio, nothing downloaded': 'Radio en vivo, sin descargar nada', + 'Spanish podcasts, remembered where you left off': 'Podcasts en español, que se acuerdan de dónde ibas', + 'Search stations…': 'Buscar emisoras…', + 'Search podcasts…': 'Buscar podcasts…', + 'Search playlists…': 'Buscar listas…', + 'Results for “{0}”': 'Resultados para “{0}”', + 'No results for “{0}”.': 'Sin resultados para “{0}”.', + 'Show more ({0})': 'Mostrar más ({0})', + '{0} shows': '{0} programas', 'Podcasts': 'Podcasts', 'Podcast': 'Podcast', 'Saved podcasts': 'Podcasts guardados', diff --git a/frontend/src/views/Music.jsx b/frontend/src/views/Music.jsx index 11a7533..2f711c7 100644 --- a/frontend/src/views/Music.jsx +++ b/frontend/src/views/Music.jsx @@ -1,4 +1,19 @@ -/* Música — the playlists a profile keeps, and the way to open them in Apple Music. +/* Música — three lists behind one search box: live radio, Spanish podcasts, and the Apple Music + * playlists a profile keeps. + * + * ── Why it is split into tabs at all ─────────────────────────────────────────────────────────── + * + * It used to be one column: the radio, then the podcasts, then the playlists. Three lists of twenty + * rows each is a screen you scroll through looking for the thing you already knew you wanted — and + * the thing you wanted was usually at the bottom. So the screen asks first (Radio | Podcasts | + * Playlists) and shows one list at a time, ten rows long, with the search box above it and a + * "show more" under it. Nothing is hidden that cannot be reached in one tap, and nothing else is on + * screen while you are deciding. + * + * The search box searches whatever tab is open, and it searches the *source*, not the page: typing + * "jazz" asks the station directory, and typing "crimen" asks Apple's podcast directory — filtered, + * as always, to Spanish. The rows it returns are the same rows a category shows, so a station found + * by search is starred, played and cached exactly like one found by browsing. * * ── Why this is a list of links and not a MusicKit integration ───────────────────────────────── * @@ -23,10 +38,11 @@ import { useStore } from '../store/useStore.js' import { useUI } from '../store/useUI.js' import { t } from '../lib/i18n.js' import { confirmSheet } from '../sheets.jsx' -import { Button } from '../components/ui.jsx' +import { Button, Segmented, SearchField } from '../components/ui.jsx' import Icon from '../components/Icon.jsx' import { parseMusicUrl, profileUrl } from '../lib/music.js' import { fmtClock, episodeMeta, resumeSeconds, isFinished } from '../lib/podcast-view.js' +import { PAGE, visible, hasMore, nextShown, hiddenCount } from '../lib/paging.js' /** A playlist tile: artwork when the public page gave us some, a note when it did not. */ function PlaylistCard({ item, onRemove }) { @@ -98,7 +114,7 @@ function AddPlaylistSheet({ close }) { * worth ranking: SomaFM and Radio Paradise are listener-supported by mission, and the directory's * thousands are mostly commercial broadcasters that may air ads. */ -function RadioSection() { +function RadioSection({ q }) { const radio = useUI(s => s.radio) const playRadio = useUI(s => s.playRadio) const toast = useUI(s => s.toast) @@ -122,6 +138,7 @@ function RadioSection() { sometimes a homepage rather than an image, which renders as a broken-image icon mid-list. A row that fails falls back to the same placeholder as a row that never had one. */ const [noArt, setNoArt] = useState(() => new Set()) + const [shown, setShown] = useState(PAGE) const saved = (S.music && S.music.stations) || [] const load = key => { @@ -131,11 +148,26 @@ function RadioSection() { setGenres(r.genres) setGenre(r.genre) setStations(r.stations) + setShown(PAGE) }) .catch(e => toast(e.message)) .finally(() => setBusy(false)) } - useEffect(() => { if (canRadio) load(null) }, [canRadio]) + useEffect(() => { if (canRadio && !q) load(null) }, [canRadio]) + + /* A search replaces the list rather than filtering the twenty rows already on screen: the answer + to "jazz" is every jazz station in the directory, not the jazz stations that happened to be in + the genre you were looking at. Debounced, because every letter is a request. */ + useEffect(() => { + if (!canRadio || !q) return + let live = true + setBusy(true) + api('/api/radio?q=' + encodeURIComponent(q)) + .then(r => { if (live) { setStations(r.stations); setShown(PAGE) } }) + .catch(e => { if (live) toast(e.message) }) + .finally(() => { if (live) setBusy(false) }) + return () => { live = false } + }, [canRadio, q]) const play = station => { // Synchronous on purpose: `play()` has to happen inside this tap for iOS to allow it. @@ -162,8 +194,10 @@ function RadioSection() { + const list = stations || [] return <> -

{t('Radio')}{stations ? · {t('{0} stations', stations.length)} : null}

+

{q ? t('Results for “{0}”', q) : t('Radio')} + {stations ? · {t('{0} stations', stations.length)} : null}

{!canRadio ?
{staleApi @@ -171,31 +205,41 @@ function RadioSection() { : t('The radio comes from your server, so it needs a profile: sign in and the stations appear here.')}
: <> -
+ {!q &&
{t('These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.')} -
-
+
} + {!q &&
{(genres || []).map(g => )} -
- {saved.length > 0 && <> +
} + {!q && saved.length > 0 && <>
{t('Saved stations')}
{saved.map(st => row(st))} } {busy && !stations &&
{t('Loading stations…')}
} - {stations && stations.map(st => row(st))} - {stations && !stations.length &&
- {t('That station is not answering. Try another one.')} + {visible(list, shown).map(st => row(st))} + setShown(n => nextShown(n, list.length))} /> + {stations && !list.length &&
+ {q ? t('No results for “{0}”.', q) : t('That station is not answering. Try another one.')}
} - {radio &&
- {radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)} -
} - {!radio &&
{t('Nothing playing. Pick a station below.')}
} + {!q && (radio + ?
+ {radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)} +
+ :
{t('Nothing playing. Pick a station below.')}
)} } } +/** The house "show more": ten rows, then ten more, and the button says how many it is hiding. */ +function More({ list, shown, onMore }) { + if (!hasMore(list, shown)) return null + return
+ +
+} + /* ---------- podcasts ---------- * * Spanish-language shows, by category, from Apple's directory (free, no key), with the episodes read @@ -208,7 +252,7 @@ function RadioSection() { * audio element in lib/player.js. Tapping an episode plays it inside the tap, which is the only way * iOS lets audio start. */ -function PodcastSection() { +function PodcastSection({ q }) { const user = useStore(s => s.user) const cfg = useStore(s => s.config) const S = useStore(s => s.S) @@ -222,6 +266,7 @@ function PodcastSection() { const [shows, setShows] = useState(null) const [busy, setBusy] = useState(false) const [noArt, setNoArt] = useState(() => new Set()) + const [shown, setShown] = useState(PAGE) const saved = (S.podcasts && S.podcasts.shows) || [] // The same two situations the radio has, for the same reason: the list comes from the server, and // a guest or an api older than the app must not look like a request that quietly failed. @@ -235,11 +280,26 @@ function PodcastSection() { setCategories(r.categories) setCategory(r.category) setShows(r.shows) + setShown(PAGE) }) .catch(e => toast(e.message)) .finally(() => setBusy(false)) } - useEffect(() => { if (canPodcasts) load(null) }, [canPodcasts]) + useEffect(() => { if (canPodcasts && !q) load(null) }, [canPodcasts]) + + /* Searching shows the same catalogue a category does, filtered by the same rules — the Spanish + check runs on a search result exactly as it does on a chart entry, which is the whole reason + both go through one function on the server. */ + useEffect(() => { + if (!canPodcasts || !q) return + let live = true + setBusy(true) + api('/api/podcasts?q=' + encodeURIComponent(q)) + .then(r => { if (live) { setShows(r.shows); setShown(PAGE) } }) + .catch(e => { if (live) toast(e.message) }) + .finally(() => { if (live) setBusy(false) }) + return () => { live = false } + }, [canPodcasts, q]) const isSaved = show => saved.some(x => x.feed === show.feed) @@ -260,8 +320,10 @@ function PodcastSection() {
+ const list = shows || [] return <> -

{t('Podcasts')}

+

{q ? t('Results for “{0}”', q) : t('Podcasts')} + {shows ? · {t('{0} shows', shows.length)} : null}

{!canPodcasts ?
{staleApi @@ -269,22 +331,23 @@ function PodcastSection() { : t('Podcasts come from your server, so they need a profile: sign in and the shows appear here.')}
: <> -
+ {!q &&
{t('Spanish podcasts only, which is checked in each show’s own feed rather than assumed from the store. Nothing is downloaded: the episode goes straight from the publisher to your phone, and what you have heard is remembered per profile.')} -
-
+
} + {!q &&
{(categories || []).map(c => )} -
- {saved.length > 0 && <> +
} + {!q && saved.length > 0 && <>
{t('Saved podcasts')}
{saved.map(st => row(st))} } {busy && !shows &&
{t('Loading podcasts…')}
} - {shows && shows.map(st => row(st))} - {shows && !shows.length &&
- {t('No Spanish shows came back for this category. Try another one.')} + {visible(list, shown).map(st => row(st))} + setShown(n => nextShown(n, list.length))} /> + {shows && !list.length &&
+ {q ? t('No results for “{0}”.', q) : t('No Spanish shows came back for this category. Try another one.')}
} } @@ -296,6 +359,8 @@ function ShowSheet({ show, close, progress }) { const playEpisode = useUI(s => s.playEpisode) const [data, setData] = useState(null) const [err, setErr] = useState('') + // Forty episodes in a sheet is a wall with a scrollbar; ten and "show more" is a list. + const [shown, setShown] = useState(PAGE) useEffect(() => { let live = true @@ -332,7 +397,7 @@ function ShowSheet({ show, close, progress }) { {err &&
{err}
} {!data && !err &&
{t('Reading the feed…')}
} {data &&
- {data.episodes.map(ep => )} + setShown(n => nextShown(n, data.episodes.length))} />
} {data && !data.episodes.length &&
{t('That feed has no playable episodes in it — trailers only, or subscriber-only audio.')} @@ -358,6 +424,22 @@ export default function Music() { const removePlaylist = useStore(s => s.removePlaylist) const list = (S.music && S.music.playlists) || [] const profile = profileUrl(S.music && S.music.user) + /* Radio first: it is the one that needs no account, no Apple Music, and no decision. */ + const [tab, setTab] = useState('radio') + const [q, setQ] = useState('') + /* What the sections actually search on. Four hundred milliseconds: long enough that typing + "entrenamiento" is one request instead of fourteen, short enough that it feels like typing. */ + const typed = q.trim() + const query = useDebounced(typed, 400) + /* One letter is not a search: it matches everything, and asking the directory to prove it costs a + request per keystroke for an answer nobody can use. Below two characters the screen keeps + showing what it was showing, which is also what makes the transition into a search calm. */ + const searching = query.length >= 2 + // The playlists are local links, so their search is local too — no request, no debounce needed. + const playlists = searching + ? list.filter(p => [p.name, p.curator].filter(Boolean).join(' ').toLowerCase().includes(query.toLowerCase())) + : list + const [shownPlaylists, setShownPlaylists] = useState(PAGE) const askRemove = item => confirmSheet({ title: t('Remove “{0}”?', item.name), @@ -366,48 +448,77 @@ export default function Music() { onConfirm: () => removePlaylist(item.id) }) + const placeholder = tab === 'radio' ? t('Search stations…') : tab === 'podcasts' ? t('Search podcasts…') : t('Search playlists…') + return <>

{t('Music')}

-
{list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}
+
{tab === 'radio' ? t('Live radio, nothing downloaded') + : tab === 'podcasts' ? t('Spanish podcasts, remembered where you left off') + : list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}
- {profile - ? - - - @{S.music.user} - {t('Your public Apple Music profile')} - - - - :
- -
-
{t('Add your Apple Music profile')}
-
- {t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')} +
+ setQ(e.target.value)} onClear={() => setQ('')} placeholder={placeholder} /> +
+ { setTab(v); setQ('') }} /> + + {/* One list at a time. Switching tabs clears the search box, because a query typed for the + stations ("jazz") means nothing for the playlists, and a box that keeps it looks stuck. */} + {tab === 'radio' && } + {tab === 'podcasts' && } + {tab === 'playlists' && <> + {profile + ? + + + @{S.music.user} + {t('Your public Apple Music profile')} + + + + :
+ +
+
{t('Add your Apple Music profile')}
+
+ {t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')} +
-
-
} +
} - - - - -

{t('Playlists')}

- {list.length === 0 - ?
-
- {t('No playlists yet.')}
- {t('Add one from the + above.')} -
- : list.map(item => askRemove(item)} />)} +

{searching ? t('Results for “{0}”', query) : t('Playlists')} + {playlists.length ? · {t('{0} playlists', playlists.length)} : null}

+ {playlists.length === 0 + ? (searching + ?
{t('No results for “{0}”.', query)}
+ :
+
+ {t('No playlists yet.')}
+ {t('Add one from the + above.')} +
) + : visible(playlists, shownPlaylists).map(item => askRemove(item)} />)} + setShownPlaylists(n => nextShown(n, playlists.length))} /> + }
} + +/** A value, delayed: the search box types on every keystroke and the server should not hear them all. */ +function useDebounced(value, ms) { + const [slow, setSlow] = useState(value) + useEffect(() => { + const id = setTimeout(() => setSlow(value), ms) + return () => clearTimeout(id) + }, [value, ms]) + return slow +} diff --git a/frontend/src/views/Music.test.jsx b/frontend/src/views/Music.test.jsx index 4342f11..dcf6a32 100644 --- a/frontend/src/views/Music.test.jsx +++ b/frontend/src/views/Music.test.jsx @@ -53,7 +53,9 @@ beforeEach(() => { api.mockResolvedValue({ genres: [], genre: null, stations: [] }) playStream.mockClear() playFile.mockClear() - act(() => { useUI.setState({ radio: null }) }) + /* The UI store is module-level, so a sheet left open by one test is still open for the next one: + `sheets` is part of the state that has to be reset, not just the player. */ + act(() => { useUI.setState({ radio: null, pod: null, sheets: [] }) }) host = document.createElement('div') document.body.appendChild(host) root = createRoot(host) @@ -65,7 +67,9 @@ beforeEach(() => { config: null })) }) -afterEach(() => { act(() => root.unmount()); host.remove() }) +/* `#modal-root` is created once by Modals and lives on the body, so a sheet left open by one test + is still in the DOM for the next one. */ +afterEach(() => { act(() => root.unmount()); host.remove(); document.getElementById('modal-root')?.remove() }) /* The screen now asks two endpoints as well as the Apple Music lookup, so a test that cares about one of them says what the others answer: a single `mockResolvedValue` for all of them made the @@ -79,11 +83,28 @@ const stubApi = ({ radio = { genres: [], genre: null, stations: [] }, podcasts = }) const mount = async () => { await act(async () => { root.render() }) } +/* The screen shows one list at a time now, so a test says which one it means. */ +const openTab = async name => { + const btn = [...host.querySelectorAll('.seg button')].find(b => b.textContent.includes(name)) + act(() => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + await act(async () => { await Promise.resolve() }) +} +/* Typing in a search box that is debounced by 400 ms, and waiting it out. */ +const type = async text => { + const input = host.querySelector('.searchf input') + act(() => { + const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set + set.call(input, text) + input.dispatchEvent(new Event('input', { bubbles: true })) + }) + await act(async () => { await new Promise(r => setTimeout(r, 450)) }) +} const links = () => [...host.querySelectorAll('a')] describe('Música', () => { it('says how to get a playlist when there are none', async () => { await mount() + await openTab('Playlists') expect(host.textContent).toContain('No playlists yet.') expect(host.textContent).toContain('Add your Apple Music profile') expect(links().length).toBe(0) @@ -92,6 +113,7 @@ describe('Música', () => { it('makes each playlist a link to its own Apple Music page', async () => { useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [item()] } } })) await mount() + await openTab('Playlists') const [profile, playlist] = links() expect(profile.getAttribute('href')).toBe('https://music.apple.com/profile/ana') expect(playlist.getAttribute('href')).toBe('https://music.apple.com/us/playlist/leg-day/pl.aaa') @@ -106,6 +128,7 @@ describe('Música', () => { it('removes one without touching the others', async () => { useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day' })] } } })) await mount() + await openTab('Playlists') expect(host.textContent).toContain('Leg Day') act(() => { useStore.getState().removePlaylist('pl.aaa') }) await act(async () => {}) @@ -119,6 +142,7 @@ describe('Música', () => { it('adds what the form was given, all the way through the sheet', async () => { api.mockResolvedValue({ ok: true, meta: { title: 'Leg Day', artwork: 'https://is1-ssl.mzstatic.com/x/600x600bb.jpg', tracks: 42, curator: 'Ana' } }) await act(async () => { root.render(<>) }) + await openTab('Playlists') act(() => { [...document.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Add a playlist').dispatchEvent(new MouseEvent('click', { bubbles: true })) }) const fields = [...document.querySelectorAll('#modal-root input')] expect(fields.length).toBe(2) // the link, then the optional name @@ -212,6 +236,7 @@ describe('Música', () => { act(() => { useStore.getState().addPlaylist(item()) }) act(() => { useStore.getState().addPlaylist(item({ name: 'Leg Day (again)' })) }) await mount() + await openTab('Playlists') expect(host.querySelectorAll('.mus-card').length).toBe(1) expect(host.textContent).toContain('Leg Day') }) @@ -226,6 +251,7 @@ describe('Música', () => { it('lists the categories the server offers, and the Spanish shows in the first one', async () => { stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } }) await mount() + await openTab('Podcasts') const chips = [...host.querySelectorAll('.chips .chip')] expect(chips.map(c => c.textContent)).toContain('Salud y fitness') const rows = [...host.querySelectorAll('.mus-rad')] @@ -238,6 +264,7 @@ describe('Música', () => { it('saves a show with the star, and it comes back as a saved row', async () => { stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } }) await mount() + await openTab('Podcasts') const star = [...host.querySelectorAll('.mus-rad-save')].pop() act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) await act(async () => {}) @@ -254,6 +281,7 @@ describe('Música', () => { // Ten minutes in, from a previous session on another device. useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] }, podcasts: { shows: [], progress: { 'ep-1': { pos: 600, dur: 3600, at: Date.now() } } } } })) await act(async () => { root.render(<>) }) + await openTab('Podcasts') const rows = [...host.querySelectorAll('.mus-rad')] act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) }) await act(async () => { await Promise.resolve() }) @@ -276,6 +304,7 @@ describe('Música', () => { show: { feed: 'https://a.example.com/feed', spanish: false, show: { title: 'English Show', language: 'en' }, episodes: [] } }) await act(async () => { root.render(<>) }) + await openTab('Podcasts') const rows = [...host.querySelectorAll('.mus-rad')] act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) }) await act(async () => { await Promise.resolve() }) @@ -285,6 +314,7 @@ describe('Música', () => { it('tells a guest where the podcasts come from, without asking the server', async () => { useStore.setState({ user: null }) await mount() + await openTab('Podcasts') expect(host.textContent).toContain('Podcasts come from your server, so they need a profile') expect(api).not.toHaveBeenCalled() }) @@ -292,9 +322,129 @@ describe('Música', () => { it('says the server is older when it does not offer podcasts yet', async () => { useStore.setState({ config: { features: ['vitals', 'radio'] } }) await mount() + await openTab('Podcasts') expect(host.textContent).toContain('Your server has not been updated for the podcasts yet') // The radio is offered by this server, so it asks; the podcasts are not, so they are not asked // for at all — a chip that 404s is worse than a sentence that explains. expect(api.mock.calls.some(c => String(c[0]).startsWith('/api/podcasts'))).toBe(false) }) + + /* ---------- one list at a time, ten rows at a time, and a search box ---------- */ + + const station = i => ({ + src: 'rb', id: 's' + i, name: 'Emisora ' + i, genre: 'jazz', detail: 'Argentina · MP3', + url: 'https://stream.example.com/' + i, image: null + }) + const moreBtn = () => [...host.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more')) + + it('shows one list at a time, and the tab is what decides which', async () => { + stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1)] }, podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } }) + await mount() + expect(host.textContent).toContain('Emisora 1') + expect(host.querySelectorAll('.mus-rad')).toHaveLength(1) + + await openTab('Podcasts') + // The stations are gone, not merely below the fold: that was the whole complaint about this + // screen — three long lists in one column, with what you wanted at the bottom. + expect(host.textContent).not.toContain('Emisora 1') + expect(host.textContent).toContain('Tiene Sentido') + expect(api.mock.calls.some(c => String(c[0]).startsWith('/api/podcasts'))).toBe(true) + }) + + it('shows ten rows and says how many it is hiding', async () => { + stubApi({ radio: { genres: [], genre: 'workout', stations: Array.from({ length: 25 }, (_, i) => station(i)) } }) + await mount() + expect(host.querySelectorAll('.mus-rad')).toHaveLength(10) + expect(host.textContent).toContain('Emisora 9') + expect(host.textContent).not.toContain('Emisora 10') + expect(moreBtn().textContent).toBe('Show more (15)') + + act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true }))) + await act(async () => {}) + expect(host.querySelectorAll('.mus-rad')).toHaveLength(20) + expect(moreBtn().textContent).toBe('Show more (5)') + + act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true }))) + await act(async () => {}) + expect(host.querySelectorAll('.mus-rad')).toHaveLength(25) + // Nothing left to reveal, so the button is gone rather than sitting there doing nothing. + expect(moreBtn()).toBeUndefined() + }) + + it('pages the episodes of a show too, because forty rows is a wall', async () => { + const episodes = Array.from({ length: 23 }, (_, i) => ({ ...ep({ id: 'ep-' + i, title: 'Episodio ' + i }) })) + stubApi({ + podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] }, + show: { feed: 'https://a.example.com/feed', spanish: true, show: { title: 'Tiene Sentido' }, episodes } + }) + await act(async () => { root.render(<>) }) + await openTab('Podcasts') + const rows = [...host.querySelectorAll('.mus-rad')] + act(() => { rows[rows.length - 1].querySelector('.mus-rad-main').dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + await act(async () => { await Promise.resolve() }) + const sheet = document.querySelector('#modal-root') + expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(10) + const more = [...sheet.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more')) + expect(more.textContent).toBe('Show more (13)') + act(() => more.dispatchEvent(new MouseEvent('click', { bubbles: true }))) + await act(async () => {}) + expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(20) + }) + + it('searches the station directory, not the page it is showing', async () => { + stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1), station(2)] } }) + await mount() + expect(host.querySelectorAll('.mus-rad')).toHaveLength(2) + + api.mockImplementation(path => { + if (String(path).startsWith('/api/radio?q=')) return Promise.resolve({ ok: true, query: 'jazz', stations: [station(7)] }) + return Promise.resolve({ ok: true }) + }) + await type('jazz') + // It asked the server for "jazz" — the answer is every jazz station in the directory, not the + // jazz stations that happened to be in the genre on screen. + expect(api.mock.calls.some(c => c[0] === '/api/radio?q=jazz')).toBe(true) + expect(host.textContent).toContain('Results for “jazz”') + expect(host.textContent).toContain('Emisora 7') + expect(host.textContent).not.toContain('Emisora 1') + // The genre chips step aside: they are for browsing, and this is not browsing. + expect(host.querySelectorAll('.chips .chip')).toHaveLength(0) + }) + + it('searches the podcast directory the same way, and says when there is nothing', async () => { + stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } }) + await mount() + await openTab('Podcasts') + + api.mockImplementation(path => { + if (String(path).startsWith('/api/podcasts?q=')) return Promise.resolve({ ok: true, query: 'zzz', shows: [] }) + return Promise.resolve({ ok: true }) + }) + await type('zzz') + expect(api.mock.calls.some(c => c[0] === '/api/podcasts?q=zzz')).toBe(true) + expect(host.textContent).toContain('No results for “zzz”.') + // A query too short to search is not sent at all: one letter matches everything. + api.mockClear() + await type('z') + expect(api).not.toHaveBeenCalled() + }) + + it('searches the playlists locally, since they are links and not a directory', async () => { + useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day', curator: null })] } } })) + stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } }) + await mount() + await openTab('Playlists') + expect(host.querySelectorAll('.mus-card')).toHaveLength(2) + + await type('push') + expect(host.querySelectorAll('.mus-card')).toHaveLength(1) + expect(host.textContent).toContain('Push Day') + expect(host.textContent).not.toContain('Leg Day') + // No request: this list is in the profile already. + expect(api.mock.calls.some(c => String(c[0]).includes('música'))).toBe(false) + + await type('nada de nada') + expect(host.querySelectorAll('.mus-card')).toHaveLength(0) + expect(host.textContent).toContain('No results for “nada de nada”.') + }) }) diff --git a/website/api.html b/website/api.html index 0532ce9..7e40579 100644 --- a/website/api.html +++ b/website/api.html @@ -1026,8 +1026,14 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon

The audio never passes through this server. The list is the whole feature on this side: the phone then talks to the station directly, so this instance spends no bandwidth and keeps no copy of anything. Sources are SomaFM (commercial-free) and Radio Paradise for the curated picks, and the public radio-browser directory for the rest, filtered to HTTPS and to codecs a browser plays without a library (HLS streams are skipped — that would mean shipping a player library).

A session is required. Not to protect the stations — they are public — but because this container sits on the owner's own network and fetches on behalf of whoever asks.

An unknown or missing genre is not an error: it falls back to the first genre.

+

?q= searches instead of browsing, and it is the same route on purpose: the screen has one list, and what fills it changes. A query is matched against the curated channels and Radio Paradise mixes locally, and the directory is asked by name — ordered by how many people listen, then re-ordered so a station called "Jazz 24" comes before one with "jazz" buried in a forty-character marketing name. A query shorter than two characters is not a search and answers an empty list without asking anybody.

Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.

Query parameters

+
+ q + string (≤ 60 chars) + A name search. Two characters or more; when present, genre is ignored. +
genre "workout" | "techno" | "rnb" | "latin" | "hiphop" | "reggae" | "chill" | "jazz" | "rock" | "electronic" @@ -1039,7 +1045,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
200 - The genres for the chips, and the stations for the one that was asked for.{ ok: boolean, genres: object[], genre: string, label: string, stations: RadioStation[] } + The genres for the chips, and the stations for the one that was asked for.{ ok: boolean, genres: object[], genre: string, label: string, query: string, stations: RadioStation[] }
401 @@ -1111,13 +1117,18 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon "fitness" | "sports" | "comedy" | "news" | "history" | "truecrime" | "science" | "tech" | "society" | "business" | "fiction" | "education" | "music" | "leisure" Category key. Missing or unrecognised falls back to fitness.
+
+ q + string (≤ 80 chars) + A search by name. Two characters or more; when present, category is ignored and the same Spanish-language check runs on the results as on a category's chart entries — a search is not a second, weaker way into the catalogue. +

Responses

200 - The categories for the chips, and the Spanish shows in the one asked for.{ ok: boolean, categories: object[], category: string, label: string, shows: PodcastShow[], skipped: object } + The categories for the chips, and the Spanish shows in the one asked for.{ ok: boolean, categories: object[], category: string, label: string, query: string, shows: PodcastShow[], skipped: object }
401