Podcasts: en español solamente, y se acuerdan de dónde ibas
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Música tiene una sección **Podcasts**: programas por categoría —Salud y fitness, Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología, Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el directorio de Apple es público. **En español se comprueba, no se supone.** La tienda dice dónde se *vende* un podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada programa (los primeros 64 KB, con una petición `Range`: el idioma está en las primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda: feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué (`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en otro idioma se contesta con `spanish:false` en vez de con una lista vacía. Es la otra mitad de la radio y es lo contrario en todo lo que le importa al reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj; la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo escuchado con el teléfono guardado. Media Session muestra episodio, programa y progreso en la pantalla bloqueada. Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del `enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca posible —un feed vive en cualquier host—, así que la puerta es **https, host real y nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro de una casa. Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES, es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como `spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido. Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están, con radio y podcasts incluidas.
This commit is contained in:
1 parent
a3e13df279
commit
22654c61fc
31 files changed
+3687
-360
No files matched your search
+44
-1
@@ -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 `<language>` 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
|
||||
`<audio>` **vive fuera de React** (`lib/radio-player.js`), porque un elemento dentro de un componente
|
||||
`<audio>` **vive fuera de React** (hoy `lib/player.js`, el mismo elemento que usan los podcasts),
|
||||
porque un elemento dentro de un componente
|
||||
se desmonta con él: eso era cambiar de pantalla y que se corte la música, que es exactamente lo que
|
||||
no puede pasar en medio de una serie.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ media/ exercise img/gif, gitignored, fetched at runtime by the `media` compo
|
||||
website/ static marketing site (plain HTML/CSS/JS) — not deployed for this fork; built by hand
|
||||
when someone wants it (node scripts/build-api-docs.mjs fills in api.html).
|
||||
docs/ SELF_HOSTING.md, MOBILE.md, AI_COACH.md, HEALTH.md (Apple Health ingest),
|
||||
RADIO.md (live stations).
|
||||
RADIO.md (live stations), PODCASTS.md (Spanish-language episodes).
|
||||
```
|
||||
|
||||
## Commands
|
||||
@@ -90,10 +90,15 @@ would catch is a change nothing checks here.
|
||||
stores numbers; this decides how they read.
|
||||
- `music.js` — reading and validating the Apple Music share links a profile keeps. Apple has no
|
||||
API for somebody else's public playlists, so a playlist here is a link, not an integration.
|
||||
- `radio-player.js` — the single `<audio>` element and Media Session, held **outside React** on
|
||||
purpose: an element owned by a component unmounts with it, which is how a player stops when
|
||||
somebody changes screens. `play()` is called synchronously from the tap because iOS only allows
|
||||
audio to start inside a gesture — see `docs/RADIO.md` before touching any of it.
|
||||
- `player.js` — the single `<audio>` element and Media Session, for both the radio and the
|
||||
podcasts, held **outside React** on purpose: an element owned by a component unmounts with it,
|
||||
which is how a player stops when somebody changes screens. `play()` is called synchronously from
|
||||
the tap because iOS only allows audio to start inside a gesture, and one element is what keeps a
|
||||
station and an episode from ever playing at once. See `docs/RADIO.md` and `docs/PODCASTS.md`
|
||||
before touching any of it.
|
||||
- `podcast-view.js` — where to resume, what counts as heard, what comes next, and how many
|
||||
positions to keep. Pure, because "resumed into the last twenty seconds" and "marked heard after
|
||||
five minutes" are bugs nobody reports — they just stop using the feature.
|
||||
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
|
||||
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
|
||||
session back, is a pure helper here with a unit test beside it** — not verifiable by
|
||||
@@ -127,12 +132,17 @@ gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a
|
||||
`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
|
||||
auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
|
||||
|
||||
`vitals.js`, `music.js` and `radio.js` sit beside `server.js` as the modules with real logic on the
|
||||
API side: HAE parsing, the idempotent merge (the reason a 5-minute automation does not double a day
|
||||
of steps) and retention in the first; reading what a public Apple Music page says about itself,
|
||||
behind a host allowlist, in the second; the live-station directory — SomaFM, Radio Paradise and
|
||||
radio-browser — in the third, which is also where the rule lives that **audio is never proxied**: the
|
||||
api hands out a resolved stream URL and the phone talks to the station directly. `server.js` owns the
|
||||
`vitals.js`, `music.js`, `radio.js` and `podcasts.js` sit beside `server.js` as the modules with real
|
||||
logic on the API side: HAE parsing, the idempotent merge (the reason a 5-minute automation does not
|
||||
double a day of steps) and retention in the first; reading what a public Apple Music page says about
|
||||
itself, behind a host allowlist, in the second; the live-station directory — SomaFM, Radio Paradise
|
||||
and radio-browser — in the third; and Apple's podcast directory plus a tolerant RSS reader in the
|
||||
fourth, where the two rules that matter are **Spanish only** (checked in each feed's own
|
||||
`<language>`, not assumed from the storefront) and **no private address is ever fetched** (a feed can
|
||||
live anywhere, so there is no allowlist to hide behind: https, a real host, and a check of where the
|
||||
request ended up as well as where it was pointed). All of them hold the same line about audio:
|
||||
**nothing is proxied**. The api hands out a resolved stream URL or the publisher's own episode URL,
|
||||
and the phone talks to the station or the publisher directly. `server.js` owns the
|
||||
sockets; those files own the parsing, which is why they are testable without a phone or a network.
|
||||
All of them are listed in the Dockerfile's `COPY` — an import of a file that is not copied there is a
|
||||
container that boots into ERR_MODULE_NOT_FOUND.
|
||||
|
||||
@@ -95,6 +95,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
- 🌍 **14 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI, TH, HU); exercise instructions localized in 12 of them and built-in exercise names shown bilingually in PT-BR and HU, all loaded on demand so the app stays fast
|
||||
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy** (CSV or directly with a [Hevy Pro API key](https://hevy.com/settings?developer)), or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
|
||||
- 📻 **Radio while you train** — a **Radio** section in Música: live stations by genre (workout/rave, techno, R&B, Latin, hip-hop, reggae, chill, jazz, rock, electronic), the ad-free ones first — SomaFM and Radio Paradise — then the public [radio-browser](https://www.radio-browser.info) directory. It keeps playing across screens, with the screen locked and the phone in your pocket, and the lock screen shows the station and the track. **The audio goes straight from the station to your phone** — your server hands out the list and never proxies or stores a byte of it, and nothing is downloaded. No new dependencies. See [docs/RADIO.md](docs/RADIO.md)
|
||||
- 🎙️ **Podcasts while you train** — a **Podcasts** section in Música: shows by category (health and fitness, sport, comedy, news, history, true crime, science, tech, society, business, fiction, education, music, leisure) from Apple's public directory, **in Spanish only** — and that is checked in each show's own feed, not assumed from the storefront it was found in. An episode is a file, so it resumes where you left off, marks itself heard, seeks back 15 s and forward 30 s, and plays the next one when it ends; the lock screen shows the episode and how far in you are. **Nothing is downloaded and no audio passes through your server** — the feed says where the file is and the phone goes and gets it. No new dependencies. See [docs/PODCASTS.md](docs/PODCASTS.md)
|
||||
- ❤️ **Salud: your Apple Health, live** — a **Salud** screen (the heart button in Home's header) draws whatever your iPhone reports: steps, heart rate, sleep, weight, oxygen, workouts and every other metric Health Auto Export can send, as cards with trends over 7/30/90/365 days. Per profile and private by construction — each profile mints its own **write-only** ingest key, the phone's data lands in its own file, and re-sends are de-duplicated, so an automation firing every five minutes never counts a day twice. See [docs/HEALTH.md](docs/HEALTH.md)
|
||||
- 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry**; switching kg ↔ lb offers to convert every stored number
|
||||
- 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there
|
||||
|
||||
+3
-2
@@ -55,8 +55,9 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force
|
||||
# (a test, a script, a stray JSON) cannot reach the published image. vitals.js joined the list
|
||||
# with the Apple Health ingest and music.js with the Música one — an import of a file that is not
|
||||
# copied here is a container that boots straight into ERR_MODULE_NOT_FOUND, which is exactly what
|
||||
# the first health build would have done. radio.js is the station directory behind the player.
|
||||
COPY server.js push-messages.js verify-error.js vitals.js music.js radio.js jev.js insights.js ./
|
||||
# the first health build would have done. radio.js is the station directory behind the player, and
|
||||
# podcasts.js the Spanish-language one behind the episodes.
|
||||
COPY server.js push-messages.js verify-error.js vitals.js music.js radio.js podcasts.js jev.js insights.js ./
|
||||
COPY coach ./coach
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
+185
-4
@@ -90,9 +90,10 @@ tags:
|
||||
per profile, write-only for the phone's ingest key
|
||||
- name: music
|
||||
description: >-
|
||||
Música — reading a public Apple Music page for a saved playlist's card, and the live radio
|
||||
station directory. Audio is never proxied by this server: the list carries resolved stream
|
||||
URLs and the phone talks to the station directly.
|
||||
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.
|
||||
- name: admin
|
||||
description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)
|
||||
|
||||
@@ -161,7 +162,7 @@ paths:
|
||||
server", never as "supports everything".
|
||||
items:
|
||||
type: string
|
||||
enum: [vitals, vitals.hours, vitals.receipt, music.lookup, radio, insights]
|
||||
enum: [vitals, vitals.hours, vitals.receipt, music.lookup, radio, podcasts, insights]
|
||||
coach:
|
||||
type: object
|
||||
description: Present only when the AI Coach is configured on this instance.
|
||||
@@ -1040,6 +1041,136 @@ paths:
|
||||
description: No such station — an unknown `src`, or an `id` that is not a plain id.
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/podcasts:
|
||||
get:
|
||||
tags: [music]
|
||||
operationId: podcastsGet
|
||||
summary: Spanish-language podcast shows for a category
|
||||
description: |
|
||||
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.
|
||||
parameters:
|
||||
- name: category
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
enum: [fitness, sports, comedy, news, history, truecrime, science, tech, society, business, fiction, education, music, leisure]
|
||||
description: Category key. Missing or unrecognised falls back to `fitness`.
|
||||
responses:
|
||||
'200':
|
||||
description: The categories for the chips, and the Spanish shows in the one asked for.
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ok: { type: boolean }
|
||||
categories:
|
||||
type: array
|
||||
description: Every chip the screen offers, so the client never hard-codes them.
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
key: { type: string }
|
||||
label: { type: string, description: Spanish label, like the rest of the show list. }
|
||||
category: { type: string, description: The category actually answered with. }
|
||||
label: { type: string }
|
||||
shows:
|
||||
type: array
|
||||
description: At most 20, Spanish-language only.
|
||||
items: { $ref: '#/components/schemas/PodcastShow' }
|
||||
skipped:
|
||||
type: object
|
||||
description: Why a candidate did not make the list — each reason counted.
|
||||
properties:
|
||||
duplicate: { type: integer, description: Listed by both storefronts. }
|
||||
language: { type: integer, description: Declared a language that is not Spanish. }
|
||||
unreadable: { type: integer, description: The feed did not answer. }
|
||||
failed: { type: integer, description: An unexpected error while checking (should be 0). }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/podcasts/show:
|
||||
get:
|
||||
tags: [music]
|
||||
operationId: podcastsShow
|
||||
summary: One show's episodes, read out of the publisher's feed
|
||||
description: |
|
||||
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.
|
||||
parameters:
|
||||
- name: feed
|
||||
in: query
|
||||
required: true
|
||||
schema: { type: string }
|
||||
description: The show's feed URL, exactly as `GET /api/podcasts` returned it.
|
||||
- name: title
|
||||
in: query
|
||||
schema: { type: string, maxLength: 120 }
|
||||
description: The directory's name for the show, used only when the feed declares none.
|
||||
- name: image
|
||||
in: query
|
||||
schema: { type: string, maxLength: 300 }
|
||||
description: The directory's artwork, used only when the feed declares none.
|
||||
responses:
|
||||
'200':
|
||||
description: 'The show and its episodes — or `show: null` when the feed did not answer.'
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
ok: { type: boolean }
|
||||
feed: { type: string }
|
||||
spanish: { type: boolean }
|
||||
show:
|
||||
allOf: [{ $ref: '#/components/schemas/PodcastShow' }]
|
||||
nullable: true
|
||||
description: Null when the feed could not be read at all.
|
||||
episodes:
|
||||
type: array
|
||||
description: At most 40, newest first. Empty when the show is not in Spanish.
|
||||
items: { $ref: '#/components/schemas/PodcastEpisode' }
|
||||
error: { type: string, nullable: true, description: '`unreadable` when `show` is null.' }
|
||||
'400':
|
||||
description: The feed URL is not one this server will fetch (not https, not a public host).
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/music/lookup:
|
||||
post:
|
||||
tags: [music]
|
||||
@@ -1808,6 +1939,56 @@ components:
|
||||
properties:
|
||||
ok: { type: boolean, const: true }
|
||||
|
||||
PodcastShow:
|
||||
type: object
|
||||
description: >-
|
||||
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.
|
||||
required: [feed, name]
|
||||
properties:
|
||||
feed: { type: string, description: The publisher's RSS URL, https and public. }
|
||||
id: { type: string, description: The directory's own id for the show. }
|
||||
name: { type: string }
|
||||
author: { type: string }
|
||||
image: { type: string, nullable: true, description: HTTPS artwork. }
|
||||
genre: { type: string, nullable: true }
|
||||
country: { type: string, description: 'The storefront it was found in: `es` or `mx`.' }
|
||||
lang:
|
||||
type: string
|
||||
nullable: true
|
||||
description: >-
|
||||
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".
|
||||
example:
|
||||
feed: https://feeds.example.com/nadie-sabe-nada.rss
|
||||
name: Nadie Sabe Nada
|
||||
author: Cadena SER
|
||||
genre: Comedy
|
||||
country: es
|
||||
lang: es-ES
|
||||
|
||||
PodcastEpisode:
|
||||
type: object
|
||||
description: >-
|
||||
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.
|
||||
required: [id, title, url]
|
||||
properties:
|
||||
id: { type: string, description: The feed's guid, or the audio URL when it has none. }
|
||||
title: { type: string }
|
||||
url: { type: string, description: The `https://` audio file to play. Never proxied. }
|
||||
date: { type: string, nullable: true, description: ISO 8601, from `pubDate`. }
|
||||
duration: { type: integer, nullable: true, description: Seconds, when the feed declares one. }
|
||||
image: { type: string, nullable: true, description: Episode artwork, else the show's. }
|
||||
episode: { type: integer, nullable: true, description: '`itunes:episode`, when the feed numbers them.' }
|
||||
bytes: { type: integer, nullable: true, description: The enclosure's declared size. }
|
||||
example:
|
||||
id: 312f2e94-ac78-5c37-8e0e-1f6c9d2a4b71
|
||||
title: Nadie Sabe Nada | 14x03 | En el corazón del ajo
|
||||
url: https://audio.example.com/nsn-14x03.mp3
|
||||
date: '2025-09-19T10:00:00.000Z'
|
||||
duration: 3135
|
||||
|
||||
RadioStation:
|
||||
type: object
|
||||
description: >-
|
||||
|
||||
+513
@@ -0,0 +1,513 @@
|
||||
/* podcasts.js — Spanish-language podcasts, browsed by category, played as files.
|
||||
*
|
||||
* Radio and podcasts are the two halves of "something to listen to while training", and they are
|
||||
* opposites in every way that matters to this code:
|
||||
*
|
||||
* - Radio is a **stream**: endless, no position, and every station is a channel somebody else is
|
||||
* programming. Nothing about it is stored.
|
||||
* - A podcast is a **file**: it has a beginning and an end, it is worth resuming where you left
|
||||
* it, and skipping back fifteen seconds is the most-used button in every podcast app ever made.
|
||||
*
|
||||
* So this module answers a different question — *which file* — and the player has to do more with
|
||||
* the answer than it does for a station.
|
||||
*
|
||||
* ## Where the list comes from, and why there is no API key
|
||||
*
|
||||
* Apple's podcast directory, through two public endpoints that need no key and no account: the
|
||||
* storefront **top charts** (`/<country>/rss/toppodcasts/limit=N/genre=<id>/json`) and
|
||||
* `lookup?id=…` for what the charts omit — above all the **feed URL**, which is the only field that
|
||||
* really matters, because the episodes come from the publisher's own RSS and from nowhere else.
|
||||
*
|
||||
* One consequence is deliberate: **no audio passes through here.** An episode is an `https://` URL
|
||||
* in the publisher's enclosure, handed to the phone; the bytes go from the publisher to the phone.
|
||||
* What this server contributes is the list, the same bargain the radio makes.
|
||||
*
|
||||
* ## "Spanish only" is checked, not assumed
|
||||
*
|
||||
* A storefront says a podcast is *sold* in Spain or Mexico, which is not the same as being in
|
||||
* Spanish, and the difference shows: the Spanish comedy chart carries a Catalan show and the
|
||||
* Argentine one carries an English one. The authoritative answer is in the feed, in `<language>`,
|
||||
* so every show is checked:
|
||||
*
|
||||
* - `feedLanguage()` reads the **first 64 KB** with a `Range` request. `<language>` is channel
|
||||
* metadata that sits in the first ~1.5 KB of every feed looked at, always before the first
|
||||
* `<item>`, so a 64 KB slice answers the question and a 5 MB feed does not have to be downloaded
|
||||
* to ask it.
|
||||
* - `es` / `es-ES` / `es-419` / `spa` keeps the show; `ca`, `en`, `pt` and the rest are dropped.
|
||||
* - **A feed with no tag at all keeps its place.** Genuinely Spanish feeds do omit it (La Ruina is
|
||||
* one), and dropping them over an omission would quietly remove good podcasts; the storefront is
|
||||
* the fallback signal, and it is not a guess.
|
||||
*
|
||||
* ## What may be fetched
|
||||
*
|
||||
* Radio has a host allowlist because it only ever talks to three services. Podcasts cannot: feeds
|
||||
* live on every host in the world. So the rule is the other one, and it is the rule that matters for
|
||||
* an api container sitting on somebody's home network:
|
||||
*
|
||||
* - **https only**, no credentials in the URL, a real hostname, and **never a private address** —
|
||||
* no loopback, no `10.`/`192.168.`/`172.16-31.`, no link-local, no IPv6 literals, no `.local` or
|
||||
* `.internal`. A feed URL is attacker-influenced data, and an api that fetches whatever it is
|
||||
* handed is how a home network gets mapped from the outside.
|
||||
* - The check is applied to the URL **and again to where the request ended up**, because a
|
||||
* redirect is otherwise the way around it — the lesson music.js learned with Apple's CDN.
|
||||
* - Bodies are read with a cap and the connection is dropped when it is reached: podcast feeds are
|
||||
* routinely several megabytes, and one of them is not allowed to be an out-of-memory bug.
|
||||
*/
|
||||
const UA = 'KuentaGYM (self-hosted)';
|
||||
const TIMEOUT_MS = 12000;
|
||||
const CACHE_MS = 30 * 60 * 1000;
|
||||
/** `<language>` lives in the first couple of KB; 64 KB is generous and still one round trip. */
|
||||
const LANG_HEAD_BYTES = 64 * 1024;
|
||||
/** A cap, not a target: the largest feeds seen are ~5 MB, and a truncated one still parses. */
|
||||
const MAX_FEED_BYTES = 6 * 1024 * 1024;
|
||||
const MAX_URL = 600;
|
||||
const CHART_LIMIT = 25;
|
||||
/* How many candidates to language-check per category, and how many at a time.
|
||||
*
|
||||
* The check is one request per show (see below), so this pair is the whole cost of a category: a
|
||||
* cold list of twenty Spanish shows needs roughly twenty-six checks, and with a pool of ten that is
|
||||
* three rounds of latency rather than twenty-six of them. Ten at once to twenty different
|
||||
* publishers is also about as far as politeness goes: they are other people's servers, and they are
|
||||
* paying for the bandwidth of being listed. */
|
||||
const CHECK_LIMIT = 26;
|
||||
const POOL = 10;
|
||||
export const MAX_SHOWS = 20;
|
||||
export const MAX_EPISODES = 40;
|
||||
/** Spain and Mexico: between them, most of what is published in Spanish. */
|
||||
export const STORES = Object.freeze(['es', 'mx']);
|
||||
|
||||
/* The categories, as the chips the screen draws.
|
||||
*
|
||||
* Apple's own genre ids with Spanish labels, which is the whole trick: an id is stable and the chart
|
||||
* is per id, so a category is one number rather than a search term whose results drift week to week.
|
||||
* Ordered so the two a gym screen actually wants come first. */
|
||||
export const CATEGORIES = Object.freeze([
|
||||
{ key: 'fitness', label: 'Salud y fitness', genre: 1512 },
|
||||
{ key: 'sports', label: 'Deporte', genre: 1545 },
|
||||
{ key: 'comedy', label: 'Comedia', genre: 1303 },
|
||||
{ key: 'news', label: 'Noticias', genre: 1489 },
|
||||
{ key: 'history', label: 'Historia', genre: 1487 },
|
||||
{ key: 'truecrime', label: 'Crímenes reales', genre: 1488 },
|
||||
{ key: 'science', label: 'Ciencia', genre: 1533 },
|
||||
{ key: 'tech', label: 'Tecnología', genre: 1318 },
|
||||
{ key: 'society', label: 'Sociedad y cultura', genre: 1324 },
|
||||
{ key: 'business', label: 'Negocios', genre: 1321 },
|
||||
{ key: 'fiction', label: 'Ficción', genre: 1483 },
|
||||
{ key: 'education', label: 'Educación', genre: 1304 },
|
||||
{ key: 'music', label: 'Música', genre: 1310 },
|
||||
{ key: 'leisure', label: 'Ocio', genre: 1502 }
|
||||
]);
|
||||
|
||||
/** The categories the screen offers, with their labels. */
|
||||
export const categoryList = () => CATEGORIES.map(c => ({ key: c.key, label: c.label }));
|
||||
|
||||
/** One category by key, or null. An unknown key falls back to the first one at the route. */
|
||||
export const categoryOf = key => CATEGORIES.find(c => c.key === String(key || '')) || null;
|
||||
|
||||
/* ---------- fetching, with the one rule ---------- */
|
||||
|
||||
const IPV4_PRIVATE = [
|
||||
/^0\./, /^10\./, /^127\./, /^169\.254\./, /^192\.168\./,
|
||||
/^172\.(1[6-9]|2\d|3[01])\./, /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./
|
||||
];
|
||||
|
||||
/** A hostname this process may talk to: public, named, and not a device in the same house. */
|
||||
export function publicHost(hostname) {
|
||||
const h = String(hostname || '').toLowerCase().replace(/\.$/, '');
|
||||
if (!h || h === 'localhost' || h.endsWith('.localhost')) return false;
|
||||
if (h.endsWith('.local') || h.endsWith('.internal') || h.endsWith('.home.arpa')) return false;
|
||||
// IPv6 literals (`::1`, `fe80::`, `fc00::/7`) arrive bracketed from URL.hostname; none of them is
|
||||
// worth the address parsing a list of hostnames would need.
|
||||
if (h.includes(':')) return false;
|
||||
if (IPV4_PRIVATE.some(re => re.test(h))) return false;
|
||||
if (/^\d+\.\d+\.\d+\.\d+$/.test(h)) return true; // a public IPv4 literal, allowed
|
||||
return /^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(h); // a real, dotted hostname
|
||||
}
|
||||
|
||||
/**
|
||||
* The URL of a feed this module will fetch: https, no credentials, a public host, and short enough
|
||||
* to be a URL rather than a payload. Exported because the rule is worth testing on its own.
|
||||
*/
|
||||
export function safeFeedUrl(url) {
|
||||
if (typeof url !== 'string' || !url.length || url.length > MAX_URL) return null;
|
||||
let u;
|
||||
try { u = new URL(url); } catch { return null }
|
||||
if (u.protocol !== 'https:') return null;
|
||||
if (u.username || u.password) return null;
|
||||
if (!publicHost(u.hostname)) return null;
|
||||
u.hash = '';
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
/* One function fetches, so the rule above is one rule in one place rather than a check each caller
|
||||
has to remember — the shape radio.js settled on after a mutation showed a stray fetch slipping
|
||||
past the allowlist. */
|
||||
export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {}, max = MAX_FEED_BYTES } = {}) {
|
||||
const safe = safeFeedUrl(url);
|
||||
if (!safe) return null;
|
||||
try {
|
||||
const r = await fetchImpl(safe, { headers: { 'User-Agent': UA, ...headers }, signal: AbortSignal.timeout(timeoutMs) });
|
||||
if (!r.ok && r.status !== 206) return null;
|
||||
// Where we ended up, not only where we were pointed: a redirect is otherwise the way around the
|
||||
// rule above.
|
||||
if (r.url && !safeFeedUrl(r.url)) return null;
|
||||
return await readCapped(r, max);
|
||||
} catch { return null }
|
||||
}
|
||||
|
||||
/**
|
||||
* A body, up to `max` bytes, with the connection dropped as soon as the cap is reached.
|
||||
*
|
||||
* `res.text()` on a five-megabyte feed is how a feed reader becomes an out-of-memory bug, and a
|
||||
* server that ignores the `Range` header we send for the language check would otherwise hand us a
|
||||
* whole archive to read the first kilobyte of.
|
||||
*/
|
||||
export async function readCapped(res, max) {
|
||||
const reader = res.body?.getReader?.();
|
||||
if (!reader) return String(await res.text().catch(() => '')).slice(0, max);
|
||||
const decoder = new TextDecoder();
|
||||
let text = '';
|
||||
let bytes = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
bytes += value.byteLength;
|
||||
text += decoder.decode(value, { stream: true });
|
||||
if (bytes >= max) { await reader.cancel().catch(() => {}); break }
|
||||
}
|
||||
} catch { /* a feed that dies mid-body still has a usable beginning */ }
|
||||
// The cap is applied to the text as well as to the loop: a body streamed in one big chunk would
|
||||
// otherwise be fully decoded before the check below ever ran.
|
||||
return text.slice(0, max);
|
||||
}
|
||||
|
||||
/* The cache, with a ceiling.
|
||||
*
|
||||
* Every entry here is small on purpose — a language tag, a parsed episode list — but "small" times
|
||||
* an unbounded number of feed URLs is still a leak on a box with 1 GB of RAM, so the oldest entries
|
||||
* go when there are too many. Nothing depends on an entry still being there: a miss is a refetch. */
|
||||
const CACHE_MAX = 400;
|
||||
let cache = new Map();
|
||||
function cached(key, ms, fn) {
|
||||
const hit = cache.get(key);
|
||||
if (hit && Date.now() - hit.at < ms) return hit.value;
|
||||
const value = Promise.resolve().then(fn).catch(() => null);
|
||||
cache.set(key, { at: Date.now(), value });
|
||||
if (cache.size > CACHE_MAX) {
|
||||
for (const k of [...cache.keys()].slice(0, cache.size - CACHE_MAX)) cache.delete(k);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
/** Only for tests: forget everything fetched. */
|
||||
export function clearPodcastCache() { cache = new Map() }
|
||||
|
||||
/* ---------- the directory ---------- */
|
||||
|
||||
const apple = path => 'https://itunes.apple.com' + path;
|
||||
|
||||
/** The rows of a storefront chart: the ids, which is all a chart is good for. */
|
||||
export function chartEntries(json) {
|
||||
const entries = json && json.feed && json.feed.entry;
|
||||
if (!Array.isArray(entries)) return [];
|
||||
return entries
|
||||
.map(e => ({ id: String(e?.id?.attributes?.['im:id'] || '') }))
|
||||
.filter(e => e.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* One show out of a `lookup` result.
|
||||
*
|
||||
* `feedUrl` is the field that matters; the rest is decoration the chart already carried, and the
|
||||
* lookup is here only because the chart does not carry the feed.
|
||||
*/
|
||||
export function showFrom(row, country) {
|
||||
const feed = safeFeedUrl(row?.feedUrl);
|
||||
if (!feed) return null;
|
||||
const name = String(row?.collectionName || '').trim();
|
||||
if (!name) return null;
|
||||
const art = [row?.artworkUrl600, row?.artworkUrl100].find(u => /^https:\/\//i.test(u || '')) || null;
|
||||
return {
|
||||
id: String(row?.collectionId || feed),
|
||||
feed,
|
||||
name: name.slice(0, 120),
|
||||
author: String(row?.artistName || '').trim().slice(0, 80),
|
||||
image: art,
|
||||
genre: String(row?.primaryGenreName || '').trim().slice(0, 40),
|
||||
country: String(country || row?.country || '').toLowerCase()
|
||||
};
|
||||
}
|
||||
|
||||
/** The storefront chart ids for a genre, cached for half an hour. */
|
||||
export async function chartIds(country, genre, { fetchImpl = fetch } = {}) {
|
||||
return cached(`chart:${country}:${genre}`, CACHE_MS, async () => {
|
||||
const text = await get(apple(`/${country}/rss/toppodcasts/limit=${CHART_LIMIT}/genre=${genre}/json`), { fetchImpl });
|
||||
if (!text) return [];
|
||||
try { return chartEntries(JSON.parse(text)).map(e => e.id) } catch { return [] }
|
||||
});
|
||||
}
|
||||
|
||||
/** The details for a set of ids, in one request: `lookup` takes a comma-separated list. */
|
||||
export async function lookupShows(ids, country, { fetchImpl = fetch } = {}) {
|
||||
if (!ids.length) return [];
|
||||
return cached(`lookup:${country}:${ids.join(',')}`, CACHE_MS, async () => {
|
||||
const text = await get(apple(`/lookup?id=${ids.join(',')}&country=${country}`), { fetchImpl });
|
||||
if (!text) return [];
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
return (json.results || []).map(r => showFrom(r, country)).filter(Boolean);
|
||||
} catch { return [] }
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- the language check ---------- */
|
||||
|
||||
/** `es`, `es-ES`, `es-419` and `spa` are Spanish; `ca`, `en`, `et` are not; nothing is a "maybe". */
|
||||
export function isSpanish(lang) {
|
||||
const l = String(lang || '').trim().toLowerCase();
|
||||
if (!l) return true;
|
||||
return /^(es|spa)(\b|[_-])/.test(l);
|
||||
}
|
||||
|
||||
/** `<language>` out of a feed, CDATA and all. */
|
||||
export function languageOf(text) {
|
||||
const m = /<language>\s*(?:<!\[CDATA\[)?\s*([^\]<\s]+)/i.exec(String(text || ''));
|
||||
return m ? m[1].trim().toLowerCase().slice(0, 12) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a feed says its language is, from the first bytes of it.
|
||||
*
|
||||
* Two different answers, and the difference matters: `{ lang: null, ok: true }` is a feed that
|
||||
* answered and declares nothing (keep it), while `null` is a feed that could not be read at all
|
||||
* (drop it — a row whose every tap fails is worse than no row). A feed whose language is declared
|
||||
* and is not Spanish is dropped on the spot.
|
||||
*/
|
||||
export async function feedLanguage(feed, { fetchImpl = fetch } = {}) {
|
||||
const url = safeFeedUrl(feed);
|
||||
if (!url) return null;
|
||||
return cached('lang:' + url, CACHE_MS, async () => {
|
||||
const head = await get(url, {
|
||||
fetchImpl,
|
||||
max: LANG_HEAD_BYTES,
|
||||
headers: { Range: `bytes=0-${LANG_HEAD_BYTES - 1}` }
|
||||
});
|
||||
if (head == null || head === '') return null;
|
||||
return { lang: languageOf(head), ok: true };
|
||||
});
|
||||
}
|
||||
|
||||
/** Run `fn` over `items` with a small pool, keeping the order and never throwing out of the pool. */
|
||||
export async function mapLimit(items, limit, fn) {
|
||||
const out = new Array(items.length).fill(null);
|
||||
let next = 0;
|
||||
const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
|
||||
for (;;) {
|
||||
const i = next++;
|
||||
if (i >= items.length) return;
|
||||
try { out[i] = await fn(items[i], i) } catch { out[i] = null }
|
||||
}
|
||||
});
|
||||
await Promise.all(workers);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shows of one category: the storefront charts, their feeds, and only the Spanish ones.
|
||||
*
|
||||
* The per-show cost is one 64 KB ranged request, so this is not free — the whole answer is cached
|
||||
* for half an hour, which is what makes a category chip a tap rather than a wait.
|
||||
*/
|
||||
export async function showsFor(genreKey, { fetchImpl = fetch } = {}) {
|
||||
const category = categoryOf(genreKey) || CATEGORIES[0];
|
||||
const perStore = await Promise.all(STORES.map(async country => {
|
||||
const ids = await chartIds(country, category.genre, { fetchImpl });
|
||||
return lookupShows(ids, country, { fetchImpl });
|
||||
}));
|
||||
// Interleaved rather than one storefront after the other: the two countries publish different
|
||||
// podcasts, and a list that shows twenty Spanish ones before the first Mexican one is not a list
|
||||
// of what is out there.
|
||||
const lists = perStore.filter(Array.isArray);
|
||||
const rows = [];
|
||||
for (let i = 0; lists.some(l => l[i]); i++) {
|
||||
for (const list of lists) if (list[i]) rows.push(list[i]);
|
||||
}
|
||||
const seen = new Set();
|
||||
/* *Why* a show was left out is reported, not just dropped.
|
||||
*
|
||||
* It used to be `return null` for every reason, which made three different things — "not in
|
||||
* Spanish", "the feed did not answer", "the pool swallowed an unexpected error" — the same
|
||||
* observable outcome. A refactor that accidentally let the third one happen then looked exactly
|
||||
* like the rule working. A count per reason makes each of them a fact a test can assert on. */
|
||||
const skipped = { duplicate: 0, language: 0, unreadable: 0, failed: 0 };
|
||||
const results = await mapLimit(rows.slice(0, CHECK_LIMIT), POOL, async show => {
|
||||
if (seen.has(show.feed)) return { skip: 'duplicate' };
|
||||
seen.add(show.feed);
|
||||
const lang = await feedLanguage(show.feed, { fetchImpl });
|
||||
if (!lang) return { skip: 'unreadable' };
|
||||
if (!isSpanish(lang.lang)) return { skip: 'language' };
|
||||
return { show: { ...show, lang: lang.lang || null } };
|
||||
});
|
||||
const shows = [];
|
||||
for (const r of results) {
|
||||
// A null is an error the pool caught: counted as a failure rather than passing for a show that
|
||||
// was filtered on purpose.
|
||||
if (!r) { skipped.failed++; continue }
|
||||
if (r.skip) { skipped[r.skip]++; continue }
|
||||
shows.push(r.show);
|
||||
if (shows.length >= MAX_SHOWS) break;
|
||||
}
|
||||
return { category, shows, skipped };
|
||||
}
|
||||
|
||||
/* ---------- the feed ---------- */
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
|
||||
const safeCodePoint = n => (Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '');
|
||||
|
||||
/** Named and numeric entities — not a parser, a decoder for what titles actually contain. */
|
||||
export function decodeEntities(text) {
|
||||
return String(text == null ? '' : text)
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => safeCodePoint(parseInt(hex, 16)))
|
||||
.replace(/&#(\d+);/g, (_, dec) => safeCodePoint(parseInt(dec, 10)))
|
||||
.replace(/&([a-z]+);/gi, (m, name) => (name.toLowerCase() in ENTITIES ? ENTITIES[name.toLowerCase()] : m));
|
||||
}
|
||||
|
||||
/** The text of a tag, CDATA unwrapped, entities decoded, whitespace collapsed. */
|
||||
export function tagText(item, tag) {
|
||||
const m = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${tag}>`, 'i').exec(String(item || ''));
|
||||
if (!m) return '';
|
||||
return decodeEntities(m[1].replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, '$1')).replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/** One attribute of the first matching tag, whatever order the feed wrote its attributes in. */
|
||||
export function tagAttr(item, tag, attr) {
|
||||
const m = new RegExp(`<${tag}(\\s[^>]*)>`, 'i').exec(String(item || ''));
|
||||
if (!m) return '';
|
||||
const a = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`, 'i').exec(m[1]);
|
||||
return a ? decodeEntities(a[1]).trim() : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* A duration in seconds, from the three shapes feeds actually use.
|
||||
*
|
||||
* `itunes:duration` is free text: `00:52:15` on one feed, the bare `4847` on the next, `1:02:03` on
|
||||
* a third — all three seen in one afternoon of Spanish comedy charts. A bare number is seconds;
|
||||
* anything with colons is h:mm:ss or m:ss.
|
||||
*/
|
||||
export function parseDuration(value) {
|
||||
const v = String(value == null ? '' : value).trim();
|
||||
if (!v) return null;
|
||||
if (/^\d+$/.test(v)) return Number(v);
|
||||
const parts = v.split(':').map(p => Number(p.trim()));
|
||||
if (parts.length < 2 || parts.length > 3) return null;
|
||||
if (parts.some(n => !Number.isFinite(n) || n < 0)) return null;
|
||||
return parts.length === 3
|
||||
? parts[0] * 3600 + parts[1] * 60 + parts[2]
|
||||
: parts[0] * 60 + parts[1];
|
||||
}
|
||||
|
||||
const AUDIO_EXT = /\.(mp3|m4a|m4b|aac|ogg|oga|opus|mp4)(\?|#|$)/i;
|
||||
|
||||
/**
|
||||
* One `<item>` into an episode, or null when there is nothing to play.
|
||||
*
|
||||
* The enclosure *is* the podcast: an item without a public audio file is a trailer, a
|
||||
* subscriber-only episode or a video — three kinds of row that would play silence or nothing. The
|
||||
* `type` attribute is trusted when it is there and the file extension when it is not, and a video
|
||||
* enclosure is refused either way, because this player has no picture.
|
||||
*/
|
||||
export function episodeFrom(item, { image = null } = {}) {
|
||||
const url = tagAttr(item, 'enclosure', 'url');
|
||||
if (!/^https:\/\//i.test(url)) return null;
|
||||
const type = tagAttr(item, 'enclosure', 'type').toLowerCase();
|
||||
if (type ? !/^audio\//.test(type) : !AUDIO_EXT.test(url)) return null;
|
||||
const title = tagText(item, 'title');
|
||||
if (!title) return null;
|
||||
const date = Date.parse(tagText(item, 'pubDate'));
|
||||
const num = Number(tagText(item, 'itunes:episode'));
|
||||
const art = tagAttr(item, 'itunes:image', 'href');
|
||||
const bytes = Number(tagAttr(item, 'enclosure', 'length'));
|
||||
return {
|
||||
id: (tagText(item, 'guid') || url).slice(0, 200),
|
||||
title: title.slice(0, 200),
|
||||
url,
|
||||
date: Number.isFinite(date) ? new Date(date).toISOString() : null,
|
||||
duration: parseDuration(tagText(item, 'itunes:duration')),
|
||||
image: /^https:\/\//i.test(art) ? art : image,
|
||||
episode: Number.isFinite(num) && num > 0 ? num : null,
|
||||
bytes: Number.isFinite(bytes) && bytes > 0 ? bytes : null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A feed into a show and its episodes.
|
||||
*
|
||||
* Deliberately tolerant, because feeds are the wild west and a rejected feed is a podcast nobody can
|
||||
* play: a body truncated by the cap above simply loses its last, unterminated item, and a channel
|
||||
* that declares no title falls back to whatever the directory called it.
|
||||
*/
|
||||
export function parseFeed(text, { fallbackTitle = '', fallbackImage = null } = {}) {
|
||||
const src = String(text || '');
|
||||
const first = src.search(/<item[\s>]/i);
|
||||
const head = first < 0 ? src : src.slice(0, first);
|
||||
const items = src.match(/<item[\s>][\s\S]*?(?:<\/item>|$)/gi) || [];
|
||||
const image = tagAttr(head, 'itunes:image', 'href') || tagAttr(head, 'image', 'url') || fallbackImage;
|
||||
const episodes = [];
|
||||
const seen = new Set();
|
||||
for (const item of items) {
|
||||
// The last item of a truncated feed has no closing tag; half an episode is not an episode.
|
||||
if (!/<\/item>/i.test(item)) continue;
|
||||
const ep = episodeFrom(item, { image });
|
||||
if (!ep || seen.has(ep.id)) continue;
|
||||
seen.add(ep.id);
|
||||
episodes.push(ep);
|
||||
}
|
||||
/* Newest first, by date when the feed gave one: a feed ordered by hand, or by an editorial
|
||||
calendar, is not the one you want at the top of a list sorted by nothing. */
|
||||
episodes.sort((a, b) => (Date.parse(b.date || '') || 0) - (Date.parse(a.date || '') || 0));
|
||||
return {
|
||||
show: {
|
||||
title: tagText(head, 'title') || fallbackTitle,
|
||||
author: tagText(head, 'itunes:author'),
|
||||
image: image || null,
|
||||
language: languageOf(src),
|
||||
episodes: episodes.length
|
||||
},
|
||||
episodes: episodes.slice(0, MAX_EPISODES)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One show with its episodes, straight from the publisher's feed.
|
||||
*
|
||||
* The feed URL is data from a directory rather than something a browser typed, and it is put through
|
||||
* `safeFeedUrl` again here — the api container is on somebody's network, so the rule is re-applied
|
||||
* at every use and not only where the URL first appeared.
|
||||
*
|
||||
* The parsed language is returned rather than enforced, so the route can say *why* a feed was
|
||||
* refused instead of answering "not found" to a Spanish user holding an English feed.
|
||||
*/
|
||||
export async function episodesFor(feed, { fetchImpl = fetch, title = '', image = null } = {}) {
|
||||
const url = safeFeedUrl(feed);
|
||||
if (!url) return null;
|
||||
/* The *parsed* feed is cached, never its text: a feed is up to six megabytes and forty episodes
|
||||
are a few kilobytes, so caching the body would be the whole memory budget for nothing. */
|
||||
const parsed = await cached('feed:' + url, CACHE_MS, async () => {
|
||||
const text = await get(url, { fetchImpl });
|
||||
if (!text) return null;
|
||||
const p = parseFeed(text);
|
||||
return p.episodes.length ? p : null;
|
||||
});
|
||||
if (!parsed) return null;
|
||||
return {
|
||||
feed: url,
|
||||
show: {
|
||||
...parsed.show,
|
||||
// The directory's name and artwork are only a fallback for a channel that declares neither.
|
||||
title: parsed.show.title || title || 'Podcast',
|
||||
image: parsed.show.image || (/^https:\/\//i.test(image || '') ? image : null)
|
||||
},
|
||||
episodes: parsed.episodes
|
||||
};
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import { verifyError } from './verify-error.js';
|
||||
import { parsePayload, mergeVitals, vitalsSeries, vitalsHours, dropMetric, emptyVitals, RETENTION_DAYS } from './vitals.js';
|
||||
import { hostAllowed, readCapped, parseMusicPage } from './music.js';
|
||||
import { genreList, stationsFor, nowPlaying } from './radio.js';
|
||||
import { categoryList, showsFor, episodesFor, safeFeedUrl, isSpanish } from './podcasts.js';
|
||||
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
|
||||
import {
|
||||
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
|
||||
@@ -36,6 +37,7 @@ export const API_FEATURES = Object.freeze([
|
||||
'vitals.receipt', // per-metric `shape`, and per-day `own` / `hours_sum`
|
||||
'music.lookup', // POST /api/music/lookup
|
||||
'radio', // GET /api/radio, GET /api/radio/now
|
||||
'podcasts', // GET /api/podcasts, GET /api/podcasts/show
|
||||
'insights' // GET/POST /api/insights (the second opinion)
|
||||
]);
|
||||
|
||||
@@ -1302,6 +1304,49 @@ const routes = {
|
||||
json(res, 200, { ok: true, now: await nowPlaying(station) });
|
||||
},
|
||||
|
||||
/* ---------- podcasts ----------
|
||||
*
|
||||
* Two routes, both session-gated, and neither proxies audio: the list of Spanish shows for a
|
||||
* category, and one show's episodes read out of the publisher's own feed. The episode URLs go to
|
||||
* the phone from here; the audio then goes from the publisher to the phone.
|
||||
*
|
||||
* Unlike the radio — three known hosts, one allowlist — a feed can live anywhere, so the gate is
|
||||
* `safeFeedUrl`: https, a real hostname, and never a private address (see api/podcasts.js). That
|
||||
* matters more here than anywhere else in this file, because this process is running inside
|
||||
* somebody's house and the URL arrives from a browser. */
|
||||
'GET /api/podcasts': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const key = new URL(req.url, 'http://x').searchParams.get('category') || '';
|
||||
const { category, shows, skipped } = await showsFor(key);
|
||||
json(res, 200, { ok: true, categories: categoryList(), category: category.key, label: category.label, shows, skipped });
|
||||
},
|
||||
|
||||
'GET /api/podcasts/show': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const q = new URL(req.url, 'http://x').searchParams;
|
||||
const feed = safeFeedUrl(q.get('feed') || '');
|
||||
if (!feed) return json(res, 400, { error: 'not a feed this server will fetch' });
|
||||
const got = await episodesFor(feed, {
|
||||
title: text(q.get('title')).slice(0, 120),
|
||||
image: text(q.get('image')).slice(0, 300)
|
||||
});
|
||||
// A feed that does not answer is not an error status: the screen says so, the same way a music
|
||||
// lookup that cannot reach Apple says so, and nothing about it is a 500.
|
||||
if (!got) return json(res, 200, { ok: true, show: null, episodes: [], error: 'unreadable' });
|
||||
/* A feed that declares another language is answered with the fact rather than hidden: the show
|
||||
exists, it is simply not in Spanish, and saying that is better than an empty list that looks
|
||||
like a feed with no episodes. */
|
||||
const spanish = isSpanish(got.show.language);
|
||||
json(res, 200, {
|
||||
ok: true,
|
||||
...got,
|
||||
spanish,
|
||||
episodes: spanish ? got.episodes : []
|
||||
});
|
||||
},
|
||||
|
||||
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
|
||||
|
||||
'POST /api/push/subscribe': async (req, res) => {
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
/* Podcasts, tested without a network: everything here is a filter, a parse or a rule about what may
|
||||
be fetched — and those are the three things that decide whether this feature is usable, safe and
|
||||
actually in Spanish.
|
||||
|
||||
The load-bearing rule is the Spanish one. A storefront says a podcast is *sold* in Spain or
|
||||
Mexico, and that is not the same as being in Spanish: the Spanish comedy chart carries a Catalan
|
||||
show and the Argentine chart carries Joe Rogan. The feed's own `<language>` is the answer, and the
|
||||
two edges of it are both tested — `ca` and `en` get dropped, and a feed that declares nothing
|
||||
stays, because Spanish feeds do omit the tag and dropping good podcasts over an omission is worse
|
||||
than keeping a rare miss.
|
||||
|
||||
The other rule is what this process will fetch. A feed URL is attacker-influenced data and the api
|
||||
container sits on somebody's home network, so loopback, private ranges and `.local` names are
|
||||
refused *before* a request is made. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
CATEGORIES, STORES, MAX_EPISODES, MAX_SHOWS, categoryList, categoryOf, isSpanish, languageOf,
|
||||
publicHost, safeFeedUrl, parseDuration, decodeEntities, episodeFrom, parseFeed, tagText, tagAttr,
|
||||
get, readCapped, feedLanguage, showsFor, episodesFor, chartEntries, showFrom, mapLimit,
|
||||
clearPodcastCache
|
||||
} from '../podcasts.js';
|
||||
|
||||
/* A stand-in for `fetch`: a body, a status, and the url it ended at. */
|
||||
const res = (text, { status = 200, url = undefined } = {}) => ({
|
||||
ok: status >= 200 && status < 300, status, url, body: null,
|
||||
text: async () => text
|
||||
});
|
||||
|
||||
/* ---------- categories ---------- */
|
||||
|
||||
test('every category has a label and an Apple genre id, and the keys are unique', () => {
|
||||
const keys = categoryList().map(c => c.key);
|
||||
assert.equal(new Set(keys).size, keys.length, 'no key twice');
|
||||
for (const c of CATEGORIES) {
|
||||
assert.ok(c.label.trim(), c.key + ' has a label');
|
||||
assert.ok(Number.isInteger(c.genre) && c.genre > 0, c.key + ' has a genre id');
|
||||
}
|
||||
// The two a gym screen wants first, and Spanish labels — this list is read in Spanish.
|
||||
assert.equal(keys[0], 'fitness');
|
||||
assert.equal(keys[1], 'sports');
|
||||
assert.equal(categoryOf('fitness').label, 'Salud y fitness');
|
||||
assert.equal(categoryOf('nope'), null);
|
||||
assert.ok(STORES.includes('es') && STORES.includes('mx'));
|
||||
});
|
||||
|
||||
/* ---------- what may be fetched ---------- */
|
||||
|
||||
test('only a public https host is ever fetched', () => {
|
||||
assert.ok(safeFeedUrl('https://feeds.example.com/show.rss'));
|
||||
assert.ok(safeFeedUrl('https://example.com/a/b/c'), 'a feed with no extension is still a feed');
|
||||
// Anything else is refused, and refused *before* the request — see the spy test below.
|
||||
for (const bad of [
|
||||
'http://feeds.example.com/show.rss', // plain http: the browser would refuse the audio too
|
||||
'https://user:pw@feeds.example.com/x.rss', // credentials in the URL
|
||||
'https://localhost/x.rss',
|
||||
'https://127.0.0.1/x.rss',
|
||||
'https://10.0.0.5/x.rss',
|
||||
'https://192.168.1.10/x.rss',
|
||||
'https://172.20.3.4/x.rss',
|
||||
'https://169.254.169.254/latest/meta-data/', // the cloud metadata address
|
||||
'https://100.64.0.1/x.rss', // carrier-grade NAT
|
||||
'https://nas.local/x.rss',
|
||||
'https://router.internal/x.rss',
|
||||
'https://[::1]/x.rss',
|
||||
'https://[fd00::1]/x.rss',
|
||||
'file:///etc/passwd',
|
||||
'not a url',
|
||||
'',
|
||||
null,
|
||||
'https://' + 'a'.repeat(600) + '.com/x.rss' // longer than any real feed URL
|
||||
]) assert.equal(safeFeedUrl(bad), null, `${bad} is refused`);
|
||||
// The host rule on its own, for the cases a feed URL cannot express.
|
||||
assert.equal(publicHost('example.com'), true);
|
||||
assert.equal(publicHost('example.com.'), true, 'a trailing dot is the same host');
|
||||
assert.equal(publicHost('8.8.8.8'), true, 'a public address literal is allowed');
|
||||
assert.equal(publicHost('evil.com.localhost'), false);
|
||||
});
|
||||
|
||||
test('an off-list url is refused without calling fetch at all', async () => {
|
||||
let called = 0;
|
||||
const fetchImpl = async () => { called++; return res('x') };
|
||||
for (const bad of ['http://example.com/x.rss', 'https://127.0.0.1/x.rss', 'https://a.local/x.rss']) {
|
||||
assert.equal(await get(bad, { fetchImpl }), null);
|
||||
}
|
||||
assert.equal(called, 0, 'the gate is inside get, so no caller can forget it');
|
||||
});
|
||||
|
||||
test('a redirect off the allowed shape is refused too', async () => {
|
||||
// Where the request ended up is checked, not only where it was pointed: a redirect to the router
|
||||
// is otherwise the whole way around the rule.
|
||||
const fetchImpl = async () => res('<rss/>', { url: 'https://192.168.1.1/x.rss' });
|
||||
assert.equal(await get('https://feeds.example.com/x.rss', { fetchImpl }), null);
|
||||
});
|
||||
|
||||
test('the body is read up to a cap and then dropped', async () => {
|
||||
clearPodcastCache();
|
||||
const huge = 'x'.repeat(5000);
|
||||
assert.equal((await readCapped(res(huge), 100)).length, 100);
|
||||
// A server that ignores Range hands us a real stream: it must be cut, not buffered whole.
|
||||
const streamed = await readCapped(new Response('y'.repeat(200000)), 1000);
|
||||
assert.equal(streamed.length, 1000);
|
||||
});
|
||||
|
||||
/* ---------- Spanish only ---------- */
|
||||
|
||||
test('a Spanish language tag is what keeps a show, and the edges are both tested', () => {
|
||||
for (const yes of ['es', 'es-ES', 'es-es', 'ES', 'es-419', 'es-MX', 'spa']) {
|
||||
assert.equal(isSpanish(yes), true, yes + ' is Spanish');
|
||||
}
|
||||
for (const no of ['ca', 'ca-ES', 'en', 'en-US', 'pt', 'pt-BR', 'gl', 'eu', 'est', 'de']) {
|
||||
assert.equal(isSpanish(no), false, no + ' is not Spanish');
|
||||
}
|
||||
// No tag at all is a "maybe": kept, because genuinely Spanish feeds omit it and the storefront is
|
||||
// the fallback signal. See the header of api/podcasts.js.
|
||||
assert.equal(isSpanish(null), true);
|
||||
assert.equal(isSpanish(''), true);
|
||||
});
|
||||
|
||||
test('the language tag is read out of a feed, CDATA and all', () => {
|
||||
assert.equal(languageOf('<channel><language>es-ES</language><item/></channel>'), 'es-es');
|
||||
assert.equal(languageOf('<language><![CDATA[es]]></language>'), 'es');
|
||||
assert.equal(languageOf('<language>\n es-419\n</language>'), 'es-419');
|
||||
assert.equal(languageOf('<channel><title>x</title></channel>'), null);
|
||||
assert.equal(languageOf(null), null);
|
||||
});
|
||||
|
||||
test('a feed that declares another language never reaches the list', async () => {
|
||||
clearPodcastCache();
|
||||
// The four cases, in one category: Spanish, no tag, Catalan, English — plus a feed that is down.
|
||||
const langs = {
|
||||
'https://a.example.com/feed': '<language>es-ES</language>',
|
||||
'https://b.example.com/feed': '<title>sin etiqueta</title>',
|
||||
'https://c.example.com/feed': '<language>ca</language>',
|
||||
'https://d.example.com/feed': '<language>en-US</language>'
|
||||
};
|
||||
const fetchImpl = async url => {
|
||||
if (url.includes('/rss/toppodcasts/')) {
|
||||
const country = url.includes('/mx/') ? 'mx' : 'es';
|
||||
return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': country + '1' } } }] } }), { url });
|
||||
}
|
||||
if (url.includes('/lookup')) {
|
||||
const country = url.split('country=')[1];
|
||||
const rows = [1, 2, 3, 4, 5].map(n => ({
|
||||
collectionId: `${country}${n}`,
|
||||
collectionName: `${country} show ${n}`,
|
||||
artistName: 'Alguien',
|
||||
artworkUrl600: 'https://img.example.com/x.jpg',
|
||||
primaryGenreName: 'Comedy',
|
||||
feedUrl: ['https://a.example.com/feed', 'https://b.example.com/feed', 'https://c.example.com/feed', 'https://d.example.com/feed', 'https://down.example.com/feed'][n - 1]
|
||||
}));
|
||||
return res(JSON.stringify({ results: rows }), { url });
|
||||
}
|
||||
if (langs[url]) return res(langs[url], { status: url.startsWith('https://b.') ? 200 : 206, url });
|
||||
return res('', { status: 500, url });
|
||||
};
|
||||
const { category, shows, skipped } = await showsFor('comedy', { fetchImpl });
|
||||
assert.equal(category.key, 'comedy');
|
||||
// Each reason is a number, so "dropped for language" cannot pass for "the fetch blew up".
|
||||
assert.equal(skipped.language, 2, 'Catalan and English');
|
||||
assert.equal(skipped.unreadable, 1, 'the feed that is down');
|
||||
assert.equal(skipped.failed, 0, 'nothing threw');
|
||||
assert.equal(skipped.duplicate, 5, 'the second storefront listed the same five feeds');
|
||||
const names = shows.map(s => s.name);
|
||||
assert.ok(names.includes('es show 1'), 'Spanish kept');
|
||||
assert.ok(names.includes('es show 2'), 'no tag kept');
|
||||
assert.ok(!names.includes('es show 3'), 'Catalan dropped');
|
||||
assert.ok(!names.includes('es show 4'), 'English dropped');
|
||||
assert.ok(!names.includes('es show 5'), 'a feed that is down is not a row that cannot play');
|
||||
assert.equal(shows[0].lang, 'es-es');
|
||||
assert.equal(shows[1].lang, null);
|
||||
// One row per feed even though both storefronts listed the same five shows.
|
||||
assert.equal(new Set(shows.map(s => s.feed)).size, shows.length);
|
||||
assert.ok(shows.length <= MAX_SHOWS);
|
||||
});
|
||||
|
||||
test('a feed that cannot be read is not Spanish-by-default', async () => {
|
||||
clearPodcastCache();
|
||||
const fetchImpl = async url => {
|
||||
if (url.includes('/rss/')) return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': '1' } } }] } }), { url });
|
||||
if (url.includes('/lookup')) return res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'S', feedUrl: 'https://a.example.com/feed' }] }), { url });
|
||||
return res('', { status: 503, url });
|
||||
};
|
||||
assert.equal(await feedLanguage('https://a.example.com/feed', { fetchImpl }), null);
|
||||
const { shows, skipped } = await showsFor('comedy', { fetchImpl });
|
||||
assert.deepEqual(shows, []);
|
||||
assert.equal(skipped.unreadable, 1, 'unreadable, by that rule and not by an accident');
|
||||
assert.equal(skipped.failed, 0, 'and not by an exception the pool swallowed');
|
||||
});
|
||||
|
||||
test('the language check reads the head of the feed, not the whole archive', async () => {
|
||||
clearPodcastCache();
|
||||
let asked = null;
|
||||
const fetchImpl = async (url, opts) => { asked = opts.headers.Range; return res('<language>es</language>', { status: 206, url }) };
|
||||
assert.deepEqual(await feedLanguage('https://a.example.com/feed', { fetchImpl }), { lang: 'es', ok: true });
|
||||
assert.equal(asked, 'bytes=0-65535');
|
||||
});
|
||||
|
||||
/* ---------- the directory rows ---------- */
|
||||
|
||||
test('a show is kept only when it has a feed this process will fetch', () => {
|
||||
const base = { collectionId: 12, collectionName: 'Un podcast', feedUrl: 'https://a.example.com/feed' };
|
||||
assert.equal(showFrom(base, 'es').feed, 'https://a.example.com/feed');
|
||||
assert.equal(showFrom(base, 'es').country, 'es');
|
||||
assert.equal(showFrom({ ...base, feedUrl: 'http://a.example.com/feed' }, 'es'), null, 'http feed');
|
||||
assert.equal(showFrom({ ...base, feedUrl: 'https://10.0.0.1/feed' }, 'es'), null, 'private host');
|
||||
assert.equal(showFrom({ ...base, feedUrl: null }, 'es'), null, 'no feed at all');
|
||||
assert.equal(showFrom({ ...base, collectionName: ' ' }, 'es'), null, 'no name');
|
||||
// An http artwork is dropped rather than shown broken.
|
||||
assert.equal(showFrom({ ...base, artworkUrl600: 'http://img/x.jpg' }, 'es').image, null);
|
||||
assert.equal(chartEntries({ feed: { entry: [{ id: { attributes: { 'im:id': '7' } } }, { id: {} }] } }).length, 1);
|
||||
assert.deepEqual(chartEntries({}), []);
|
||||
});
|
||||
|
||||
/* ---------- the feed ---------- */
|
||||
|
||||
const feed = ({ items, extra = '' }) => `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
|
||||
<channel>
|
||||
<title>Nadie Sabe Nada</title>
|
||||
<language>es-ES</language>
|
||||
<itunes:author>Cadena SER</itunes:author>
|
||||
<itunes:image href="https://img.example.com/nsn.jpg"/>
|
||||
${extra}
|
||||
${items}
|
||||
</channel></rss>`;
|
||||
|
||||
const item = ({ title = 'Un episodio', date = 'Tue, 02 Sep 2025 10:00:00 GMT', dur = '00:52:15', enc = '<enclosure url="https://audio.example.com/1.mp3" type="audio/mpeg" length="12345678"/>', guid = 'ep-1', extra = '' }) =>
|
||||
`<item><title>${title}</title><description><![CDATA[<p>bla</p>]]></description>
|
||||
<pubDate>${date}</pubDate><itunes:duration>${dur}</itunes:duration><guid>${guid}</guid>${enc}${extra}</item>`;
|
||||
|
||||
test('a duration is read in all three shapes feeds use', () => {
|
||||
assert.equal(parseDuration('00:52:15'), 3135);
|
||||
assert.equal(parseDuration('4847'), 4847);
|
||||
assert.equal(parseDuration('1:02:03'), 3723);
|
||||
assert.equal(parseDuration('12:30'), 750);
|
||||
assert.equal(parseDuration(''), null);
|
||||
assert.equal(parseDuration(null), null);
|
||||
assert.equal(parseDuration('una hora'), null);
|
||||
assert.equal(parseDuration('1:2:3:4'), null);
|
||||
});
|
||||
|
||||
test('titles come out with CDATA unwrapped and entities decoded', () => {
|
||||
assert.equal(decodeEntities('Rock & Roll — 4 < 5'), 'Rock & Roll — 4 < 5');
|
||||
assert.equal(tagText('<title><![CDATA[324. La Ruina & Co]]></title>', 'title'), '324. La Ruina & Co');
|
||||
assert.equal(tagAttr('<enclosure type="audio/mpeg" url="https://x/1.mp3"/>', 'enclosure', 'url'), 'https://x/1.mp3');
|
||||
assert.equal(tagAttr('<enclosure type="audio/mpeg"/>', 'enclosure', 'url'), '');
|
||||
});
|
||||
|
||||
test('an item with nothing to play is not an episode', () => {
|
||||
const opts = { image: 'https://img.example.com/show.jpg' };
|
||||
// A video enclosure: this player has no picture.
|
||||
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://v.example.com/1.mp4" type="video/mp4"/>' }), opts), null);
|
||||
// A subscriber-only episode has no enclosure at all.
|
||||
assert.equal(episodeFrom(item({ enc: '' }), opts), null, 'no enclosure');
|
||||
// No type, but an audio file: kept, because plenty of feeds omit the type.
|
||||
const noType = episodeFrom(item({ enc: '<enclosure url="https://audio.example.com/1.mp3"/>' }), opts);
|
||||
assert.equal(noType.url, 'https://audio.example.com/1.mp3');
|
||||
// No type and not an audio file: refused.
|
||||
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://docs.example.com/notes.pdf"/>' }), opts), null);
|
||||
// http audio would be blocked by the browser on an https page.
|
||||
assert.equal(episodeFrom(item({ enc: '<enclosure url="http://audio.example.com/1.mp3" type="audio/mpeg"/>' }), opts), null);
|
||||
assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
|
||||
const ep = episodeFrom(item({ extra: '<itunes:episode>14</itunes:episode>' }), opts);
|
||||
assert.equal(ep.episode, 14);
|
||||
assert.equal(ep.duration, 3135);
|
||||
assert.equal(ep.image, 'https://img.example.com/show.jpg', 'falls back to the channel image');
|
||||
assert.equal(ep.bytes, 12345678);
|
||||
});
|
||||
|
||||
test('a feed becomes a show with its episodes, newest first', () => {
|
||||
const text = feed({
|
||||
items: [
|
||||
item({ title: 'Viejo', date: 'Mon, 01 Sep 2025 10:00:00 GMT', guid: 'a' }),
|
||||
item({ title: 'Nuevo', date: 'Wed, 03 Sep 2025 10:00:00 GMT', guid: 'b' }),
|
||||
item({ title: 'Sin fecha', date: '', guid: 'c' })
|
||||
]
|
||||
});
|
||||
const { show, episodes } = parseFeed(text);
|
||||
assert.equal(show.title, 'Nadie Sabe Nada');
|
||||
assert.equal(show.author, 'Cadena SER');
|
||||
assert.equal(show.language, 'es-es');
|
||||
assert.equal(show.image, 'https://img.example.com/nsn.jpg');
|
||||
assert.deepEqual(episodes.map(e => e.title), ['Nuevo', 'Viejo', 'Sin fecha']);
|
||||
assert.equal(episodes.length, show.episodes);
|
||||
});
|
||||
|
||||
test('a feed truncated by the cap loses its last item and nothing else', () => {
|
||||
// The body was cut mid-item: the parser must not invent a half episode, and must not throw.
|
||||
const text = feed({ items: item({ title: 'Uno', guid: 'a' }) }) + '<item><title>Dos a medias</title><enclosure url="https://a.example.com/2.mp3" type="audio/mpeg"';
|
||||
const { episodes } = parseFeed(text);
|
||||
assert.deepEqual(episodes.map(e => e.title), ['Uno']);
|
||||
});
|
||||
|
||||
test('a show with no title of its own takes the directory name', () => {
|
||||
const { show, episodes } = parseFeed('<rss><channel><language>es</language>' + item({}) + '</channel></rss>', { fallbackTitle: 'Desde Apple' });
|
||||
assert.equal(show.title, 'Desde Apple');
|
||||
assert.equal(episodes.length, 1);
|
||||
});
|
||||
|
||||
test('the list of episodes is capped, and duplicates are one episode', () => {
|
||||
const many = Array.from({ length: MAX_EPISODES + 5 }, (_, i) => item({ title: 'E' + i, guid: 'g' + i }));
|
||||
assert.equal(parseFeed(feed({ items: many })).episodes.length, MAX_EPISODES);
|
||||
const twice = item({ title: 'Repetido', guid: 'same' }) + item({ title: 'Repetido (otra vez)', guid: 'same' });
|
||||
assert.deepEqual(parseFeed(feed({ items: twice })).episodes.map(e => e.title), ['Repetido']);
|
||||
});
|
||||
|
||||
/* ---------- the whole way through ---------- */
|
||||
|
||||
test('episodesFor refuses an unsafe feed and parses a real one', async () => {
|
||||
clearPodcastCache();
|
||||
assert.equal(await episodesFor('http://a.example.com/feed'), null);
|
||||
assert.equal(await episodesFor('https://10.0.0.1/feed'), null);
|
||||
const fetchImpl = async url => res(feed({ items: item({}) }), { url });
|
||||
const got = await episodesFor('https://a.example.com/feed', { fetchImpl, title: 'De Apple' });
|
||||
assert.equal(got.feed, 'https://a.example.com/feed');
|
||||
assert.equal(got.show.title, 'Nadie Sabe Nada');
|
||||
assert.equal(got.episodes[0].url, 'https://audio.example.com/1.mp3');
|
||||
// An unreadable feed is null, not an exception. A different URL, because the parsed feed above is
|
||||
// cached for half an hour on purpose — that cache is what keeps a big feed from being downloaded
|
||||
// again every time somebody opens the show.
|
||||
assert.equal(await episodesFor('https://b.example.com/feed', { fetchImpl: async () => res('', { status: 500 }), title: 'x' }), null);
|
||||
});
|
||||
|
||||
test('the pool keeps the order and never throws out of itself', async () => {
|
||||
const out = await mapLimit([1, 2, 3, 4, 5], 2, async n => {
|
||||
if (n === 3) throw new Error('boom');
|
||||
return n * 2;
|
||||
});
|
||||
assert.deepEqual(out, [2, 4, null, 8, 10]);
|
||||
});
|
||||
@@ -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(','));
|
||||
});
|
||||
+9
-5
@@ -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
|
||||
|
||||
|
||||
@@ -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 `<language>` is
|
||||
channel metadata that sits in the first ~1.5 KB and always before the first `<item>` — and its
|
||||
`<language>` 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 `<audio>` 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.
|
||||
+3
-2
@@ -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 `<audio>` 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 `<audio>` 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.
|
||||
|
||||
|
||||
@@ -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' && <TabBar onStart={startFlow} />}
|
||||
<RestTimer />
|
||||
{/* 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. */}
|
||||
<RadioBar />
|
||||
{/* 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. */}
|
||||
<PlayerBar />
|
||||
<Modals />
|
||||
<Toast />
|
||||
<TimerFlash />
|
||||
|
||||
@@ -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 `<audio>` 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 <RadioLine radio={radio} onToggle={toggleRadio} onStop={stopRadio} onNow={setRadioNow} />
|
||||
if (pod) return <EpisodeLine pod={pod} onToggle={togglePod} onStop={stopPod} onSeek={podSeek} onNext={podNext} />
|
||||
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 <Bar
|
||||
cover={radio.now?.cover || station.image || null}
|
||||
name={station.name}
|
||||
line={line}
|
||||
label={radio.playing ? t('Pause') : t('Play')}
|
||||
icon={radio.playing ? 'pause' : 'play'}
|
||||
onToggle={onToggle}
|
||||
progress={null}
|
||||
actions={<button className="iconbtn plr-btn" onClick={onStop} aria-label={t('Stop')}>
|
||||
<Icon name="xmark" />
|
||||
</button>} />
|
||||
}
|
||||
|
||||
/* ---------- 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 <Bar
|
||||
cover={pod.episode.image || pod.show?.image || null}
|
||||
name={pod.show?.name || t('Podcast')}
|
||||
line={pod.episode.title}
|
||||
sub={clock}
|
||||
label={pod.playing ? t('Pause') : t('Play')}
|
||||
icon={pod.playing ? 'pause' : 'play'}
|
||||
onToggle={onToggle}
|
||||
progress={pct}
|
||||
actions={<>
|
||||
<button className="plr-seek" onClick={() => onSeek(-15)} aria-label={t('15 seconds back')}>−15</button>
|
||||
<button className="plr-seek" onClick={() => onSeek(30)} aria-label={t('30 seconds forward')}>+30</button>
|
||||
{hasNext && <button className="iconbtn plr-btn" onClick={onNext} aria-label={t('Next episode')}>
|
||||
<Icon name="chevronRight" />
|
||||
</button>}
|
||||
<button className="iconbtn plr-btn" onClick={onStop} aria-label={t('Stop')}>
|
||||
<Icon name="xmark" />
|
||||
</button>
|
||||
</>} />
|
||||
}
|
||||
|
||||
/** 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 <div id="player">
|
||||
{cover && cover !== noArt
|
||||
? <img className="plr-cover" src={cover} alt="" onError={() => setNoArt(cover)} />
|
||||
: <span className="plr-cover plr-cover-ph"><Icon name="music" /></span>}
|
||||
<span className="plr-meta">
|
||||
<span className="plr-name">{name}</span>
|
||||
<span className="plr-now">{line}{sub ? <span className="plr-clock"> · {sub}</span> : null}</span>
|
||||
</span>
|
||||
<button className="iconbtn plr-btn plr-toggle" onClick={onToggle} aria-label={label}>
|
||||
<Icon name={icon} />
|
||||
</button>
|
||||
{actions}
|
||||
{progress != null && <span className="plr-progress" style={{ width: Math.max(0, Math.min(100, progress)) + '%' }} />}
|
||||
</div>
|
||||
}
|
||||
@@ -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 `<audio>` 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(<PlayerBar />) }) }
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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 `<audio>` 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 <div id="radio">
|
||||
{cover && cover !== noArt
|
||||
? <img className="rad-cover" src={cover} alt="" onError={() => setNoArt(cover)} />
|
||||
: <span className="rad-cover rad-cover-ph"><Icon name="music" /></span>}
|
||||
<span className="rad-meta">
|
||||
<span className="rad-name">{station.name}</span>
|
||||
<span className="rad-now">{line}</span>
|
||||
</span>
|
||||
<button className="iconbtn rad-btn" onClick={toggleRadio}
|
||||
aria-label={radio.playing ? t('Pause') : t('Play')}>
|
||||
<Icon name={radio.playing ? 'pause' : 'play'} />
|
||||
</button>
|
||||
<button className="iconbtn rad-btn" onClick={stopRadio} aria-label={t('Stop')}>
|
||||
<Icon name="xmark" />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -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 `<audio>` 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(<RadioBar />) }) }
|
||||
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)
|
||||
})
|
||||
})
|
||||
+54
-17
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
/* player.js — the one `<audio>` 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 `<audio>` 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 `<audio>` 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
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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({})
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
/* radio-player.js — the one `<audio>` 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 `<audio>` 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 }
|
||||
@@ -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}',
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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'])
|
||||
})
|
||||
})
|
||||
+188
-7
@@ -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
|
||||
|
||||
@@ -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 => <div key={show.feed} className="mus-rad">
|
||||
<button className="mus-rad-main" onClick={() => openSheet(close => <ShowSheet show={show} close={close} progress={progress} />)} aria-label={t('Open {0}', show.name)}>
|
||||
{show.image && !noArt.has(show.image)
|
||||
? <img className="mus-rad-i" src={show.image} alt="" onError={() => setNoArt(prev => new Set(prev).add(show.image))} />
|
||||
: <span className="mus-rad-i mus-rad-i-ph"><Icon name="music" /></span>}
|
||||
<span className="mus-rad-meta">
|
||||
<span className="mus-rad-n">{show.name}</span>
|
||||
<span className="mus-rad-s">{[show.author, show.genre].filter(Boolean).join(' · ')}</span>
|
||||
</span>
|
||||
<Icon name="chevronRight" className="mus-rad-go" />
|
||||
</button>
|
||||
<button className="iconbtn mus-rad-save" aria-label={isSaved(show) ? t('Remove') : t('Save this podcast')}
|
||||
onClick={() => isSaved(show) ? removePodcast(show.feed) : (addPodcast(show), toast(t('Saved to your podcasts')))}>
|
||||
<Icon name={isSaved(show) ? 'starFill' : 'star'} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
return <>
|
||||
<h4 className="sec">{t('Podcasts')}</h4>
|
||||
{!canPodcasts
|
||||
? <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
|
||||
{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.')}
|
||||
</div>
|
||||
: <>
|
||||
<div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
|
||||
{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.')}
|
||||
</div>
|
||||
<div className="chips" style={{ marginBottom: 10 }}>
|
||||
{(categories || []).map(c => <button key={c.key}
|
||||
className={'chip' + (category === c.key ? ' on' : '')}
|
||||
onClick={() => load(c.key)}>{c.label}</button>)}
|
||||
</div>
|
||||
{saved.length > 0 && <>
|
||||
<div className="mus-sub-h">{t('Saved podcasts')}</div>
|
||||
{saved.map(st => row(st))}
|
||||
</>}
|
||||
{busy && !shows && <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('Loading podcasts…')}</div>}
|
||||
{shows && shows.map(st => row(st))}
|
||||
{shows && !shows.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
|
||||
{t('No Spanish shows came back for this category. Try another one.')}
|
||||
</div>}
|
||||
</>}
|
||||
</>
|
||||
}
|
||||
|
||||
/* 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 <div className="pod-sheet">
|
||||
<div className="pod-head">
|
||||
{show.image
|
||||
? <img className="pod-head-i" src={show.image} alt="" />
|
||||
: <span className="pod-head-i plr-cover-ph"><Icon name="music" /></span>}
|
||||
<div>
|
||||
<div className="pod-head-n">{show.name}</div>
|
||||
{show.author && <div className="small dim">{show.author}</div>}
|
||||
</div>
|
||||
</div>
|
||||
{err && <div className="small dim" style={{ padding: '4px 2px' }}>{err}</div>}
|
||||
{!data && !err && <div className="small dim" style={{ padding: '4px 2px' }}>{t('Reading the feed…')}</div>}
|
||||
{data && <div className="pod-eps">
|
||||
{data.episodes.map(ep => <button key={ep.id} className="pod-ep" onClick={() => play(ep)}>
|
||||
<Icon name="play" className="pod-ep-i" />
|
||||
<span className="pod-ep-meta">
|
||||
<span className="pod-ep-t">{ep.title}</span>
|
||||
<span className="pod-ep-s">
|
||||
{episodeMeta(ep)}
|
||||
{progress[ep.id] ? <span className="pod-heard"> · {isFinished(progress[ep.id], ep.duration)
|
||||
? t('Heard')
|
||||
: t('{0} in', fmtClock(resumeSeconds(progress[ep.id], ep.duration)))}</span> : null}
|
||||
</span>
|
||||
</span>
|
||||
</button>)}
|
||||
</div>}
|
||||
{data && !data.episodes.length && <div className="small dim" style={{ padding: '4px 2px' }}>
|
||||
{t('That feed has no playable episodes in it — trailers only, or subscriber-only audio.')}
|
||||
</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
export default function Music() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
@@ -241,6 +397,8 @@ export default function Music() {
|
||||
|
||||
<RadioSection />
|
||||
|
||||
<PodcastSection />
|
||||
|
||||
<h4 className="sec">{t('Playlists')}</h4>
|
||||
{list.length === 0
|
||||
? <div className="empty">
|
||||
|
||||
@@ -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(<Music />) }) }
|
||||
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(<><Music /><Modals /></>) })
|
||||
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(<><Music /><Modals /></>) })
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -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' }
|
||||
|
||||
+609
-2
@@ -207,6 +207,8 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
<a class="side-link" href="#auth"><b>Auth</b><span>Passkeys & sessions</span></a>
|
||||
<a class="side-link" href="#pairing"><b>Pairing</b><span>Connect the mobile app</span></a>
|
||||
<a class="side-link" href="#data"><b>Data</b><span>State sync</span></a>
|
||||
<a class="side-link" href="#health"><b>Health</b><span>Apple Health metrics & the second opinion</span></a>
|
||||
<a class="side-link" href="#music"><b>Música</b><span>Playlists, radio & podcasts</span></a>
|
||||
<a class="side-link" href="#push"><b>Push</b><span>Notifications & rest timer</span></a>
|
||||
<a class="side-link" href="#activity"><b>Activity</b><span>Live presence</span></a>
|
||||
<a class="side-link" href="#admin"><b>Admin</b><span>Users, invites, audit log</span></a>
|
||||
@@ -232,7 +234,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
<p class="api-facts">
|
||||
<span>OpenAPI 3.1.0</span>
|
||||
<span>KuentaGYM v1.3.8</span>
|
||||
<span>41 endpoints</span>
|
||||
<span>43 endpoints</span>
|
||||
<span>AGPL-3.0-or-later</span>
|
||||
</p>
|
||||
|
||||
@@ -317,7 +319,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">Instance flags.<span class="r-sig">{ invite_only: boolean, allow_guest: boolean, features: ("vitals" | "vitals.hours" | "vitals.receipt" | "music.lookup" | "radio" | "insights")[], coach: object }</span></span>
|
||||
<span class="p-desc">Instance flags.<span class="r-sig">{ invite_only: boolean, allow_guest: boolean, features: ("vitals" | "vitals.hours" | "vitals.receipt" | "music.lookup" | "radio" | "podcasts" | "insights")[], coach: object }</span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -715,6 +717,505 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="api-sec" id="health">
|
||||
<h2>Health</h2>
|
||||
<p class="sub">Apple Health metrics ingested from an iPhone (Health Auto Export automations) — per profile, write-only for the phone's ingest key</p>
|
||||
<div class="eps">
|
||||
|
||||
<details class="ep" id="op-vitalsGet">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/vitals</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">The caller's Apple Health metrics, as per-day aggregates</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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 (<code>qty</code>, <code>Min</code>/<code>Avg</code>/<code>Max</code>, <code>systolic</code>/<code>diastolic</code>, <code>asleep</code>/<code>inBed</code>/<code>core</code>/<code>deep</code>/<code>rem</code>…), already summed and averaged for that day.</p>
|
||||
<p>The server deliberately does not decide what "steps today" means — which field a card shows is a presentation rule (frontend <code>lib/vitals-view.js</code>), so a metric HAE adds later needs no change here.</p>
|
||||
<p>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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">days</span>
|
||||
<span class="p-type">integer <span class="p-hint">(1–400, default 90)</span></span>
|
||||
<span class="p-desc">Calendar days to return, including today.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The stored metrics for the window, oldest day first.<span class="r-sig">{ ok: boolean, days: integer, key: string, updatedAt: integer, last: object, metrics: object, workouts: object[] }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-vitalsClear">
|
||||
<summary>
|
||||
<span class="m delete">DELETE</span>
|
||||
<span class="ep-path"><code>/api/vitals</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Delete the caller's health data, or one metric of it</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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.</p>
|
||||
<p>With <code>?metric=</code> it forgets <b>one</b> 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 <code>200</code> with <code>metric: null</code>, not an error.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">metric</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The metric name exactly as HAE wrote it (<code>step_count</code>, <code>heart_rate</code>…). Omit it to clear everything.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">Deleted (also when there was nothing stored).<span class="r-sig">{ ok: boolean }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-vitalsHours">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/vitals/hours</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">One metric's hours on one day</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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.</p>
|
||||
<p>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.</p>
|
||||
<p>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 <b>Hours</b> in Health Auto Export to keep them — the day remains the sum of its hours, so nothing is counted twice.</p>
|
||||
<p>Session only, like <code>GET /api/vitals</code>: the ingest key is write-only.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">metric<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The metric name exactly as HAE wrote it (<code>step_count</code>, <code>heart_rate</code>…).</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">day<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">A calendar day, in the phone's own date, as <code>YYYY-MM-DD</code>.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The hours stored for that metric and day (empty when there are none).<span class="r-sig">{ ok: boolean, metric: string, day: string, units: string, hours: object[] }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-insightsGet">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/insights</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">The profile's last second opinion, if the instance has one</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>Whether this instance is configured for a second opinion at all (<code>configured</code>, false unless <code>JEV_API_KEY</code> or <code>OPENCODE_API_KEY</code> is set), what was judged last, whether that judgment is still about the data on screen, and what is left of today's budget.</p>
|
||||
<p>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 <code>null</code> — the server never fills a gap with a guess, and the screen says the question went unanswered rather than drawing a zero.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">raw</span>
|
||||
<span class="p-type">"1"</span>
|
||||
<span class="p-desc">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.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The state of the feature and the last judgment.<span class="r-sig">{ ok: boolean, configured: boolean, model: string, host: string, insight: object, freshness: object, budget: object }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-insightsAsk">
|
||||
<summary>
|
||||
<span class="m post">POST</span>
|
||||
<span class="ep-path"><code>/api/insights</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Ask for a second opinion about this profile</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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, <b>the whole training history per exercise</b> (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.</p>
|
||||
<p><b>What leaves the instance is decided server-side and is aggregates only</b>: no name, no workout titles, no chat, and no identifier of a person. The exceptions are deliberate and small: the Coach intake's <code>limitations</code> note, because "bad shoulder" changes the answer, and the <b>library id of an exercise that has stopped progressing</b>, 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 <code>limitations</code> field, because "bad shoulder" changes the answer; the sheet in front of the button lists exactly what will be sent before it is sent.</p>
|
||||
<p>It costs a request, so it is never on a timer: the call is the ask, and the budget (<code>per profile per day</code>, 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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The judgment, parsed. Every question the model left unanswered is null.<span class="r-sig">{ ok: boolean, model: string, host: string, insight: object, freshness: object, budget: object, sent: object }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">400</span>
|
||||
<span class="p-desc">The instance has no key configured — the message names the variable to set.</span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">429</span>
|
||||
<span class="p-desc">Today's budget is spent, or ten minutes have not passed since the last ask.</span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s5">502</span>
|
||||
<span class="p-desc">The gateway refused or failed; the message carries what it said.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-vitalsIngest">
|
||||
<summary>
|
||||
<span class="m post">POST</span>
|
||||
<span class="ep-path"><code>/api/vitals/ingest</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Receive a Health Auto Export JSON export</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>The endpoint an iOS automation posts to. In Health Auto Export: Automation Type <b>REST API</b>, URL = this endpoint, header <code>Authorization: Bearer <ingest key></code> (from <code>POST /api/vitals/key</code>), Export Format <b>JSON</b>, Export Version <b>2</b>, Summarize Data <b>On</b>, Time Grouping <b>Hours</b> (or <b>Days</b> for totals with nothing behind them), Date Range <b>Previous 7 Days</b> — with the default range every sync carries today only, and the past is never in the file.</p>
|
||||
<p>The merge is idempotent, which is what makes a five-minute cadence safe:</p>
|
||||
<p>* A payload whose datapoints all sit on midnight is HAE's own day grouping, and a day total <i>replaces</i> 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 <i>hour</i> 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 <code>duplicates</code>.</p>
|
||||
<p>CSRF-exempt: the request carries its own credential in a header and has no session to borrow.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
|
||||
<p class="ep-h">Request body <span class="p-hint">(JSON)</span></p>
|
||||
<pre><code>{
|
||||
"data": {
|
||||
"metrics": [
|
||||
{
|
||||
"name": "step_count",
|
||||
"units": "count",
|
||||
"data": [
|
||||
{
|
||||
"qty": 12481,
|
||||
"date": "2026-09-03 00:00:00 +0200"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}</code></pre>
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">Accepted — including an export with nothing in it, because a scheduled automation that fires when there is nothing to report is not a failure.<span class="r-sig">{ ok: boolean, ts: integer, received: object, stored: object }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">400</span>
|
||||
<span class="p-desc">Not a Health Auto Export JSON export (or not JSON at all).<span class="r-sig"><code>{"error":"not a Health Auto Export JSON export"}</code></span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No ingest key, an unknown or rotated key, or a disabled account.<span class="r-sig"><code>{"error":"invalid ingest key"}</code></span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">413</span>
|
||||
<span class="p-desc">Body over 32 MB. Group by days in HAE, or select fewer metrics.<span class="r-sig"><code>{"error":"body too large"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-vitalsKeyCreate">
|
||||
<summary>
|
||||
<span class="m post">POST</span>
|
||||
<span class="ep-path"><code>/api/vitals/key</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Get the profile's ingest key, creating it on first use</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>Idempotent: a second call returns the key that exists rather than invalidating the configuration already pasted into the phone.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The ingest key.<span class="r-sig">{ ok: boolean, key: string }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-vitalsKeyRotate">
|
||||
<summary>
|
||||
<span class="m post">POST</span>
|
||||
<span class="ep-path"><code>/api/vitals/key/rotate</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Replace the profile's ingest key</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">A new key.<span class="r-sig">{ ok: boolean, key: string }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="api-sec" id="music">
|
||||
<h2>Música</h2>
|
||||
<p class="sub">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.</p>
|
||||
<div class="eps">
|
||||
|
||||
<details class="ep" id="op-radioGet">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/radio</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Live radio stations for a genre, with their stream URLs resolved</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>What the <b>Radio</b> section of the Música screen draws. Every station arrives with the URL to hand an <code><audio></code> element already resolved — the one non-obvious decision here, and it is about iOS: audio may only start <i>inside</i> the tap that asked for it, so anything asynchronous between the finger and the <code>play()</code> is a press that quietly does nothing.</p>
|
||||
<p>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).</p>
|
||||
<p>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.</p>
|
||||
<p>An unknown or missing <code>genre</code> is not an error: it falls back to the first genre.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">genre</span>
|
||||
<span class="p-type">"workout" | "techno" | "rnb" | "latin" | "hiphop" | "reggae" | "chill" | "jazz" | "rock" | "electronic"</span>
|
||||
<span class="p-desc">Genre key. Missing or unrecognised falls back to <code>workout</code>.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The genres for the chips, and the stations for the one that was asked for.<span class="r-sig">{ ok: boolean, genres: object[], genre: string, label: string, stations: <a href="#schema-RadioStation">RadioStation</a>[] }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-radioNow">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/radio/now</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">What a station says it is playing</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>The line under the station's name in the player bar, and the metadata the lock screen shows. Only <b>SomaFM</b> and <b>Radio Paradise</b> publish this; for anything else the answer is <code>now: null</code> and the bar shows the station itself rather than inventing a track.</p>
|
||||
<p>The station is rebuilt from <code>src</code> + <code>id</code> 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.</p>
|
||||
<p>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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">src<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">"soma" | "paradise"</span>
|
||||
<span class="p-desc">Which service the station belongs to.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">id<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The station's id at that service (a SomaFM channel like <code>beatblender</code>, or a Radio Paradise mix like <code>main</code>).</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The current track, or <code>null</code> when the station does not publish one.<span class="r-sig">{ ok: boolean, now: object }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">400</span>
|
||||
<span class="p-desc">No such station — an unknown <code>src</code>, or an <code>id</code> that is not a plain id.</span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-podcastsGet">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/podcasts</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Spanish-language podcast shows for a category</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>What the <b>Podcasts</b> 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 <code>GET /api/podcasts/show</code>.</p>
|
||||
<p><b>Spanish only, and checked rather than assumed.</b> 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 <code>Range</code> request) and its <code><language></code> decides: <code>es</code>, <code>es-ES</code>, <code>es-419</code> and <code>spa</code> are kept, <code>ca</code> and <code>en</code> 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. <code>skipped</code> reports how many went each way, so a short list is never a mystery.</p>
|
||||
<p>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.</p>
|
||||
<p>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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">category</span>
|
||||
<span class="p-type">"fitness" | "sports" | "comedy" | "news" | "history" | "truecrime" | "science" | "tech" | "society" | "business" | "fiction" | "education" | "music" | "leisure"</span>
|
||||
<span class="p-desc">Category key. Missing or unrecognised falls back to <code>fitness</code>.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The categories for the chips, and the Spanish shows in the one asked for.<span class="r-sig">{ ok: boolean, categories: object[], category: string, label: string, shows: <a href="#schema-PodcastShow">PodcastShow</a>[], skipped: object }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-podcastsShow">
|
||||
<summary>
|
||||
<span class="m get">GET</span>
|
||||
<span class="ep-path"><code>/api/podcasts/show</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">One show's episodes, read out of the publisher's feed</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>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 <code>https://</code> URL of its audio file (<code>enclosure</code>), which is what the phone plays; nothing is downloaded by this server and no audio is proxied.</p>
|
||||
<p>Two things are refused or reported rather than faked:</p>
|
||||
<ul><li><b>A URL this process will not fetch</b> is a <code>400</code>. 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 <code>10.</code>/<code>192.168.</code>/<code>172.16-31.</code>, no link-local, no IPv6 literals, no <code>.local</code>). A redirect is checked the same way, because a redirect is otherwise the way around it.</li><li><b>A feed that is not Spanish</b> is answered with <code>200</code> and <code>spanish: false</code> (with <code>episodes: []</code>), 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.</li></ul>
|
||||
<p>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.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
<p class="ep-h">Query parameters</p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">feed<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The show's feed URL, exactly as <code>GET /api/podcasts</code> returned it.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">title</span>
|
||||
<span class="p-type">string <span class="p-hint">(≤ 120 chars)</span></span>
|
||||
<span class="p-desc">The directory's name for the show, used only when the feed declares none.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">image</span>
|
||||
<span class="p-type">string <span class="p-hint">(≤ 300 chars)</span></span>
|
||||
<span class="p-desc">The directory's artwork, used only when the feed declares none.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">The show and its episodes — or <code>show: null</code> when the feed did not answer.<span class="r-sig">{ ok: boolean, feed: string, spanish: boolean, show: object, episodes: <a href="#schema-PodcastEpisode">PodcastEpisode</a>[], error: string }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">400</span>
|
||||
<span class="p-desc">The feed URL is not one this server will fetch (not https, not a public host).</span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep" id="op-musicLookup">
|
||||
<summary>
|
||||
<span class="m post">POST</span>
|
||||
<span class="ep-path"><code>/api/music/lookup</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">Read what a public Apple Music page says about itself</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p>Apple has no API for somebody else's public playlists, so a playlist saved in KuentaGYM is a <i>link</i> — 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).</p>
|
||||
<p>The URL must be an Apple Music link on an allowlisted host (<code>hostAllowed</code>), 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.</p>
|
||||
<p>An unreachable page or a page that left the allowlist is <b>not</b> an error status — the answer is <code>200</code> with <code>meta: null</code> and an <code>error</code> naming which of the two happened, because the app's job then is to save the link anyway with the name the person typed.</p>
|
||||
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer <token></code> from mobile-app pairing.</span></p>
|
||||
|
||||
<p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">url<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">A public <code>https://music.apple.com/...</code> link.</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="ep-h">Responses</p>
|
||||
<div class="ptab">
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s2">200</span>
|
||||
<span class="p-desc">What the page said, or <code>meta: null</code> with a reason.<span class="r-sig">{ ok: boolean, meta: object, error: string }</span></span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">400</span>
|
||||
<span class="p-desc">Not an Apple Music link, or a plain-<code>http</code>/off-host URL. Refused before any request is made.</span>
|
||||
</div>
|
||||
<div class="prow rrow">
|
||||
<span class="r-code s4">401</span>
|
||||
<span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{"error":"not signed in"}</code></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="api-sec" id="push">
|
||||
<h2>Push</h2>
|
||||
<p class="sub">Web Push (VAPID) subscriptions, rest-timer and test pushes</p>
|
||||
@@ -1385,6 +1886,112 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep sch" id="schema-PodcastShow">
|
||||
<summary>
|
||||
<span class="sch-name"><code>PodcastShow</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">One show in the Podcasts section.</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
<p><code>feed</code> is the only field the episodes can be fetched with, and it is what the show is saved by in a profile.</p>
|
||||
<div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">feed<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The publisher's RSS URL</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">id</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The directory's own id for the show.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">name<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc"></span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">author</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc"></span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">image</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">HTTPS artwork.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">genre</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc"></span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">country</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The storefront it was found in: <code>es</code> or <code>mx</code>.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">lang</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">What the feed itself declares — <code>es</code>, <code>es-ES</code>, <code>es-mx</code>… — or null when it declares nothing, which is a "kept, unconfirmed" and not a "not Spanish".</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep sch" id="schema-PodcastEpisode">
|
||||
<summary>
|
||||
<span class="sch-name"><code>PodcastEpisode</code></span>
|
||||
<span class="ep-chev" aria-hidden="true"></span>
|
||||
<span class="ep-sum">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.</span>
|
||||
</summary>
|
||||
<div class="ep-body">
|
||||
|
||||
<div class="ptab">
|
||||
<div class="prow">
|
||||
<span class="p-name">id<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The feed's guid</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">title<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc"></span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">url<em class="p-req" title="required">required</em></span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">The <code>https://</code> audio file to play. Never proxied.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">date</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">ISO 8601</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">duration</span>
|
||||
<span class="p-type">integer</span>
|
||||
<span class="p-desc">Seconds</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">image</span>
|
||||
<span class="p-type">string</span>
|
||||
<span class="p-desc">Episode artwork</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">episode</span>
|
||||
<span class="p-type">integer</span>
|
||||
<span class="p-desc"><code>itunes:episode</code>, when the feed numbers them.</span>
|
||||
</div>
|
||||
<div class="prow">
|
||||
<span class="p-name">bytes</span>
|
||||
<span class="p-type">integer</span>
|
||||
<span class="p-desc">The enclosure's declared size.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="ep sch" id="schema-RadioStation">
|
||||
<summary>
|
||||
<span class="sch-name"><code>RadioStation</code></span>
|
||||
|
||||
Reference in new issue
Block a user