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.
414 lines
21 KiB
JavaScript
414 lines
21 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, searchShows, appleSearch, normQuery
|
|
} 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]);
|
|
});
|
|
|
|
/* ---------- 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('<language>es-ES</language>', { status: 206, url });
|
|
if (url === 'https://feeds.example.com/mx') return res('<language>en</language>', { 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('<language>es</language>', { 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('<language>es</language>', { 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');
|
|
});
|