/* podcasts.js — Spanish-language podcasts, browsed by category, played as files. * * Radio and podcasts are the two halves of "something to listen to while training", and they are * opposites in every way that matters to this code: * * - Radio is a **stream**: endless, no position, and every station is a channel somebody else is * programming. Nothing about it is stored. * - A podcast is a **file**: it has a beginning and an end, it is worth resuming where you left * it, and skipping back fifteen seconds is the most-used button in every podcast app ever made. * * So this module answers a different question — *which file* — and the player has to do more with * the answer than it does for a station. * * ## Where the list comes from, and why there is no API key * * Apple's podcast directory, through two public endpoints that need no key and no account: the * storefront **top charts** (`//rss/toppodcasts/limit=N/genre=/json`) and * `lookup?id=…` for what the charts omit — above all the **feed URL**, which is the only field that * really matters, because the episodes come from the publisher's own RSS and from nowhere else. * * One consequence is deliberate: **no audio passes through here.** An episode is an `https://` URL * in the publisher's enclosure, handed to the phone; the bytes go from the publisher to the phone. * What this server contributes is the list, the same bargain the radio makes. * * ## "Spanish only" is checked, not assumed * * A storefront says a podcast is *sold* in Spain or Mexico, which is not the same as being in * Spanish, and the difference shows: the Spanish comedy chart carries a Catalan show and the * Argentine one carries an English one. The authoritative answer is in the feed, in ``, * so every show is checked: * * - `feedLanguage()` reads the **first 64 KB** with a `Range` request. `` is channel * metadata that sits in the first ~1.5 KB of every feed looked at, always before the first * ``, so a 64 KB slice answers the question and a 5 MB feed does not have to be downloaded * to ask it. * - `es` / `es-ES` / `es-419` / `spa` keeps the show; `ca`, `en`, `pt` and the rest are dropped. * - **A feed with no tag at all keeps its place.** Genuinely Spanish feeds do omit it (La Ruina is * one), and dropping them over an omission would quietly remove good podcasts; the storefront is * the fallback signal, and it is not a guess. * * ## What may be fetched * * Radio has a host allowlist because it only ever talks to three services. Podcasts cannot: feeds * live on every host in the world. So the rule is the other one, and it is the rule that matters for * an api container sitting on somebody's home network: * * - **https only**, no credentials in the URL, a real hostname, and **never a private address** — * no loopback, no `10.`/`192.168.`/`172.16-31.`, no link-local, no IPv6 literals, no `.local` or * `.internal`. A feed URL is attacker-influenced data, and an api that fetches whatever it is * handed is how a home network gets mapped from the outside. * - The check is applied to the URL **and again to where the request ended up**, because a * redirect is otherwise the way around it — the lesson music.js learned with Apple's CDN. * - Bodies are read with a cap and the connection is dropped when it is reached: podcast feeds are * routinely several megabytes, and one of them is not allowed to be an out-of-memory bug. */ const UA = 'KuentaGYM (self-hosted)'; const TIMEOUT_MS = 12000; const CACHE_MS = 30 * 60 * 1000; /** `` lives in the first couple of KB; 64 KB is generous and still one round trip. */ const LANG_HEAD_BYTES = 64 * 1024; /** A cap, not a target: the largest feeds seen are ~5 MB, and a truncated one still parses. */ const MAX_FEED_BYTES = 6 * 1024 * 1024; const MAX_URL = 600; const CHART_LIMIT = 25; /* How many candidates to language-check per category, and how many at a time. * * The check is one request per show (see below), so this pair is the whole cost of a category: a * cold list of twenty Spanish shows needs roughly twenty-six checks, and with a pool of ten that is * three rounds of latency rather than twenty-six of them. Ten at once to twenty different * publishers is also about as far as politeness goes: they are other people's servers, and they are * paying for the bandwidth of being listed. */ const CHECK_LIMIT = 26; const POOL = 10; export const MAX_SHOWS = 20; export const MAX_EPISODES = 40; /** Spain and Mexico: between them, most of what is published in Spanish. */ export const STORES = Object.freeze(['es', 'mx']); /* The categories, as the chips the screen draws. * * Apple's own genre ids with Spanish labels, which is the whole trick: an id is stable and the chart * is per id, so a category is one number rather than a search term whose results drift week to week. * Ordered so the two a gym screen actually wants come first. */ export const CATEGORIES = Object.freeze([ { key: 'fitness', label: 'Salud y fitness', genre: 1512 }, { key: 'sports', label: 'Deporte', genre: 1545 }, { key: 'comedy', label: 'Comedia', genre: 1303 }, { key: 'news', label: 'Noticias', genre: 1489 }, { key: 'history', label: 'Historia', genre: 1487 }, { key: 'truecrime', label: 'Crímenes reales', genre: 1488 }, { key: 'science', label: 'Ciencia', genre: 1533 }, { key: 'tech', label: 'Tecnología', genre: 1318 }, { key: 'society', label: 'Sociedad y cultura', genre: 1324 }, { key: 'business', label: 'Negocios', genre: 1321 }, { key: 'fiction', label: 'Ficción', genre: 1483 }, { key: 'education', label: 'Educación', genre: 1304 }, { key: 'music', label: 'Música', genre: 1310 }, { key: 'leisure', label: 'Ocio', genre: 1502 } ]); /** The categories the screen offers, with their labels. */ export const categoryList = () => CATEGORIES.map(c => ({ key: c.key, label: c.label })); /** One category by key, or null. An unknown key falls back to the first one at the route. */ export const categoryOf = key => CATEGORIES.find(c => c.key === String(key || '')) || null; /* ---------- fetching, with the one rule ---------- */ const IPV4_PRIVATE = [ /^0\./, /^10\./, /^127\./, /^169\.254\./, /^192\.168\./, /^172\.(1[6-9]|2\d|3[01])\./, /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./ ]; /** A hostname this process may talk to: public, named, and not a device in the same house. */ export function publicHost(hostname) { const h = String(hostname || '').toLowerCase().replace(/\.$/, ''); if (!h || h === 'localhost' || h.endsWith('.localhost')) return false; if (h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.home.arpa')) return false; // IPv6 literals (`::1`, `fe80::`, `fc00::/7`) arrive bracketed from URL.hostname; none of them is // worth the address parsing a list of hostnames would need. if (h.includes(':')) return false; if (IPV4_PRIVATE.some(re => re.test(h))) return false; if (/^\d+\.\d+\.\d+\.\d+$/.test(h)) return true; // a public IPv4 literal, allowed return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(h); // a real, dotted hostname } /** * The URL of a feed this module will fetch: https, no credentials, a public host, and short enough * to be a URL rather than a payload. Exported because the rule is worth testing on its own. */ export function safeFeedUrl(url) { if (typeof url !== 'string' || !url.length || url.length > MAX_URL) return null; let u; try { u = new URL(url); } catch { return null } if (u.protocol !== 'https:') return null; if (u.username || u.password) return null; if (!publicHost(u.hostname)) return null; u.hash = ''; return u.toString(); } /* One function fetches, so the rule above is one rule in one place rather than a check each caller has to remember — the shape radio.js settled on after a mutation showed a stray fetch slipping past the allowlist. */ export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {}, max = MAX_FEED_BYTES } = {}) { const safe = safeFeedUrl(url); if (!safe) return null; try { const r = await fetchImpl(safe, { headers: { 'User-Agent': UA, ...headers }, signal: AbortSignal.timeout(timeoutMs) }); if (!r.ok && r.status !== 206) return null; // Where we ended up, not only where we were pointed: a redirect is otherwise the way around the // rule above. if (r.url && !safeFeedUrl(r.url)) return null; return await readCapped(r, max); } catch { return null } } /** * A body, up to `max` bytes, with the connection dropped as soon as the cap is reached. * * `res.text()` on a five-megabyte feed is how a feed reader becomes an out-of-memory bug, and a * server that ignores the `Range` header we send for the language check would otherwise hand us a * whole archive to read the first kilobyte of. */ export async function readCapped(res, max) { const reader = res.body?.getReader?.(); if (!reader) return String(await res.text().catch(() => '')).slice(0, max); const decoder = new TextDecoder(); let text = ''; let bytes = 0; try { for (;;) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; text += decoder.decode(value, { stream: true }); if (bytes >= max) { await reader.cancel().catch(() => {}); break } } } catch { /* a feed that dies mid-body still has a usable beginning */ } // The cap is applied to the text as well as to the loop: a body streamed in one big chunk would // otherwise be fully decoded before the check below ever ran. return text.slice(0, max); } /* The cache, with a ceiling. * * Every entry here is small on purpose — a language tag, a parsed episode list — but "small" times * an unbounded number of feed URLs is still a leak on a box with 1 GB of RAM, so the oldest entries * go when there are too many. Nothing depends on an entry still being there: a miss is a refetch. */ const CACHE_MAX = 400; let cache = new Map(); function cached(key, ms, fn) { const hit = cache.get(key); if (hit && Date.now() - hit.at < ms) return hit.value; const value = Promise.resolve().then(fn).catch(() => null); cache.set(key, { at: Date.now(), value }); if (cache.size > CACHE_MAX) { for (const k of [...cache.keys()].slice(0, cache.size - CACHE_MAX)) cache.delete(k); } return value; } /** Only for tests: forget everything fetched. */ export function clearPodcastCache() { cache = new Map() } /* ---------- the directory ---------- */ const apple = path => 'https://itunes.apple.com' + path; /** The rows of a storefront chart: the ids, which is all a chart is good for. */ export function chartEntries(json) { const entries = json && json.feed && json.feed.entry; if (!Array.isArray(entries)) return []; return entries .map(e => ({ id: String(e?.id?.attributes?.['im:id'] || '') })) .filter(e => e.id); } /** * One show out of a `lookup` result. * * `feedUrl` is the field that matters; the rest is decoration the chart already carried, and the * lookup is here only because the chart does not carry the feed. */ export function showFrom(row, country) { const feed = safeFeedUrl(row?.feedUrl); if (!feed) return null; const name = String(row?.collectionName || '').trim(); if (!name) return null; const art = [row?.artworkUrl600, row?.artworkUrl100].find(u => /^https:\/\//i.test(u || '')) || null; return { id: String(row?.collectionId || feed), feed, name: name.slice(0, 120), author: String(row?.artistName || '').trim().slice(0, 80), image: art, genre: String(row?.primaryGenreName || '').trim().slice(0, 40), country: String(country || row?.country || '').toLowerCase() }; } /** The storefront chart ids for a genre, cached for half an hour. */ export async function chartIds(country, genre, { fetchImpl = fetch } = {}) { return cached(`chart:${country}:${genre}`, CACHE_MS, async () => { const text = await get(apple(`/${country}/rss/toppodcasts/limit=${CHART_LIMIT}/genre=${genre}/json`), { fetchImpl }); if (!text) return []; try { return chartEntries(JSON.parse(text)).map(e => e.id) } catch { return [] } }); } /** The details for a set of ids, in one request: `lookup` takes a comma-separated list. */ export async function lookupShows(ids, country, { fetchImpl = fetch } = {}) { if (!ids.length) return []; return cached(`lookup:${country}:${ids.join(',')}`, CACHE_MS, async () => { const text = await get(apple(`/lookup?id=${ids.join(',')}&country=${country}`), { fetchImpl }); if (!text) return []; try { const json = JSON.parse(text); return (json.results || []).map(r => showFrom(r, country)).filter(Boolean); } catch { return [] } }); } /* ---------- the language check ---------- */ /** `es`, `es-ES`, `es-419` and `spa` are Spanish; `ca`, `en`, `et` are not; nothing is a "maybe". */ export function isSpanish(lang) { const l = String(lang || '').trim().toLowerCase(); if (!l) return true; return /^(es|spa)(\b|[_-])/.test(l); } /** `` out of a feed, CDATA and all. */ export function languageOf(text) { const m = /\s*(?: { const head = await get(url, { fetchImpl, max: LANG_HEAD_BYTES, headers: { Range: `bytes=0-${LANG_HEAD_BYTES - 1}` } }); if (head == null || head === '') return null; return { lang: languageOf(head), ok: true }; }); } /** Run `fn` over `items` with a small pool, keeping the order and never throwing out of the pool. */ export async function mapLimit(items, limit, fn) { const out = new Array(items.length).fill(null); let next = 0; const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => { for (;;) { const i = next++; if (i >= items.length) return; try { out[i] = await fn(items[i], i) } catch { out[i] = null } } }); await Promise.all(workers); return out; } /** * The shows of one category: the storefront charts, their feeds, and only the Spanish ones. * * The per-show cost is one 64 KB ranged request, so this is not free — the whole answer is cached * for half an hour, which is what makes a category chip a tap rather than a wait. */ export async function showsFor(genreKey, { fetchImpl = fetch } = {}) { const category = categoryOf(genreKey) || CATEGORIES[0]; const perStore = await Promise.all(STORES.map(async country => { const ids = await chartIds(country, category.genre, { fetchImpl }); return lookupShows(ids, country, { fetchImpl }); })); // Interleaved rather than one storefront after the other: the two countries publish different // podcasts, and a list that shows twenty Spanish ones before the first Mexican one is not a list // of what is out there. 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 { 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(); 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' }; seen.add(show.feed); const lang = await feedLanguage(show.feed, { fetchImpl }); if (!lang) return { skip: 'unreadable' }; if (!isSpanish(lang.lang)) return { skip: 'language' }; return { show: { ...show, lang: lang.lang || null } }; }); const shows = []; for (const r of results) { // A null is an error the pool caught: counted as a failure rather than passing for a show that // was filtered on purpose. if (!r) { skipped.failed++; continue } if (r.skip) { skipped[r.skip]++; continue } shows.push(r.show); if (shows.length >= limit) break; } 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 ---------- */ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }; const safeCodePoint = n => (Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : ''); /** Named and numeric entities — not a parser, a decoder for what titles actually contain. */ export function decodeEntities(text) { return String(text == null ? '' : text) .replace(/&#x([0-9a-f]+);/gi, (_, hex) => safeCodePoint(parseInt(hex, 16))) .replace(/&#(\d+);/g, (_, dec) => safeCodePoint(parseInt(dec, 10))) .replace(/&([a-z]+);/gi, (m, name) => (name.toLowerCase() in ENTITIES ? ENTITIES[name.toLowerCase()] : m)); } /** The text of a tag, CDATA unwrapped, entities decoded, whitespace collapsed. */ export function tagText(item, tag) { const m = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)`, 'i').exec(String(item || '')); if (!m) return ''; return decodeEntities(m[1].replace(//g, '$1')).replace(/\s+/g, ' ').trim(); } /** One attribute of the first matching tag, whatever order the feed wrote its attributes in. */ export function tagAttr(item, tag, attr) { const m = new RegExp(`<${tag}(\\s[^>]*)>`, 'i').exec(String(item || '')); if (!m) return ''; const a = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`, 'i').exec(m[1]); return a ? decodeEntities(a[1]).trim() : ''; } /** * A duration in seconds, from the three shapes feeds actually use. * * `itunes:duration` is free text: `00:52:15` on one feed, the bare `4847` on the next, `1:02:03` on * a third — all three seen in one afternoon of Spanish comedy charts. A bare number is seconds; * anything with colons is h:mm:ss or m:ss. */ export function parseDuration(value) { const v = String(value == null ? '' : value).trim(); if (!v) return null; if (/^\d+$/.test(v)) return Number(v); const parts = v.split(':').map(p => Number(p.trim())); if (parts.length < 2 || parts.length > 3) return null; if (parts.some(n => !Number.isFinite(n) || n < 0)) return null; return parts.length === 3 ? parts[0] * 3600 + parts[1] * 60 + parts[2] : parts[0] * 60 + parts[1]; } const AUDIO_EXT = /\.(mp3|m4a|m4b|aac|ogg|oga|opus|mp4)(\?|#|$)/i; /** * One `` into an episode, or null when there is nothing to play. * * The enclosure *is* the podcast: an item without a public audio file is a trailer, a * subscriber-only episode or a video — three kinds of row that would play silence or nothing. The * `type` attribute is trusted when it is there and the file extension when it is not, and a video * enclosure is refused either way, because this player has no picture. */ export function episodeFrom(item, { image = null } = {}) { const url = tagAttr(item, 'enclosure', 'url'); if (!/^https:\/\//i.test(url)) return null; const type = tagAttr(item, 'enclosure', 'type').toLowerCase(); if (type ? !/^audio\//.test(type) : !AUDIO_EXT.test(url)) return null; const title = tagText(item, 'title'); if (!title) return null; const date = Date.parse(tagText(item, 'pubDate')); const num = Number(tagText(item, 'itunes:episode')); const art = tagAttr(item, 'itunes:image', 'href'); const bytes = Number(tagAttr(item, 'enclosure', 'length')); return { id: (tagText(item, 'guid') || url).slice(0, 200), title: title.slice(0, 200), url, date: Number.isFinite(date) ? new Date(date).toISOString() : null, duration: parseDuration(tagText(item, 'itunes:duration')), image: /^https:\/\//i.test(art) ? art : image, episode: Number.isFinite(num) && num > 0 ? num : null, bytes: Number.isFinite(bytes) && bytes > 0 ? bytes : null }; } /** * A feed into a show and its episodes. * * Deliberately tolerant, because feeds are the wild west and a rejected feed is a podcast nobody can * play: a body truncated by the cap above simply loses its last, unterminated item, and a channel * that declares no title falls back to whatever the directory called it. */ export function parseFeed(text, { fallbackTitle = '', fallbackImage = null } = {}) { const src = String(text || ''); const first = src.search(/]/i); const head = first < 0 ? src : src.slice(0, first); const items = src.match(/][\s\S]*?(?:<\/item>|$)/gi) || []; const image = tagAttr(head, 'itunes:image', 'href') || tagAttr(head, 'image', 'url') || fallbackImage; const episodes = []; const seen = new Set(); for (const item of items) { // The last item of a truncated feed has no closing tag; half an episode is not an episode. if (!/<\/item>/i.test(item)) continue; const ep = episodeFrom(item, { image }); if (!ep || seen.has(ep.id)) continue; seen.add(ep.id); episodes.push(ep); } /* Newest first, by date when the feed gave one: a feed ordered by hand, or by an editorial calendar, is not the one you want at the top of a list sorted by nothing. */ episodes.sort((a, b) => (Date.parse(b.date || '') || 0) - (Date.parse(a.date || '') || 0)); return { show: { title: tagText(head, 'title') || fallbackTitle, author: tagText(head, 'itunes:author'), image: image || null, language: languageOf(src), episodes: episodes.length }, episodes: episodes.slice(0, MAX_EPISODES) }; } /** * One show with its episodes, straight from the publisher's feed. * * The feed URL is data from a directory rather than something a browser typed, and it is put through * `safeFeedUrl` again here — the api container is on somebody's network, so the rule is re-applied * at every use and not only where the URL first appeared. * * The parsed language is returned rather than enforced, so the route can say *why* a feed was * refused instead of answering "not found" to a Spanish user holding an English feed. */ export async function episodesFor(feed, { fetchImpl = fetch, title = '', image = null } = {}) { const url = safeFeedUrl(feed); if (!url) return null; /* The *parsed* feed is cached, never its text: a feed is up to six megabytes and forty episodes are a few kilobytes, so caching the body would be the whole memory budget for nothing. */ const parsed = await cached('feed:' + url, CACHE_MS, async () => { const text = await get(url, { fetchImpl }); if (!text) return null; const p = parseFeed(text); return p.episodes.length ? p : null; }); if (!parsed) return null; return { feed: url, show: { ...parsed.show, // The directory's name and artwork are only a fallback for a channel that declares neither. title: parsed.show.title || title || 'Podcast', image: parsed.show.image || (/^https:\/\//i.test(image || '') ? image : null) }, episodes: parsed.episodes }; }