diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a794dd..f0a5809 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,47 @@
# Changelog
+## 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,
+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**. Sólo
+en español, y eso se **comprueba**: la tienda de Apple 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 `` del propio feed de cada programa (los primeros 64 KB, con una petición
+`Range`, porque el idioma está en las primeras líneas) y se descarta lo que no sea español. Un feed
+que no declara idioma se queda: feeds genuinamente españoles lo omiten, y tirarlos por una omisión
+sería sacar podcasts buenos de la lista. La respuesta dice cuántos quedaron afuera y por qué, así que
+una lista corta nunca es un misterio.
+
+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 exacto en el que ibas—. Por eso la barra crece
+una línea de progreso, **−15 s** y **+30 s**, un botón de siguiente episodio y el reloj
+(`12:31 / 52:15`), y por eso la posición se guarda **por perfil**: cada episodio se retoma donde
+estaba, se marca escuchado a veinte segundos del final (y si lo abrís de nuevo, empieza de nuevo en
+vez de arrancar en los últimos segundos), y al terminar sigue con el que viene. Lo que suena con la
+pantalla bloqueada muestra en la pantalla de bloqueo el episodio, el programa y **cuánto llevás**,
+porque la posición también va a Media Session.
+
+Nada de esto pasa por tu servidor: un episodio llega como la URL del `enclosure` del feed, el
+teléfono la reproduce y el audio va del que publica al teléfono. **No se descarga nada y no queda
+ninguna copia.** Lo que sí cuesta son peticiones: el directorio de Apple (sin clave ni cuenta), una
+petición de 64 KB por programa para leer su idioma, y un feed por programa cuando lo abrís —cacheado
+media hora, y se guarda **parseado**, nunca el cuerpo: cuarenta episodios son unos kilobytes y un
+feed son megabytes.
+
+Y una regla nueva, porque acá no hay lista blanca posible: un feed vive en cualquier host del mundo,
+así que la puerta es **https, host real y nunca una dirección privada** —nada de loopback,
+`10.`/`192.168.`/`172.16-31.`, link-local (la dirección de metadatos `169.254.169.254` incluida),
+IPv6 literales ni `.local`—, comprobada en la URL **y en dónde terminó el pedido**, porque una
+redirección es si no la forma de rodearla. El cuerpo se lee con tope y se corta la conexión al
+llegar. Este contenedor vive adentro de una casa: que no sea el camino para mapearla desde afuera.
+
+También acá: la página de la API (`website/api.html`) estaba **ocultando dos tercios de la API**.
+El generador sólo dibujaba las secciones que estaban en su tabla de etiquetas, y `health` (todo el
+ingest de Apple Health, la lectura de Salud y la segunda opinión) y `music` (listas, radio, podcasts)
+no estaban: los contadores de arriba seguían contándolas y las tarjetas no aparecían en ninguna
+parte. Ahora están, con las de podcasts y radio incluidas.
+
## Sin publicar — Radio (música en vivo mientras entrenás)
Música tiene ahora una sección **Radio**: estaciones en vivo por género — *Workout / Rave, Techno /
@@ -22,7 +64,8 @@ en ningún lado, ni tuya ni de la app.
La URL viene resuelta en la lista por una razón que decide si la función existe en un iPhone:
**iOS sólo deja arrancar audio dentro del gesto del toque**, así que nada asíncrono puede quedar
entre el dedo y el `play()` — ni un `fetch`, ni un cambio de estado, ni un re-render. Y el elemento
-`
]]>
+${date}${dur}${guid}${enc}${extra}`;
+
+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'), '324. La Ruina & Co');
+ assert.equal(tagAttr('', 'enclosure', 'url'), 'https://x/1.mp3');
+ assert.equal(tagAttr('', '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: '' }), 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: '' }), opts);
+ assert.equal(noType.url, 'https://audio.example.com/1.mp3');
+ // No type and not an audio file: refused.
+ assert.equal(episodeFrom(item({ enc: '' }), opts), null);
+ // http audio would be blocked by the browser on an https page.
+ assert.equal(episodeFrom(item({ enc: '' }), opts), null);
+ assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
+ const ep = episodeFrom(item({ extra: '14' }), 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' }) }) + 'Dos a medias e.title), ['Uno']);
+});
+
+test('a show with no title of its own takes the directory name', () => {
+ const { show, episodes } = parseFeed('es' + item({}) + '', { 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]);
+});
diff --git a/api/test/server-podcasts.test.js b/api/test/server-podcasts.test.js
new file mode 100644
index 0000000..8849e61
--- /dev/null
+++ b/api/test/server-podcasts.test.js
@@ -0,0 +1,91 @@
+/* The two podcast routes, against the real server: who may call them, and which feed URLs this
+ process will agree to fetch.
+
+ The feed rule is the one that matters, and it matters more here than in any other route: a podcast
+ feed can live on any host in the world, so there is no allowlist to fall back on — only the rule
+ in `safeFeedUrl`. This container runs inside somebody's house, and the URL arrives from a browser,
+ so `http://192.168.1.1/…` is not a bad feed, it is a request this process must never make. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import net from 'node:net';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = crypto.randomBytes(32).toString('hex');
+
+function mintSession(uid, sv = 0) {
+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+}
+const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
+
+const freePort = () => new Promise(r => {
+ const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
+});
+
+async function startServer(t) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-podcasts-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_p', name: 'One', created: '2026-01-01T00:00:00.000Z' }], creds: [], subs: [], invites: [] }));
+ const port = await freePort();
+ const child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }
+ });
+ const h = { api: `http://127.0.0.1:${port}`, log: '' };
+ child.stdout.on('data', d => h.log += d);
+ child.stderr.on('data', d => h.log += d);
+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+ let up = false;
+ for (let i = 0; i < 100 && !up; i++) {
+ try { up = (await fetch(`${h.api}/api/health`)).ok } catch { /* not up yet */ }
+ if (!up) await new Promise(r => setTimeout(r, 100));
+ }
+ assert.ok(up, `server never came up:\n${h.log}`);
+ return h;
+}
+
+test('the podcast list needs a session', async t => {
+ const h = await startServer(t);
+ const r = await fetch(`${h.api}/api/podcasts`);
+ assert.equal(r.status, 401);
+});
+
+test('so does a show', async t => {
+ const h = await startServer(t);
+ const r = await fetch(`${h.api}/api/podcasts/show?feed=${encodeURIComponent('https://feeds.example.com/x.rss')}`);
+ assert.equal(r.status, 401);
+});
+
+test('a feed URL that is not public https is refused before any request is made', async t => {
+ const h = await startServer(t);
+ for (const feed of [
+ 'http://169.254.169.254/latest/meta-data/', // the cloud metadata address
+ 'http://127.0.0.1:3000/api/health',
+ 'https://127.0.0.1/x.rss',
+ 'https://192.168.1.1/x.rss',
+ 'https://10.0.0.5/x.rss',
+ 'https://router.local/x.rss',
+ 'https://[::1]/x.rss',
+ 'http://feeds.example.com/x.rss', // plain http, even on a real host
+ 'https://user:pw@feeds.example.com/x.rss',
+ 'file:///etc/passwd',
+ 'not a url',
+ ''
+ ]) {
+ const r = await fetch(`${h.api}/api/podcasts/show?feed=${encodeURIComponent(feed)}`, { headers: cookie('u_p') });
+ assert.equal(r.status, 400, `${feed} is refused`);
+ assert.match((await r.json()).error, /feed this server will fetch/);
+ }
+});
+
+test('the instance says it supports podcasts', async t => {
+ const h = await startServer(t);
+ const cfg = await (await fetch(`${h.api}/api/config`)).json();
+ assert.ok(cfg.features.includes('podcasts'), 'features: ' + cfg.features.join(','));
+});
diff --git a/docs/MOBILE.md b/docs/MOBILE.md
index dc14089..a20ef98 100644
--- a/docs/MOBILE.md
+++ b/docs/MOBILE.md
@@ -161,9 +161,10 @@ and an `-exportArchive` step — none of that is set up.
### Audio with the screen locked (the shells only)
-The web app plays radio fine with the phone locked: **Safari and Chrome keep the audio alive
-underneath the page**, and Media Session puts the station and its controls on the lock screen. The
-packaged shells are a different story, and it is a config gap rather than a code one:
+The web app plays radio and podcasts fine with the phone locked: **Safari and Chrome keep the audio
+alive underneath the page**, and Media Session puts the station — or the episode, with its progress
+bar — and the controls on the lock screen. The packaged shells are a different story, and it is a
+config gap rather than a code one:
- **iOS** (`frontend/ios`) — the app needs `UIBackgroundModes: audio` in `Info.plist`. Without it,
iOS suspends the WebView's audio a moment after the screen locks.
@@ -171,8 +172,11 @@ packaged shells are a different story, and it is a config gap rather than a code
`mediaPlayback` type and its notification) to keep playing while the app is not in front;
`android:foregroundServiceType` plus the service's own declaration, not a manifest flag alone.
-Neither is set today, so **radio in a packaged build stops when the screen locks** — install the PWA
-instead (Add to Home Screen) if that matters, which is the recommended path here anyway.
+Neither is set today, so **audio in a packaged build stops when the screen locks** — install the PWA
+instead (Add to Home Screen) if that matters, which is the recommended path here anyway. One more
+consequence for podcasts: a locked page's timers are suspended, so the listening position is written
+to the profile on pause, on stop, when an episode ends and when the app goes to the background —
+never from a tick alone, which is why locking the phone does not lose your place.
### Release notes for maintainers
diff --git a/docs/PODCASTS.md b/docs/PODCASTS.md
new file mode 100644
index 0000000..4eac7b3
--- /dev/null
+++ b/docs/PODCASTS.md
@@ -0,0 +1,109 @@
+# Podcasts
+
+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*,
+*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.
+
+## Why podcasts and not just more radio
+
+They are opposites in every way that matters to the player, and the difference is not cosmetic:
+
+| | Radio | A podcast |
+|---|---|---|
+| Source | a live stream | a file with a beginning and an end |
+| Position | meaningless | *the* feature |
+| Pause | pause the stream | pause, resume, seek ±, remember |
+| Playing next | the station's job | yours: `next episode` |
+| Length | unknown, forever | minutes, and worth showing |
+
+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.
+
+## Spanish only — checked, not assumed
+
+The user asked for Spanish, so the app checks, and this is the part worth knowing before trusting a
+short list:
+
+- Apple's directory is browsed per **storefront** (`es` and `mx`). A storefront says where a podcast
+ is *sold*, which is not the same as the language it is in: the Spanish comedy chart carries a
+ Catalan show, and the Argentine one carries an English show.
+- So every show's **feed** is read — its first 64 KB, with a `Range` request, because `` is
+ channel metadata that sits in the first ~1.5 KB and always before the first `` — and its
+ `` decides. `es`, `es-ES`, `es-419` and `spa` stay; `ca`, `en`, `pt` and the rest go.
+- **A feed with no tag at all stays.** Some genuinely Spanish feeds omit it (La Ruina does), and
+ dropping them over an omission would quietly remove good podcasts; the storefront is the fallback
+ signal, and it is not a guess.
+- The response says how many shows were dropped and why (`skipped: { duplicate, language,
+ unreadable, failed }`), so a list of fifteen is never a mystery.
+- Opening a show re-checks against the *whole* feed, and a show in another language is answered with
+ `spanish: false` and a sentence — not with an empty episode list that looks like a feed with
+ nothing in it.
+
+## Nothing is proxied, and nothing is downloaded
+
+An episode arrives as an `https://` URL from the publisher's own `enclosure`, the phone plays it, and
+the bytes go from the publisher to the phone. This server contributes the *list*, exactly the bargain
+the radio makes — no audio through the container, no copies, no downloads, no disk.
+
+What this does cost, server-side, is requests: Apple's charts and lookup (two per category), one
+64 KB `Range` request per show to read its language, and one fetch per feed when a show is opened
+(up to ~6 MB for a big archive — cached for half an hour, parsed, and the *parsed* episodes are what
+is kept, never the body, because forty episodes are a few kilobytes and a feed is megabytes).
+
+## What may be fetched
+
+Radio has a host allowlist because it talks to three services. Podcasts cannot: feeds live on every
+host in the world. So this is the other rule, and it is the rule that matters for an api container
+sitting inside somebody's house:
+
+- **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 carrier-grade NAT, no link-local (the
+ `169.254.169.254` metadata address is the classic target), no IPv6 literals, no `.local` or
+ `.internal`.
+- The URL is checked **and so is where the request ended up**, because a redirect is otherwise the
+ way around it.
+- Bodies are read with a cap and the connection is dropped the moment it is reached.
+- Both routes need a session — not to protect public podcasts, but because this process fetches on
+ behalf of whoever asks.
+
+## The player, and the two things that are easy to get wrong
+
+- **Audio only starts inside the tap.** iOS allows audio to begin from a user gesture and from
+ nothing else, so nothing asynchronous may sit between the finger and the `play()`: the episode URL
+ is already in hand, and the store's `playEpisode` calls straight through.
+- **The `` element lives outside React** (`frontend/src/lib/player.js`), shared with the radio,
+ so changing screens does not stop it and two kinds of media can never play at once.
+
+Positions are saved to your profile — per episode, throttled to once every few seconds, and always on
+pause, on stop, when an episode ends and when the app goes to the background. That last one matters:
+**iOS suspends a locked page's timers**, so a position saved only from a tick would lose whatever was
+played with the screen off.
+
+Episodes count as heard when they are within twenty seconds of the end, and starting one of those
+begins it again rather than resuming into its last seconds. Two hundred positions are kept per
+profile, newest first.
+
+## The screen locked, and the native shells
+
+Safari and the installed PWA keep playing with the phone locked, and Media Session puts the episode,
+the show and the progress bar on the lock screen, with the controls reaching the same audio element.
+The two shell builds need configuration for that (see [MOBILE.md](MOBILE.md)) — in the PWA, nothing.
+
+## What this deliberately is not
+
+- **Not a downloads app.** There is no offline mode and no stored audio: the episode plays from the
+ publisher every time, which is also why nothing here will ever be a copyright question.
+- **Not Apple Podcasts' API.** There is no such thing for third parties; the directory and the feeds
+ are public, and that is what this uses — no key, no account, no Apple ID.
+- **Not a proxy or a transcriber.** No audio through the server, no speed-up, no ad-skipping.
+- **Not a general podcast directory.** Spanish is a filter, not a preference to be toggled.
+
+## Credits
+
+- [Apple Podcasts directory](https://www.apple.com/apple-podcasts/) — the charts and lookup used to
+ find shows and their feeds. Public, keyless endpoints; the shows and episodes are the publishers'
+ own.
+- The shows themselves belong to the people who make them; the audio is served from their hosts.
diff --git a/docs/RADIO.md b/docs/RADIO.md
index 5d837d6..5dc12ce 100644
--- a/docs/RADIO.md
+++ b/docs/RADIO.md
@@ -61,8 +61,9 @@ finger and the `play()` — a `fetch`, a state update, a re-render — is a pres
no error anywhere. So the list arrives complete: by the time a station has been drawn on the screen,
its stream URL is already in the object the row holds, and the press calls `play()` synchronously.
-The `` element lives in `frontend/src/lib/radio-player.js`, **outside React**, as a
-module-level singleton. An element owned by a component is unmounted when the component is, which is
+The `` element lives in `frontend/src/lib/player.js`, **outside React**, as a module-level
+singleton — the same element the podcasts use, which is also what keeps a station and an episode from
+ever playing at once. An element owned by a component is unmounted when the component is, which is
how a player stops the moment you change screens — and changing screens mid-session is the normal
case here, not the edge case.
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 06ea097..9b8c0a4 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -20,7 +20,7 @@ import Modals from './components/Modals.jsx'
import Toast from './components/Toast.jsx'
import SyncBanner from './components/SyncBanner.jsx'
import RestTimer from './components/RestTimer.jsx'
-import RadioBar from './components/RadioBar.jsx'
+import PlayerBar from './components/PlayerBar.jsx'
import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
@@ -217,9 +217,10 @@ function Shell() {
{/* The chat owns the bottom of the screen: its composer sits where the tabs would be. */}
{loc.pathname !== '/coach' && }
- {/* The radio lives here, not in the Música screen: a player inside a route is unmounted when
- somebody navigates away, and that is how music stops mid-set. */}
-
+ {/* The player bar lives here, not in the Música screen: a player inside a route is unmounted
+ when somebody navigates away, and that is how music stops mid-set — for a station and for
+ an episode alike. */}
+
diff --git a/frontend/src/components/PlayerBar.jsx b/frontend/src/components/PlayerBar.jsx
new file mode 100644
index 0000000..ec5452e
--- /dev/null
+++ b/frontend/src/components/PlayerBar.jsx
@@ -0,0 +1,142 @@
+/* The player bar: one line above the tab bar, while anything is playing.
+ *
+ * It follows the rest timer's shape on purpose — same place, same glass, same slide-up — because a
+ * second floating bar with its own look would read as a second app. What it adds is what is playing,
+ * what that thing says it is playing, and the buttons that matter.
+ *
+ * **The `` element is not here.** It lives in lib/player.js, outside React, so that changing
+ * screens cannot unmount it and stop the music — which is the whole reason this bar is mounted above
+ * the router instead of inside the Música screen. This component reads the store and draws; the
+ * player reports and the store decides.
+ *
+ * Two kinds of media, so two shapes of the same line:
+ *
+ * - **Radio** has no position and no end. The line under the station is what the station says it is
+ * playing — or the station's own description, never an invented track — and the buttons are
+ * pause and stop.
+ * - **An episode** has all of it: a length, a place you are in, a place you left off, and a next
+ * one. So the bar grows a progress hairline, −15 s and +30 s, and a next-episode button when the
+ * queue has one. The two seek buttons are written as text rather than drawn as icons: no arrow
+ * glyph says "fifteen seconds", and this row is used with a sweaty thumb.
+ */
+import { useEffect, useState } from 'react'
+import { useUI } from '../store/useUI.js'
+import { api } from '../lib/api.js'
+import { t } from '../lib/i18n.js'
+import { fmtClock, nextEpisode, progressPct } from '../lib/podcast-view.js'
+import Icon from './Icon.jsx'
+
+/* How often the station is asked what it is playing.
+ *
+ * Forty-five seconds: long enough to be polite to two community services that run on donations,
+ * short enough that the line is usually right by the time a song ends. Not zero — a station's
+ * current track is the thing that makes a radio feel alive — and not per second, which would be
+ * abusing somebody else's bandwidth for a caption.
+ *
+ * While the screen is locked iOS suspends these timers, so the line simply stops moving and the
+ * music keeps playing. When the person looks again the next tick fixes it. */
+const NOW_EVERY_MS = 45000
+
+export default function PlayerBar() {
+ const radio = useUI(s => s.radio)
+ const pod = useUI(s => s.pod)
+ const { toggleRadio, stopRadio, setRadioNow, togglePod, stopPod, podSeek, podNext } = useUI()
+ const on = !!radio || !!pod
+
+ // The page makes room for the bar while it is there, the same class trick the rest timer uses.
+ useEffect(() => {
+ document.body.classList.toggle('playing-media', on)
+ return () => document.body.classList.remove('playing-media')
+ }, [on])
+
+ if (radio) return
+ if (pod) return
+ return null
+}
+
+/* ---------- radio ---------- */
+
+function RadioLine({ radio, onToggle, onStop, onNow }) {
+ const station = radio.station
+
+ // Poll for what is playing, only for the sources that publish it (the api answers null for the
+ // rest, which costs one small request and shows nothing).
+ useEffect(() => {
+ if (!radio.playing || !station) return
+ let live = true
+ const ask = () => api('/api/radio/now?src=' + encodeURIComponent(station.src) + '&id=' + encodeURIComponent(station.id))
+ .then(r => { if (live && r?.now) onNow(r.now) })
+ .catch(() => {})
+ ask()
+ const id = setInterval(ask, NOW_EVERY_MS)
+ return () => { live = false; clearInterval(id) }
+ }, [radio.playing, station?.src, station?.id])
+
+ const line = radio.now
+ ? [radio.now.artist, radio.now.title].filter(Boolean).join(' · ')
+ : (station.detail || station.genre || t('Live radio'))
+
+ return
+
+ } />
+}
+
+/* ---------- an episode ---------- */
+
+function EpisodeLine({ pod, onToggle, onStop, onSeek, onNext }) {
+ const pct = progressPct({ pos: pod.position, dur: pod.duration }, pod.duration)
+ const hasNext = !!nextEpisode(pod.queue, pod.episode.id)
+ const clock = Number.isFinite(pod.duration) && pod.duration > 0
+ ? `${fmtClock(pod.position)} / ${fmtClock(pod.duration)}`
+ : fmtClock(pod.position)
+
+ return
+
+
+ {hasNext && }
+
+ >} />
+}
+
+/** The line itself, shared by both: cover, two lines of text, the controls, a progress hairline. */
+function Bar({ cover, name, line, sub, label, icon, onToggle, progress, actions }) {
+ /* Artwork that does not load. A directory entry's "logo" is sometimes a homepage rather than an
+ image, and a broken image in the bar looks worse than the placeholder — so whatever failed is
+ remembered and never asked for twice. */
+ const [noArt, setNoArt] = useState(null)
+ return
+}
diff --git a/frontend/src/components/PlayerBar.test.jsx b/frontend/src/components/PlayerBar.test.jsx
new file mode 100644
index 0000000..7f5651c
--- /dev/null
+++ b/frontend/src/components/PlayerBar.test.jsx
@@ -0,0 +1,183 @@
+// @vitest-environment happy-dom
+/* The player bar, in both of its shapes, and the four things about it that are invisible when wrong.
+ *
+ * One: it disappears completely when nothing is playing — a bar that renders empty would sit over
+ * the tab bar and eat taps. Two: pause *pauses* — the station stays, and so does the episode, which
+ * is the whole point of listening while training. Three: an episode's seek buttons seek, and the
+ * progress hairline is the position, since a podcast you cannot scrub is a podcast you do not use.
+ * Four: the bar is mounted above the router, so it must not care which screen is on.
+ *
+ * The `` element itself lives in lib/player.js, outside React (see the comment there), so it
+ * is mocked here: this file is about what the bar draws and what it asks the store to do. */
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useUI } from '../store/useUI.js'
+
+const api = vi.fn()
+vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
+const playStream = vi.fn(() => true)
+const playFile = vi.fn(() => true)
+const seekBy = vi.fn(() => 100)
+vi.mock('../lib/player.js', () => ({
+ playStream: (...a) => playStream(...a),
+ playFile: (...a) => playFile(...a),
+ pausePlayer: vi.fn(),
+ resumePlayer: vi.fn(() => true),
+ seekBy: (...a) => seekBy(...a),
+ seekTo: vi.fn(() => 0),
+ playerTime: () => ({ position: 0, duration: null }),
+ setPlayerVolume: vi.fn(),
+ setStreamSession: vi.fn(),
+ setEpisodeSession: vi.fn(),
+ setSessionPosition: vi.fn(),
+ wireSessionHandlers: vi.fn(),
+ clearSession: vi.fn(),
+ onPlayer: () => () => {}
+}))
+
+const { default: PlayerBar } = await import('./PlayerBar.jsx')
+
+const station = (over = {}) => ({
+ src: 'soma', id: 'beatblender', name: 'Beat Blender',
+ detail: 'A late night blend', genre: 'Electronic',
+ url: 'https://ice2.somafm.com/beatblender-128-mp3', image: null, ...over
+})
+const episode = (over = {}) => ({
+ id: 'ep-1', title: 'En el corazón del ajo', url: 'https://audio.example.com/1.mp3',
+ date: '2025-09-02T10:00:00.000Z', duration: 3135, image: null, ...over
+})
+const show = { feed: 'https://a.example.com/feed', name: 'Nadie Sabe Nada', image: null }
+
+let host, root
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ api.mockReset()
+ api.mockResolvedValue({ ok: true, now: null })
+ playStream.mockClear()
+ playFile.mockClear()
+ seekBy.mockClear()
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+ act(() => { useUI.setState({ radio: null, pod: null }) })
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ document.body.classList.remove('playing-media')
+})
+
+const mount = async () => { await act(async () => { root.render() }) }
+const btn = label => [...host.querySelectorAll('#player button')].find(b => b.getAttribute('aria-label') === label)
+
+describe('the player bar', () => {
+ it('draws nothing at all before something is playing', async () => {
+ await mount()
+ expect(host.querySelector('#player')).toBe(null)
+ expect(document.body.classList.contains('playing-media')).toBe(false)
+ })
+
+ it('names the station and what it says it is playing', async () => {
+ api.mockResolvedValue({ ok: true, now: { artist: 'The Orb', title: 'Little Fluffy Clouds' } })
+ act(() => { useUI.getState().playRadio(station()) })
+ await mount()
+ await act(async () => { await Promise.resolve() })
+ expect(host.querySelector('.plr-name').textContent).toBe('Beat Blender')
+ expect(host.querySelector('.plr-now').textContent).toBe('The Orb · Little Fluffy Clouds')
+ // The page makes room for the bar, the same class trick the rest timer uses.
+ expect(document.body.classList.contains('playing-media')).toBe(true)
+ // And it asked the station what is playing, instead of inventing a caption.
+ expect(api.mock.calls[0][0]).toBe('/api/radio/now?src=soma&id=beatblender')
+ })
+
+ it('pauses a station without losing it', async () => {
+ act(() => { useUI.getState().playRadio(station()) })
+ await mount()
+ act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ expect(useUI.getState().radio.playing).toBe(false)
+ expect(useUI.getState().radio.station.id).toBe('beatblender')
+ expect(btn('Play')).toBeTruthy()
+ })
+
+ it('stops a station and takes the bar with it', async () => {
+ act(() => { useUI.getState().playRadio(station()) })
+ await mount()
+ act(() => { btn('Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ await act(async () => {})
+ expect(useUI.getState().radio).toBe(null)
+ expect(host.querySelector('#player')).toBe(null)
+ expect(document.body.classList.contains('playing-media')).toBe(false)
+ })
+
+ /* ---------- an episode ---------- */
+
+ it('shows the episode, the show and how far into it you are', async () => {
+ act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), [episode({ duration: 3600 })]) })
+ await mount()
+ expect(host.querySelector('.plr-name').textContent).toBe('Nadie Sabe Nada')
+ expect(host.querySelector('.plr-now').textContent).toContain('En el corazón del ajo')
+ // The clock is the position out of the length — a podcast without one looks like a stream.
+ expect(host.querySelector('.plr-clock').textContent).toBe(' · 0:00 / 1:00:00')
+ expect(host.querySelector('.plr-progress')).toBeTruthy()
+ })
+
+ it('draws the position as a filled hairline, and no line at all for a stream', async () => {
+ act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), []) })
+ await mount()
+ act(() => { useUI.getState().setPodPlayback({ position: 900 }) })
+ await act(async () => {})
+ expect(host.querySelector('.plr-progress').style.width).toBe('25%')
+
+ // A station has no position to draw: no hairline, nothing to scrub.
+ act(() => { useUI.getState().playRadio(station()) })
+ await act(async () => {})
+ expect(host.querySelector('.plr-progress')).toBe(null)
+ })
+
+ it('seeks by the two amounts a podcast is actually driven with', async () => {
+ act(() => { useUI.getState().playEpisode(show, episode(), []) })
+ await mount()
+ // Through the store's own action, so this is the real path: button → store → element.
+ act(() => { btn('15 seconds back').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ act(() => { btn('30 seconds forward').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ expect(seekBy.mock.calls.map(c => c[0])).toEqual([-15, 30])
+ // And the bar's own clock follows the element rather than its own arithmetic.
+ expect(useUI.getState().pod.position).toBe(100)
+ })
+
+ it('offers the next episode only when the queue has one', async () => {
+ const first = episode({ id: 'ep-1' })
+ const second = episode({ id: 'ep-2', title: 'Otro' })
+ act(() => { useUI.getState().playEpisode(show, first, [first, second]) })
+ await mount()
+ expect(btn('Next episode')).toBeTruthy()
+
+ act(() => { useUI.getState().playEpisode(show, second, [first, second]) })
+ await act(async () => {})
+ expect(btn('Next episode')).toBeUndefined()
+ })
+
+ it('pauses an episode without losing the position, and plays it again there', async () => {
+ act(() => { useUI.getState().playEpisode(show, episode(), []) })
+ await mount()
+ act(() => { useUI.getState().setPodPlayback({ position: 620 }) })
+ act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ expect(useUI.getState().pod.playing).toBe(false)
+ expect(useUI.getState().pod.position).toBe(620)
+
+ playFile.mockClear()
+ act(() => { btn('Play').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ // Started again where it was, not from the beginning.
+ expect(playFile).toHaveBeenCalledWith(episode().url, { startAt: 620 })
+ })
+
+ it('shows the placeholder when the artwork does not load', async () => {
+ act(() => { useUI.getState().playEpisode({ ...show, image: 'https://x/not-an-image' }, episode({ image: null }), []) })
+ await mount()
+ expect(host.querySelector('.plr-cover').tagName).toBe('IMG')
+ act(() => { host.querySelector('.plr-cover').dispatchEvent(new Event('error')) })
+ await act(async () => {})
+ const art = host.querySelector('.plr-cover')
+ expect(art.tagName).toBe('SPAN')
+ expect(art.classList.contains('plr-cover-ph')).toBe(true)
+ })
+})
diff --git a/frontend/src/components/RadioBar.jsx b/frontend/src/components/RadioBar.jsx
deleted file mode 100644
index fbf111f..0000000
--- a/frontend/src/components/RadioBar.jsx
+++ /dev/null
@@ -1,77 +0,0 @@
-/* The radio bar: one line above the tab bar, while something is playing.
- *
- * It follows the rest timer's shape on purpose — same place, same glass, same slide-up — because a
- * second floating bar with its own look would read as a second app. What it adds is the station,
- * what the station says it is playing, and a pause button.
- *
- * The `` element is *not* here: it lives in lib/radio-player.js, outside React, so that
- * changing screens cannot unmount it and stop the music. This component reads the store, draws the
- * line, and asks it to poll the station for what is playing.
- */
-import { useEffect, useState } from 'react'
-import { useUI } from '../store/useUI.js'
-import { api } from '../lib/api.js'
-import { t } from '../lib/i18n.js'
-import Icon from './Icon.jsx'
-
-/* How often the station is asked what it is playing.
- *
- * Forty-five seconds: long enough to be polite to two community services that run on donations,
- * short enough that the line is usually right by the time a song ends. Not zero — a station's
- * current track is the thing that makes a radio feel alive — and not per second, which would be
- * abusing somebody else's bandwidth for a caption.
- *
- * While the screen is locked iOS suspends these timers, so the line simply stops moving and the
- * music keeps playing. When the person looks again the next tick fixes it. */
-const NOW_EVERY_MS = 45000
-
-export default function RadioBar() {
- const radio = useUI(s => s.radio)
- const { toggleRadio, stopRadio, setRadioNow } = useUI()
- const station = radio?.station
- /* A cover that did not load. A directory station's "logo" is sometimes a homepage URL rather than
- an image, and a broken image in the bar is worse than the placeholder — so whatever failed is
- remembered and never asked for twice. */
- const [noArt, setNoArt] = useState(null)
-
- // Poll for what is playing, only for the sources that publish it (the api answers null for the
- // rest, which costs one small request and shows nothing).
- useEffect(() => {
- if (!radio?.playing || !station) return
- let live = true
- const ask = () => api('/api/radio/now?src=' + encodeURIComponent(station.src) + '&id=' + encodeURIComponent(station.id))
- .then(r => { if (live && r?.now) setRadioNow(r.now) })
- .catch(() => {})
- ask()
- const id = setInterval(ask, NOW_EVERY_MS)
- return () => { live = false; clearInterval(id) }
- }, [radio?.playing, station?.src, station?.id])
-
- // The page makes room for the bar while it is there, the same class trick the rest timer uses.
- useEffect(() => {
- document.body.classList.toggle('radioing', !!radio)
- return () => document.body.classList.remove('radioing')
- }, [!!radio])
-
- if (!radio) return null
- const now = radio.now
- const cover = now?.cover || station.image || null
- const line = now ? [now.artist, now.title].filter(Boolean).join(' · ') : (station.detail || station.genre || t('Live radio'))
-
- return
-}
diff --git a/frontend/src/components/RadioBar.test.jsx b/frontend/src/components/RadioBar.test.jsx
deleted file mode 100644
index baa7fdb..0000000
--- a/frontend/src/components/RadioBar.test.jsx
+++ /dev/null
@@ -1,126 +0,0 @@
-// @vitest-environment happy-dom
-/* The radio bar, and the two things about it that are easy to get wrong and invisible when wrong.
- *
- * One: it has to disappear completely when nothing is playing — a bar that renders empty would sit
- * over the tab bar and eat taps. Two: the pause button has to *pause*, not stop: stopping drops the
- * station, and the whole point of listening while training is that the same station is still there
- * after the rest.
- *
- * The `` element itself lives in lib/radio-player.js, outside React (see the comment there),
- * so it is mocked here — this file is about what the bar draws and what it asks the store to do. */
-import React, { act } from 'react'
-import { createRoot } from 'react-dom/client'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { useUI } from '../store/useUI.js'
-
-const api = vi.fn()
-vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
-const playStream = vi.fn(() => true)
-vi.mock('../lib/radio-player.js', () => ({
- playStream: (...a) => playStream(...a),
- pauseStream: vi.fn(),
- setStreamVolume: vi.fn(),
- setMediaSession: vi.fn(),
- clearMediaSession: vi.fn()
-}))
-
-const { default: RadioBar } = await import('./RadioBar.jsx')
-
-const station = (over = {}) => ({
- src: 'somafm', id: 'beatblender', name: 'Beat Blender',
- detail: 'A late night blend', genre: 'Electronic',
- url: 'https://ice2.somafm.com/beatblender-128-mp3', image: null, ...over
-})
-
-let host, root
-beforeEach(() => {
- globalThis.IS_REACT_ACT_ENVIRONMENT = true
- api.mockReset()
- api.mockResolvedValue({ ok: true, now: null })
- playStream.mockClear()
- host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
- act(() => { useUI.setState({ radio: null }) })
-})
-afterEach(() => {
- act(() => root.unmount())
- host.remove()
- document.body.classList.remove('radioing')
-})
-
-const mount = async () => { await act(async () => { root.render() }) }
-const btn = label => [...host.querySelectorAll('#radio button')].find(b => b.getAttribute('aria-label') === label)
-
-describe('the radio bar', () => {
- it('draws nothing at all before something is playing', async () => {
- await mount()
- expect(host.querySelector('#radio')).toBe(null)
- expect(document.body.classList.contains('radioing')).toBe(false)
- })
-
- it('names the station and what it says it is playing', async () => {
- api.mockResolvedValue({ ok: true, now: { artist: 'The Orb', title: 'Little Fluffy Clouds' } })
- act(() => { useUI.getState().playRadio(station()) })
- await mount()
- await act(async () => { await Promise.resolve() })
- expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
- expect(host.querySelector('.rad-now').textContent).toBe('The Orb · Little Fluffy Clouds')
- // The page makes room for the bar, the same class trick the rest timer uses.
- expect(document.body.classList.contains('radioing')).toBe(true)
- // And it asked the station what is playing, instead of inventing a caption.
- expect(api.mock.calls[0][0]).toBe('/api/radio/now?src=somafm&id=beatblender')
- })
-
- it('falls back to what the station is when it publishes no track', async () => {
- act(() => { useUI.getState().playRadio(station({ genre: 'Techno' })) })
- await mount()
- await act(async () => { await Promise.resolve() })
- expect(host.querySelector('.rad-now').textContent).toBe('A late night blend')
- })
-
- it('pause keeps the station, so the same one is still there after the rest', async () => {
- act(() => { useUI.getState().playRadio(station()) })
- await mount()
- act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
- expect(useUI.getState().radio.playing).toBe(false)
- expect(useUI.getState().radio.station.id).toBe('beatblender')
- // Still on screen, still named, and the button now offers to start it again.
- expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
- expect(btn('Play')).toBeTruthy()
- })
-
- it('stop takes the bar away with the station', async () => {
- act(() => { useUI.getState().playRadio(station()) })
- await mount()
- act(() => { btn('Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
- await act(async () => {})
- expect(useUI.getState().radio).toBe(null)
- expect(host.querySelector('#radio')).toBe(null)
- expect(document.body.classList.contains('radioing')).toBe(false)
- })
-
- it('shows the station logo when the station publishes no track', async () => {
- act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
- await mount()
- expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/logo.png')
- })
-
- it('prefers the cover of the track it is playing over the station logo', async () => {
- api.mockResolvedValue({ ok: true, now: { artist: 'A', title: 'B', cover: 'https://x/cover.jpg' } })
- act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
- await mount()
- expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/cover.jpg')
- })
-
- /* A directory station's "logo" is sometimes a homepage rather than an image, and a broken image
- in the bar looks worse than no artwork at all. */
- it('falls back to the placeholder when the artwork does not load', async () => {
- act(() => { useUI.getState().playRadio(station({ image: 'https://x/not-an-image' })) })
- await mount()
- expect(host.querySelector('.rad-cover').tagName).toBe('IMG')
- act(() => { host.querySelector('.rad-cover').dispatchEvent(new Event('error')) })
- await act(async () => {})
- const art = host.querySelector('.rad-cover')
- expect(art.tagName).toBe('SPAN')
- expect(art.classList.contains('rad-cover-ph')).toBe(true)
- })
-})
diff --git a/frontend/src/index.css b/frontend/src/index.css
index d992056..f2207ea 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1117,7 +1117,9 @@ body.chips-dragging *{cursor:inherit}
#timer .t{font-size:26px;font-weight:600;letter-spacing:-.026em;font-variant-numeric:tabular-nums;min-width:66px}
#timer .bar{flex:1;height:4px;background:var(--surface-3);border-radius:99px;overflow:hidden}
#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}
-/* A station row: the whole row plays it, and a star saves it for this profile. */
+/* A row in Música: a radio station (the whole row plays it) or a podcast (the whole row opens it),
+ with a star that saves it for this profile. One shape for both, because they are the same object
+ as far as the eye is concerned — a square logo, a name, a line of detail. */
.mus-rad{display:flex;align-items:center;gap:4px;margin-bottom:6px}
.mus-rad.on .mus-rad-n{color:var(--acc)}
.mus-rad-main{flex:1;min-width:0;display:flex;align-items:center;gap:10px;text-align:left;
@@ -1135,10 +1137,29 @@ body.chips-dragging *{cursor:inherit}
.mus-rad-save .icn{font-size:17px}
.mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px}
-/* The radio bar: the rest timer's shape, lower in the stack. It sits above the tab bar and, when
+/* The episodes sheet: a show's feed, newest first. Rows are buttons because the whole row plays the
+ episode — that tap is also the user gesture iOS requires before any audio may start. */
+.pod-head{display:flex;align-items:center;gap:11px;padding:2px 2px 10px}
+.pod-head-i{width:46px;height:46px;border-radius:10px;object-fit:cover;flex:0 0 auto}
+.pod-head-n{font-size:15px;font-weight:650;color:var(--label)}
+.pod-eps{display:flex;flex-direction:column;gap:5px}
+.pod-ep{display:flex;align-items:flex-start;gap:10px;text-align:left;padding:9px 11px;border-radius:var(--r-md);
+ background:var(--glass);border:var(--hair) solid var(--sep-op)}
+.pod-ep:active{background:var(--surface-3)}
+.pod-ep-i{font-size:15px;color:var(--acc);flex:0 0 auto;margin-top:1px}
+.pod-ep-meta{display:flex;flex-direction:column;gap:2px;min-width:0}
+.pod-ep-t{font-size:13.5px;color:var(--label);line-height:1.3}
+.pod-ep-s{font-size:11.5px;color:var(--label-3)}
+.pod-heard{color:var(--acc)}
+
+/* The player bar: the rest timer's shape, lower in the stack. It sits above the tab bar and, when
a rest countdown is also on screen, above that too — the countdown is the one you act on seconds
- from now, so it keeps the lower slot. */
-#radio{
+ from now, so it keeps the lower slot.
+
+ One bar for the radio and for a podcast, because there is one audio element behind both. The only
+ difference is that an episode has a length, so its bar carries a progress hairline (`.plr-progress`,
+ absolutely positioned along the bottom edge) and two text seek buttons. */
+#player{
position:fixed;left:12px;right:12px;bottom:calc(88px + var(--sab));z-index:59;
background:color-mix(in srgb,var(--surface) 97%,transparent);
-webkit-backdrop-filter:saturate(180%) blur(10px);backdrop-filter:saturate(180%) blur(10px);
@@ -1146,22 +1167,38 @@ body.chips-dragging *{cursor:inherit}
display:flex;align-items:center;gap:10px;
box-shadow:0 12px 34px -8px rgba(0,0,0,.55);
animation:slideup var(--med) var(--ease);
+ overflow:hidden;
}
-body.resting #radio{bottom:calc(190px + var(--sab))}
-body.radioing #app{padding-bottom:calc(146px + var(--sab))}
+body.resting #player{bottom:calc(190px + var(--sab))}
+body.playing-media #app{padding-bottom:calc(146px + var(--sab))}
@media (min-width:1000px){
- #radio{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
- body.resting #radio{bottom:200px}
- body.radioing #app{padding-bottom:calc(186px + var(--sab))}
+ #player{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
+ body.resting #player{bottom:200px}
+ body.playing-media #app{padding-bottom:calc(186px + var(--sab))}
+}
+.plr-cover{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;display:block}
+.plr-cover-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
+.plr-cover-ph .icn{font-size:18px}
+.plr-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
+.plr-name{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.plr-now{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.plr-clock{color:var(--label-3);font-variant-numeric:tabular-nums}
+.plr-btn{flex:0 0 auto;color:var(--label-2)}
+.plr-btn .icn{font-size:20px}
+/* −15 / +30 as text: no arrow glyph says "fifteen seconds", and this is a button used with a
+ sweaty thumb. A 34px target, which is the smallest one worth having in a gym. */
+.plr-seek{
+ flex:0 0 auto;min-width:34px;height:34px;padding:0 6px;border-radius:10px;border:0;
+ background:var(--surface-3);color:var(--label);font:600 11.5px/1 var(--font);
+ font-variant-numeric:tabular-nums;cursor:pointer;
+}
+.plr-seek:active{background:var(--surface-2)}
+/* The progress hairline: two pixels along the bottom edge of the bar, filled from the left. */
+.plr-progress{
+ position:absolute;left:0;bottom:0;height:2px;
+ background:var(--acc);border-radius:0 2px 2px 0;
+ transition:width var(--fast) linear;
}
-.rad-cover{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;display:block}
-.rad-cover-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
-.rad-cover-ph .icn{font-size:18px}
-.rad-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
-.rad-name{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-.rad-now{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
-.rad-btn{flex:0 0 auto;color:var(--label-2)}
-.rad-btn .icn{font-size:20px}
/* rest variant: −15/+15/Skip and the clock won't share one line on a phone, so the clock and
bar take the top row and the controls take their own. The work timer keeps a single row —
it only ever has two buttons. */
diff --git a/frontend/src/lib/player.js b/frontend/src/lib/player.js
new file mode 100644
index 0000000..9d5e82d
--- /dev/null
+++ b/frontend/src/lib/player.js
@@ -0,0 +1,261 @@
+/* player.js — the one `` element, for both the radio and the podcasts.
+ *
+ * Two kinds of media, one element, and the reasons are all about iOS:
+ *
+ * **It has to be one element.** A second `` competing for the audio session is how a phone
+ * ends up playing a station and an episode at once, or ducking one to silence. The store guarantees
+ * they are mutually exclusive; this module is the thing they share.
+ *
+ * **It has to be module-level, outside React.** An `` owned by a component is unmounted with
+ * it, which is how a player stops the moment somebody changes screens — and changing screens
+ * mid-session is the normal case in this app, not the edge case.
+ *
+ * **`play()` has to happen inside the tap.** iOS only allows audio to start from a user gesture, so
+ * nothing asynchronous may sit between the finger and the play: no fetch, no state update, no
+ * re-render. The radio therefore arrives with its stream URL already resolved, and an episode is a
+ * plain `https://` file URL, so both can be handed straight to `playStream`/`playFile`.
+ *
+ * A stream and a file are then treated differently on purpose:
+ *
+ * - A **stream** is endless: no duration, no seeking, nothing to resume. Position is meaningless.
+ * - A **file** has a length, a place you left off, and an end — so it reports time, accepts a
+ * seek, and applies a starting position. That is what makes resuming and "next episode" possible
+ * at all.
+ *
+ * Media Session is the other half of both: with metadata and action handlers set, iOS and Android
+ * show the station or the episode, with its progress, on the lock screen, and the sound keeps going
+ * with the phone in a pocket. While the screen is locked the browser suspends this page's timers, so
+ * the *caption* stops moving; the audio is played by the browser underneath, not by the page.
+ */
+let audio = null
+let handlers = new Set()
+/** The position a file should start at, kept until the browser knows its duration. */
+let pendingStart = 0
+
+function emit(event, extra = {}) {
+ const state = { position: positionOf(), duration: durationOf(), ...extra }
+ for (const h of [...handlers]) {
+ try { h(event, state) } catch { /* one listener throwing must not stop the others */ }
+ }
+}
+
+const positionOf = () => (audio && Number.isFinite(audio.currentTime) ? audio.currentTime : 0)
+const durationOf = () => (audio && Number.isFinite(audio.duration) && audio.duration > 0 ? audio.duration : null)
+
+/**
+ * The element, created on first use — there is no audio before somebody presses play.
+ *
+ * The event listeners are attached once, here, because every other function in this module is a
+ * thin command and the state of the player is only ever reported through them.
+ */
+export function playerEl() {
+ if (audio) return audio
+ if (typeof Audio === 'undefined') return null
+ audio = new Audio()
+ audio.preload = 'none'
+ // Radio has no end and no seeking: those two defaults are for files, and they make a stream
+ // misbehave on some browsers.
+ audio.loop = false
+ audio.addEventListener('timeupdate', () => emit('time'))
+ audio.addEventListener('play', () => emit('playing'))
+ audio.addEventListener('pause', () => emit('paused'))
+ audio.addEventListener('ended', () => emit('ended'))
+ audio.addEventListener('error', () => emit('error'))
+ audio.addEventListener('loadedmetadata', () => {
+ // The starting position of a file can only be applied once the browser knows how long it is.
+ if (pendingStart > 0 && audio.duration > 0) {
+ try { audio.currentTime = Math.min(pendingStart, Math.max(0, audio.duration - 1)) } catch { /* live stream */ }
+ pendingStart = 0
+ }
+ emit('meta')
+ })
+ return audio
+}
+
+/**
+ * Listen to the player. Returns the unsubscribe, and every handler is optional.
+ *
+ * Events: `playing`, `paused`, `time` (a position tick), `meta` (the length is known), `ended`,
+ * `error`. The second argument is always `{ position, duration }`.
+ */
+export function onPlayer(handler) {
+ if (typeof handler !== 'function') return () => {}
+ handlers.add(handler)
+ return () => handlers.delete(handler)
+}
+
+/** Start a live stream. Returns false when the browser refused, which the caller reports. */
+export function playStream(url, volume = 1) {
+ const el = playerEl()
+ if (!el || !url) return false
+ pendingStart = 0
+ el.volume = volume
+ if (el.src !== url) el.src = url
+ return start(el)
+}
+
+/**
+ * Start a file — an episode — at `startAt` seconds in.
+ *
+ * The position is applied when the browser knows the duration, because assigning `currentTime` on a
+ * media element that has not loaded throws or is ignored depending on the browser.
+ */
+export function playFile(url, { startAt = 0, volume = 1 } = {}) {
+ const el = playerEl()
+ if (!el || !url) return false
+ el.volume = volume
+ if (el.src !== url) {
+ el.src = url
+ pendingStart = Math.max(0, Number(startAt) || 0)
+ } else if (startAt > 0 && Math.abs(el.currentTime - startAt) > 2) {
+ pendingStart = Number(startAt) || 0
+ }
+ if (pendingStart > 0 && el.readyState >= 1 && el.duration > 0) {
+ try { el.currentTime = Math.min(pendingStart, Math.max(0, el.duration - 1)) } catch { /* not seekable */ }
+ pendingStart = 0
+ }
+ return start(el)
+}
+
+function start(el) {
+ try {
+ const p = el.play()
+ // A rejected promise is the autoplay policy or a dead stream; either way the screen should not
+ // claim it is playing.
+ if (p && typeof p.catch === 'function') p.catch(() => emit('error'))
+ return true
+ } catch { return false }
+}
+
+/** Start the element again where it is — used by the lock screen's play button. */
+export function resumePlayer() {
+ const el = playerEl()
+ return el ? start(el) : false
+}
+
+export function pausePlayer() {
+ try { audio?.pause() } catch { /* nothing playing */ }
+}
+
+/** Move inside the current file. Streams have no duration, so this does nothing on one. */
+export function seekTo(seconds) {
+ if (!audio) return null
+ const dur = durationOf()
+ const target = Math.max(0, Math.min(Number(seconds) || 0, dur ? dur - 1 : Number.MAX_SAFE_INTEGER))
+ try { audio.currentTime = target } catch { return null }
+ emit('time')
+ return target
+}
+
+/** Fifteen seconds back is the most-used button in every podcast app ever made. */
+export const seekBy = seconds => seekTo(positionOf() + (Number(seconds) || 0))
+
+export const playerTime = () => ({ position: positionOf(), duration: durationOf() })
+
+export function setPlayerVolume(volume) {
+ if (audio) audio.volume = Math.max(0, Math.min(1, Number(volume) || 0))
+}
+
+/**
+ * What the lock screen shows for a **station**. `now` is whatever the station publishes — SomaFM and
+ * Radio Paradise do, the directory's stations do not — and when there is none the station itself is
+ * the answer rather than an invented track.
+ */
+export function setStreamSession(station, now) {
+ setMetadata({
+ title: now?.title || station?.name || '',
+ artist: now?.artist || station?.genre || station?.detail || '',
+ album: 'KuentaGYM Radio',
+ artwork: now?.cover || station?.image || null
+ })
+}
+
+/** What the lock screen shows for an **episode**: the episode, the show, and where you are in it. */
+export function setEpisodeSession(show, episode) {
+ setMetadata({
+ title: episode?.title || show?.name || '',
+ artist: show?.name || '',
+ album: 'KuentaGYM Podcasts',
+ artwork: episode?.image || show?.image || null
+ })
+ setSessionPosition()
+}
+
+function setMetadata({ title, artist, album, artwork }) {
+ const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
+ if (!ms) return
+ // Looked up per call rather than captured at load: a browser (or a test) that defines
+ // MediaMetadata later still gets a lock screen, and one without it keeps working the same way.
+ const Metadata = typeof MediaMetadata !== 'undefined' ? MediaMetadata : null
+ try {
+ if (Metadata) {
+ ms.metadata = new Metadata({
+ title: title || '',
+ artist: artist || '',
+ album,
+ artwork: /^https:\/\//i.test(artwork || '') ? [{ src: artwork, sizes: '512x512', type: 'image/jpeg' }] : []
+ })
+ }
+ } catch { /* a browser without Media Session simply shows nothing */ }
+}
+
+/**
+ * The lock screen's progress bar.
+ *
+ * Wrapped in a try/catch because `setPositionState` throws on anything it considers inconsistent
+ * (a position past the end, a zero duration, a missing one) and a lock screen is not worth an
+ * exception in the middle of a workout.
+ */
+export function setSessionPosition(duration = durationOf(), position = positionOf(), playbackRate = 1) {
+ const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
+ if (!ms?.setPositionState) return
+ try {
+ if (!Number.isFinite(duration) || duration <= 0) { ms.setPositionState(); return }
+ ms.setPositionState({
+ duration,
+ playbackRate,
+ position: Math.max(0, Math.min(Number(position) || 0, duration))
+ })
+ } catch { /* an older browser, or a state it did not like */ }
+}
+
+/* The handlers are how the lock screen's buttons reach this element. They are set once per session
+ rather than per track: `play` and `pause` mean the same thing for a station and an episode. */
+let sessionWired = false
+export function wireSessionHandlers() {
+ const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
+ if (!ms || sessionWired) return
+ sessionWired = true
+ try {
+ ms.setActionHandler?.('play', () => resumePlayer())
+ ms.setActionHandler?.('pause', () => pausePlayer())
+ ms.setActionHandler?.('stop', () => pausePlayer())
+ ms.setActionHandler?.('seekbackward', () => seekBy(-15))
+ ms.setActionHandler?.('seekforward', () => seekBy(30))
+ ms.setActionHandler?.('seekto', e => { if (e?.seekTime != null) seekTo(e.seekTime) })
+ } catch { /* a browser without those actions */ }
+}
+
+export function clearSession() {
+ const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
+ if (!ms) return
+ try {
+ ms.metadata = null
+ ms.setPositionState?.()
+ ms.setActionHandler?.('play', null)
+ ms.setActionHandler?.('pause', null)
+ ms.setActionHandler?.('stop', null)
+ ms.setActionHandler?.('seekbackward', null)
+ ms.setActionHandler?.('seekforward', null)
+ ms.setActionHandler?.('seekto', null)
+ } catch { /* as above */ }
+}
+
+/** Only for tests: forget the element and the listeners so each one starts clean. */
+export function __resetPlayer() {
+ try { audio?.pause() } catch { /* nothing playing */ }
+ audio = null
+ handlers = new Set()
+ pendingStart = 0
+ sessionWired = false
+}
diff --git a/frontend/src/lib/player.test.js b/frontend/src/lib/player.test.js
new file mode 100644
index 0000000..1f742f8
--- /dev/null
+++ b/frontend/src/lib/player.test.js
@@ -0,0 +1,213 @@
+// @vitest-environment happy-dom
+/* The one audio element, and the file-vs-stream difference that decides whether podcasts work.
+ *
+ * What is tested here is the part that cannot be seen by tapping: that a file's starting position is
+ * applied *after* the browser knows the length (assigning `currentTime` before that is ignored or
+ * throws, per browser), that a seek is clamped inside the file, and that the lock screen's metadata
+ * and progress are set for both kinds of media — a podcast on a locked phone should show the
+ * episode, the show and how far in you are, not a blank rectangle.
+ *
+ * `duration` is a read-only getter in a DOM, so the tests define it on the element the way the
+ * browser fills it in and then dispatch the event that says so. */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ playerEl, playStream, playFile, pausePlayer, resumePlayer, seekTo, seekBy, playerTime,
+ setPlayerVolume, onPlayer, setStreamSession, setEpisodeSession, setSessionPosition,
+ wireSessionHandlers, clearSession, __resetPlayer
+} from './player.js'
+
+/** Pretend the browser finished loading a file of this length. */
+function pretendLoaded(el, seconds) {
+ Object.defineProperty(el, 'duration', { value: seconds, configurable: true })
+ el.dispatchEvent(new Event('loadedmetadata'))
+}
+
+let session
+beforeEach(() => {
+ __resetPlayer()
+ session = { metadata: null, position: null, handlers: {}, setPositionState (s) { this.position = s ?? null } }
+ session.setActionHandler = (name, fn) => { session.handlers[name] = fn }
+ Object.defineProperty(navigator, 'mediaSession', { value: session, configurable: true })
+ // happy-dom has neither, and both are what a phone actually has: the metadata object the lock
+ // screen is handed, and the session it hangs off.
+ vi.stubGlobal('MediaMetadata', class { constructor(o) { Object.assign(this, o) } })
+})
+afterEach(() => { __resetPlayer(); delete navigator.mediaSession; vi.unstubAllGlobals() })
+
+describe('one element for everything', () => {
+ it('is created once and shared, so a station and an episode never play at the same time', () => {
+ const a = playerEl()
+ expect(a).toBe(playerEl())
+ __resetPlayer()
+ expect(playerEl()).not.toBe(a)
+ expect(playerEl).toBeTruthy()
+ })
+
+ it('hands a station straight to play, inside the tap that asked for it', () => {
+ const el = playerEl()
+ const play = vi.spyOn(el, 'play')
+ expect(playStream('https://ice2.somafm.com/x-128-mp3', 0.6)).toBe(true)
+ expect(el.src).toBe('https://ice2.somafm.com/x-128-mp3')
+ expect(el.volume).toBe(0.6)
+ expect(play).toHaveBeenCalled()
+ expect(playStream('', 1)).toBe(false)
+ })
+
+ it('refuses to claim it is playing when the browser rejects the play', () => {
+ const el = playerEl()
+ el.play = () => { throw new Error('not allowed') }
+ expect(playStream('https://x/1.mp3')).toBe(false)
+ })
+})
+
+describe('a file, which is what an episode is', () => {
+ it('applies the starting position only once the length is known', () => {
+ const el = playerEl()
+ playFile('https://audio.example.com/1.mp3', { startAt: 600 })
+ expect(el.src).toBe('https://audio.example.com/1.mp3')
+ // Nothing yet: the browser has no duration, so a seek here would be ignored or throw.
+ expect(el.currentTime).toBe(0)
+ pretendLoaded(el, 3135)
+ expect(el.currentTime).toBe(600)
+ })
+
+ it('starts a file from the beginning when the saved position was past its end', () => {
+ const el = playerEl()
+ playFile('https://audio.example.com/1.mp3', { startAt: 99999 })
+ expect(el.currentTime).toBe(0, 'no seek before metadata')
+ pretendLoaded(el, 3135)
+ // Clamped inside the file rather than to its exact end, which some browsers treat as "finished".
+ expect(el.currentTime).toBe(3134)
+ })
+
+ it('reports the position and the length together', () => {
+ const el = playerEl()
+ playFile('https://audio.example.com/1.mp3')
+ expect(playerTime()).toEqual({ position: 0, duration: null })
+ pretendLoaded(el, 1200)
+ expect(playerTime()).toEqual({ position: 0, duration: 1200 })
+ })
+
+ it('seeks forward and back inside the file, and never outside it', () => {
+ const el = playerEl()
+ playFile('https://audio.example.com/1.mp3')
+ pretendLoaded(el, 1200)
+ el.currentTime = 100
+ expect(seekBy(15)).toBe(115)
+ expect(seekBy(-15)).toBe(100)
+ // Fifteen back from the first seconds lands at zero, not at a negative position.
+ expect(seekTo(5)).toBe(5)
+ expect(seekBy(-15)).toBe(0)
+ expect(seekTo(99999)).toBe(1199)
+ expect(seekTo(-5)).toBe(0)
+ })
+
+ it('resumes where it is, which is what the lock screen asks for', () => {
+ const el = playerEl()
+ const play = vi.spyOn(el, 'play')
+ el.currentTime = 42
+ expect(resumePlayer()).toBe(true)
+ expect(play).toHaveBeenCalled()
+ expect(el.currentTime).toBe(42)
+ pausePlayer()
+ })
+
+ it('clamps the volume', () => {
+ const el = playerEl()
+ setPlayerVolume(0.4)
+ expect(el.volume).toBe(0.4)
+ setPlayerVolume(9)
+ expect(el.volume).toBe(1)
+ setPlayerVolume('x')
+ expect(el.volume).toBe(0)
+ })
+})
+
+describe('what the rest of the app hears', () => {
+ it('reports playing, paused, time and the end of an episode', () => {
+ const el = playerEl()
+ const seen = []
+ const off = onPlayer((event, state) => seen.push([event, state.position, state.duration]))
+ pretendLoaded(el, 300)
+ el.dispatchEvent(new Event('play'))
+ el.dispatchEvent(new Event('timeupdate'))
+ el.dispatchEvent(new Event('pause'))
+ el.dispatchEvent(new Event('ended'))
+ expect(seen.map(s => s[0])).toEqual(['meta', 'playing', 'time', 'paused', 'ended'])
+ expect(seen[0][2]).toBe(300)
+ off()
+ el.dispatchEvent(new Event('timeupdate'))
+ expect(seen.length).toBe(5)
+ })
+
+ it('keeps going when one listener throws', () => {
+ const el = playerEl()
+ const other = vi.fn()
+ onPlayer(() => { throw new Error('boom') })
+ onPlayer(other)
+ el.dispatchEvent(new Event('play'))
+ expect(other).toHaveBeenCalled()
+ })
+})
+
+describe('the lock screen', () => {
+ it('shows the station, and the track when the station publishes one', () => {
+ setStreamSession({ name: 'Beat Blender', genre: 'Electronic', image: 'https://x/logo.png' })
+ expect(session.metadata.title).toBe('Beat Blender')
+ expect(session.metadata.artist).toBe('Electronic')
+ setStreamSession({ name: 'Beat Blender' }, { artist: 'Tycho', title: 'From Home', cover: 'https://x/c.jpg' })
+ expect(session.metadata.title).toBe('From Home')
+ expect(session.metadata.artist).toBe('Tycho')
+ })
+
+ it('shows the episode and the show, and how far into it you are', () => {
+ const el = playerEl()
+ playFile('https://audio.example.com/1.mp3')
+ pretendLoaded(el, 3600)
+ el.currentTime = 900
+ setEpisodeSession({ name: 'Tiene Sentido', image: 'https://x/show.jpg' }, { title: 'Episodio 12' })
+ expect(session.metadata.title).toBe('Episodio 12')
+ expect(session.metadata.artist).toBe('Tiene Sentido')
+ expect(session.position).toEqual({ duration: 3600, position: 900, playbackRate: 1 })
+ })
+
+ it('does not set a position state it cannot justify, and never throws on one', () => {
+ // A live stream has no duration: no progress bar, and `setPositionState()` with nothing is how
+ // it is cleared.
+ expect(() => setSessionPosition(null, 0)).not.toThrow()
+ expect(session.position).toBe(null)
+ // A duration of zero, or a position past the end, is exactly what the API throws on.
+ expect(() => setSessionPosition(0, 10)).not.toThrow()
+ session.setPositionState = () => { throw new Error('InvalidStateError') }
+ expect(() => setSessionPosition(100, 500)).not.toThrow()
+ })
+
+ it('puts the lock screen buttons on the element, once', () => {
+ const el = playerEl()
+ wireSessionHandlers()
+ wireSessionHandlers()
+ expect(typeof session.handlers.pause).toBe('function')
+ expect(typeof session.handlers.seekbackward).toBe('function')
+ playFile('https://audio.example.com/1.mp3')
+ pretendLoaded(el, 600)
+ el.currentTime = 100
+ session.handlers.seekbackward()
+ expect(el.currentTime).toBe(85)
+ session.handlers.seekforward()
+ expect(el.currentTime).toBe(115)
+ session.handlers.seekto({ seekTime: 300 })
+ expect(el.currentTime).toBe(300)
+ const pause = vi.spyOn(el, 'pause')
+ session.handlers.pause()
+ expect(pause).toHaveBeenCalled()
+ })
+
+ it('clears everything when the player is stopped', () => {
+ setStreamSession({ name: 'Beat Blender' })
+ wireSessionHandlers()
+ clearSession()
+ expect(session.metadata).toBe(null)
+ expect(session.handlers.play).toBe(null)
+ expect(session.handlers.pause).toBe(null)
+ })
+})
diff --git a/frontend/src/lib/podcast-view.js b/frontend/src/lib/podcast-view.js
new file mode 100644
index 0000000..de72c42
--- /dev/null
+++ b/frontend/src/lib/podcast-view.js
@@ -0,0 +1,127 @@
+/* The rules behind the podcast player: where to resume, how long an episode is, what comes next.
+ *
+ * A stream needs none of this — radio has no position, no end and nothing to continue — but every
+ * one of these is the difference between a podcast app you use and one you fight with while your
+ * hands are on a bar:
+ *
+ * - **Resume.** Coming back to a 50-minute episode must not mean finding your place again. The
+ * position is kept per episode, in the profile, and this decides when it is worth using.
+ * - **Almost finished is finished.** Resuming 20 seconds before the end is a worse experience than
+ * starting over, and it also leaves an episode that always looks unplayed.
+ * - **Next.** Episodes are made in order; the end of one should be the start of the next.
+ *
+ * All of it is pure and tested, because "started the wrong episode halfway through" is not something
+ * anybody reports as a bug — they just stop using the feature. */
+import { fmtDate } from './format.js'
+
+/** Resume under this many seconds in: not worth it, start from the beginning. */
+export const MIN_RESUME = 30
+/** Within this much of the end, the episode counts as finished. */
+export const END_SLACK = 20
+/** Positions kept per profile. Unbounded growth in a synced document is a slow, silent leak. */
+export const MAX_PROGRESS = 200
+
+/** `52:15`, `1:02:03` — the clock a player shows, not a human summary. */
+export function fmtClock(seconds) {
+ const s = Math.max(0, Math.floor(Number(seconds) || 0))
+ const h = Math.floor(s / 3600)
+ const m = Math.floor((s % 3600) / 60)
+ const ss = String(s % 60).padStart(2, '0')
+ return h ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`
+}
+
+/** `52 min`, `1h 12m` — what an episode's length reads as in a list. Null when the feed said nothing. */
+export function fmtLength(seconds) {
+ if (!Number.isFinite(seconds) || seconds <= 0) return null
+ // A trailer is under a minute and should not round up to "1 min".
+ if (seconds < 60) return '<1 min'
+ const m = Math.round(seconds / 60)
+ return m >= 60 ? `${Math.floor(m / 60)}h ${m % 60}m` : `${m} min`
+}
+
+/**
+ * The second line of an episode row: the date it came out, and how long it is.
+ *
+ * Either half can be missing — plenty of feeds publish no `pubDate`, and `itunes:duration` is
+ * optional — so the separator only appears when there is something on both sides of it.
+ */
+export function episodeMeta(ep) {
+ const date = typeof ep?.date === 'string' && /^\d{4}-\d{2}-\d{2}/.test(ep.date)
+ ? fmtDate(ep.date.slice(0, 10), false, true)
+ : null
+ return [date, fmtLength(ep?.duration)].filter(Boolean).join(' · ')
+}
+
+/** Where to start an episode, given what was saved for it before. 0 means "from the beginning". */
+export function resumeSeconds(entry, duration) {
+ const pos = Number(entry?.pos)
+ if (!Number.isFinite(pos) || pos < MIN_RESUME) return 0
+ const dur = Number(duration ?? entry?.dur)
+ // A finished episode starts over: resuming into the last twenty seconds is a puzzle, not a
+ // feature, and it also leaves an episode that looks permanently unplayed.
+ if (Number.isFinite(dur) && dur > 0 && pos >= dur - END_SLACK) return 0
+ return pos
+}
+
+/** How far through the episode is, 0-100, or null when the length is unknown. */
+export function progressPct(entry, duration) {
+ const dur = Number(duration ?? entry?.dur)
+ const pos = Number(entry?.pos)
+ if (!Number.isFinite(dur) || dur <= 0 || !Number.isFinite(pos)) return null
+ return Math.max(0, Math.min(100, (pos / dur) * 100))
+}
+
+/** Played to (near enough) the end. Used to mark a row as heard rather than to stop anything. */
+export function isFinished(entry, duration) {
+ const dur = Number(duration ?? entry?.dur)
+ const pos = Number(entry?.pos)
+ if (!Number.isFinite(dur) || dur <= 0 || !Number.isFinite(pos)) return false
+ return pos >= dur - END_SLACK
+}
+
+/** The episode after this one in the queue, or null at the end of it. No wrapping. */
+export function nextEpisode(queue, currentId) {
+ const list = Array.isArray(queue) ? queue : []
+ const i = list.findIndex(e => e && e.id === currentId)
+ return i >= 0 && i + 1 < list.length ? list[i + 1] : null
+}
+
+/** The episode before this one, or null. Used by the bar's back button. */
+export function prevEpisode(queue, currentId) {
+ const list = Array.isArray(queue) ? queue : []
+ const i = list.findIndex(e => e && e.id === currentId)
+ return i > 0 ? list[i - 1] : null
+}
+
+/** The queue an episode was started from: the list it was tapped in, in the order it was shown. */
+export function queueFor(episodes, episode) {
+ const list = Array.isArray(episodes) ? episodes.filter(Boolean) : []
+ return list.some(e => e.id === episode?.id) ? list : [episode].filter(Boolean)
+}
+
+/**
+ * Keep the newest `max` positions and forget the rest.
+ *
+ * `at` is when the position was last written; the oldest entries go first, so somebody with years of
+ * listening keeps the episodes they are actually in the middle of.
+ */
+export function trimProgress(progress, max = MAX_PROGRESS) {
+ const entries = Object.entries(progress || {})
+ if (entries.length <= max) return progress || {}
+ /* Newest first, and on a tie the later entry wins: several positions can be written inside the
+ same millisecond, and an object's own order is insertion order — so the tie-break is exactly
+ "the one saved most recently", instead of leaving the outcome to the sort's stability. */
+ return Object.fromEntries(entries
+ .map(([key, value], i) => ({ key, value, at: Number(value?.at) || 0, i }))
+ .sort((a, b) => (b.at - a.at) || (b.i - a.i))
+ .slice(0, max)
+ .map(e => [e.key, e.value]))
+}
+
+/** Whether a position is worth writing down at all: a two-second tap on play is not progress. */
+export function worthSaving(entry, duration) {
+ const pos = Number(entry?.pos)
+ if (!Number.isFinite(pos) || pos < 5) return false
+ const dur = Number(duration ?? entry?.dur)
+ return !(Number.isFinite(dur) && dur > 0 && pos >= dur - END_SLACK)
+}
diff --git a/frontend/src/lib/podcast-view.test.js b/frontend/src/lib/podcast-view.test.js
new file mode 100644
index 0000000..844c074
--- /dev/null
+++ b/frontend/src/lib/podcast-view.test.js
@@ -0,0 +1,116 @@
+/* The podcast player's rules, tested — because none of them fail loudly.
+ *
+ * `isFinished` and `resumeSeconds` are the pair that matter: resuming 15 seconds before the end, or
+ * marking a half-heard episode as heard, are both bugs that look like the app being stubborn rather
+ * than broken, and nobody reports those. */
+import { describe, expect, it } from 'vitest'
+import {
+ MIN_RESUME, END_SLACK, MAX_PROGRESS, fmtClock, fmtLength, episodeMeta, resumeSeconds,
+ progressPct, isFinished, nextEpisode, prevEpisode, queueFor, trimProgress, worthSaving
+} from './podcast-view.js'
+
+const ep = (over = {}) => ({ id: 'e1', title: 'Un episodio', url: 'https://a/1.mp3', date: '2025-09-12T10:00:00.000Z', duration: 3135, ...over })
+
+describe('how an episode reads', () => {
+ it('shows a clock, not a human summary', () => {
+ expect(fmtClock(3135)).toBe('52:15')
+ expect(fmtClock(3723)).toBe('1:02:03')
+ expect(fmtClock(59)).toBe('0:59')
+ expect(fmtClock(0)).toBe('0:00')
+ expect(fmtClock(-5)).toBe('0:00')
+ expect(fmtClock(undefined)).toBe('0:00')
+ })
+
+ it('summarises a length the way a list wants it', () => {
+ expect(fmtLength(3135)).toBe('52 min')
+ expect(fmtLength(7200)).toBe('2h 0m')
+ expect(fmtLength(30)).toBe('<1 min')
+ // A feed that declares no duration gets no invented one.
+ expect(fmtLength(null)).toBe(null)
+ expect(fmtLength(0)).toBe(null)
+ })
+
+ it('puts the date and the length on one line, and works when either is missing', () => {
+ expect(episodeMeta(ep())).toContain('52 min')
+ expect(episodeMeta(ep())).toMatch(/2025/)
+ expect(episodeMeta(ep({ duration: null }))).not.toContain('·')
+ expect(episodeMeta(ep({ date: null }))).toBe('52 min')
+ expect(episodeMeta(ep({ date: null, duration: null }))).toBe('')
+ expect(episodeMeta(null)).toBe('')
+ })
+})
+
+describe('picking up where you left off', () => {
+ it('resumes a real position', () => {
+ expect(resumeSeconds({ pos: 600, dur: 3135 }, 3135)).toBe(600)
+ })
+
+ it('does not bother for the first few seconds', () => {
+ expect(resumeSeconds({ pos: MIN_RESUME - 1 }, 3135)).toBe(0)
+ expect(resumeSeconds({ pos: 0 }, 3135)).toBe(0)
+ expect(resumeSeconds(null, 3135)).toBe(0)
+ expect(resumeSeconds({ pos: 'x' }, 3135)).toBe(0)
+ })
+
+ it('starts a finished episode over instead of resuming into its last seconds', () => {
+ expect(resumeSeconds({ pos: 3135 - END_SLACK, dur: 3135 }, 3135)).toBe(0)
+ expect(resumeSeconds({ pos: 3130 }, 3135)).toBe(0)
+ // With no length stored, the position is all there is to go on — and it is used.
+ expect(resumeSeconds({ pos: 3130 }, null)).toBe(3130)
+ })
+
+ it('counts an episode near its end as finished, and a shorter one is not', () => {
+ expect(isFinished({ pos: 3130, dur: 3135 }, 3135)).toBe(true)
+ expect(isFinished({ pos: 3000, dur: 3135 }, 3135)).toBe(false)
+ expect(isFinished({ pos: 600 }, null)).toBe(false)
+ expect(isFinished(null, 3135)).toBe(false)
+ })
+
+ it('reports progress as a percentage, and refuses to invent a length', () => {
+ expect(progressPct({ pos: 1567, dur: 3134 }, 3134)).toBeCloseTo(50, 0)
+ expect(progressPct({ pos: 9999, dur: 3134 }, 3134)).toBe(100)
+ expect(progressPct({ pos: 100 }, null)).toBe(null)
+ expect(progressPct(null, 3134)).toBe(null)
+ })
+
+ it('only writes down a position worth having', () => {
+ expect(worthSaving({ pos: 4 }, 3135)).toBe(false)
+ expect(worthSaving({ pos: 5 }, 3135)).toBe(true)
+ // The last seconds of an episode are not a position to come back to.
+ expect(worthSaving({ pos: 3131 }, 3135)).toBe(false)
+ expect(worthSaving({ pos: 60 }, null)).toBe(true)
+ })
+})
+
+describe('the queue', () => {
+ const a = ep({ id: 'a' }), b = ep({ id: 'b' }), c = ep({ id: 'c' })
+
+ it('goes to the next episode, and stops at the end', () => {
+ expect(nextEpisode([a, b, c], 'a').id).toBe('b')
+ expect(nextEpisode([a, b, c], 'c')).toBe(null)
+ expect(nextEpisode([a, b, c], 'nope')).toBe(null)
+ expect(nextEpisode(null, 'a')).toBe(null)
+ })
+
+ it('goes back, and stops at the beginning', () => {
+ expect(prevEpisode([a, b, c], 'c').id).toBe('b')
+ expect(prevEpisode([a, b, c], 'a')).toBe(null)
+ })
+
+ it('plays an episode that was not in the list it came from, on its own', () => {
+ expect(queueFor([a, b], a).map(e => e.id)).toEqual(['a', 'b'])
+ const orphan = ep({ id: 'z' })
+ expect(queueFor([a, b], orphan).map(e => e.id)).toEqual(['z'])
+ expect(queueFor(null, a).map(e => e.id)).toEqual(['a'])
+ })
+
+ it('keeps the newest positions and lets the old ones go', () => {
+ const many = Object.fromEntries(Array.from({ length: MAX_PROGRESS + 20 }, (_, i) => ['e' + i, { pos: 10, at: i }]))
+ const kept = trimProgress(many)
+ expect(Object.keys(kept).length).toBe(MAX_PROGRESS)
+ expect(kept['e' + (MAX_PROGRESS + 19)]).toBeTruthy() // the most recent
+ expect(kept.e0).toBeUndefined() // and the oldest is gone
+ expect(trimProgress({ a: { pos: 1 } })).toEqual({ a: { pos: 1 } })
+ expect(trimProgress(null)).toEqual({})
+ })
+})
diff --git a/frontend/src/lib/radio-player.js b/frontend/src/lib/radio-player.js
deleted file mode 100644
index 248e335..0000000
--- a/frontend/src/lib/radio-player.js
+++ /dev/null
@@ -1,94 +0,0 @@
-/* radio-player.js — the one `` element, and the lock screen.
- *
- * A module of its own, and a module-level element, for one reason that decides whether this feature
- * works at all on an iPhone: **`play()` has to be called inside the tap's own task.** iOS only lets
- * audio start from a gesture, so anything asynchronous between the press and the play — a fetch, a
- * state update, a re-render — is a press that does nothing. The stream URL therefore arrives with
- * the station (the api resolves it when it builds the list), the press calls `play()` synchronously
- * on this element, and the store only records what happened afterwards.
- *
- * The element lives outside React on purpose. An `` owned by a component is unmounted when
- * that component is, which is how a player stops the moment somebody changes screens; this one
- * survives every navigation, which is what makes listening while training possible.
- *
- * Media Session is the other half: with metadata and action handlers set, iOS and Android show the
- * station, the track and the controls on the lock screen, and the music keeps playing with the
- * phone in a pocket.
- */
-const MEDIA_METADATA = typeof MediaMetadata !== 'undefined' ? MediaMetadata : null
-
-let audio = null
-/** The element, created on first use — there is no audio before somebody presses play. */
-export function radioAudio() {
- if (audio) return audio
- if (typeof Audio === 'undefined') return null
- audio = new Audio()
- audio.preload = 'none'
- // Radio has no end, and no seeking: those two defaults are for files, and they make a stream
- // misbehave on some browsers.
- audio.loop = false
- return audio
-}
-
-/** Start a stream. Returns false when the browser refused, which the caller reports. */
-export function playStream(url, volume = 1) {
- const el = radioAudio()
- if (!el || !url) return false
- el.volume = volume
- if (el.src !== url) el.src = url
- try {
- const p = el.play()
- // A rejected promise is the autoplay policy or a dead stream; either way the screen should not
- // claim it is playing.
- if (p && typeof p.catch === 'function') p.catch(() => {})
- return true
- } catch { return false }
-}
-
-export function pauseStream() {
- try { audio?.pause() } catch { /* nothing playing */ }
-}
-
-export function setStreamVolume(volume) {
- if (audio) audio.volume = Math.max(0, Math.min(1, Number(volume) || 0))
-}
-
-/**
- * What the lock screen shows. `now` is whatever the station publishes — SomaFM and Radio Paradise
- * do, the directory's stations do not — and when there is none the station itself is the answer
- * rather than an invented track.
- */
-export function setMediaSession(station, now) {
- const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
- if (!ms || !station) return
- try {
- if (MEDIA_METADATA) {
- ms.metadata = new MEDIA_METADATA({
- title: now?.title || station.name || '',
- artist: now?.artist || station.genre || station.detail || '',
- album: 'KuentaGYM Radio',
- artwork: station.image || now?.cover
- ? [{ src: (station.image || now?.cover), sizes: '512x512', type: 'image/jpeg' }]
- : []
- })
- }
- // The handlers are how the lock screen's buttons reach this element.
- ms.setActionHandler?.('play', () => playStream(audio?.src))
- ms.setActionHandler?.('pause', () => pauseStream())
- ms.setActionHandler?.('stop', () => pauseStream())
- } catch { /* a browser without Media Session simply shows nothing */ }
-}
-
-export function clearMediaSession() {
- const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
- if (!ms) return
- try {
- ms.metadata = null
- ms.setActionHandler?.('play', null)
- ms.setActionHandler?.('pause', null)
- ms.setActionHandler?.('stop', null)
- } catch { /* as above */ }
-}
-
-/** Only for tests: forget the element so each one starts clean. */
-export function __resetRadioAudio() { audio = null }
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 5642460..19ff6ee 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1408,6 +1408,28 @@ export default {
// segunda opinión (Jev)
'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
+ 'Podcasts': 'Podcasts',
+ 'Podcast': 'Podcast',
+ 'Saved podcasts': 'Podcasts guardados',
+ 'Save this podcast': 'Guardar este podcast',
+ 'Saved to your podcasts': 'Guardado en tus podcasts',
+ 'Open {0}': 'Abrir {0}',
+ 'Loading podcasts…': 'Cargando podcasts…',
+ 'Reading the feed…': 'Leyendo el feed…',
+ 'No Spanish shows come back for this category. Try another one.': 'No volvió ningún programa en español para esta categoría. Probá con otra.',
+ 'No Spanish shows came back for this category. Try another one.': 'No volvió ningún programa en español para esta categoría. Probá con otra.',
+ 'That feed did not answer. It may be down, or it may block this server.': 'Ese feed no respondió. Puede estar caído, o bloquear a este servidor.',
+ 'That podcast is not in Spanish, so it is not listed here.': 'Ese podcast no está en español, así que no se lista acá.',
+ 'That feed has no playable episodes in it — trailers only, or subscriber-only audio.': 'Ese feed no tiene episodios que se puedan reproducir: sólo avances, o audio sólo para suscriptores.',
+ '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.': 'Sólo podcasts en español, y eso se comprueba en el feed de cada programa en vez de darlo por hecho por la tienda. No se descarga nada: el episodio va directo de quien lo publica a tu teléfono, y lo que ya escuchaste queda guardado por perfil.',
+ 'Your server has not been updated for the podcasts yet: it is the server that finds them, and this app is newer than it. Restarting it should be enough.': 'Tu servidor todavía no se actualizó para los podcasts: los busca el servidor, y esta app es más nueva que él. Reiniciarlo debería alcanzar.',
+ 'Podcasts come from your server, so they need a profile: sign in and the shows appear here.': 'Los podcasts vienen de tu servidor, así que necesitan un perfil: entrá a tu cuenta y los programas aparecen acá.',
+ '15 seconds back': '15 segundos atrás',
+ '30 seconds forward': '30 segundos adelante',
+ 'Next episode': 'Siguiente episodio',
+ 'Heard': 'Escuchado',
+ '{0} in': 'en {0}',
// radio
'Radio': 'Radio',
'Playing {0}': 'Sonando {0}',
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 2cde6e4..4bce86e 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -11,6 +11,7 @@ import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js
import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'
import { WC_DEFAULT } from '../lib/workout-controls.js'
+import { trimProgress } from '../lib/podcast-view.js'
const KEY = 'gym_state_v1'
// Where this device stands with the server: the revision it last adopted or pushed, and its own
@@ -36,6 +37,10 @@ export const DEF = {
// are the share links the Music app copies, with whatever the public page could tell us about
// them. In the profile document like the routines, so they sync and they are backed up.
music: { user: '', playlists: [], stations: [] },
+ // Podcasts: the shows saved next to the radio stations, and where each episode was left off.
+ // The positions are the whole reason this is in the profile document rather than in memory — a
+ // 50-minute episode resumed from the beginning on the next device is the feature not working.
+ podcasts: { shows: [], progress: {} },
// How the active workout is laid out — 'cards' (one exercise at a time with Prev/Next),
// 'list' (every exercise stacked and scrollable) or 'compact' (that stack stripped to just
// names and set rows — no media, tags, notes, last-time or progression line). Purely
@@ -373,6 +378,42 @@ export const useStore = create((set, get) => {
})
},
+ /* Podcast shows, keyed by their feed: the same show reached from two categories is one row, and
+ unstarring one never depends on its position. */
+ addPodcast(show) {
+ if (!show || !show.feed) return
+ get().update(s => {
+ const pod = s.podcasts || { shows: [], progress: {} }
+ const list = pod.shows || []
+ if (list.some(x => x.feed === show.feed)) return
+ s.podcasts = {
+ ...pod,
+ shows: [...list, {
+ feed: show.feed, name: show.name || '', author: show.author || '',
+ image: show.image || null, genre: show.genre || '', lang: show.lang || null
+ }]
+ }
+ })
+ },
+ removePodcast(feed) {
+ get().update(s => {
+ const pod = s.podcasts || { shows: [], progress: {} }
+ s.podcasts = { ...pod, shows: (pod.shows || []).filter(x => x.feed !== feed) }
+ })
+ },
+ /* Where an episode was left off. Called on the player's own schedule (not on every tick), and
+ trimmed: two hundred episodes is years of listening, and an unbounded map in a document that
+ syncs to the server is a slow leak nobody would ever notice. */
+ savePodcastPosition(episodeId, position, duration) {
+ if (!episodeId || !Number.isFinite(Number(position))) return
+ get().update(s => {
+ const pod = s.podcasts || { shows: [], progress: {} }
+ const progress = { ...(pod.progress || {}) }
+ progress[episodeId] = { pos: Math.max(0, Math.round(Number(position))), dur: Math.round(Number(duration) || 0) || null, at: Date.now() }
+ s.podcasts = { ...pod, progress: trimProgress(progress) }
+ })
+ },
+
/* Apple Music playlists (views/Music.jsx). Two mutations rather than one generic setter,
because the list is keyed by the playlist id: adding the same link twice is a no-op rather
than two identical cards, and removing one never depends on its position. */
diff --git a/frontend/src/store/useStore.podcasts.test.jsx b/frontend/src/store/useStore.podcasts.test.jsx
new file mode 100644
index 0000000..c77e7c3
--- /dev/null
+++ b/frontend/src/store/useStore.podcasts.test.jsx
@@ -0,0 +1,91 @@
+// @vitest-environment happy-dom
+/* The shows a profile saves, and where each episode was left off.
+ *
+ * The positions are the reason this state is in the profile document instead of in memory: resume a
+ * 50-minute episode from the beginning on the next device and the feature simply does not exist. Two
+ * things have to hold, and neither is visible from the screen:
+ *
+ * - A position is *merged*, never rebuilt. `podcasts` holds the shows and the positions, and the
+ * methods that touch one must leave the other alone — the same bug the radio stations had, where
+ * removing a playlist wiped them.
+ * - It is *bounded*. Two hundred episodes is years of listening; an unbounded map in a document
+ * that syncs to the server is a leak nobody would ever notice. */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('../lib/api.js', () => ({ api: vi.fn().mockResolvedValue({}) }))
+
+import { useStore } from './useStore.js'
+import { MAX_PROGRESS } from '../lib/podcast-view.js'
+
+const show = (over = {}) => ({ feed: 'https://a.example.com/feed', name: 'Nadie Sabe Nada', author: 'Cadena SER', genre: 'Comedy', image: 'https://x/a.jpg', ...over })
+
+const pod = () => useStore.getState().S.podcasts
+beforeEach(() => {
+ useStore.setState(s => ({ S: { ...s.S, podcasts: { shows: [], progress: {} } } }))
+})
+
+describe('saved podcasts', () => {
+ it('saves a show by its feed, and the same feed twice is one row', () => {
+ useStore.getState().addPodcast(show())
+ useStore.getState().addPodcast(show({ name: 'Nadie Sabe Nada (otra vez)' }))
+ expect(pod().shows).toHaveLength(1)
+ expect(pod().shows[0].name).toBe('Nadie Sabe Nada')
+ })
+
+ it('refuses a show with no feed, which could never be opened again', () => {
+ useStore.getState().addPodcast(show({ feed: null }))
+ useStore.getState().addPodcast(null)
+ expect(pod().shows).toHaveLength(0)
+ })
+
+ it('unsaves the one it was asked about, and only that one', () => {
+ useStore.getState().addPodcast(show())
+ useStore.getState().addPodcast(show({ feed: 'https://b.example.com/feed', name: 'Otro' }))
+ useStore.getState().removePodcast('https://a.example.com/feed')
+ expect(pod().shows.map(s => s.name)).toEqual(['Otro'])
+ })
+
+ it('survives a state that predates podcasts', () => {
+ useStore.setState(s => ({ S: { ...s.S, podcasts: undefined } }))
+ useStore.getState().addPodcast(show())
+ expect(pod().shows).toHaveLength(1)
+ expect(pod().progress).toEqual({})
+ })
+})
+
+describe('where an episode was left off', () => {
+ it('writes a position with its length and a timestamp', () => {
+ useStore.getState().savePodcastPosition('ep-1', 620.7, 3135.4)
+ const entry = pod().progress['ep-1']
+ expect(entry.pos).toBe(621)
+ expect(entry.dur).toBe(3135)
+ expect(entry.at).toBeGreaterThan(0)
+ })
+
+ it('refuses a position that is not a number', () => {
+ useStore.getState().savePodcastPosition('ep-1', Number.NaN, 100)
+ useStore.getState().savePodcastPosition('ep-2', 'mucho', 100)
+ useStore.getState().savePodcastPosition(null, 10, 100)
+ expect(pod().progress).toEqual({})
+ })
+
+ it('keeps the newest positions and forgets the oldest', () => {
+ for (let i = 0; i < MAX_PROGRESS + 10; i++) useStore.getState().savePodcastPosition('ep-' + i, 100, 3600)
+ const kept = pod().progress
+ expect(Object.keys(kept).length).toBe(MAX_PROGRESS)
+ expect(kept['ep-' + (MAX_PROGRESS + 9)]).toBeTruthy()
+ expect(kept['ep-0']).toBeUndefined()
+ })
+
+ it('is not dropped by the mutations that share `podcasts`', () => {
+ useStore.getState().addPodcast(show())
+ useStore.getState().savePodcastPosition('ep-1', 600, 3135)
+ useStore.getState().savePodcastPosition('ep-2', 60, 3135)
+ useStore.getState().removePodcast('https://a.example.com/feed')
+ expect(pod().shows).toHaveLength(0)
+ expect(Object.keys(pod().progress)).toEqual(['ep-1', 'ep-2'])
+
+ useStore.getState().addPodcast(show())
+ expect(Object.keys(pod().progress)).toEqual(['ep-1', 'ep-2'])
+ })
+})
diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js
index 9af847a..3fe0f77 100644
--- a/frontend/src/store/useUI.js
+++ b/frontend/src/store/useUI.js
@@ -2,7 +2,12 @@ import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
-import { playStream, pauseStream, setStreamVolume, setMediaSession, clearMediaSession } from '../lib/radio-player.js'
+import {
+ playStream, playFile, pausePlayer, resumePlayer, seekBy, setPlayerVolume,
+ setStreamSession, setEpisodeSession, setSessionPosition, wireSessionHandlers,
+ clearSession, playerTime, onPlayer
+} from '../lib/player.js'
+import { resumeSeconds, nextEpisode, prevEpisode, queueFor, worthSaving } from '../lib/podcast-view.js'
import { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
import { useStore } from './useStore.js'
@@ -26,6 +31,53 @@ if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => { if (document.hidden) pageHiddenAt = Date.now() })
}
+/* ---------- the podcast's own bookkeeping, at module scope ----------
+ *
+ * How often an episode's position reaches the profile. Not on every `timeupdate` — that is four
+ * times a second, and the document syncs to the server — but every few seconds, and always at the
+ * moments where losing it would hurt: pausing, stopping, the end of an episode, and the app going
+ * to the background (the last tick before a locked screen is the last one for a while: iOS
+ * suspends these timers, so if the position were saved only from a tick, locking the phone would
+ * lose up to five seconds of listening — and, worse, anything at all if the tab were killed). */
+const POD_SAVE_MS = 5000;
+let podSavedAt = 0;
+
+/** Write the current position into the profile, if it is worth writing and the moment is right. */
+function savePodPosition(force = false) {
+ const { pod } = useUI.getState();
+ if (!pod?.episode) return;
+ const { position, duration } = playerTime();
+ const pos = Number.isFinite(position) ? position : pod.position;
+ const dur = Number.isFinite(duration) && duration > 0 ? duration : pod.duration;
+ if (!worthSaving({ pos }, dur)) return;
+ const now = Date.now();
+ if (!force && now - podSavedAt < POD_SAVE_MS) return;
+ podSavedAt = now;
+ useStore.getState().savePodcastPosition(pod.episode.id, pos, dur || 0);
+}
+
+if (typeof document !== 'undefined') {
+ // `pagehide` and the hidden state, because neither is a promise to come back: a phone that locks
+ // while an episode plays is the normal case here, not the edge case.
+ document.addEventListener('visibilitychange', () => { if (document.hidden) savePodPosition(true) });
+ window.addEventListener('pagehide', () => savePodPosition(true));
+}
+
+/* The player reports; the store decides. Registered once, at import, so the bar and the profile keep
+ up whether or not any component happens to be mounted — which matters, because the whole point of
+ the bar living above the router is that the music outlives the screen it started on. */
+onPlayer((event, state) => {
+ const ui = useUI.getState();
+ if (!ui.pod) return;
+ if (event === 'time') { ui.setPodPlayback({ position: state.position, duration: state.duration }); return }
+ if (event === 'meta') { setSessionPosition(state.duration, state.position); ui.setPodPlayback({ duration: state.duration }); return }
+ if (event === 'playing') { ui.setPodPlayback({ playing: true }); return }
+ if (event === 'paused') { ui.setPodPlayback({ playing: false }); savePodPosition(true); return }
+ if (event === 'ended') { ui.podEnded(); return }
+ // A dead file is not a wrong tap: the bar says it stopped rather than claiming it is playing.
+ if (event === 'error') { ui.setPodPlayback({ playing: false }); savePodPosition(true) }
+});
+
// The Push switch in Settings is the one place notifications are turned on, and "on" means this
// browser holds a push subscription. This local alert used to ignore it: every rest asked for the
// permission by itself, and once granted — a page cannot hand a permission back — it fired with the
@@ -64,7 +116,8 @@ export const useUI = create((set, get) => ({
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
toastMsg: '',
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
- radio: null, // { station, playing, volume, now } — the audio element lives in lib/radio-player.js
+ radio: null, // { station, playing, volume, now } — the audio element lives in lib/player.js
+ pod: null, // { show, episode, queue, playing, position, duration } — same element, a file
// forIdx: index of the active entry whose set started the rest (undefined when unknown)
work: null, // work countdown DURING a timed set (issue #16) — { left, total, endsAt, label }
timerFlashId: 0, // changing the id retriggers the theme-blink visual alert
@@ -90,26 +143,154 @@ export const useUI = create((set, get) => ({
},
/* Radio. The stream URL arrives with the station, so this is synchronous from the press to the
- `play()` — which is the whole reason iOS lets it start at all. Nothing here fetches. */
+ `play()` — which is the whole reason iOS lets it start at all. Nothing here fetches, and
+ nothing here waits: the one thing that would break it is an `await` before the play. */
playRadio(station, { volume } = {}) {
if (!station || !station.url) return false
+ // One element, two kinds of media: starting a station ends the episode, and vice versa.
+ get().stopPod()
const v = volume != null ? volume : (get().radio?.volume ?? 1)
const ok = playStream(station.url, v)
set({ radio: { station, playing: ok, volume: v, now: null } })
- setMediaSession(station, null)
+ setStreamSession(station, null)
+ wireSessionHandlers()
return ok
},
toggleRadio() {
const r = get().radio
if (!r) return
- if (r.playing) { pauseStream(); set({ radio: { ...r, playing: false } }) }
+ if (r.playing) { pausePlayer(); set({ radio: { ...r, playing: false } }) }
else { const ok = playStream(r.station.url, r.volume); set({ radio: { ...r, playing: ok } }) }
},
stopRadio() {
- pauseStream()
- clearMediaSession()
+ pausePlayer()
+ clearSession()
set({ radio: null })
},
+ /* Volume, for whoever puts a slider on screen. Nothing draws one today, and there is a reason to
+ think before drawing one: **iOS ignores `HTMLMediaElement.volume` entirely** — the hardware
+ buttons are the only volume there — so a slider on an iPhone would be a control that does
+ nothing. It works on Android and desktop, where the element's volume is real. */
+ setRadioVolume(volume) {
+ const r = get().radio
+ setPlayerVolume(volume)
+ if (r) set({ radio: { ...r, volume } })
+ },
+ /* What the station says it is playing. Only SomaFM and Radio Paradise publish it, and the
+ lock screen gets it too — that is what makes the phone in a pocket show the track. */
+ setRadioNow(now) {
+ const r = get().radio
+ if (!r) return
+ set({ radio: { ...r, now } })
+ setStreamSession(r.station, now)
+ },
+
+ /* ---------- podcasts: the same element, but a file ----------
+ *
+ * Where a stream is one command and done, an episode has state that has to be remembered: the
+ * position, what to play when it ends, and where you were the next time you open it. All of that
+ * lives here, and every write to the profile is throttled — a position is saved on the player's
+ * schedule and when the app goes to the background, never on every tick, because the document
+ * syncs to the server and a tick is four times a second. */
+
+ /** Play an episode, resuming where it was left off. Synchronous, for the reason above. */
+ playEpisode(show, episode, queue) {
+ if (!episode || !episode.url) return false
+ get().stopRadio()
+ const saved = useStore.getState().S.podcasts?.progress?.[episode.id]
+ const startAt = resumeSeconds(saved, episode.duration)
+ const ok = playFile(episode.url, { startAt })
+ set({
+ pod: {
+ show: show || null,
+ episode,
+ queue: queueFor(queue, episode),
+ playing: ok,
+ position: startAt,
+ duration: Number(episode.duration) || null
+ }
+ })
+ setEpisodeSession(show, episode)
+ wireSessionHandlers()
+ savePodPosition(true)
+ return ok
+ },
+ togglePod() {
+ const p = get().pod
+ if (!p) return
+ if (p.playing) {
+ pausePlayer()
+ set({ pod: { ...p, playing: false } })
+ savePodPosition(true)
+ } else {
+ const ok = playFile(p.episode.url, { startAt: p.position || 0 })
+ set({ pod: { ...p, playing: ok } })
+ }
+ },
+ stopPod() {
+ if (!get().pod) return
+ pausePlayer()
+ savePodPosition(true)
+ clearSession()
+ set({ pod: null })
+ },
+ /** Fifteen seconds back, thirty forward — the two buttons a podcast is actually driven with. */
+ podSeek(seconds) {
+ const p = get().pod
+ if (!p) return
+ const to = seekBy(seconds)
+ if (to == null) return
+ set({ pod: { ...p, position: to } })
+ setSessionPosition()
+ },
+ podNext() {
+ const p = get().pod
+ if (!p) return false
+ const next = nextEpisode(p.queue, p.episode.id)
+ // The end of the queue is the end: no wrapping back to the start, which is a surprise nobody
+ // wants in the middle of a workout.
+ if (!next) return false
+ return get().playEpisode(p.show, next, p.queue)
+ },
+ podPrev() {
+ const p = get().pod
+ if (!p) return false
+ const prev = prevEpisode(p.queue, p.episode.id)
+ if (!prev) return false
+ return get().playEpisode(p.show, prev, p.queue)
+ },
+ /** Called by the player's own events: the position on screen, and sometimes the profile.
+ *
+ * The position is only written to the store when the whole second changed. `timeupdate` fires
+ * about four times a second, and four renders a second for a clock that shows seconds is work
+ * nobody can see — while the *saved* position is on its own, slower schedule again. */
+ setPodPlayback({ position, duration, playing } = {}) {
+ const p = get().pod
+ if (!p) return
+ const sameSecond = !Number.isFinite(position) || Math.floor(position) === Math.floor(p.position || 0)
+ const sameDuration = !Number.isFinite(duration) || duration <= 0 || duration === p.duration
+ const samePlaying = playing == null || playing === p.playing
+ if (sameSecond && sameDuration && samePlaying) return
+ set({
+ pod: {
+ ...p,
+ position: Number.isFinite(position) ? position : p.position,
+ duration: Number.isFinite(duration) && duration > 0 ? duration : p.duration,
+ playing: playing == null ? p.playing : playing
+ }
+ })
+ savePodPosition(false)
+ },
+ /** Mark this episode heard and start the next one, or stop at the end of the queue. */
+ podEnded() {
+ const p = get().pod
+ if (!p) return
+ const { position, duration } = playerTime()
+ useStore.getState().savePodcastPosition(p.episode.id, duration || p.duration || 0, duration || p.duration)
+ if (get().podNext()) return
+ pausePlayer()
+ set({ pod: { ...p, playing: false, position: Number.isFinite(duration) ? duration : p.position } })
+ },
/* Volume, for whoever puts a slider on screen. Nothing draws one today, and there is a reason to
think before drawing one: **iOS ignores `HTMLMediaElement.volume` entirely** — the hardware
buttons are the only volume there — so a slider on an iPhone would be a control that does
diff --git a/frontend/src/views/Music.jsx b/frontend/src/views/Music.jsx
index 7da986e..11a7533 100644
--- a/frontend/src/views/Music.jsx
+++ b/frontend/src/views/Music.jsx
@@ -26,6 +26,7 @@ import { confirmSheet } from '../sheets.jsx'
import { Button } 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'
/** A playlist tile: artwork when the public page gave us some, a note when it did not. */
function PlaylistCard({ item, onRemove }) {
@@ -91,7 +92,7 @@ function AddPlaylistSheet({ close }) {
* Live stations, not files: a public stream is made to be listened to, so nothing is downloaded and
* the audio goes from the station straight to the phone. What this screen does is the list — which
* genres, which stations, what is playing — and the play button hands the stream to the single audio
- * element in lib/radio-player.js.
+ * element in lib/player.js — the one element it shares with the podcasts.
*
* The stations with no advertising at all come first in every genre, because that is a property
* worth ranking: SomaFM and Radio Paradise are listener-supported by mission, and the directory's
@@ -195,6 +196,161 @@ function RadioSection() {
>
}
+/* ---------- podcasts ----------
+ *
+ * Spanish-language shows, by category, from Apple's directory (free, no key), with the episodes read
+ * out of the publisher's own feed — the long version is in api/podcasts.js, which owns the two rules
+ * that matter: **nothing but Spanish**, checked in the feed itself rather than trusted from the
+ * storefront, and **nothing fetched from a private address**, because this container lives inside
+ * somebody's house.
+ *
+ * The audio never passes through the server: an episode is an `https://` file URL, handed to the one
+ * 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() {
+ const user = useStore(s => s.user)
+ const cfg = useStore(s => s.config)
+ const S = useStore(s => s.S)
+ const addPodcast = useStore(s => s.addPodcast)
+ const removePodcast = useStore(s => s.removePodcast)
+ const progress = (S.podcasts && S.podcasts.progress) || {}
+ const openSheet = useUI(s => s.openSheet)
+ const toast = useUI(s => s.toast)
+ const [categories, setCategories] = useState(null)
+ const [category, setCategory] = useState(null)
+ const [shows, setShows] = useState(null)
+ const [busy, setBusy] = useState(false)
+ const [noArt, setNoArt] = useState(() => new Set())
+ 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.
+ const staleApi = !!cfg && Array.isArray(cfg.features) && !cfg.features.includes('podcasts')
+ const canPodcasts = !!user && !staleApi
+
+ const load = key => {
+ setBusy(true)
+ api('/api/podcasts' + (key ? '?category=' + encodeURIComponent(key) : ''))
+ .then(r => {
+ setCategories(r.categories)
+ setCategory(r.category)
+ setShows(r.shows)
+ })
+ .catch(e => toast(e.message))
+ .finally(() => setBusy(false))
+ }
+ useEffect(() => { if (canPodcasts) load(null) }, [canPodcasts])
+
+ const isSaved = show => saved.some(x => x.feed === show.feed)
+
+ const row = show =>
+
+
+
+
+ return <>
+
{t('Podcasts')}
+ {!canPodcasts
+ ?
+ {staleApi
+ ? t('Your server has not been updated for the podcasts yet: it is the server that finds them, and this app is newer than it. Restarting it should be enough.')
+ : t('Podcasts come from your server, so they need a profile: sign in and the shows appear here.')}
+
+ : <>
+
+ {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.')}
+
+ {t('No Spanish shows came back for this category. Try another one.')}
+
}
+ >}
+ >
+}
+
+/* The episodes of one show, in a sheet: tap one and it plays. The list comes from the feed, newest
+ first, and every row says where you are in it. */
+function ShowSheet({ show, close, progress }) {
+ const playEpisode = useUI(s => s.playEpisode)
+ const [data, setData] = useState(null)
+ const [err, setErr] = useState('')
+
+ useEffect(() => {
+ let live = true
+ const q = new URLSearchParams({ feed: show.feed })
+ if (show.name) q.set('title', show.name)
+ if (show.image) q.set('image', show.image)
+ api('/api/podcasts/show?' + q.toString())
+ .then(r => {
+ if (!live) return
+ if (!r.show) { setErr(t('That feed did not answer. It may be down, or it may block this server.')); return }
+ if (r.spanish === false) { setErr(t('That podcast is not in Spanish, so it is not listed here.')); return }
+ setData(r)
+ })
+ .catch(e => { if (live) setErr(e.message) })
+ return () => { live = false }
+ }, [show.feed])
+
+ const play = ep => {
+ // Synchronous on purpose: the `play()` has to happen inside this tap for iOS to allow it.
+ playEpisode({ ...(data?.show || {}), name: show.name, image: show.image }, ep, data?.episodes || [])
+ close()
+ }
+
+ return
+
+ {show.image
+ ?
+ : }
+
+
{show.name}
+ {show.author &&
{show.author}
}
+
+
+ {err &&
{err}
}
+ {!data && !err &&
{t('Reading the feed…')}
}
+ {data &&
+ {data.episodes.map(ep => )}
+
}
+ {data && !data.episodes.length &&
+ {t('That feed has no playable episodes in it — trailers only, or subscriber-only audio.')}
+
}
+
+}
+
export default function Music() {
const nav = useNavigate()
const S = useStore(s => s.S)
@@ -241,6 +397,8 @@ export default function Music() {
+
+
{t('Playlists')}
{list.length === 0
?
diff --git a/frontend/src/views/Music.test.jsx b/frontend/src/views/Music.test.jsx
index abcabdc..4342f11 100644
--- a/frontend/src/views/Music.test.jsx
+++ b/frontend/src/views/Music.test.jsx
@@ -14,15 +14,27 @@ vi.mock('react-router-dom', () => ({ useNavigate: () => nav }))
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const api = vi.fn()
vi.mock('../lib/api.js', async importOriginal => ({ ...(await importOriginal()), api: (...a) => api(...a) }))
-/* The audio element lives in lib/radio-player.js, outside React; the radio section reaches it
- through the store. Mocked so a test can assert *when* it was asked to play — see the row test. */
+/* The audio element lives in lib/player.js, outside React; both sections reach it through the store.
+ Mocked so a test can assert *when* it was asked to play — see the station row test. `onPlayer` is
+ called once at module scope (the store listens from import), so it has to exist and answer with an
+ unsubscribe. */
const playStream = vi.fn(() => true)
-vi.mock('../lib/radio-player.js', () => ({
+const playFile = vi.fn(() => true)
+vi.mock('../lib/player.js', () => ({
playStream: (...a) => playStream(...a),
- pauseStream: vi.fn(),
- setStreamVolume: vi.fn(),
- setMediaSession: vi.fn(),
- clearMediaSession: vi.fn()
+ playFile: (...a) => playFile(...a),
+ pausePlayer: vi.fn(),
+ resumePlayer: vi.fn(() => true),
+ seekBy: vi.fn(() => 0),
+ seekTo: vi.fn(() => 0),
+ playerTime: () => ({ position: 0, duration: null }),
+ setPlayerVolume: vi.fn(),
+ setStreamSession: vi.fn(),
+ setEpisodeSession: vi.fn(),
+ setSessionPosition: vi.fn(),
+ wireSessionHandlers: vi.fn(),
+ clearSession: vi.fn(),
+ onPlayer: () => () => {}
}))
const { default: Music } = await import('./Music.jsx')
@@ -40,6 +52,7 @@ beforeEach(() => {
api.mockReset()
api.mockResolvedValue({ genres: [], genre: null, stations: [] })
playStream.mockClear()
+ playFile.mockClear()
act(() => { useUI.setState({ radio: null }) })
host = document.createElement('div')
document.body.appendChild(host)
@@ -54,6 +67,17 @@ beforeEach(() => {
})
afterEach(() => { act(() => root.unmount()); host.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
+ sections fight over one object. */
+const stubApi = ({ radio = { genres: [], genre: null, stations: [] }, podcasts = { categories: [], category: null, shows: [] }, show = { show: null, episodes: [], error: 'unreadable' } } = {}) =>
+ api.mockImplementation(path => {
+ if (String(path).startsWith('/api/radio')) return Promise.resolve(radio)
+ if (String(path).startsWith('/api/podcasts/show')) return Promise.resolve(show)
+ if (String(path).startsWith('/api/podcasts')) return Promise.resolve(podcasts)
+ return Promise.resolve({ ok: true })
+ })
+
const mount = async () => { await act(async () => { root.render() }) }
const links = () => [...host.querySelectorAll('a')]
@@ -191,4 +215,86 @@ describe('Música', () => {
expect(host.querySelectorAll('.mus-card').length).toBe(1)
expect(host.textContent).toContain('Leg Day')
})
+
+ /* ---------- podcasts ---------- */
+
+ const category = { key: 'fitness', label: 'Salud y fitness' }
+ const cat = { key: 'fitness', label: 'Salud y fitness' }
+ const showRow = (over = {}) => ({ feed: 'https://a.example.com/feed', name: 'Tiene Sentido', author: 'Eli Romero', genre: 'Health & Fitness', image: null, lang: 'es', ...over })
+ const ep = (over = {}) => ({ id: 'ep-1', title: 'Experta en Inflamación', url: 'https://audio.example.com/1.mp3', date: '2025-09-21T10:00:00.000Z', duration: 3600, image: null, ...over })
+
+ 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()
+ const chips = [...host.querySelectorAll('.chips .chip')]
+ expect(chips.map(c => c.textContent)).toContain('Salud y fitness')
+ const rows = [...host.querySelectorAll('.mus-rad')]
+ const show = rows[rows.length - 1]
+ expect(show.textContent).toContain('Tiene Sentido')
+ expect(show.textContent).toContain('Eli Romero · Health & Fitness')
+ expect(api).toHaveBeenCalledWith('/api/podcasts')
+ })
+
+ 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()
+ const star = [...host.querySelectorAll('.mus-rad-save')].pop()
+ act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ await act(async () => {})
+ expect(useStore.getState().S.podcasts.shows.map(s => s.feed)).toEqual(['https://a.example.com/feed'])
+ expect(host.textContent).toContain('Saved podcasts')
+ })
+
+ it('opens a show into its episodes, and plays one — resuming where it was left off', async () => {
+ const one = ep()
+ stubApi({
+ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
+ show: { feed: 'https://a.example.com/feed', spanish: true, show: { title: 'Tiene Sentido', author: 'Eli', language: 'es' }, episodes: [one, ep({ id: 'ep-2', title: 'Otro' })] }
+ })
+ // 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(<>>) })
+ 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 eps = [...document.querySelectorAll('#modal-root .pod-ep')]
+ expect(eps.map(e => e.textContent)).toHaveLength(2)
+ expect(eps[0].textContent).toContain('Experta en Inflamación')
+ // Already ten minutes into it, from wherever it was left off — the tests run on the English keys.
+ expect(eps[0].textContent).toContain('10:00 in')
+
+ act(() => { eps[0].dispatchEvent(new MouseEvent('click', { bubbles: true })) })
+ expect(playFile).toHaveBeenCalledWith('https://audio.example.com/1.mp3', { startAt: 600 })
+ expect(useUI.getState().pod.episode.id).toBe('ep-1')
+ expect(useUI.getState().pod.queue).toHaveLength(2)
+ })
+
+ it('says so when a feed is not in Spanish, instead of showing an empty episode list', async () => {
+ stubApi({
+ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
+ show: { feed: 'https://a.example.com/feed', spanish: false, show: { title: 'English Show', language: 'en' }, episodes: [] }
+ })
+ await act(async () => { root.render(<>>) })
+ 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() })
+ expect(document.querySelector('#modal-root').textContent).toContain('not in Spanish')
+ })
+
+ it('tells a guest where the podcasts come from, without asking the server', async () => {
+ useStore.setState({ user: null })
+ await mount()
+ expect(host.textContent).toContain('Podcasts come from your server, so they need a profile')
+ expect(api).not.toHaveBeenCalled()
+ })
+
+ it('says the server is older when it does not offer podcasts yet', async () => {
+ useStore.setState({ config: { features: ['vitals', 'radio'] } })
+ await mount()
+ 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)
+ })
})
diff --git a/scripts/build-api-docs.mjs b/scripts/build-api-docs.mjs
index 9e6c5cb..b4d2ed8 100644
--- a/scripts/build-api-docs.mjs
+++ b/scripts/build-api-docs.mjs
@@ -119,11 +119,19 @@ function ptab (rows) {
/* ------------------------------------------------------------ endpoint cards */
+/* Every tag the spec uses, and the section it becomes.
+ *
+ * A tag missing from this map is a tag whose operations are silently dropped from the page: the
+ * counters at the top kept counting them while `health` — the whole Apple Health ingest, the Salud
+ * reads and the second opinion — and `music` (playlists, radio, podcasts) rendered nowhere at all.
+ * The build never failed; the page was just missing two thirds of the app. */
const TAGS = {
meta: { title: 'Meta', side: 'Health & public config' },
auth: { title: 'Auth', side: 'Passkeys & sessions' },
pairing: { title: 'Pairing', side: 'Connect the mobile app' },
data: { title: 'Data', side: 'State sync' },
+ health: { title: 'Health', side: 'Apple Health metrics & the second opinion' },
+ music: { title: 'Música', side: 'Playlists, radio & podcasts' },
push: { title: 'Push', side: 'Notifications & rest timer' },
activity: { title: 'Activity', side: 'Live presence' },
admin: { title: 'Admin', side: 'Users, invites, audit log' }
diff --git a/website/api.html b/website/api.html
index ded6acd..0532ce9 100644
--- a/website/api.html
+++ b/website/api.html
@@ -207,6 +207,8 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
AuthPasskeys & sessionsPairingConnect the mobile appDataState sync
+ HealthApple Health metrics & the second opinion
+ MúsicaPlaylists, radio & podcastsPushNotifications & rest timerActivityLive presenceAdminUsers, invites, audit log
@@ -232,7 +234,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
Apple Health metrics ingested from an iPhone (Health Auto Export automations) — per profile, write-only for the phone's ingest key
+
+
+
+
+ GET
+ /api/vitals
+
+ The caller's Apple Health metrics, as per-day aggregates
+
+
+
What the Salud view renders: one entry per metric, one bucket per day, and every bucket carrying every numeric field HAE sent under the name it used (qty, Min/Avg/Max, systolic/diastolic, asleep/inBed/core/deep/rem…), already summed and averaged for that day.
+
The server deliberately does not decide what "steps today" means — which field a card shows is a presentation rule (frontend lib/vitals-view.js), so a metric HAE adds later needs no change here.
+
A session is always required: the ingest key is write-only, so a key that leaks out of a phone can add to a profile's health file and still cannot read it back.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ days
+ integer (1–400, default 90)
+ Calendar days to return, including today.
+
+
+
+
Responses
+
+
+ 200
+ The stored metrics for the window, oldest day first.{ ok: boolean, days: integer, key: string, updatedAt: integer, last: object, metrics: object, workouts: object[] }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ DELETE
+ /api/vitals
+
+ Delete the caller's health data, or one metric of it
+
+
+
Removes the profile's health file and nothing else: the workout history, the account and the ingest key are untouched, so a phone needs no re-configuring to sync again.
+
With ?metric= it forgets one measurement instead, days and hours included, and leaves every other metric in place — the answer to "these numbers look wrong, start this one over". It is a reset rather than a loss whenever the automation's Date Range is wider than a day: the next sync sends that metric again from Apple Health. A metric the profile does not have answers 200 with metric: null, not an error.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ metric
+ string
+ The metric name exactly as HAE wrote it (step_count, heart_rate…). Omit it to clear everything.
+
+
+
+
Responses
+
+
+ 200
+ Deleted (also when there was nothing stored).{ ok: boolean }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ GET
+ /api/vitals/hours
+
+ One metric's hours on one day
+
+
+
The detail behind a card: the hourly buckets the phone sent for a single metric on a single day, oldest first, each carrying the same per-field aggregates a day does.
+
This is a separate request on purpose. The hours are the bulky part of health data (24 buckets per metric per day), and they are only interesting once somebody taps a card, so a screen listing forty metrics fetches none of them.
+
A day the automation grouped by Day has no hours and comes back as an empty list rather than a fabricated one: the honest answer to "what did the hours look like" for a payload that never carried hours is that the automation does not send them. Set Time Grouping to Hours in Health Auto Export to keep them — the day remains the sum of its hours, so nothing is counted twice.
+
Session only, like GET /api/vitals: the ingest key is write-only.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ metricrequired
+ string
+ The metric name exactly as HAE wrote it (step_count, heart_rate…).
+
+
+ dayrequired
+ string
+ A calendar day, in the phone's own date, as YYYY-MM-DD.
+
+
+
+
Responses
+
+
+ 200
+ The hours stored for that metric and day (empty when there are none).{ ok: boolean, metric: string, day: string, units: string, hours: object[] }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ GET
+ /api/insights
+
+ The profile's last second opinion, if the instance has one
+
+
+
Whether this instance is configured for a second opinion at all (configured, false unless JEV_API_KEY or OPENCODE_API_KEY is set), what was judged last, whether that judgment is still about the data on screen, and what is left of today's budget.
+
The judgment itself is a small object: one entry per question the server asked, each with the option or level the model chose and the probability it put there. A question it did not answer is null — the server never fills a gap with a guess, and the screen says the question went unanswered rather than drawing a zero.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ raw
+ "1"
+ Include the gateway's own response body, exactly as it arrived. Debugging detail: the default response leaves it out, because a screen polling this does not need it.
+
+
+
+
Responses
+
+
+ 200
+ The state of the feature and the last judgment.{ ok: boolean, configured: boolean, model: string, host: string, insight: object, freshness: object, budget: object }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ POST
+ /api/insights
+
+ Ask for a second opinion about this profile
+
+
+
Builds a state from the profile's own data — a week of every health metric it has, the sets per body part over four weeks, the last few sessions, the whole training history per exercise (sessions, the estimate of the best set then and now, one point per session, and where it has stalled), the weekly load and volume of the last ten weeks, the newest weigh-in, and the Coach intake's goal and limitations note — sends it to Jev (TypeSafe's System One model, through the OpenCode Zen gateway) with four typed questions, and stores the answers.
+
What leaves the instance is decided server-side and is aggregates only: no name, no workout titles, no chat, and no identifier of a person. The exceptions are deliberate and small: the Coach intake's limitations note, because "bad shoulder" changes the answer, and the library id of an exercise that has stopped progressing, because a question about which exercise to change has to name something the app can edit — a library id is a row in a public dataset, not an identifier of anybody. The one piece of the person's own writing that goes is the intake's limitations field, because "bad shoulder" changes the answer; the sheet in front of the button lists exactly what will be sent before it is sent.
+
It costs a request, so it is never on a timer: the call is the ask, and the budget (per profile per day, plus a ten-minute floor) is enforced here rather than trusted to the client. A profile with no health data and no training still gets an answer — the questions that cannot be answered are simply not asked.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
+
+
Responses
+
+
+ 200
+ The judgment, parsed. Every question the model left unanswered is null.{ ok: boolean, model: string, host: string, insight: object, freshness: object, budget: object, sent: object }
+
+
+ 400
+ The instance has no key configured — the message names the variable to set.
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+ 429
+ Today's budget is spent, or ten minutes have not passed since the last ask.
+
+
+ 502
+ The gateway refused or failed; the message carries what it said.
+
+
+
+
+
+
+
+ POST
+ /api/vitals/ingest
+
+ Receive a Health Auto Export JSON export
+
+
+
The endpoint an iOS automation posts to. In Health Auto Export: Automation Type REST API, URL = this endpoint, header Authorization: Bearer <ingest key> (from POST /api/vitals/key), Export Format JSON, Export Version 2, Summarize Data On, Time Grouping Hours (or Days for totals with nothing behind them), Date Range Previous 7 Days — with the default range every sync carries today only, and the past is never in the file.
+
The merge is idempotent, which is what makes a five-minute cadence safe:
+
* A payload whose datapoints all sit on midnight is HAE's own day grouping, and a day total replaces the day it names — so the same day re-sent all afternoon converges on the day's total instead of adding up. * A payload whose datapoints all sit on the hour is its hour grouping: the hour is replaced for the same reason (the hour in progress grows on every run), and the day is recomputed as the sum of its hours, so the day and the hourly detail can never disagree. * Anything else is a real sample: it is identified by its instant plus its numbers and is counted once, and it also lands in its own hour, which is where intraday detail comes from. Repeats come back as duplicates.
+
CSRF-exempt: the request carries its own credential in a header and has no session to borrow.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+ 200
+ Accepted — including an export with nothing in it, because a scheduled automation that fires when there is nothing to report is not a failure.{ ok: boolean, ts: integer, received: object, stored: object }
+
+
+ 400
+ Not a Health Auto Export JSON export (or not JSON at all).{"error":"not a Health Auto Export JSON export"}
+
+
+ 401
+ No ingest key, an unknown or rotated key, or a disabled account.{"error":"invalid ingest key"}
+
+
+ 413
+ Body over 32 MB. Group by days in HAE, or select fewer metrics.{"error":"body too large"}
+
+
+
+
+
+
+
+ POST
+ /api/vitals/key
+
+ Get the profile's ingest key, creating it on first use
+
+
+
Idempotent: a second call returns the key that exists rather than invalidating the configuration already pasted into the phone.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ POST
+ /api/vitals/key/rotate
+
+ Replace the profile's ingest key
+
+
+
The old key stops working everywhere at once. Stored health data is untouched; the phone stops syncing until the new key is pasted in. Separate from the session token on purpose — losing a phone should not sign you out of the app.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
+
+
Responses
+
+
+ 200
+ A new key.{ ok: boolean, key: string }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+
+
Música
+
Música — reading a public Apple Music page for a saved playlist's card, the live radio station directory, and the Spanish-language podcast directory. Audio is never proxied by this server: a station arrives as a resolved stream URL, an episode as the publisher's own file URL, and the phone talks to the station or the publisher directly.
+
+
+
+
+ GET
+ /api/radio
+
+ Live radio stations for a genre, with their stream URLs resolved
+
+
+
What the Radio section of the Música screen draws. Every station arrives with the URL to hand an <audio> element already resolved — the one non-obvious decision here, and it is about iOS: audio may only start inside the tap that asked for it, so anything asynchronous between the finger and the play() is a press that quietly does nothing.
+
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.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+ 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[] }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ GET
+ /api/radio/now
+
+ What a station says it is playing
+
+
+
The line under the station's name in the player bar, and the metadata the lock screen shows. Only SomaFM and Radio Paradise publish this; for anything else the answer is now: null and the bar shows the station itself rather than inventing a track.
+
The station is rebuilt from src + id rather than accepted as an object, and the id is checked against a plain-id pattern, because the id is used to build a URL this process fetches: without that, a session would be enough to make the api a request proxy for anything on the owner's network. The two known sources are the only ones accepted.
+
The client polls this every 45 seconds while something plays — the screen's own timer, so when iOS suspends it on a locked screen the caption freezes and the music does not.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ srcrequired
+ "soma" | "paradise"
+ Which service the station belongs to.
+
+
+ idrequired
+ string
+ The station's id at that service (a SomaFM channel like beatblender, or a Radio Paradise mix like main).
+
+
+
+
Responses
+
+
+ 200
+ The current track, or null when the station does not publish one.{ ok: boolean, now: object }
+
+
+ 400
+ No such station — an unknown src, or an id that is not a plain id.
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ GET
+ /api/podcasts
+
+ Spanish-language podcast shows for a category
+
+
+
What the Podcasts section of the Música screen draws. Apple's public podcast directory (no API key, no account) supplies the storefront charts per category and the feed URL behind each show; the episodes themselves come from the publisher's own RSS, fetched by GET /api/podcasts/show.
+
Spanish only, and checked rather than assumed. A storefront says a podcast is sold in Spain or Mexico, which is not the same as being in Spanish — the Spanish comedy chart carries a Catalan show, the Argentine one an English show. So each show's feed is read (its first 64 KB, with a Range request) and its <language> decides: es, es-ES, es-419 and spa are kept, ca and en are dropped, and a feed that declares no language at all is kept too — genuinely Spanish feeds omit the tag, and dropping them over an omission would quietly remove good podcasts. skipped reports how many went each way, so a short list is never a mystery.
+
The audio never passes through this server: an episode is a file URL in the publisher's enclosure, handed to the phone. What this route costs is server-side requests to Apple and to each publisher's feed, so the answer is cached for thirty minutes.
+
A session is required. Not to protect the shows — they are public — but because this container sits on the owner's own network and fetches on behalf of whoever asks.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+ 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 }
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ GET
+ /api/podcasts/show
+
+ One show's episodes, read out of the publisher's feed
+
+
+
The episode list behind a show, newest first, from the publisher's own RSS — the same feed every podcast app in the world reads. Each episode carries the https:// URL of its audio file (enclosure), which is what the phone plays; nothing is downloaded by this server and no audio is proxied.
+
Two things are refused or reported rather than faked:
+
A URL this process will not fetch is a 400. Podcast feeds live on every host in the world, so there is no allowlist to hide behind: the rule is https, no credentials, 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). A redirect is checked the same way, because a redirect is otherwise the way around it.
A feed that is not Spanish is answered with 200 and spanish: false (with episodes: []), not with a hidden empty list: the show exists, it is simply not in Spanish, and saying which of the two it is is the whole point of the field.
+
Episodes without a public audio enclosure are left out: a trailer, a subscriber-only episode or a video is a row that plays silence or nothing. Feeds are up to a few megabytes, so the body is read with a cap and the connection is dropped at it; a feed cut off mid-item simply loses that last, unparseable item.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
Query parameters
+
+ feedrequired
+ string
+ The show's feed URL, exactly as GET /api/podcasts returned it.
+
+
+ title
+ string (≤ 120 chars)
+ The directory's name for the show, used only when the feed declares none.
+
+
+ image
+ string (≤ 300 chars)
+ The directory's artwork, used only when the feed declares none.
+
+
+
+
Responses
+
+
+ 200
+ The show and its episodes — or show: null when the feed did not answer.{ ok: boolean, feed: string, spanish: boolean, show: object, episodes: PodcastEpisode[], error: string }
+
+
+ 400
+ The feed URL is not one this server will fetch (not https, not a public host).
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
+ POST
+ /api/music/lookup
+
+ Read what a public Apple Music page says about itself
+
+
+
Apple has no API for somebody else's public playlists, so a playlist saved in KuentaGYM is a link — and this is how the card gets its title, artwork, track count and curator without the client fetching Apple itself (which CORS would refuse anyway).
+
The URL must be an Apple Music link on an allowlisted host (hostAllowed), and so must the URL the request ends up at: a redirect is otherwise a way around the allowlist. This container sits on the owner's own network, which is the whole reason for the check.
+
An unreachable page or a page that left the allowlist is not an error status — the answer is 200 with meta: null and an error naming which of the two happened, because the app's job then is to save the link anyway with the name the person typed.
+
Requires a session — the cookie set at sign-in, or Authorization: Bearer <token> from mobile-app pairing.
+
+
Request body (JSON)
+
+ urlrequired
+ string
+ A public https://music.apple.com/... link.
+
+
+
Responses
+
+
+ 200
+ What the page said, or meta: null with a reason.{ ok: boolean, meta: object, error: string }
+
+
+ 400
+ Not an Apple Music link, or a plain-http/off-host URL. Refused before any request is made.
+
+
+ 401
+ No session, expired/revoked session, or a disabled account.{"error":"not signed in"}
+
+
+
+
+
+
+
Push
Web Push (VAPID) subscriptions, rest-timer and test pushes
@@ -1385,6 +1886,112 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
+
+
+ PodcastShow
+
+ One show in the Podcasts section.
+
+
+
feed is the only field the episodes can be fetched with, and it is what the show is saved by in a profile.
+
+
+ feedrequired
+ string
+ The publisher's RSS URL
+
+
+ id
+ string
+ The directory's own id for the show.
+
+
+ namerequired
+ string
+
+
+
+ author
+ string
+
+
+
+ image
+ string
+ HTTPS artwork.
+
+
+ genre
+ string
+
+
+
+ country
+ string
+ The storefront it was found in: es or mx.
+
+
+ lang
+ string
+ What the feed itself declares — es, es-ES, es-mx… — or null when it declares nothing, which is a "kept, unconfirmed" and not a "not Spanish".
+
+
+
+
+
+
+
+ PodcastEpisode
+
+ One episode: a file with a length, which is the difference that matters against a radio station — there is a position to remember and a place to resume from.
+
+
+
+
+
+ idrequired
+ string
+ The feed's guid
+
+
+ titlerequired
+ string
+
+
+
+ urlrequired
+ string
+ The https:// audio file to play. Never proxied.
+
+
+ date
+ string
+ ISO 8601
+
+
+ duration
+ integer
+ Seconds
+
+
+ image
+ string
+ Episode artwork
+
+
+ episode
+ integer
+ itunes:episode, when the feed numbers them.
+
+
+ bytes
+ integer
+ The enclosure's declared size.
+