Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Música tiene una sección **Podcasts**: programas por categoría —Salud y fitness, Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología, Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el directorio de Apple es público. **En español se comprueba, no se supone.** La tienda dice dónde se *vende* un podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada programa (los primeros 64 KB, con una petición `Range`: el idioma está en las primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda: feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué (`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en otro idioma se contesta con `spanish:false` en vez de con una lista vacía. Es la otra mitad de la radio y es lo contrario en todo lo que le importa al reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj; la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo escuchado con el teléfono guardado. Media Session muestra episodio, programa y progreso en la pantalla bloqueada. Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del `enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca posible —un feed vive en cualquier host—, así que la puerta es **https, host real y nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro de una casa. Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES, es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como `spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido. Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están, con radio y podcasts incluidas.
332 lines
17 KiB
JavaScript
332 lines
17 KiB
JavaScript
/* Podcasts, tested without a network: everything here is a filter, a parse or a rule about what may
|
|
be fetched — and those are the three things that decide whether this feature is usable, safe and
|
|
actually in Spanish.
|
|
|
|
The load-bearing rule is the Spanish one. A storefront says a podcast is *sold* in Spain or
|
|
Mexico, and that is not the same as being in Spanish: the Spanish comedy chart carries a Catalan
|
|
show and the Argentine chart carries Joe Rogan. The feed's own `<language>` is the answer, and the
|
|
two edges of it are both tested — `ca` and `en` get dropped, and a feed that declares nothing
|
|
stays, because Spanish feeds do omit the tag and dropping good podcasts over an omission is worse
|
|
than keeping a rare miss.
|
|
|
|
The other rule is what this process will fetch. A feed URL is attacker-influenced data and the api
|
|
container sits on somebody's home network, so loopback, private ranges and `.local` names are
|
|
refused *before* a request is made. */
|
|
import { test } from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
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
|
|
} from '../podcasts.js';
|
|
|
|
/* A stand-in for `fetch`: a body, a status, and the url it ended at. */
|
|
const res = (text, { status = 200, url = undefined } = {}) => ({
|
|
ok: status >= 200 && status < 300, status, url, body: null,
|
|
text: async () => text
|
|
});
|
|
|
|
/* ---------- categories ---------- */
|
|
|
|
test('every category has a label and an Apple genre id, and the keys are unique', () => {
|
|
const keys = categoryList().map(c => c.key);
|
|
assert.equal(new Set(keys).size, keys.length, 'no key twice');
|
|
for (const c of CATEGORIES) {
|
|
assert.ok(c.label.trim(), c.key + ' has a label');
|
|
assert.ok(Number.isInteger(c.genre) && c.genre > 0, c.key + ' has a genre id');
|
|
}
|
|
// The two a gym screen wants first, and Spanish labels — this list is read in Spanish.
|
|
assert.equal(keys[0], 'fitness');
|
|
assert.equal(keys[1], 'sports');
|
|
assert.equal(categoryOf('fitness').label, 'Salud y fitness');
|
|
assert.equal(categoryOf('nope'), null);
|
|
assert.ok(STORES.includes('es') && STORES.includes('mx'));
|
|
});
|
|
|
|
/* ---------- what may be fetched ---------- */
|
|
|
|
test('only a public https host is ever fetched', () => {
|
|
assert.ok(safeFeedUrl('https://feeds.example.com/show.rss'));
|
|
assert.ok(safeFeedUrl('https://example.com/a/b/c'), 'a feed with no extension is still a feed');
|
|
// Anything else is refused, and refused *before* the request — see the spy test below.
|
|
for (const bad of [
|
|
'http://feeds.example.com/show.rss', // plain http: the browser would refuse the audio too
|
|
'https://user:pw@feeds.example.com/x.rss', // credentials in the URL
|
|
'https://localhost/x.rss',
|
|
'https://127.0.0.1/x.rss',
|
|
'https://10.0.0.5/x.rss',
|
|
'https://192.168.1.10/x.rss',
|
|
'https://172.20.3.4/x.rss',
|
|
'https://169.254.169.254/latest/meta-data/', // the cloud metadata address
|
|
'https://100.64.0.1/x.rss', // carrier-grade NAT
|
|
'https://nas.local/x.rss',
|
|
'https://router.internal/x.rss',
|
|
'https://[::1]/x.rss',
|
|
'https://[fd00::1]/x.rss',
|
|
'file:///etc/passwd',
|
|
'not a url',
|
|
'',
|
|
null,
|
|
'https://' + 'a'.repeat(600) + '.com/x.rss' // longer than any real feed URL
|
|
]) assert.equal(safeFeedUrl(bad), null, `${bad} is refused`);
|
|
// The host rule on its own, for the cases a feed URL cannot express.
|
|
assert.equal(publicHost('example.com'), true);
|
|
assert.equal(publicHost('example.com.'), true, 'a trailing dot is the same host');
|
|
assert.equal(publicHost('8.8.8.8'), true, 'a public address literal is allowed');
|
|
assert.equal(publicHost('evil.com.localhost'), false);
|
|
});
|
|
|
|
test('an off-list url is refused without calling fetch at all', async () => {
|
|
let called = 0;
|
|
const fetchImpl = async () => { called++; return res('x') };
|
|
for (const bad of ['http://example.com/x.rss', 'https://127.0.0.1/x.rss', 'https://a.local/x.rss']) {
|
|
assert.equal(await get(bad, { fetchImpl }), null);
|
|
}
|
|
assert.equal(called, 0, 'the gate is inside get, so no caller can forget it');
|
|
});
|
|
|
|
test('a redirect off the allowed shape is refused too', async () => {
|
|
// Where the request ended up is checked, not only where it was pointed: a redirect to the router
|
|
// is otherwise the whole way around the rule.
|
|
const fetchImpl = async () => res('<rss/>', { url: 'https://192.168.1.1/x.rss' });
|
|
assert.equal(await get('https://feeds.example.com/x.rss', { fetchImpl }), null);
|
|
});
|
|
|
|
test('the body is read up to a cap and then dropped', async () => {
|
|
clearPodcastCache();
|
|
const huge = 'x'.repeat(5000);
|
|
assert.equal((await readCapped(res(huge), 100)).length, 100);
|
|
// A server that ignores Range hands us a real stream: it must be cut, not buffered whole.
|
|
const streamed = await readCapped(new Response('y'.repeat(200000)), 1000);
|
|
assert.equal(streamed.length, 1000);
|
|
});
|
|
|
|
/* ---------- Spanish only ---------- */
|
|
|
|
test('a Spanish language tag is what keeps a show, and the edges are both tested', () => {
|
|
for (const yes of ['es', 'es-ES', 'es-es', 'ES', 'es-419', 'es-MX', 'spa']) {
|
|
assert.equal(isSpanish(yes), true, yes + ' is Spanish');
|
|
}
|
|
for (const no of ['ca', 'ca-ES', 'en', 'en-US', 'pt', 'pt-BR', 'gl', 'eu', 'est', 'de']) {
|
|
assert.equal(isSpanish(no), false, no + ' is not Spanish');
|
|
}
|
|
// No tag at all is a "maybe": kept, because genuinely Spanish feeds omit it and the storefront is
|
|
// the fallback signal. See the header of api/podcasts.js.
|
|
assert.equal(isSpanish(null), true);
|
|
assert.equal(isSpanish(''), true);
|
|
});
|
|
|
|
test('the language tag is read out of a feed, CDATA and all', () => {
|
|
assert.equal(languageOf('<channel><language>es-ES</language><item/></channel>'), 'es-es');
|
|
assert.equal(languageOf('<language><![CDATA[es]]></language>'), 'es');
|
|
assert.equal(languageOf('<language>\n es-419\n</language>'), 'es-419');
|
|
assert.equal(languageOf('<channel><title>x</title></channel>'), null);
|
|
assert.equal(languageOf(null), null);
|
|
});
|
|
|
|
test('a feed that declares another language never reaches the list', async () => {
|
|
clearPodcastCache();
|
|
// The four cases, in one category: Spanish, no tag, Catalan, English — plus a feed that is down.
|
|
const langs = {
|
|
'https://a.example.com/feed': '<language>es-ES</language>',
|
|
'https://b.example.com/feed': '<title>sin etiqueta</title>',
|
|
'https://c.example.com/feed': '<language>ca</language>',
|
|
'https://d.example.com/feed': '<language>en-US</language>'
|
|
};
|
|
const fetchImpl = async url => {
|
|
if (url.includes('/rss/toppodcasts/')) {
|
|
const country = url.includes('/mx/') ? 'mx' : 'es';
|
|
return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': country + '1' } } }] } }), { url });
|
|
}
|
|
if (url.includes('/lookup')) {
|
|
const country = url.split('country=')[1];
|
|
const rows = [1, 2, 3, 4, 5].map(n => ({
|
|
collectionId: `${country}${n}`,
|
|
collectionName: `${country} show ${n}`,
|
|
artistName: 'Alguien',
|
|
artworkUrl600: 'https://img.example.com/x.jpg',
|
|
primaryGenreName: 'Comedy',
|
|
feedUrl: ['https://a.example.com/feed', 'https://b.example.com/feed', 'https://c.example.com/feed', 'https://d.example.com/feed', 'https://down.example.com/feed'][n - 1]
|
|
}));
|
|
return res(JSON.stringify({ results: rows }), { url });
|
|
}
|
|
if (langs[url]) return res(langs[url], { status: url.startsWith('https://b.') ? 200 : 206, url });
|
|
return res('', { status: 500, url });
|
|
};
|
|
const { category, shows, skipped } = await showsFor('comedy', { fetchImpl });
|
|
assert.equal(category.key, 'comedy');
|
|
// Each reason is a number, so "dropped for language" cannot pass for "the fetch blew up".
|
|
assert.equal(skipped.language, 2, 'Catalan and English');
|
|
assert.equal(skipped.unreadable, 1, 'the feed that is down');
|
|
assert.equal(skipped.failed, 0, 'nothing threw');
|
|
assert.equal(skipped.duplicate, 5, 'the second storefront listed the same five feeds');
|
|
const names = shows.map(s => s.name);
|
|
assert.ok(names.includes('es show 1'), 'Spanish kept');
|
|
assert.ok(names.includes('es show 2'), 'no tag kept');
|
|
assert.ok(!names.includes('es show 3'), 'Catalan dropped');
|
|
assert.ok(!names.includes('es show 4'), 'English dropped');
|
|
assert.ok(!names.includes('es show 5'), 'a feed that is down is not a row that cannot play');
|
|
assert.equal(shows[0].lang, 'es-es');
|
|
assert.equal(shows[1].lang, null);
|
|
// One row per feed even though both storefronts listed the same five shows.
|
|
assert.equal(new Set(shows.map(s => s.feed)).size, shows.length);
|
|
assert.ok(shows.length <= MAX_SHOWS);
|
|
});
|
|
|
|
test('a feed that cannot be read is not Spanish-by-default', async () => {
|
|
clearPodcastCache();
|
|
const fetchImpl = async url => {
|
|
if (url.includes('/rss/')) return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': '1' } } }] } }), { url });
|
|
if (url.includes('/lookup')) return res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'S', feedUrl: 'https://a.example.com/feed' }] }), { url });
|
|
return res('', { status: 503, url });
|
|
};
|
|
assert.equal(await feedLanguage('https://a.example.com/feed', { fetchImpl }), null);
|
|
const { shows, skipped } = await showsFor('comedy', { fetchImpl });
|
|
assert.deepEqual(shows, []);
|
|
assert.equal(skipped.unreadable, 1, 'unreadable, by that rule and not by an accident');
|
|
assert.equal(skipped.failed, 0, 'and not by an exception the pool swallowed');
|
|
});
|
|
|
|
test('the language check reads the head of the feed, not the whole archive', async () => {
|
|
clearPodcastCache();
|
|
let asked = null;
|
|
const fetchImpl = async (url, opts) => { asked = opts.headers.Range; return res('<language>es</language>', { status: 206, url }) };
|
|
assert.deepEqual(await feedLanguage('https://a.example.com/feed', { fetchImpl }), { lang: 'es', ok: true });
|
|
assert.equal(asked, 'bytes=0-65535');
|
|
});
|
|
|
|
/* ---------- the directory rows ---------- */
|
|
|
|
test('a show is kept only when it has a feed this process will fetch', () => {
|
|
const base = { collectionId: 12, collectionName: 'Un podcast', feedUrl: 'https://a.example.com/feed' };
|
|
assert.equal(showFrom(base, 'es').feed, 'https://a.example.com/feed');
|
|
assert.equal(showFrom(base, 'es').country, 'es');
|
|
assert.equal(showFrom({ ...base, feedUrl: 'http://a.example.com/feed' }, 'es'), null, 'http feed');
|
|
assert.equal(showFrom({ ...base, feedUrl: 'https://10.0.0.1/feed' }, 'es'), null, 'private host');
|
|
assert.equal(showFrom({ ...base, feedUrl: null }, 'es'), null, 'no feed at all');
|
|
assert.equal(showFrom({ ...base, collectionName: ' ' }, 'es'), null, 'no name');
|
|
// An http artwork is dropped rather than shown broken.
|
|
assert.equal(showFrom({ ...base, artworkUrl600: 'http://img/x.jpg' }, 'es').image, null);
|
|
assert.equal(chartEntries({ feed: { entry: [{ id: { attributes: { 'im:id': '7' } } }, { id: {} }] } }).length, 1);
|
|
assert.deepEqual(chartEntries({}), []);
|
|
});
|
|
|
|
/* ---------- the feed ---------- */
|
|
|
|
const feed = ({ items, extra = '' }) => `<?xml version="1.0" encoding="UTF-8"?>
|
|
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
|
|
<channel>
|
|
<title>Nadie Sabe Nada</title>
|
|
<language>es-ES</language>
|
|
<itunes:author>Cadena SER</itunes:author>
|
|
<itunes:image href="https://img.example.com/nsn.jpg"/>
|
|
${extra}
|
|
${items}
|
|
</channel></rss>`;
|
|
|
|
const item = ({ title = 'Un episodio', date = 'Tue, 02 Sep 2025 10:00:00 GMT', dur = '00:52:15', enc = '<enclosure url="https://audio.example.com/1.mp3" type="audio/mpeg" length="12345678"/>', guid = 'ep-1', extra = '' }) =>
|
|
`<item><title>${title}</title><description><![CDATA[<p>bla</p>]]></description>
|
|
<pubDate>${date}</pubDate><itunes:duration>${dur}</itunes:duration><guid>${guid}</guid>${enc}${extra}</item>`;
|
|
|
|
test('a duration is read in all three shapes feeds use', () => {
|
|
assert.equal(parseDuration('00:52:15'), 3135);
|
|
assert.equal(parseDuration('4847'), 4847);
|
|
assert.equal(parseDuration('1:02:03'), 3723);
|
|
assert.equal(parseDuration('12:30'), 750);
|
|
assert.equal(parseDuration(''), null);
|
|
assert.equal(parseDuration(null), null);
|
|
assert.equal(parseDuration('una hora'), null);
|
|
assert.equal(parseDuration('1:2:3:4'), null);
|
|
});
|
|
|
|
test('titles come out with CDATA unwrapped and entities decoded', () => {
|
|
assert.equal(decodeEntities('Rock & Roll — 4 < 5'), 'Rock & Roll — 4 < 5');
|
|
assert.equal(tagText('<title><![CDATA[324. La Ruina & Co]]></title>', 'title'), '324. La Ruina & Co');
|
|
assert.equal(tagAttr('<enclosure type="audio/mpeg" url="https://x/1.mp3"/>', 'enclosure', 'url'), 'https://x/1.mp3');
|
|
assert.equal(tagAttr('<enclosure type="audio/mpeg"/>', 'enclosure', 'url'), '');
|
|
});
|
|
|
|
test('an item with nothing to play is not an episode', () => {
|
|
const opts = { image: 'https://img.example.com/show.jpg' };
|
|
// A video enclosure: this player has no picture.
|
|
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://v.example.com/1.mp4" type="video/mp4"/>' }), opts), null);
|
|
// A subscriber-only episode has no enclosure at all.
|
|
assert.equal(episodeFrom(item({ enc: '' }), opts), null, 'no enclosure');
|
|
// No type, but an audio file: kept, because plenty of feeds omit the type.
|
|
const noType = episodeFrom(item({ enc: '<enclosure url="https://audio.example.com/1.mp3"/>' }), opts);
|
|
assert.equal(noType.url, 'https://audio.example.com/1.mp3');
|
|
// No type and not an audio file: refused.
|
|
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://docs.example.com/notes.pdf"/>' }), opts), null);
|
|
// http audio would be blocked by the browser on an https page.
|
|
assert.equal(episodeFrom(item({ enc: '<enclosure url="http://audio.example.com/1.mp3" type="audio/mpeg"/>' }), opts), null);
|
|
assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
|
|
const ep = episodeFrom(item({ extra: '<itunes:episode>14</itunes:episode>' }), opts);
|
|
assert.equal(ep.episode, 14);
|
|
assert.equal(ep.duration, 3135);
|
|
assert.equal(ep.image, 'https://img.example.com/show.jpg', 'falls back to the channel image');
|
|
assert.equal(ep.bytes, 12345678);
|
|
});
|
|
|
|
test('a feed becomes a show with its episodes, newest first', () => {
|
|
const text = feed({
|
|
items: [
|
|
item({ title: 'Viejo', date: 'Mon, 01 Sep 2025 10:00:00 GMT', guid: 'a' }),
|
|
item({ title: 'Nuevo', date: 'Wed, 03 Sep 2025 10:00:00 GMT', guid: 'b' }),
|
|
item({ title: 'Sin fecha', date: '', guid: 'c' })
|
|
]
|
|
});
|
|
const { show, episodes } = parseFeed(text);
|
|
assert.equal(show.title, 'Nadie Sabe Nada');
|
|
assert.equal(show.author, 'Cadena SER');
|
|
assert.equal(show.language, 'es-es');
|
|
assert.equal(show.image, 'https://img.example.com/nsn.jpg');
|
|
assert.deepEqual(episodes.map(e => e.title), ['Nuevo', 'Viejo', 'Sin fecha']);
|
|
assert.equal(episodes.length, show.episodes);
|
|
});
|
|
|
|
test('a feed truncated by the cap loses its last item and nothing else', () => {
|
|
// The body was cut mid-item: the parser must not invent a half episode, and must not throw.
|
|
const text = feed({ items: item({ title: 'Uno', guid: 'a' }) }) + '<item><title>Dos a medias</title><enclosure url="https://a.example.com/2.mp3" type="audio/mpeg"';
|
|
const { episodes } = parseFeed(text);
|
|
assert.deepEqual(episodes.map(e => e.title), ['Uno']);
|
|
});
|
|
|
|
test('a show with no title of its own takes the directory name', () => {
|
|
const { show, episodes } = parseFeed('<rss><channel><language>es</language>' + item({}) + '</channel></rss>', { fallbackTitle: 'Desde Apple' });
|
|
assert.equal(show.title, 'Desde Apple');
|
|
assert.equal(episodes.length, 1);
|
|
});
|
|
|
|
test('the list of episodes is capped, and duplicates are one episode', () => {
|
|
const many = Array.from({ length: MAX_EPISODES + 5 }, (_, i) => item({ title: 'E' + i, guid: 'g' + i }));
|
|
assert.equal(parseFeed(feed({ items: many })).episodes.length, MAX_EPISODES);
|
|
const twice = item({ title: 'Repetido', guid: 'same' }) + item({ title: 'Repetido (otra vez)', guid: 'same' });
|
|
assert.deepEqual(parseFeed(feed({ items: twice })).episodes.map(e => e.title), ['Repetido']);
|
|
});
|
|
|
|
/* ---------- the whole way through ---------- */
|
|
|
|
test('episodesFor refuses an unsafe feed and parses a real one', async () => {
|
|
clearPodcastCache();
|
|
assert.equal(await episodesFor('http://a.example.com/feed'), null);
|
|
assert.equal(await episodesFor('https://10.0.0.1/feed'), null);
|
|
const fetchImpl = async url => res(feed({ items: item({}) }), { url });
|
|
const got = await episodesFor('https://a.example.com/feed', { fetchImpl, title: 'De Apple' });
|
|
assert.equal(got.feed, 'https://a.example.com/feed');
|
|
assert.equal(got.show.title, 'Nadie Sabe Nada');
|
|
assert.equal(got.episodes[0].url, 'https://audio.example.com/1.mp3');
|
|
// An unreadable feed is null, not an exception. A different URL, because the parsed feed above is
|
|
// cached for half an hour on purpose — that cache is what keeps a big feed from being downloaded
|
|
// again every time somebody opens the show.
|
|
assert.equal(await episodesFor('https://b.example.com/feed', { fetchImpl: async () => res('', { status: 500 }), title: 'x' }), null);
|
|
});
|
|
|
|
test('the pool keeps the order and never throws out of itself', async () => {
|
|
const out = await mapLimit([1, 2, 3, 4, 5], 2, async n => {
|
|
if (n === 3) throw new Error('boom');
|
|
return n * 2;
|
|
});
|
|
assert.deepEqual(out, [2, 4, null, 8, 10]);
|
|
});
|