Compare commits

..
10 Commits
Author SHA1 Message Date
dsantillan 660bd4f0ff Los videos en videos/, que se ve: .tools/ está oculto
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Pregunta textual: "¿dónde busco el video?". Estaba en .tools/video/brag-output/, y
.tools/ empieza con punto, así que el explorador de archivos no lo muestra. Los videos
van ahora a videos/ —misma cosa, pero visible— y sigue ignorado por git: son 9 MB que
se re-renderizan con ./.tools/hf.
2026-09-24 22:02:49 -04:00
dsantillan 65f766b9d9 Ignorar .tools/: la cadena de video local (Hyperframes, ffmpeg estático y /brag)
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
No es una dependencia de la app —nada en frontend/ ni en api/ lo importa— y pesa
cientos de megas, así que no tiene nada que hacer en el repo. Queda documentado en
.tools/README.md: qué se instaló, el wrapper que hace falta porque $HOME es de sólo
lectura en este entorno, y cómo se hace un video.
2026-09-24 22:00:41 -04:00
dsantillan 78b815ae8f El reproductor completo al tocar la barra, y el episodio siguiente al terminar
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
Tocar la barra abre el reproductor completo, como el de Spotify: portada en grande,
título entero, programa, autor, número de episodio y fecha, una barra que se arrastra,
el tiempo transcurrido y **lo que falta**, −15/+30, anterior y siguiente, y una línea
que dice **"Después: …"** con el nombre del que sigue —o que es el último de la lista.
Es una hoja, no una ruta, por lo mismo de siempre: una pantalla dentro del router se
desmonta al navegar y esto no puede ser lo que corte el audio. Para una emisora el
mismo reproductor no dibuja barra de progreso: una radio en vivo no tiene posición ni
final, y decirlo es mejor que un slider muerto.

Un episodio que termina **sigue con el siguiente** de la lista en la que lo pusiste a
sonar, sin tocar el teléfono; al final de la lista se detiene y el reproductor lo
avisa antes. El que termina queda marcado como escuchado. Los botones de siguiente y
anterior de la **pantalla bloqueada** ahora llegan al elemento de audio, que es donde
alguien con las manos en la barra los va a apretar.

Y dos cosas que aparecieron revisando esto:

- `setRadioNow` llamaba a `setMediaSession`, una función que ya no existe desde que el
  reproductor se unificó (hoy `setStreamSession`). El error quedaba **tragado** por el
  `.catch` del sondeo: la pantalla mostraba el tema —el estado se actualiza antes de la
  línea que falla— y la **pantalla bloqueada nunca se enteraba** del tema que sonaba.
  Ahora hay un test que lo mira y se comprobó por mutación.
- `useUI` tenía **dos definiciones** de `setRadioVolume` y `setRadioNow`: al insertar el
  bloque de podcasts había quedado duplicado el final del bloque de radio, y en un
  objeto literal la última gana en silencio. Una copia era código muerto que se leía
  como vivo — y fue la que hizo que el primer intento de comprobar lo anterior "pasara".

Tests nuevos: useUI.podcast.test.js (16, con el reproductor burlado emitiendo lo que
emite un navegador: ended → siguiente, time → reloj, paused → posición guardada),
NowPlaying.test.jsx (13) y el toque en la barra en PlayerBar.test.jsx.
2026-09-23 21:40:17 -04:00
dsantillan d5cf0d8d64 Música se ordena: pestañas, buscador, y listas de diez con "Mostrar más"
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
La pantalla era una sola columna —radio, después podcasts, después listas— y tres
listas de veinte filas es una pantalla por la que se baja buscando lo que ya sabías
que querías. Ahora pregunta primero: **Radio | Podcasts | Listas**, una lista a la
vez, **diez filas** y un **"Mostrar más"** que dice cuántas esconde. Nada queda fuera
de alcance y nada más está en pantalla mientras decidís: el subtítulo también dice qué
estás mirando en vez de hablar siempre de listas.

El **buscador** busca lo que tengas abierto y en el origen, no en la página: `jazz`
le pregunta al directorio de emisoras y `crimen` al de podcasts de Apple —filtrado,
como siempre, a español, y pasando por **la misma** función de filtro que una
categoría, porque un segundo camino más barato al catálogo es como se pierde una
regla—. Con menos de dos letras no se busca ni se pide nada: una letra coincide con
todo y sería una petición por tecla para una respuesta inservible.

La búsqueda de emisoras **ordena por lo que se buscó**: el directorio coincide con
subcadenas en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS -
DANCE & DJ MIX RADIO" —real, con "techno" entre sus etiquetas— por delante de toda
emisora llamada Techno Algo. El nombre pesa antes que la popularidad y a igual peso
gana el nombre más corto; los canales de SomaFM y los mixes de Paradise que coinciden
van primero, porque no tienen publicidad y su stream ya se sabe que funciona. La
búsqueda del directorio va con `is_https=true`, cacheada por consulta.

`lib/paging.js` es puro y tiene test porque tiene un borde fácil de equivocar en un
componente: una lista que se encoge —una búsqueda nueva, una emisora desmarcada— no
puede dejar el tamaño de página pasado del final, que se ve como "Mostrar más" que no
hace nada.

Verificado contra los directorios reales: `radio?q=jazz` → Sonic Universe (SomaFM) y
después Jazz 24; `radio?q=miami` → Miami Beach Radio, 105 Miami; `podcasts?q=crimen`
→ 20 programas en español (es, es-ar) y `q=entrenamiento en casa` → 3; `?q=j` no
busca. `relevance` y `rankStations` se comprobaron por mutación: sacar el orden hace
fallar el test que lo mira de punta a punta.
2026-09-23 21:24:50 -04:00
dsantillan 22654c61fc 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
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.
2026-09-23 21:11:20 -04:00
dsantillan a3e13df279 La radio no se dibuja para un invitado ni contra un servidor viejo
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
Las emisoras las busca el servidor, así que dos situaciones que no son bugs se veían
como uno: sin sesión (el modo invitado nunca habla con la api) y una api más vieja
que la app —se despliegan por separado, y un deploy que reconstruyó `web` y no el
contenedor de la api es una pantalla cuyos pedidos fallan todos.

Ahora la sección lo dice y no pide nada en ninguno de los dos casos. Para poder
distinguirlos, `radio` entra en `features` (`GET /api/config`), que es exactamente
para lo que existe esa lista, y queda documentado en la especificación junto con
`features` entero —que hasta ahora no estaba.

De paso: la fila y la barra caen al marcador de posición cuando el logo o la portada
no cargan, que es el caso de una parte del directorio.
2026-09-23 20:45:21 -04:00
dsantillan 8f26b536fd Guardar una emisora no guardaba nada, y las listas la borraban
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
Dos bugs del mismo tipo —silenciosos, y los dos visibles sólo leyendo— en las
estaciones guardadas:

1. `update(mut)` muta el borrador que recibe; el valor de retorno se descarta. La
   primera versión de `addStation` *devolvía* `{ music: … }`, así que la estrella de
   una emisora no hacía absolutamente nada: el aviso decía "guardada", la lista
   seguía vacía y nada en ninguna parte decía por qué.
2. `music` tiene las listas, el usuario de Apple Music **y** estas emisoras. Los
   métodos de listas lo reconstruían con los dos campos que les importaban, así que
   quitar una lista —o escribir tu usuario en Ajustes— tiraba todas las emisoras
   guardadas al piso.

useStore.radio.test.jsx fija las dos (y las dos se comprobaron por mutación: cada
una rompe el test que le toca) y Music.test.jsx recorre el camino entero, de la
estrella al store y de vuelta a la pantalla.

También: la fila de una emisora cae al marcador de posición cuando su logo no
carga —el directorio a veces guarda una página web en el campo del icono, y una
imagen rota se ve peor que ninguna—, y la barra hace lo mismo con la portada.
2026-09-23 20:41:36 -04:00
dsantillan 48cf976635 Radio: estaciones en vivo mientras entrenás
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 **Radio**: estaciones en vivo por género (Workout/Rave,
Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica),
sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de
radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js.

Tres decisiones que no se ven en la pantalla y son las que hacen que funcione:

- **El audio no pasa por el servidor.** La api entrega la lista y después no ve un
  byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias.
- **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar
  audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el
  play() es un botón que no hace nada, sin error en ninguna parte.
- **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de
  un componente se desmonta con él, y eso es la música cortándose al cambiar de
  pantalla — justo lo que no puede pasar en medio de una serie.

Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y
parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y
las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y
Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de
inventar una pista.

api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id`
reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el
caso de la fila en Music.test.jsx guardan lo demás.

También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado
es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now
(con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md.
2026-09-23 20:38:19 -04:00
dsantillan e1d28f971d El registro de actividad abre plegado en los diez más nuevos
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
"Muéstrame los últimos 10 y que diga mostrar más, para que no se vea todo eso para abajo." Exacto:
con 25 eventos el registro llenaba la pantalla y empujaba el resto del panel fuera de vista, y con un
día movido son cientos. El encabezado ya decía cuántos hay ("25 events, kept for 90 days"); el cuerpo
ahora empieza por los diez más nuevos y un botón **Show more** revela diez más por vez.

Tres detalles que lo hacen correcto en vez de sólo corto:

  · **Lo que ya está cargado se revela antes de pedir nada.** El botón revela de la lista que tiene y
    sólo va al servidor cuando no le queda nada por mostrar — y entonces pide la página siguiente con
    `before`, que ya sabía hacer. Sin esto, cada clic sería un viaje de red para datos que ya estaban
    en memoria.
  · **Al lado del botón dice "10 of 25"**, así que nunca queda la duda de cuánto falta; el número sale
    del `total` del servidor, no del largo de lo cargado.
  · **El botón desaparece cuando no queda nada**, en vez de quedarse invitando a un clic que no hace
    nada. Y al recargar (el ↻ del encabezado) vuelve a plegarse, que es el punto de plegarlo.

De paso, `load` ya no asume que la respuesta traiga `events`: una respuesta sin eventos es una
respuesta sin eventos, no un crash — y un crash acá se lleva la tarjeta entera del panel.

Tests: 4 en `Admin.test.jsx` (abre en diez y revela hasta el final; pide la página siguiente cuando se
le acaba lo cargado, y no antes; log vacío sin botón). Mutation-check de las dos mitades: sin el
recorte se renderizan todos, y con la página en 50 fallan los dos de plegado.
2026-09-23 19:57:43 -04:00
dsantillan f36a32e8af Deploy path: pin the project name the instance already runs under
The file this deployment is pasted from had no `name:`, so the project name came from the
directory Dokploy writes it in. It already runs as `kuentagym`, and the volumes are pinned by
`name:` either way — this just stops a pasted copy from renaming the stack and the containers
in every `docker` command and log line.
2026-09-23 19:51:35 -04:00
41 changed files with 6813 additions and 127 deletions

No files matched your search

+8
View File
@@ -27,3 +27,11 @@ frontend/bundle-size.json
# the web, resources/splash.jpg for the native shells), so a clone builds and runs without it — only
# regenerating the splash needs the original, which the script says out loud when it is missing.
assets/splash.jpg
# The video toolchain (Hyperframes + ffmpeg + the /brag skill) and its renders. ~200 MB of tooling
# that no app file imports: see .tools/README.md. Ignored so `git status` stays about the tracker.
.tools/
# Los videos de lanzamiento, en una carpeta que se ve (a diferencia de .tools/, que está oculta).
# 9 MB de MP4 que se re-renderizan con ./.tools/hf: ver .tools/README.md.
videos/
+143
View File
@@ -1,5 +1,148 @@
# Changelog
## Sin publicar — El reproductor completo, y lo que sigue después
Tocar la barra del reproductor **abre el reproductor completo**, como el de Spotify: la portada en
grande, el título del episodio entero en vez de recortado, el programa, el autor, el número de
episodio y la fecha, una **barra que se arrastra** (el slider de la casa, con `data-nodrag` para que
un arrastre lateral no se lea como cerrar la hoja), el tiempo transcurrido y **lo que falta** —que es
el número con el que se decide si da para otro episodio—, −15 / +30, anterior y siguiente, y
**"Después: …"** con el nombre del que sigue. Es una *hoja*, no una ruta: una pantalla dentro del
router se desmonta al navegar, y esto no puede ser nunca lo que corte el audio. Se cierra
deslizando hacia abajo, con el gesto de siempre, o con el botón de atrás de Android.
Para una **emisora** el mismo reproductor muestra el logo, el nombre, el género y qué está sonando
—o que esa emisora no publica lo que suena— y **no dibuja barra de progreso**: una radio en vivo no
tiene posición ni final, y decirlo es mejor que un slider muerto.
**Cuando un episodio termina, sigue el siguiente** de la lista en la que lo pusiste a sonar, sin
tocar el teléfono; al final de esa lista se detiene y el reproductor completo lo avisa antes
("Es el último episodio de esta lista"). El que terminó queda marcado como escuchado antes de pasar
al otro. Lo mismo está en la **pantalla bloqueada**: los botones de siguiente y anterior ahora
llegan al elemento de audio, que es donde alguien con las manos en la barra los va a apretar.
Dos cosas que aparecieron revisando esto, y que valen más que la función:
- `setRadioNow` llamaba a una función que ya no existía desde que el reproductor se unificó
(`setMediaSession`, hoy `setStreamSession`). El error quedaba **tragado** por el `.catch` del
sondeo: la pantalla mostraba el tema —el estado se actualizaba antes de la línea que fallaba— y la
**pantalla bloqueada nunca se enteraba**. Un fallo invisible que sólo se ve comparando lo que dice
el teléfono con lo que dice la app; ahora hay un test que lo mira, y se comprobó por mutación.
- `useUI` tenía **dos definiciones** de `setRadioVolume` y `setRadioNow`: al insertar el bloque de
podcasts quedó el final del bloque de radio duplicado, y en un objeto literal la última gana en
silencio. Una de las dos copias era código muerto que se leía como vivo — y fue justamente la que
hizo que el primer intento de comprobar lo anterior "pasara".
## Sin publicar — Música se ordena: pestañas, buscador y listas de diez
La pantalla de Música era una sola columna: la radio, después los podcasts, después las listas.
Tres listas de veinte filas cada una es una pantalla por la que se baja buscando lo que ya sabías
que querías — y lo que querías solía estar abajo. Ahora **pregunta primero**: *Radio | Podcasts |
Listas*, una lista a la vez, **diez filas** y un **"Mostrar más"** que dice cuántas queda
escondiendo. Nada quedó fuera de alcance: todo está a un toque, y nada más está en pantalla mientras
decidís.
Arriba de las pestañas hay un **buscador** que busca lo que tengas abierto, y busca en el origen, no
en la página: escribir *jazz* le pregunta al directorio de emisoras, y *crimen* al de podcasts de
Apple —filtrado, como siempre, a español—. Las filas que devuelve son las mismas que muestra una
categoría, así que una emisora encontrada buscando se guarda, suena y se cachea igual que una
encontrada navegando. Con menos de dos letras no se busca nada: una letra coincide con todo, y
pedirle al directorio que lo demuestre es una petición por tecla para una respuesta que nadie puede
usar.
La búsqueda de emisoras **ordena por lo que la persona buscó**: el directorio coincide con subcadenas
en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS - DANCE & DJ MIX RADIO" —una
emisora real, con "techno" entre sus etiquetas— por delante de toda emisora llamada Techno Algo. El
nombre pesa antes que la popularidad, y a igual peso gana el nombre más corto. Los canales de SomaFM
y los mixes de Radio Paradise que coinciden van primero, porque no tienen publicidad y su stream ya
se sabe que funciona.
También: la lista de episodios de un programa (hasta cuarenta) se muestra de a diez; y el subtítulo
de la pantalla dice qué estás mirando en vez de hablar siempre de listas.
## 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 /
House, R&B / Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica* — que suenan mientras
entrenás sin salir de la app, con la pantalla bloqueada y el teléfono en el bolsillo. No es un
reproductor de archivos ni una lista que hay que armar: es radio, con lo bueno y lo malo de la radio
— no elegís el tema, y a cambio no hay que elegirlo cada vez.
Las **primeras de cada género son las que no tienen publicidad** (los canales de **SomaFM** y los
cuatro mixes de **Radio Paradise**), y detrás va el resto del directorio público de
[radio-browser](https://www.radio-browser.info) — miles de estaciones comunitarias, filtradas a HTTPS
y a las que responden. No hay **ninguna dependencia nueva**: la lista la arma `api/radio.js`, que
habla con esos tres servicios y con nada más.
**El audio va del teléfono a la estación, no pasa por tu servidor.** Este servidor entrega la lista
—con la URL del stream ya resuelta— y después no ve nada: ni tráfico, ni disco, ni un byte de audio.
Eso también quiere decir que no hay nada que grabar: no se descarga música y no queda ninguna copia
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** (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.
Lo demás está donde se espera: una **barra arriba de la barra de pestañas** mientras algo suena, con
la estación, qué está sonando y dos botones — **pausa** (que deja la estación donde estaba, para
seguir con la misma después del descanso) y **parar** (que la saca). La **pantalla bloqueada** muestra
la estación, la pista y los controles donde el teléfono los pone, vía Media Session, y las canciones
siguen con la pantalla apagada porque el audio lo maneja el sistema, no la página. Las estaciones se
pueden **guardar por perfil** con la estrella y quedan arriba de la lista.
Qué está sonando lo dicen **SomaFM y Radio Paradise** y nadie más: en esas dos la barra muestra
artista y tema (con la portada), y en el resto muestra la estación — **no se inventa una pista**.
Preguntarlo cuesta una petición cada 45 segundos, sólo mientras suena, y con la pantalla bloqueada ni
eso: iOS suspende los temporizadores, el rótulo se queda quieto y la música sigue. Todo lo que el
servidor le pregunta a esas dos es *qué suena ahora en tal canal*; no sabe qué escuchaste, cuánto ni
por cuánto tiempo.
## Sin publicar — La segunda opinión (Jev por OpenCode Zen)
Salud puede llevar ahora un **juicio** sobre tus propios números, no solo los números: qué tan listo
+25 -7
View File
@@ -27,7 +27,8 @@ mcp/ optional MCP server — read-only stdio bridge exposing a user's work
media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
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).
docs/ SELF_HOSTING.md, MOBILE.md, AI_COACH.md, HEALTH.md (Apple Health ingest),
RADIO.md (live stations), PODCASTS.md (Spanish-language episodes).
```
## Commands
@@ -89,6 +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.
- `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
@@ -122,12 +132,20 @@ 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` and `music.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. `server.js` owns the sockets; those files own the parsing, which is why
they are testable without a phone or a network. Both 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.
`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.
### MCP server (`mcp/src`)
+2
View File
@@ -94,6 +94,8 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone
- 🌍 **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 **continues with the next one when it ends**; tapping the bar opens the **full player** (artwork at size, a draggable scrubber, what is left, and what plays next), and the lock screen shows the episode, its progress, and its next/previous buttons. **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
View File
@@ -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.
COPY server.js push-messages.js verify-error.js vitals.js music.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
+419 -1
View File
@@ -88,6 +88,12 @@ tags:
description: >-
Apple Health metrics ingested from an iPhone (Health Auto Export automations) —
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, 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`)
@@ -125,6 +131,12 @@ paths:
description: |
The flags the login screen needs before anyone is signed in. Both reflect
environment variables on the server (`INVITE_ONLY`, `ALLOW_GUEST`).
`features` is the one that exists because the app and the api are deployed separately: the
frontend is rebuilt from source on every deploy while the api's code lives inside its
container, so a deploy can leave a new screen on top of an older api. Naming what this
server can do lets a screen say "this server is older than the app" instead of showing a
request that quietly fails — or, worse, a number that never moves.
security: []
responses:
'200':
@@ -142,7 +154,25 @@ paths:
description: >-
When false, the client hides "continue without account".
Guest mode is purely client-side and never calls this API.
example: { invite_only: true, allow_guest: false }
features:
type: array
description: >-
What this build of the api supports, so a client can tell an older server from
a broken one. Clients must treat a missing or non-array `features` as "old
server", never as "supports everything".
items:
type: string
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.
properties:
enabled: { type: boolean }
provider: { type: string }
providerLabel: { type: string }
authMode: { type: string, enum: [instance, byok] }
community: { type: boolean }
example: { invite_only: true, allow_guest: false, features: [vitals, radio, insights] }
/api/me:
get:
@@ -909,6 +939,308 @@ paths:
description: The gateway refused or failed; the message carries what it said.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/radio:
get:
tags: [music]
operationId: radioGet
summary: Live radio stations for a genre, with their stream URLs resolved
description: |
What the **Radio** section of the Música screen draws. Every station arrives with the URL to
hand an `<audio>` element already resolved — the one non-obvious decision here, and it is
about iOS: audio may only start *inside* the tap that asked for it, so anything asynchronous
between the finger and the `play()` is a press that quietly does nothing.
The audio never passes through this server. The list is the whole feature on this side: the
phone then talks to the station directly, so this instance spends no bandwidth and keeps no
copy of anything. Sources are SomaFM (commercial-free) and Radio Paradise for the curated
picks, and the public radio-browser directory for the rest, filtered to HTTPS and to codecs a
browser plays without a library (HLS streams are skipped — that would mean shipping a player
library).
A session is required. Not to protect the stations — they are public — but because this
container sits on the owner's own network and fetches on behalf of whoever asks.
An unknown or missing `genre` is not an error: it falls back to the first genre.
**`?q=` searches instead of browsing**, and it is the same route on purpose: the screen has
one list, and what fills it changes. A query is matched against the curated channels and
Radio Paradise mixes locally, and the directory is asked by name — ordered by how many people
listen, then re-ordered so a station *called* "Jazz 24" comes before one with "jazz" buried
in a forty-character marketing name. A query shorter than two characters is not a search and
answers an empty list without asking anybody.
parameters:
- name: q
in: query
schema: { type: string, maxLength: 60 }
description: A name search. Two characters or more; when present, `genre` is ignored.
- name: genre
in: query
schema:
type: string
enum: [workout, techno, rnb, latin, hiphop, reggae, chill, jazz, rock, electronic]
description: Genre key. Missing or unrecognised falls back to `workout`.
responses:
'200':
description: The genres for the chips, and the stations for the one that was asked for.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
genres:
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 }
genre: { type: string, description: The genre actually answered with. Absent on a search. }
label: { type: string, description: That genre's human label. Absent on a search. }
query: { type: string, description: Present only on a search — the normalised query that was used. }
stations:
type: array
description: Curated, ad-free picks first, then the directory. At most 40.
items: { $ref: '#/components/schemas/RadioStation' }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/radio/now:
get:
tags: [music]
operationId: radioNow
summary: What a station says it is playing
description: |
The line under the station's name in the player bar, and the metadata the lock screen shows.
Only **SomaFM** and **Radio Paradise** publish this; for anything else the answer is
`now: null` and the bar shows the station itself rather than inventing a track.
The station is rebuilt from `src` + `id` rather than accepted as an object, and the id is
checked against a plain-id pattern, because the id is used to build a URL this process
fetches: without that, a session would be enough to make the api a request proxy for anything
on the owner's network. The two known sources are the only ones accepted.
The client polls this every 45 seconds while something plays — the screen's own timer, so
when iOS suspends it on a locked screen the caption freezes and the music does not.
parameters:
- name: src
in: query
required: true
schema: { type: string, enum: [soma, paradise] }
description: Which service the station belongs to.
- name: id
in: query
required: true
schema: { type: string, pattern: '^[A-Za-z0-9_-]{1,40}$' }
description: The station's id at that service (a SomaFM channel like `beatblender`, or a Radio Paradise mix like `main`).
responses:
'200':
description: The current track, or `null` when the station does not publish one.
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
now:
type: object
nullable: true
properties:
artist: { type: string, nullable: true }
title: { type: string }
cover: { type: string, nullable: true, description: HTTPS album art, when the station sends one. }
'400':
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`.
- name: q
in: query
schema: { type: string, maxLength: 80 }
description: >-
A search by name. Two characters or more; when present, `category` is ignored and the
same Spanish-language check runs on the results as on a category's chart entries — a
search is not a second, weaker way into the catalogue.
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. Absent on a search. }
label: { type: string }
query: { type: string, description: Present only on a search — the term that was used. }
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]
operationId: musicLookup
summary: Read what a public Apple Music page says about itself
description: |
Apple has no API for somebody else's public playlists, so a playlist saved in KuentaGYM is a
*link* — and this is how the card gets its title, artwork, track count and curator without
the client fetching Apple itself (which CORS would refuse anyway).
The URL must be an Apple Music link on an allowlisted host (`hostAllowed`), and so must the
URL the request ends up at: a redirect is otherwise a way around the allowlist. This
container sits on the owner's own network, which is the whole reason for the check.
An unreachable page or a page that left the allowlist is **not** an error status — the answer
is `200` with `meta: null` and an `error` naming which of the two happened, because the app's
job then is to save the link anyway with the name the person typed.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [url]
properties:
url: { type: string, description: A public `https://music.apple.com/...` link. }
responses:
'200':
description: 'What the page said, or `meta: null` with a reason.'
content:
application/json:
schema:
type: object
properties:
ok: { type: boolean }
meta:
type: object
nullable: true
properties:
title: { type: string, nullable: true }
artwork: { type: string, nullable: true }
tracks: { type: integer, nullable: true }
curator: { type: string, nullable: true }
error:
type: string
description: Present only when `meta` is null — `unreachable`, `off-host` or `http-<status>`.
'400':
description: Not an Apple Music link, or a plain-`http`/off-host URL. Refused before any request is made.
'401': { $ref: '#/components/responses/Unauthorized' }
/api/vitals/ingest:
post:
tags: [health]
@@ -1627,6 +1959,92 @@ 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: >-
One row in the Radio section: everything the screen needs to draw the station *and* to start
playing it, because the `play()` has to happen inside the tap that chose it.
required: [src, id, name, url]
properties:
src:
type: string
enum: [soma, paradise, rb]
description: >-
Where it came from — `soma` (SomaFM, commercial-free), `paradise` (Radio Paradise, four
hand-mixed channels) or `rb` (the public radio-browser directory). `src` + `id` is what
`GET /api/radio/now` is asked about, and only the first two answer.
id: { type: string, description: The station's id at that source. }
name: { type: string }
genre: { type: string, nullable: true, description: Free-form tags or the channel's own genre. }
detail:
type: string
nullable: true
description: The second line — country, codec, bitrate for the directory, or "no advertising" for the curated ones.
image: { type: string, nullable: true, description: HTTPS logo, when the source publishes one. }
url:
type: string
description: >-
The stream, already resolved to an HTTPS URL a browser plays natively. For SomaFM this
comes from the channel's own `.pls` rather than a guessed bitrate URL.
example:
src: soma
id: beatblender
name: Beat Blender
genre: Electronic
detail: A late night blend
image: null
url: https://ice2.somafm.com/beatblender-128-mp3
SessionUser:
type: object
description: The caller's identity, as returned by /api/me and the sign-in routes.
+567
View File
@@ -0,0 +1,567 @@
/* 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 { shows, skipped } = await spanishOnly(rows, { fetchImpl });
return { category, shows, skipped };
}
/**
* The Spanish filter, shared by a category list and a search: check each candidate's feed, keep the
* Spanish ones, and count why the others went.
*
* *Why* a show was left out is reported and not just dropped. It used to be `return null` for every
* reason, which made three different things — "not in Spanish", "the feed did not answer", "the pool
* swallowed an unexpected error" — the same observable outcome, so a refactor that accidentally let
* the third one happen looked exactly like the rule working. A count per reason makes each of them a
* fact a test can assert on.
*/
export async function spanishOnly(rows, { fetchImpl = fetch, limit = MAX_SHOWS } = {}) {
const seen = new Set();
const skipped = { duplicate: 0, language: 0, unreadable: 0, failed: 0 };
const results = await mapLimit(rows.slice(0, CHECK_LIMIT), POOL, async show => {
if (seen.has(show.feed)) return { skip: 'duplicate' };
seen.add(show.feed);
const lang = await feedLanguage(show.feed, { fetchImpl });
if (!lang) return { skip: 'unreadable' };
if (!isSpanish(lang.lang)) return { skip: 'language' };
return { show: { ...show, lang: lang.lang || null } };
});
const shows = [];
for (const r of results) {
// A null is an error the pool caught: counted as a failure rather than passing for a show that
// was filtered on purpose.
if (!r) { skipped.failed++; continue }
if (r.skip) { skipped[r.skip]++; continue }
shows.push(r.show);
if (shows.length >= limit) break;
}
return { shows, skipped };
}
/* ---------- search ---------- */
/**
* Shows by name, from the same directory as the categories.
*
* Apple's search endpoint takes the same shape as its charts did in `lookup` — `collectionName`,
* `feedUrl`, `artworkUrl600` — so the rows go straight through `showFrom`, and then through the very
* same Spanish filter as a category list. That sharing is the point: a search is not a second,
* weaker way into the catalogue, and "Spanish only" cannot quietly stop applying to it.
*
* The two storefronts are searched because they publish different podcasts, and the results are
* interleaved so neither country fills the screen.
*/
export async function searchShows(query, { fetchImpl = fetch } = {}) {
const term = normQuery(query);
if (!term) return { query: '', shows: [], skipped: { duplicate: 0, language: 0, unreadable: 0, failed: 0 } };
const perStore = await Promise.all(STORES.map(country => appleSearch(term, country, { fetchImpl })));
const lists = perStore.filter(Array.isArray);
const rows = [];
for (let i = 0; lists.some(l => l[i]); i++) {
for (const list of lists) if (list[i]) rows.push(list[i]);
}
const { shows, skipped } = await spanishOnly(rows, { fetchImpl });
return { query: term, shows, skipped };
}
/** One query, normalised: one letter matches everything and costs a request per storefront to say so. */
export function normQuery(query) {
const q = String(query == null ? '' : query).replace(/\s+/g, ' ').trim().slice(0, 80);
return q.length < 2 ? '' : q;
}
/** The directory's search for one storefront, cached: the same query is the same answer. */
export async function appleSearch(term, country, { fetchImpl = fetch } = {}) {
return cached(`search:${country}:${term.toLowerCase()}`, CACHE_MS, async () => {
const params = new URLSearchParams({ media: 'podcast', term, country, limit: String(CHART_LIMIT), lang: 'es' });
const text = await get(apple('/search?' + params), { fetchImpl });
if (!text) return [];
try {
const json = JSON.parse(text);
return (json.results || []).map(r => showFrom(r, country)).filter(Boolean);
} catch { return [] }
});
}
/* ---------- the feed ---------- */
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
const safeCodePoint = n => (Number.isFinite(n) && n > 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '');
/** Named and numeric entities — not a parser, a decoder for what titles actually contain. */
export function decodeEntities(text) {
return String(text == null ? '' : text)
.replace(/&#x([0-9a-f]+);/gi, (_, hex) => safeCodePoint(parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec) => safeCodePoint(parseInt(dec, 10)))
.replace(/&([a-z]+);/gi, (m, name) => (name.toLowerCase() in ENTITIES ? ENTITIES[name.toLowerCase()] : m));
}
/** The text of a tag, CDATA unwrapped, entities decoded, whitespace collapsed. */
export function tagText(item, tag) {
const m = new RegExp(`<${tag}(?:\\s[^>]*)?>([\\s\\S]*?)</${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
};
}
+411
View File
@@ -0,0 +1,411 @@
/* radio.js — the radio stations the app can play.
*
* Radio, not files, and that is the whole point: a public stream is made to be listened to — it is
* the radio in a car, not a download — so nothing here copies anything, and the audio never passes
* through this server. The browser gets a stream URL and plays it straight from the station, which
* is why a music library costs this instance no disk and no bandwidth.
*
* Three sources, each picked for a reason:
*
* SomaFM listener-supported since 2000, no advertising at all, and a channel list
* published as JSON for exactly this kind of use. Their `.pls` gives the direct
* stream, so nothing is guessed from a channel id.
* Radio Paradise listener-supported, no advertising, four mixes, and a public now-playing API
* that even carries the cover of the album.
* radio-browser an open-source directory (AGPL) of ~50,000 stations, no key, no account. It is
* where the genres SomaFM does not carry come from — salsa, reggaetón, latin
* broadcasters — with the honest caveat that those stations are commercial and may
* air advertising. The directory has none; the stations are their own business.
*
* Everything here is a pure function of what is fetched, with `fetch` injected, so the filters —
* HTTPS only, MP3/AAC only, no HLS, no dead entries — are testable without a network.
*/
/* The hosts *this process* is allowed to call, and only these.
*
* A different list from the music lookup's, because it guards a different thing: that one screens
* URLs a signed-in person typed, this one screens the calls this module makes — which are our own
* constants plus the community directory. The stream hosts (ice*.somafm.com, the directory's
* stations, the Paradise mixes) are never fetched here: they are handed to the browser, which
* reaches them directly. That is the point of radio — the audio does not pass through this server. */
export const RADIO_HOSTS = Object.freeze([
'somafm.com', // the channel list, and what is playing
'api.somafm.com', // the .pls that resolves to a stream
'api.radioparadise.com', // what is playing, with the cover
'all.api.radio-browser.info', // the directory (a load-balanced name, so it is the one to use)
'de1.api.radio-browser.info', // the same, pinned, in case the round-robin name is unreachable
'nl1.api.radio-browser.info'
]);
/** HTTPS and on the list. Exported because the rule is worth testing on its own. */
export function allowedHost(url, hosts = RADIO_HOSTS) {
try {
const u = new URL(String(url));
return u.protocol === 'https:' && hosts.includes(u.hostname.toLowerCase());
} catch { return false }
}
const UA = 'KuentaGYM (self-hosted)';
const TIMEOUT_MS = 12000;
const CACHE_MS = 10 * 60 * 1000;
const MAX_STATIONS = 40;
/** How many curated channels a search may answer with before the directory takes over. */
const MAX_CURATED_HITS = 5;
/* The genres, as the chips the screen draws.
*
* Each one names the SomaFM channels that fit it (curated by hand, because a machine cannot know
* that "Seven Inch Soul" is the R&B one) and the radio-browser tags that fill in the rest. A genre
* with neither is a chip that shows nothing, so there are none. */
export const GENRES = Object.freeze([
{ key: 'workout', label: 'Workout / Rave', soma: ['beatblender', 'thetrip', 'cliqhop', 'dubstep', 'defcon'], tags: ['rave', 'dance', 'techno'], paradise: ['main'] },
{ key: 'techno', label: 'Techno / House', soma: ['beatblender', 'thetrip', 'lush'], tags: ['techno', 'house', 'deep house'], paradise: [] },
{ key: 'rnb', label: 'R&B / Soul', soma: ['7soul', 'fluid'], tags: ['r&b', 'soul', 'funk'], paradise: ['mellow'] },
{ key: 'latin', label: 'Latina / Salsa', soma: ['bossa', 'reggae'], tags: ['salsa', 'latin', 'reggaeton', 'bachata'], paradise: ['global'] },
{ key: 'hiphop', label: 'Hip-Hop', soma: ['fluid', 'cliqhop'], tags: ['hip hop', 'rap'], paradise: [] },
{ key: 'reggae', label: 'Reggae', soma: ['reggae', 'suburbsofgoa'], tags: ['reggae', 'dancehall'], paradise: ['global'] },
{ key: 'chill', label: 'Chill / Focus', soma: ['groovesalad', 'dronezone', 'synphaera', 'deepspaceone'], tags: ['chillout', 'ambient', 'lounge'], paradise: ['mellow'] },
{ key: 'jazz', label: 'Jazz / Lounge', soma: ['sonicuniverse', 'illstreet', 'secretagent'], tags: ['jazz', 'lounge', 'swing'], paradise: ['mellow'] },
{ key: 'rock', label: 'Rock / Indie', soma: ['indiepop', 'poptron', 'metal', 'seventies', 'u80s'], tags: ['rock', 'indie', 'alternative'], paradise: ['main', 'rock'] },
{ key: 'electronic', label: 'Electrónica', soma: ['digitalis', 'spacestation', 'vaporwaves', 'u80s'], tags: ['electronic', 'synthwave', 'electro'], paradise: ['main'] }
]);
export const genreOf = key => GENRES.find(g => g.key === key) || null;
/** The four Radio Paradise mixes. Fixed URLs: the mixes are the station, and they do not move. */
export const PARADISE = Object.freeze([
{ id: 'main', name: 'Radio Paradise', detail: 'eclectic rock, no advertising', url: 'https://stream.radioparadise.com/mp3-192' },
{ id: 'mellow', name: 'Radio Paradise · Mellow', detail: 'calm mix', url: 'https://stream.radioparadise.com/mellow-192' },
{ id: 'rock', name: 'Radio Paradise · Rock', detail: 'harder mix', url: 'https://stream.radioparadise.com/rock-192' },
{ id: 'global', name: 'Radio Paradise · Global', detail: 'world mix', url: 'https://stream.radioparadise.com/global-192' }
]);
/* ---------- a small polite cache ----------
*
* radio-browser is a community service run on donations and SomaFM is listener-supported: neither
* should see a request per tap. Everything fetched here is cached for ten minutes, which is also
* what makes switching genres on the screen feel instant the second time. */
const cache = new Map();
function cached(key, ttl, produce) {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ttl) return hit.value;
return produce().then(value => {
if (value != null) cache.set(key, { at: Date.now(), value });
return value;
});
}
export const clearRadioCache = () => cache.clear();
/** One GET, allowlisted, with a timeout, returning text or null. Never throws at the caller. */
export async function get(url, { fetchImpl = fetch, timeoutMs = TIMEOUT_MS, headers = {} } = {}) {
// The gate: every outgoing call in this module goes through here, so the allowlist is one rule in
// one place rather than a check each caller has to remember.
if (!allowedHost(url)) return null;
try {
const r = await fetchImpl(url, {
headers: { 'User-Agent': UA, ...headers },
signal: AbortSignal.timeout(timeoutMs)
});
if (!r.ok) return null;
return await r.text();
} catch { return null; }
}
/* ---------- SomaFM ---------- */
/**
* The stream inside a `.pls`. SomaFM publishes one playlist per channel and format, with several
* mirrors of the same stream; the first entry is the canonical one. Reading it is what makes this
* work for every channel without guessing a bitrate into a URL.
*/
export function parsePls(text) {
if (typeof text !== 'string') return null;
const line = text.split(/\r?\n/).find(l => /^\s*file1\s*=/i.test(l));
if (!line) return null;
const url = line.slice(line.indexOf('=') + 1).trim();
return /^https:\/\//i.test(url) ? url : null;
}
/** The playlist URL for a channel: the best quality it publishes, preferring MP3 (it plays everywhere). */
export function pickPlaylist(channel) {
const lists = Array.isArray(channel?.playlists) ? channel.playlists : [];
const best = lists.filter(p => p && /^https:\/\//i.test(p.url || ''));
const order = best.find(p => p.format === 'mp3' && p.quality === 'highest')
|| best.find(p => p.format === 'mp3')
|| best.find(p => p.format === 'aac' && p.quality === 'highest')
|| best.find(p => p.format === 'aac')
|| best[0];
return order ? order.url : null;
}
/** One SomaFM channel, as a station the screen can list. */
export function somaStation(channel) {
const id = String(channel?.id || '').trim();
const name = String(channel?.title || '').trim();
const pls = pickPlaylist(channel);
if (!id || !name || !pls) return null;
return {
src: 'soma',
id,
name,
genre: String(channel.genre || '').trim(),
detail: String(channel.description || '').replace(/\s+/g, ' ').trim().slice(0, 160),
image: /^https:\/\//i.test(channel.xlimage || channel.largeimage || '') ? (channel.xlimage || channel.largeimage) : null,
listeners: Number(channel.listeners) || null,
// The `.pls` is resolved into a real stream URL when somebody presses play, not here: forty
// channels would be forty requests to list a screen.
pls
};
}
/** The channel list, cached. */
export async function somaChannels({ fetchImpl = fetch } = {}) {
return cached('soma:channels', CACHE_MS, async () => {
const text = await get('https://somafm.com/channels.json', { fetchImpl });
if (!text) return [];
try {
const data = JSON.parse(text);
return (data.channels || []).map(somaStation).filter(Boolean);
} catch { return []; }
});
}
/* ---------- radio-browser ---------- */
/* The codecs a browser plays natively, without a library: HLS (`.m3u8`) needs one on Chrome and
Android, and this project does not add a dependency for a station. */
const PLAYABLE = /^(mp3|aac|aac\+|aacp|ogg|opus)$/i;
/**
* Station rows from the directory, filtered to what can actually be played and heard.
*
* HTTPS is not a preference: the app is served over HTTPS and a browser refuses to play an HTTP
* stream from an HTTPS page, so an `http://` row is a station that silently does nothing. The same
* argument, one step earlier, for a dead or broken entry.
*/
export function rbStations(rows) {
if (!Array.isArray(rows)) return [];
const out = [];
const seen = new Set();
for (const r of rows) {
const url = String(r?.url_resolved || r?.url || '').trim();
if (!/^https:\/\//i.test(url)) continue;
if (/\.m3u8(\?|$)/i.test(url)) continue; // HLS: not without a library
const codec = String(r?.codec || '').trim();
if (codec && !PLAYABLE.test(codec)) continue;
const name = String(r?.name || '').replace(/\s+/g, ' ').trim();
if (!name || seen.has(url)) continue;
seen.add(url);
out.push({
src: 'rb',
id: String(r.stationuuid || url).slice(0, 60),
name: name.slice(0, 80),
genre: String(r.tags || '').split(',').slice(0, 3).join(', ').slice(0, 60),
detail: [r.country, codec, r.bitrate ? r.bitrate + ' kbps' : null].filter(Boolean).join(' · '),
image: /^https:\/\//i.test(r.favicon || '') ? r.favicon : null,
url
});
}
return out;
}
/** The directory's best stations for one tag, cached per tag. */
export async function rbByTag(tag, { fetchImpl = fetch } = {}) {
const key = 'rb:' + tag;
return cached(key, CACHE_MS, async () => {
const q = new URLSearchParams({
limit: '20', hidebroken: 'true', order: 'clickcount', reverse: 'true'
});
const text = await get(`https://all.api.radio-browser.info/json/stations/bytagexact/${encodeURIComponent(tag)}?${q}`, { fetchImpl });
if (!text) return [];
try { return rbStations(JSON.parse(text)); } catch { return []; }
});
}
/**
* A name search across everything this module knows: the curated channels, the Paradise mixes, and
* the directory's thousands.
*
* The curated sources are matched **locally** (they are already in memory, and a match there is a
* better answer than anything the directory can return: no advertising, and a stream that is known
* to work), and the directory is asked by name. Money is what orders the directory's answer — by
* how many people actually listen — so the first rows of "jazz" are jazz stations people use rather
* than whatever was registered most recently.
*
* Like the genre list, a station here arrives with its stream URL already resolved: iOS only allows
* audio to start inside the tap, so waiting for a round trip first is a press that does nothing.
*/
export async function searchStations(query, { fetchImpl = fetch } = {}) {
const q = normQuery(query);
if (!q) return [];
const [channels, directory] = await Promise.all([
somaChannels({ fetchImpl }),
rbSearch(q, { fetchImpl })
]);
const hits = channels.filter(c => matches(c, q)).slice(0, MAX_CURATED_HITS);
// `somaChannels()` already answers with station rows (name, genre, detail, `pls`), so they only
// need their stream resolved here — `somaStation` is for a *raw* channel from the JSON.
const picks = (await Promise.all(
hits.map(async st => ({ ...st, url: await streamFor(st, { fetchImpl }) }))
)).filter(st => st && st.url);
const paradise = PARADISE.filter(p => matches({ title: p.name, genre: p.detail, description: '' }, q))
.map(p => ({ src: 'paradise', id: p.id, name: p.name, genre: p.detail, detail: 'no advertising', image: null, url: p.url }));
const seen = new Set(picks.map(p => p.id));
const rest = rankStations(directory.filter(st => !seen.has(st.id)), q);
return [...picks, ...paradise, ...rest].slice(0, MAX_STATIONS);
}
/* How well a station's *name* answers the query, 0 (it is the name) to 4 (it is somewhere in there).
*
* The directory's search matches substrings anywhere, so a query like "techno" comes back with
* "# TOP 100 CLUB CHARTS - DANCE & DJ MIX RADIO" — a real station, with "techno" somewhere in its
* tags — ahead of every station actually called Techno Something. Ordering by this before the
* directory's own popularity is the difference between a search that looks broken and one that
* looks clever. */
export function relevance(station, q) {
const name = String(station?.name || '').toLowerCase().trim();
if (!name) return 4;
if (name === q) return 0;
if (name.startsWith(q + ' ') || name.startsWith(q + ':') || name.startsWith(q + ' -')) return 1;
if (name.startsWith(q)) return 2;
const word = new RegExp('(^|[^a-z0-9])' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '([^a-z0-9]|$)');
if (word.test(name)) return 3;
return 4;
}
/** The directory's matches, best answer first: relevance, then the shorter name, then as it came. */
export function rankStations(list, q) {
return [...(Array.isArray(list) ? list : [])]
.map((st, i) => ({ st, i, r: relevance(st, q) }))
.sort((a, b) => a.r - b.r || String(a.st.name).length - String(b.st.name).length || a.i - b.i)
.map(e => e.st);
}
/** One query, normalised: trimmed, lower-cased, and short enough to be a search rather than a wall. */
export function normQuery(query) {
const q = String(query == null ? '' : query).replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 60);
// One letter is not a search: it matches everything and costs the directory a request to say so.
return q.length < 2 ? '' : q;
}
/** Whether a curated channel or mix matches the query, by name, genre or description. */
export function matches(entry, q) {
const hay = [entry?.title, entry?.name, entry?.genre, entry?.description].filter(Boolean).join(' ').toLowerCase();
return hay.includes(q);
}
/** The directory, searched by name. Cached per query: a search is the same answer for everybody. */
export async function rbSearch(q, { fetchImpl = fetch } = {}) {
return cached('rb:q:' + q, CACHE_MS, async () => {
const params = new URLSearchParams({
name: q, limit: '30', hidebroken: 'true', order: 'clickcount', reverse: 'true', is_https: 'true'
});
const text = await get(`https://all.api.radio-browser.info/json/stations/search?${params}`, { fetchImpl });
if (!text) return [];
try { return rbStations(JSON.parse(text)) } catch { return [] }
});
}
/* ---------- the list the screen shows ---------- */
/**
* Every station for a genre: the curated SomaFM channels first (no advertising, and the ones worth
* pressing), then Radio Paradise on the genres it fits, then the directory for everything else.
*/
export async function stationsFor(genreKey, { fetchImpl = fetch } = {}) {
const genre = genreOf(genreKey) || GENRES[0];
const [channels, ...tagged] = await Promise.all([
somaChannels({ fetchImpl }),
...genre.tags.map(tag => rbByTag(tag, { fetchImpl }))
]);
const bySoma = new Map(channels.map(c => [c.id, c]));
/* The curated channels get their stream resolved *here*, in the list, for one reason: on iOS
`play()` has to be called inside the tap's own task, and waiting for a round trip first is what
makes a press do nothing. Five channels per genre, cached for ten minutes, is a cheap price for
a play button that always plays. A channel whose stream cannot be resolved is left out rather
than listed as a row that does nothing. */
const picks = (await Promise.all(
genre.soma.map(id => bySoma.get(id)).filter(Boolean).map(async c => ({ ...c, url: await streamFor(c, { fetchImpl }) }))
)).filter(c => c.url);
// The mixes of Radio Paradise that fit this genre, named per genre rather than offered everywhere:
// "Rock" under Chill is a suggestion nobody asked for.
const wanted = new Set(genre.paradise || []);
const paradise = PARADISE.filter(p => wanted.has(p.id))
.map(p => ({ src: 'paradise', id: p.id, name: p.name, genre: p.detail, detail: 'no advertising', image: null, url: p.url }));
const seen = new Set(picks.map(p => p.id));
const rest = [];
for (const list of tagged) {
for (const s of list) {
if (seen.has(s.id)) continue;
seen.add(s.id);
rest.push(s);
}
}
return { genre, stations: [...picks, ...paradise, ...rest].slice(0, MAX_STATIONS) };
}
/** The genres the screen offers, with their labels. */
export const genreList = () => GENRES.map(g => ({ key: g.key, label: g.label }));
/* ---------- resolving a station into a stream ---------- */
/**
* The URL to hand an `<audio>` element.
*
* SomaFM's `.pls` is fetched (and cached) at this point, because that is when it is needed and not
* when the list is drawn. Everything else already carries its stream.
*/
export async function streamFor(station, { fetchImpl = fetch } = {}) {
if (!station) return null;
if (station.src === 'soma') {
if (!station.pls || !allowedHost(station.pls)) return null;
return cached('pls:' + station.pls, CACHE_MS, async () => parsePls(await get(station.pls, { fetchImpl })));
}
const url = String(station.url || '');
return /^https:\/\//i.test(url) ? url : null;
}
/* ---------- what is playing ---------- */
/**
* The current track, where the station publishes one.
*
* Only SomaFM and Radio Paradise do, and the difference is the whole reason they are first in each
* genre: a station that says what it is playing is a station you can trust with your ears. Anything
* else — the directory's thousands — gets no line, rather than an invented one.
*/
export function nowFrom(src, data) {
if (src === 'soma') {
const song = (data && Array.isArray(data.songs) && data.songs[0]) || null;
if (!song || !song.title) return null;
return {
artist: String(song.artist || '').trim().slice(0, 80) || null,
title: String(song.title).trim().slice(0, 120),
cover: /^https:\/\//i.test(song.albumArt || '') ? song.albumArt : null
};
}
if (src === 'paradise') {
if (!data || !data.title) return null;
return {
artist: String(data.artist || '').trim().slice(0, 80) || null,
title: String(data.title).trim().slice(0, 120),
cover: /^https:\/\//i.test(data.cover || '') ? data.cover : null
};
}
return null;
}
/** Fetches what is playing, for the two sources that publish it. */
export async function nowPlaying(station, { fetchImpl = fetch } = {}) {
if (!station) return null;
if (station.src === 'soma') {
const text = await get(`https://somafm.com/songs/${encodeURIComponent(station.id)}.json`, { fetchImpl });
if (!text) return null;
try { return nowFrom('soma', JSON.parse(text)); } catch { return null; }
}
if (station.src === 'paradise') {
const chan = PARADISE.findIndex(p => p.id === station.id);
const text = await get('https://api.radioparadise.com/api/now_playing?chan=' + (chan < 0 ? 0 : chan), { fetchImpl });
if (!text) return null;
try { return nowFrom('paradise', JSON.parse(text)); } catch { return null; }
}
return null;
}
+100
View File
@@ -21,6 +21,8 @@ import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
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, searchStations, normQuery } from './radio.js';
import { categoryList, showsFor, searchShows, episodesFor, safeFeedUrl, isSpanish } from './podcasts.js';
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
import {
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
@@ -34,6 +36,8 @@ export const API_FEATURES = Object.freeze([
'vitals.hours', // hourly buckets, and GET /api/vitals/hours
'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)
]);
@@ -133,6 +137,21 @@ function writeVitals(uid, doc) { atomicWrite(vitalsFile(uid), JSON.stringify(doc
/** What a sync is answered with: how much is in the profile now, not just what just arrived. */
const wantRaw = req => new URL(req.url, 'http://x').searchParams.get('raw') === '1';
/* One station, rebuilt from the query string rather than trusted as an object.
*
* The client only ever sends back what it was given, but "only ever" is not a security property:
* what comes back is a source and an id, and the id is used to build a URL this process fetches.
* So the shape is checked here — a known source, a plain id — and the URL for a SomaFM channel is
* rebuilt from the allowlisted host rather than taken from the request. */
function stationFromQuery(q) {
const src = String(q.get('src') || '');
const id = String(q.get('id') || '');
if (!/^[a-z0-9_-]{1,40}$/i.test(id)) return null;
if (src === 'soma') return { src, id };
if (src === 'paradise') return { src, id };
return null;
}
const storedCounts = doc => ({
metrics: doc ? Object.keys(doc.metrics || {}).length : 0,
days: doc ? Object.values(doc.metrics || {}).reduce((n, m) => n + Object.keys(m.days || {}).length, 0) : 0,
@@ -1261,6 +1280,87 @@ const routes = {
json(res, 200, { ok: true, meta: parseMusicPage(html) });
},
/* ---------- radio ----------
*
* Two routes, both session-gated, and neither proxies audio: the list — every station with the
* stream URL already resolved, so a tap can call `play()` inside the gesture iOS demands — and
* what is playing on the stations that publish it. The audio itself goes from the phone straight to the
* station — this server's part is the list, and a session requirement is what stops it becoming
* an open gateway someone else's page can borrow. */
'GET /api/radio': 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;
/* `?q=` is a name search and `?genre=` is a browse, and they are the same route on purpose: the
screen has one list, and what fills it changes. A search answers without the genre list
because the chips are already on the client — it does not need to be told again what the
genres are to show results. */
const query = normQuery(q.get('q'));
if (query) return json(res, 200, { ok: true, query, stations: await searchStations(query) });
const key = q.get('genre') || '';
const { genre, stations } = await stationsFor(key);
json(res, 200, { ok: true, genres: genreList(), genre: genre.key, label: genre.label, stations });
},
'GET /api/radio/now': 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 station = stationFromQuery(q);
if (!station) return json(res, 400, { error: 'no such station' });
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 q = new URL(req.url, 'http://x').searchParams;
// Same shape as the radio list: `?q=` searches, `?category=` browses, one route for one screen.
const query = normQuery(q.get('q'));
if (query) {
const { shows, skipped } = await searchShows(query);
return json(res, 200, { ok: true, query, shows, skipped });
}
const key = q.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) => {
+413
View File
@@ -0,0 +1,413 @@
/* Podcasts, tested without a network: everything here is a filter, a parse or a rule about what may
be fetched — and those are the three things that decide whether this feature is usable, safe and
actually in Spanish.
The load-bearing rule is the Spanish one. A storefront says a podcast is *sold* in Spain or
Mexico, and that is not the same as being in Spanish: the Spanish comedy chart carries a Catalan
show and the Argentine chart carries Joe Rogan. The feed's own `<language>` is the answer, and the
two edges of it are both tested — `ca` and `en` get dropped, and a feed that declares nothing
stays, because Spanish feeds do omit the tag and dropping good podcasts over an omission is worse
than keeping a rare miss.
The other rule is what this process will fetch. A feed URL is attacker-influenced data and the api
container sits on somebody's home network, so loopback, private ranges and `.local` names are
refused *before* a request is made. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
CATEGORIES, STORES, MAX_EPISODES, MAX_SHOWS, categoryList, categoryOf, isSpanish, languageOf,
publicHost, safeFeedUrl, parseDuration, decodeEntities, episodeFrom, parseFeed, tagText, tagAttr,
get, readCapped, feedLanguage, showsFor, episodesFor, chartEntries, showFrom, mapLimit,
clearPodcastCache, searchShows, appleSearch, normQuery
} from '../podcasts.js';
/* A stand-in for `fetch`: a body, a status, and the url it ended at. */
const res = (text, { status = 200, url = undefined } = {}) => ({
ok: status >= 200 && status < 300, status, url, body: null,
text: async () => text
});
/* ---------- categories ---------- */
test('every category has a label and an Apple genre id, and the keys are unique', () => {
const keys = categoryList().map(c => c.key);
assert.equal(new Set(keys).size, keys.length, 'no key twice');
for (const c of CATEGORIES) {
assert.ok(c.label.trim(), c.key + ' has a label');
assert.ok(Number.isInteger(c.genre) && c.genre > 0, c.key + ' has a genre id');
}
// The two a gym screen wants first, and Spanish labels — this list is read in Spanish.
assert.equal(keys[0], 'fitness');
assert.equal(keys[1], 'sports');
assert.equal(categoryOf('fitness').label, 'Salud y fitness');
assert.equal(categoryOf('nope'), null);
assert.ok(STORES.includes('es') && STORES.includes('mx'));
});
/* ---------- what may be fetched ---------- */
test('only a public https host is ever fetched', () => {
assert.ok(safeFeedUrl('https://feeds.example.com/show.rss'));
assert.ok(safeFeedUrl('https://example.com/a/b/c'), 'a feed with no extension is still a feed');
// Anything else is refused, and refused *before* the request — see the spy test below.
for (const bad of [
'http://feeds.example.com/show.rss', // plain http: the browser would refuse the audio too
'https://user:pw@feeds.example.com/x.rss', // credentials in the URL
'https://localhost/x.rss',
'https://127.0.0.1/x.rss',
'https://10.0.0.5/x.rss',
'https://192.168.1.10/x.rss',
'https://172.20.3.4/x.rss',
'https://169.254.169.254/latest/meta-data/', // the cloud metadata address
'https://100.64.0.1/x.rss', // carrier-grade NAT
'https://nas.local/x.rss',
'https://router.internal/x.rss',
'https://[::1]/x.rss',
'https://[fd00::1]/x.rss',
'file:///etc/passwd',
'not a url',
'',
null,
'https://' + 'a'.repeat(600) + '.com/x.rss' // longer than any real feed URL
]) assert.equal(safeFeedUrl(bad), null, `${bad} is refused`);
// The host rule on its own, for the cases a feed URL cannot express.
assert.equal(publicHost('example.com'), true);
assert.equal(publicHost('example.com.'), true, 'a trailing dot is the same host');
assert.equal(publicHost('8.8.8.8'), true, 'a public address literal is allowed');
assert.equal(publicHost('evil.com.localhost'), false);
});
test('an off-list url is refused without calling fetch at all', async () => {
let called = 0;
const fetchImpl = async () => { called++; return res('x') };
for (const bad of ['http://example.com/x.rss', 'https://127.0.0.1/x.rss', 'https://a.local/x.rss']) {
assert.equal(await get(bad, { fetchImpl }), null);
}
assert.equal(called, 0, 'the gate is inside get, so no caller can forget it');
});
test('a redirect off the allowed shape is refused too', async () => {
// Where the request ended up is checked, not only where it was pointed: a redirect to the router
// is otherwise the whole way around the rule.
const fetchImpl = async () => res('<rss/>', { url: 'https://192.168.1.1/x.rss' });
assert.equal(await get('https://feeds.example.com/x.rss', { fetchImpl }), null);
});
test('the body is read up to a cap and then dropped', async () => {
clearPodcastCache();
const huge = 'x'.repeat(5000);
assert.equal((await readCapped(res(huge), 100)).length, 100);
// A server that ignores Range hands us a real stream: it must be cut, not buffered whole.
const streamed = await readCapped(new Response('y'.repeat(200000)), 1000);
assert.equal(streamed.length, 1000);
});
/* ---------- Spanish only ---------- */
test('a Spanish language tag is what keeps a show, and the edges are both tested', () => {
for (const yes of ['es', 'es-ES', 'es-es', 'ES', 'es-419', 'es-MX', 'spa']) {
assert.equal(isSpanish(yes), true, yes + ' is Spanish');
}
for (const no of ['ca', 'ca-ES', 'en', 'en-US', 'pt', 'pt-BR', 'gl', 'eu', 'est', 'de']) {
assert.equal(isSpanish(no), false, no + ' is not Spanish');
}
// No tag at all is a "maybe": kept, because genuinely Spanish feeds omit it and the storefront is
// the fallback signal. See the header of api/podcasts.js.
assert.equal(isSpanish(null), true);
assert.equal(isSpanish(''), true);
});
test('the language tag is read out of a feed, CDATA and all', () => {
assert.equal(languageOf('<channel><language>es-ES</language><item/></channel>'), 'es-es');
assert.equal(languageOf('<language><![CDATA[es]]></language>'), 'es');
assert.equal(languageOf('<language>\n es-419\n</language>'), 'es-419');
assert.equal(languageOf('<channel><title>x</title></channel>'), null);
assert.equal(languageOf(null), null);
});
test('a feed that declares another language never reaches the list', async () => {
clearPodcastCache();
// The four cases, in one category: Spanish, no tag, Catalan, English — plus a feed that is down.
const langs = {
'https://a.example.com/feed': '<language>es-ES</language>',
'https://b.example.com/feed': '<title>sin etiqueta</title>',
'https://c.example.com/feed': '<language>ca</language>',
'https://d.example.com/feed': '<language>en-US</language>'
};
const fetchImpl = async url => {
if (url.includes('/rss/toppodcasts/')) {
const country = url.includes('/mx/') ? 'mx' : 'es';
return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': country + '1' } } }] } }), { url });
}
if (url.includes('/lookup')) {
const country = url.split('country=')[1];
const rows = [1, 2, 3, 4, 5].map(n => ({
collectionId: `${country}${n}`,
collectionName: `${country} show ${n}`,
artistName: 'Alguien',
artworkUrl600: 'https://img.example.com/x.jpg',
primaryGenreName: 'Comedy',
feedUrl: ['https://a.example.com/feed', 'https://b.example.com/feed', 'https://c.example.com/feed', 'https://d.example.com/feed', 'https://down.example.com/feed'][n - 1]
}));
return res(JSON.stringify({ results: rows }), { url });
}
if (langs[url]) return res(langs[url], { status: url.startsWith('https://b.') ? 200 : 206, url });
return res('', { status: 500, url });
};
const { category, shows, skipped } = await showsFor('comedy', { fetchImpl });
assert.equal(category.key, 'comedy');
// Each reason is a number, so "dropped for language" cannot pass for "the fetch blew up".
assert.equal(skipped.language, 2, 'Catalan and English');
assert.equal(skipped.unreadable, 1, 'the feed that is down');
assert.equal(skipped.failed, 0, 'nothing threw');
assert.equal(skipped.duplicate, 5, 'the second storefront listed the same five feeds');
const names = shows.map(s => s.name);
assert.ok(names.includes('es show 1'), 'Spanish kept');
assert.ok(names.includes('es show 2'), 'no tag kept');
assert.ok(!names.includes('es show 3'), 'Catalan dropped');
assert.ok(!names.includes('es show 4'), 'English dropped');
assert.ok(!names.includes('es show 5'), 'a feed that is down is not a row that cannot play');
assert.equal(shows[0].lang, 'es-es');
assert.equal(shows[1].lang, null);
// One row per feed even though both storefronts listed the same five shows.
assert.equal(new Set(shows.map(s => s.feed)).size, shows.length);
assert.ok(shows.length <= MAX_SHOWS);
});
test('a feed that cannot be read is not Spanish-by-default', async () => {
clearPodcastCache();
const fetchImpl = async url => {
if (url.includes('/rss/')) return res(JSON.stringify({ feed: { entry: [{ id: { attributes: { 'im:id': '1' } } }] } }), { url });
if (url.includes('/lookup')) return res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'S', feedUrl: 'https://a.example.com/feed' }] }), { url });
return res('', { status: 503, url });
};
assert.equal(await feedLanguage('https://a.example.com/feed', { fetchImpl }), null);
const { shows, skipped } = await showsFor('comedy', { fetchImpl });
assert.deepEqual(shows, []);
assert.equal(skipped.unreadable, 1, 'unreadable, by that rule and not by an accident');
assert.equal(skipped.failed, 0, 'and not by an exception the pool swallowed');
});
test('the language check reads the head of the feed, not the whole archive', async () => {
clearPodcastCache();
let asked = null;
const fetchImpl = async (url, opts) => { asked = opts.headers.Range; return res('<language>es</language>', { status: 206, url }) };
assert.deepEqual(await feedLanguage('https://a.example.com/feed', { fetchImpl }), { lang: 'es', ok: true });
assert.equal(asked, 'bytes=0-65535');
});
/* ---------- the directory rows ---------- */
test('a show is kept only when it has a feed this process will fetch', () => {
const base = { collectionId: 12, collectionName: 'Un podcast', feedUrl: 'https://a.example.com/feed' };
assert.equal(showFrom(base, 'es').feed, 'https://a.example.com/feed');
assert.equal(showFrom(base, 'es').country, 'es');
assert.equal(showFrom({ ...base, feedUrl: 'http://a.example.com/feed' }, 'es'), null, 'http feed');
assert.equal(showFrom({ ...base, feedUrl: 'https://10.0.0.1/feed' }, 'es'), null, 'private host');
assert.equal(showFrom({ ...base, feedUrl: null }, 'es'), null, 'no feed at all');
assert.equal(showFrom({ ...base, collectionName: ' ' }, 'es'), null, 'no name');
// An http artwork is dropped rather than shown broken.
assert.equal(showFrom({ ...base, artworkUrl600: 'http://img/x.jpg' }, 'es').image, null);
assert.equal(chartEntries({ feed: { entry: [{ id: { attributes: { 'im:id': '7' } } }, { id: {} }] } }).length, 1);
assert.deepEqual(chartEntries({}), []);
});
/* ---------- the feed ---------- */
const feed = ({ items, extra = '' }) => `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<channel>
<title>Nadie Sabe Nada</title>
<language>es-ES</language>
<itunes:author>Cadena SER</itunes:author>
<itunes:image href="https://img.example.com/nsn.jpg"/>
${extra}
${items}
</channel></rss>`;
const item = ({ title = 'Un episodio', date = 'Tue, 02 Sep 2025 10:00:00 GMT', dur = '00:52:15', enc = '<enclosure url="https://audio.example.com/1.mp3" type="audio/mpeg" length="12345678"/>', guid = 'ep-1', extra = '' }) =>
`<item><title>${title}</title><description><![CDATA[<p>bla</p>]]></description>
<pubDate>${date}</pubDate><itunes:duration>${dur}</itunes:duration><guid>${guid}</guid>${enc}${extra}</item>`;
test('a duration is read in all three shapes feeds use', () => {
assert.equal(parseDuration('00:52:15'), 3135);
assert.equal(parseDuration('4847'), 4847);
assert.equal(parseDuration('1:02:03'), 3723);
assert.equal(parseDuration('12:30'), 750);
assert.equal(parseDuration(''), null);
assert.equal(parseDuration(null), null);
assert.equal(parseDuration('una hora'), null);
assert.equal(parseDuration('1:2:3:4'), null);
});
test('titles come out with CDATA unwrapped and entities decoded', () => {
assert.equal(decodeEntities('Rock &amp; Roll &#8212; 4 &lt; 5'), 'Rock & Roll — 4 < 5');
assert.equal(tagText('<title><![CDATA[324. La Ruina & Co]]></title>', 'title'), '324. La Ruina & Co');
assert.equal(tagAttr('<enclosure type="audio/mpeg" url="https://x/1.mp3"/>', 'enclosure', 'url'), 'https://x/1.mp3');
assert.equal(tagAttr('<enclosure type="audio/mpeg"/>', 'enclosure', 'url'), '');
});
test('an item with nothing to play is not an episode', () => {
const opts = { image: 'https://img.example.com/show.jpg' };
// A video enclosure: this player has no picture.
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://v.example.com/1.mp4" type="video/mp4"/>' }), opts), null);
// A subscriber-only episode has no enclosure at all.
assert.equal(episodeFrom(item({ enc: '' }), opts), null, 'no enclosure');
// No type, but an audio file: kept, because plenty of feeds omit the type.
const noType = episodeFrom(item({ enc: '<enclosure url="https://audio.example.com/1.mp3"/>' }), opts);
assert.equal(noType.url, 'https://audio.example.com/1.mp3');
// No type and not an audio file: refused.
assert.equal(episodeFrom(item({ enc: '<enclosure url="https://docs.example.com/notes.pdf"/>' }), opts), null);
// http audio would be blocked by the browser on an https page.
assert.equal(episodeFrom(item({ enc: '<enclosure url="http://audio.example.com/1.mp3" type="audio/mpeg"/>' }), opts), null);
assert.equal(episodeFrom(item({ title: '' }), opts), null, 'no title');
const ep = episodeFrom(item({ extra: '<itunes:episode>14</itunes:episode>' }), opts);
assert.equal(ep.episode, 14);
assert.equal(ep.duration, 3135);
assert.equal(ep.image, 'https://img.example.com/show.jpg', 'falls back to the channel image');
assert.equal(ep.bytes, 12345678);
});
test('a feed becomes a show with its episodes, newest first', () => {
const text = feed({
items: [
item({ title: 'Viejo', date: 'Mon, 01 Sep 2025 10:00:00 GMT', guid: 'a' }),
item({ title: 'Nuevo', date: 'Wed, 03 Sep 2025 10:00:00 GMT', guid: 'b' }),
item({ title: 'Sin fecha', date: '', guid: 'c' })
]
});
const { show, episodes } = parseFeed(text);
assert.equal(show.title, 'Nadie Sabe Nada');
assert.equal(show.author, 'Cadena SER');
assert.equal(show.language, 'es-es');
assert.equal(show.image, 'https://img.example.com/nsn.jpg');
assert.deepEqual(episodes.map(e => e.title), ['Nuevo', 'Viejo', 'Sin fecha']);
assert.equal(episodes.length, show.episodes);
});
test('a feed truncated by the cap loses its last item and nothing else', () => {
// The body was cut mid-item: the parser must not invent a half episode, and must not throw.
const text = feed({ items: item({ title: 'Uno', guid: 'a' }) }) + '<item><title>Dos a medias</title><enclosure url="https://a.example.com/2.mp3" type="audio/mpeg"';
const { episodes } = parseFeed(text);
assert.deepEqual(episodes.map(e => e.title), ['Uno']);
});
test('a show with no title of its own takes the directory name', () => {
const { show, episodes } = parseFeed('<rss><channel><language>es</language>' + item({}) + '</channel></rss>', { fallbackTitle: 'Desde Apple' });
assert.equal(show.title, 'Desde Apple');
assert.equal(episodes.length, 1);
});
test('the list of episodes is capped, and duplicates are one episode', () => {
const many = Array.from({ length: MAX_EPISODES + 5 }, (_, i) => item({ title: 'E' + i, guid: 'g' + i }));
assert.equal(parseFeed(feed({ items: many })).episodes.length, MAX_EPISODES);
const twice = item({ title: 'Repetido', guid: 'same' }) + item({ title: 'Repetido (otra vez)', guid: 'same' });
assert.deepEqual(parseFeed(feed({ items: twice })).episodes.map(e => e.title), ['Repetido']);
});
/* ---------- the whole way through ---------- */
test('episodesFor refuses an unsafe feed and parses a real one', async () => {
clearPodcastCache();
assert.equal(await episodesFor('http://a.example.com/feed'), null);
assert.equal(await episodesFor('https://10.0.0.1/feed'), null);
const fetchImpl = async url => res(feed({ items: item({}) }), { url });
const got = await episodesFor('https://a.example.com/feed', { fetchImpl, title: 'De Apple' });
assert.equal(got.feed, 'https://a.example.com/feed');
assert.equal(got.show.title, 'Nadie Sabe Nada');
assert.equal(got.episodes[0].url, 'https://audio.example.com/1.mp3');
// An unreadable feed is null, not an exception. A different URL, because the parsed feed above is
// cached for half an hour on purpose — that cache is what keeps a big feed from being downloaded
// again every time somebody opens the show.
assert.equal(await episodesFor('https://b.example.com/feed', { fetchImpl: async () => res('', { status: 500 }), title: 'x' }), null);
});
test('the pool keeps the order and never throws out of itself', async () => {
const out = await mapLimit([1, 2, 3, 4, 5], 2, async n => {
if (n === 3) throw new Error('boom');
return n * 2;
});
assert.deepEqual(out, [2, 4, null, 8, 10]);
});
/* ---------- search ---------- */
test('a query has to be a query here too', () => {
assert.equal(normQuery(' Crimen real '), 'Crimen real', 'the term goes to Apple as typed');
assert.equal(normQuery('a'), '');
assert.equal(normQuery(null), '');
assert.equal(normQuery('x'.repeat(200)).length, 80);
});
test('a search is Apple\'s, one request per storefront, Spanish and no key', async () => {
clearPodcastCache();
const asked = [];
const fetchImpl = async url => {
asked.push(url);
if (url.includes('/search?')) {
const country = new URL(url).searchParams.get('country');
return res(JSON.stringify({ results: [{
collectionId: country + '1',
collectionName: 'Crimen ' + country,
artistName: 'Alguien',
artworkUrl600: 'https://img.example.com/x.jpg',
primaryGenreName: 'True Crime',
feedUrl: 'https://feeds.example.com/' + country
}] }), { url });
}
// Both feeds declare Spanish, except the Mexican one, which declares English.
if (url === 'https://feeds.example.com/es') return res('<language>es-ES</language>', { status: 206, url });
if (url === 'https://feeds.example.com/mx') return res('<language>en</language>', { status: 206, url });
return res('', { status: 500, url });
};
const { query, shows, skipped } = await searchShows('crimen', { fetchImpl });
assert.equal(query, 'crimen');
assert.deepEqual(shows.map(s => s.name), ['Crimen es'], 'only the Spanish one');
assert.equal(shows[0].lang, 'es-es');
assert.equal(skipped.language, 1, 'and the other one is counted, not silently missing');
assert.equal(skipped.failed, 0);
// One request per storefront, not one per show: `media=podcast`, the storefront, and `lang=es`.
const searches = asked.filter(u => u.includes('/search?'));
assert.equal(searches.length, 2);
const q = new URL(searches[0]).searchParams;
assert.equal(q.get('media'), 'podcast');
assert.equal(q.get('term'), 'crimen');
assert.equal(q.get('lang'), 'es');
assert.deepEqual(searches.map(u => new URL(u).searchParams.get('country')).sort(), ['es', 'mx']);
});
test('a search result goes through the same feed rule as a chart entry', async () => {
clearPodcastCache();
const fetchImpl = async url => {
if (url.includes('/search?')) {
return res(JSON.stringify({ results: [
{ collectionId: '1', collectionName: 'Bueno', feedUrl: 'https://feeds.example.com/a' },
{ collectionId: '2', collectionName: 'Inservible', feedUrl: 'http://feeds.example.com/b' },
{ collectionId: '3', collectionName: 'Privado', feedUrl: 'https://10.0.0.9/c' }
] }), { url });
}
return res('<language>es</language>', { status: 206, url });
};
const { shows } = await searchShows('algo', { fetchImpl });
assert.deepEqual(shows.map(s => s.name), ['Bueno'], 'an http feed and a private host are not shows');
});
test('one letter is not a search, and nobody is asked', async () => {
clearPodcastCache();
let called = 0;
const fetchImpl = async () => { called++; return res('{}') };
const { shows, query } = await searchShows('c', { fetchImpl });
assert.deepEqual(shows, []);
assert.equal(query, '');
assert.equal(called, 0);
// And the storefronts are cached: the same query twice is one request each.
const impl = async url => url.includes('/search?')
? res(JSON.stringify({ results: [{ collectionId: '1', collectionName: 'X', feedUrl: 'https://feeds.example.com/x' }] }), { url })
: res('<language>es</language>', { status: 206, url });
let n = 0;
const counting = async (url, ...rest) => { if (url.includes('/search?')) n++; return impl(url, ...rest) };
await searchShows('comedia', { fetchImpl: counting });
await searchShows('comedia', { fetchImpl: counting });
assert.equal(n, 2, 'one per storefront, then cached');
});
+327
View File
@@ -0,0 +1,327 @@
/* The radio sources, tested without a network: everything here is a filter or a parse, and the
filters are the point. A station that cannot be played is worse than no station — a row that does
nothing when tapped, on a screen whose whole job is to make sound.
The three rules that are load-bearing: HTTPS (an http stream is blocked by the browser on an
https page, silently), no HLS (Chrome and Android need a library, and this project does not add
one for a station), and nothing fetched from a host that is not on our own list. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
GENRES, genreList, genreOf, PARADISE, parsePls, pickPlaylist, somaStation, rbStations,
nowFrom, allowedHost, get, streamFor, stationsFor, nowPlaying, RADIO_HOSTS, clearRadioCache,
searchStations, rbSearch, normQuery, relevance, rankStations
} from '../radio.js';
const pls = 'https://api.somafm.com/beatblender.pls';
const channel = (over = {}) => ({
id: 'beatblender', title: 'Beat Blender', genre: 'electronic',
description: 'A late night blend of deep-house and downtempo chill.',
playlists: [
{ url: pls, format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/beatblender130.pls', format: 'aac', quality: 'highest' }
],
...over
});
test('the genres the screen offers are the ones a person asked for', () => {
const keys = genreList().map(g => g.key);
for (const want of ['workout', 'techno', 'rnb', 'latin', 'hiphop', 'reggae', 'chill', 'jazz', 'rock', 'electronic']) {
assert.ok(keys.includes(want), want + ' is offered');
}
// Every genre names at least one SomaFM channel or one tag: a chip that shows nothing is a chip
// that should not be there.
for (const g of GENRES) assert.ok(g.soma.length + g.tags.length > 0, g.key + ' has a source');
assert.equal(genreOf('nope'), null);
assert.equal(genreOf('rnb').label, 'R&B / Soul');
});
test('a .pls gives the stream, and anything else gives nothing', () => {
const text = [
'[playlist]', 'numberofentries=2',
'File1=https://ice2.somafm.com/beatblender-128-mp3',
'Title1=SomaFM: Beat Blender', 'Length1=-1',
'File2=https://ice6.somafm.com/beatblender-128-mp3',
'Version=2'
].join('\n');
assert.equal(parsePls(text), 'https://ice2.somafm.com/beatblender-128-mp3', 'the first mirror');
// An http stream would be blocked by the browser on an https page, so it is not a stream here.
assert.equal(parsePls('[playlist]\nFile1=http://ice2.somafm.com/x'), null);
assert.equal(parsePls('<html>nope</html>'), null);
assert.equal(parsePls(null), null);
assert.equal(parsePls(''), null);
});
test('the playlist chosen is the best one that plays everywhere', () => {
assert.equal(pickPlaylist(channel()), pls, 'mp3 highest wins over aac highest');
assert.equal(pickPlaylist(channel({ playlists: [
{ url: 'https://api.somafm.com/x256.pls', format: 'mp3', quality: 'highest' },
{ url: 'https://api.somafm.com/x.pls', format: 'mp3', quality: 'high' }
] })), 'https://api.somafm.com/x256.pls');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'https://api.somafm.com/x130.pls', format: 'aac', quality: 'highest' }] })),
'https://api.somafm.com/x130.pls', 'aac is the fallback, not nothing');
assert.equal(pickPlaylist(channel({ playlists: [{ url: 'http://api.somafm.com/x.pls', format: 'mp3' }] })), null);
assert.equal(pickPlaylist(channel({ playlists: [] })), null);
});
test('a SomaFM channel becomes a station, and a broken one does not', () => {
const s = somaStation(channel());
assert.equal(s.src, 'soma');
assert.equal(s.id, 'beatblender');
assert.equal(s.pls, pls);
assert.equal(s.detail, 'A late night blend of deep-house and downtempo chill.');
assert.equal(somaStation(channel({ id: '' })), null);
assert.equal(somaStation(channel({ title: ' ' })), null);
assert.equal(somaStation(channel({ playlists: [] })), null);
assert.equal(somaStation(null), null);
});
test('the directory is filtered down to what can be played', () => {
const rows = [
{ stationuuid: 'a', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3', bitrate: 192, country: 'Germany', tags: 'techno,dance' },
{ stationuuid: 'b', name: 'Plain HTTP', url_resolved: 'http://x.example/stream', codec: 'MP3' },
{ stationuuid: 'c', name: 'HLS only', url_resolved: 'https://x.example/live.m3u8', codec: 'AAC' },
{ stationuuid: 'd', name: 'Unknown codec', url_resolved: 'https://x.example/wm', codec: 'WMAL' },
{ stationuuid: 'e', name: 'Wild', url_resolved: 'https://x.example/wm2' },
{ stationuuid: 'f', name: 'Techno One', url_resolved: 'https://x.example/stream', codec: 'MP3' },
{ stationuuid: 'g', name: ' ', url_resolved: 'https://x.example/blank', codec: 'MP3' },
{ stationuuid: 'h', name: 'AAC+ Latin', url_resolved: 'https://y.example/aac', codec: 'AAC+', bitrate: 64, country: 'Colombia' }
];
const out = rbStations(rows);
// "Wild" has no codec at all, and that is kept on purpose: a blank codec means the directory did
// not say, which is common, rather than that the station is unplayable. The ones it *does* name
// and that no browser plays (WMAL), and the HLS ones, are the ones dropped.
assert.deepEqual(out.map(s => s.name), ['Techno One', 'Wild', 'AAC+ Latin'], 'only what is known to be unplayable is dropped');
assert.equal(out[0].detail, 'Germany · MP3 · 192 kbps');
assert.equal(out[0].genre, 'techno, dance');
assert.equal(out[2].detail, 'Colombia · AAC+ · 64 kbps');
assert.equal(rbStations('nope').length, 0);
assert.equal(rbStations([{ name: 'no url' }]).length, 0);
});
test('what is playing is read from the two stations that publish it, and invented for nobody', () => {
assert.deepEqual(nowFrom('soma', { songs: [{ title: 'Cuban Nights', artist: 'Miguel Migs', albumArt: 'https://cdn.example/a.jpg' }] }),
{ artist: 'Miguel Migs', title: 'Cuban Nights', cover: 'https://cdn.example/a.jpg' });
assert.deepEqual(nowFrom('paradise', { artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' }),
{ artist: 'Yes', title: 'I have seen all good people', cover: 'https://img.example/c.jpg' });
// No song playing, no cover, or a source that publishes nothing: null, never a placeholder.
assert.equal(nowFrom('soma', { songs: [] }), null);
assert.equal(nowFrom('soma', null), null);
assert.equal(nowFrom('rb', { title: 'x' }), null);
assert.equal(nowFrom('paradise', {}), null);
const noArt = nowFrom('soma', { songs: [{ title: 'x' }] });
assert.equal(noArt.artist, null);
assert.equal(noArt.cover, null);
});
test('only our own hosts may be fetched, over https', () => {
assert.equal(allowedHost('https://somafm.com/channels.json'), true);
assert.equal(allowedHost('https://api.somafm.com/beatblender.pls'), true);
assert.equal(allowedHost('https://all.api.radio-browser.info/json/stations'), true);
assert.equal(allowedHost('https://api.radioparadise.com/api/now_playing?chan=0'), true);
// The stream hosts are reached by the browser, never by this process — so they are not here.
assert.equal(allowedHost('https://ice2.somafm.com/beatblender-128-mp3'), false);
assert.equal(allowedHost('http://somafm.com/channels.json'), false, 'https only');
assert.equal(allowedHost('https://evil.example/somafm.com'), false);
assert.equal(allowedHost('https://somafm.com.evil.example/x'), false);
assert.equal(allowedHost('not a url'), false);
assert.equal(allowedHost('https://somafm.com/', ['example.com']), false, 'the list is the argument');
assert.ok(RADIO_HOSTS.every(h => h === h.toLowerCase()));
});
/* The gate itself, and the one test that can see it: `get` is the only place this module makes an
outgoing call, so an off-list URL must die there — not at a caller that might forget. */
test('get refuses an off-list url without calling fetch at all', async () => {
let calls = 0;
const fetchImpl = async () => { calls++; return { ok: true, text: async () => 'x' }; };
for (const url of ['https://evil.example/x', 'http://somafm.com/channels.json', 'https://somafm.com.evil.example/x', 'not a url']) {
assert.equal(await get(url, { fetchImpl }), null, url);
}
assert.equal(calls, 0, 'nothing left this process');
// ...and an on-list one does go out, so the test above is not passing because get never works.
assert.equal(await get('https://somafm.com/channels.json', { fetchImpl }), 'x');
assert.equal(calls, 1);
});
test('resolving a stream never fetches anything outside the allowlist', async () => {
clearRadioCache();
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('evil')) throw new Error('should not be called');
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/beatblender-128-mp3\n' };
};
const url = await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl });
assert.equal(url, 'https://ice2.somafm.com/beatblender-128-mp3');
assert.deepEqual(calls, [pls]);
// Cached: a second press does not ask SomaFM again.
assert.equal(await streamFor({ src: 'soma', id: 'beatblender', pls }, { fetchImpl }), url);
assert.equal(calls.length, 1);
// A directory station carries its own stream: nothing is fetched, and an http one is refused.
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), 'https://y.example/aac');
assert.equal(await streamFor({ src: 'rb', id: 'x', url: 'http://y.example/aac' }, { fetchImpl }), null);
assert.equal(await streamFor(null, { fetchImpl }), null);
// A SomaFM station whose playlist points off the list is refused rather than followed.
assert.equal(await streamFor({ src: 'soma', id: 'x', pls: 'https://evil.example/x.pls' }, { fetchImpl }), null);
assert.equal(calls.length, 1);
});
test('a genre list puts the curated channels first and the directory last', async () => {
clearRadioCache();
const fetchImpl = async (url) => {
const u = String(url);
if (u.includes('channels.json')) {
return { ok: true, text: async () => JSON.stringify({ channels: [
channel(), channel({ id: 'bossa', title: 'Bossa Beyond' }), channel({ id: 'reggae', title: 'Heavyweight Reggae' })
] }) };
}
if (u.includes('api.somafm.com')) {
// The channel's own playlist, which is what turns a channel into something playable.
return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/x-128-mp3\n' };
}
if (u.includes('radio-browser')) {
return { ok: true, text: async () => JSON.stringify([
{ stationuuid: 'z1', name: 'Salsa Dura', url_resolved: 'https://z.example/salsa', codec: 'MP3', country: 'Colombia', tags: 'salsa' },
{ stationuuid: 'z2', name: 'Dead', url_resolved: 'http://z.example/dead', codec: 'MP3' }
]) };
}
return { ok: false, text: async () => '' };
};
// The curated channels come back with their stream already resolved (`fetchImpl` answers the
// `.pls` above), and a channel whose stream cannot be resolved is not listed at all.
const { genre, stations } = await stationsFor('latin', { fetchImpl });
assert.equal(genre.key, 'latin');
const names = stations.map(s => s.name);
// The no-advertising stations first — that is what the order is for.
assert.deepEqual(names.slice(0, 3), ['Bossa Beyond', 'Heavyweight Reggae', 'Radio Paradise · Global']);
assert.ok(names.includes('Salsa Dura'), 'and the directory fills in the genres SomaFM does not carry');
assert.ok(stations.every(s => /^https:\/\//.test(s.url || '')), 'every row can be played when it is tapped');
assert.equal(names.includes('Dead'), false);
// An unknown genre falls back to the first one rather than showing a blank screen.
const fallback = await stationsFor('nope', { fetchImpl });
assert.equal(fallback.genre.key, 'workout');
});
test('what is playing is asked for at the right address, per source', async () => {
const calls = [];
const fetchImpl = async (url) => {
calls.push(String(url));
if (String(url).includes('somafm')) return { ok: true, text: async () => JSON.stringify({ songs: [{ title: 'T', artist: 'A' }] }) };
return { ok: true, text: async () => JSON.stringify({ title: 'Paradise Song', artist: 'PR' }) };
};
const soma = await nowPlaying({ src: 'soma', id: 'beatblender' }, { fetchImpl });
assert.equal(soma.title, 'T');
assert.match(calls[0], /somafm\.com\/songs\/beatblender\.json/);
const para = await nowPlaying({ src: 'paradise', id: 'rock' }, { fetchImpl });
assert.equal(para.artist, 'PR');
assert.match(calls[1], /chan=2/, 'the third mix is chan=2');
// A directory station publishes nothing, so nothing is asked and nothing is shown.
assert.equal(await nowPlaying({ src: 'rb', id: 'x', url: 'https://y.example/aac' }, { fetchImpl }), null);
assert.equal(calls.length, 2);
assert.equal(PARADISE.length, 4);
});
/* ---------- search ---------- */
test('a query has to be a query: trimmed, lowered, and at least two characters', () => {
assert.equal(normQuery(' Jazz '), 'jazz');
assert.equal(normQuery('Deep HOUSE'), 'deep house');
assert.equal(normQuery('j'), '', 'one letter matches everything and costs a request to say so');
assert.equal(normQuery(''), '');
assert.equal(normQuery(null), '');
assert.equal(normQuery('x'.repeat(200)).length, 60, 'a wall of text is truncated, not refused');
});
test('the best answer to "techno" is a station called Techno Something', () => {
// The directory matches substrings anywhere, so a chart station with "techno" in its tags used to
// come back ahead of every station actually named after the genre. This is the ordering that fixes
// it: the name is the answer, and where in the name it appears is the ranking.
assert.equal(relevance({ name: 'Techno' }, 'techno'), 0);
assert.equal(relevance({ name: 'Techno: Live' }, 'techno'), 1);
assert.equal(relevance({ name: 'TechnoFM' }, 'techno'), 2);
assert.equal(relevance({ name: 'Radio Techno Club' }, 'techno'), 3);
assert.equal(relevance({ name: '# TOP 100 CLUB CHARTS - DANCE & DJ MIX' }, 'techno'), 4);
assert.equal(relevance({ name: '' }, 'techno'), 4);
const ranked = rankStations([
{ name: 'Radio Techno Club' },
{ name: '# TOP 100 CLUB CHARTS' },
{ name: 'Techno' },
{ name: 'TechnoFM' }
], 'techno').map(s => s.name);
assert.deepEqual(ranked, ['Techno', 'TechnoFM', 'Radio Techno Club', '# TOP 100 CLUB CHARTS']);
// Ties fall back to the shorter name, then to the order the directory gave: a 90-character
// marketing string is noise next to "Jazz 24".
assert.deepEqual(rankStations([{ name: 'Jazz FM 106.9 Yerevan Radio Station' }, { name: 'Jazz 24' }], 'jazz').map(s => s.name),
['Jazz 24', 'Jazz FM 106.9 Yerevan Radio Station']);
assert.deepEqual(rankStations(null, 'jazz'), []);
});
test('a search asks the directory by name, https only, and the curated channels come first', async () => {
clearRadioCache();
const asked = [];
const fetchImpl = async (url) => {
asked.push(url);
if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({
channels: [
channel({
id: 'sonicuniverse', title: 'Sonic Universe', genre: 'jazz',
playlists: [{ url: 'https://api.somafm.com/sonicuniverse.pls', format: 'mp3', quality: 'highest' }]
}),
channel({ id: 'beatblender', title: 'Beat Blender', genre: 'electronic' }) // not a jazz hit
]
}) };
// As the directory answers: the noisy name first — which is exactly the problem the ranking
// exists for. It matches "jazz" inside a marketing string; "Jazz 24" starts with it.
if (url.includes('/stations/search')) return { ok: true, text: async () => JSON.stringify([
{ name: 'Smooth Jazz Worldwide Radio Charts Network', codec: 'MP3', country: 'Germany', url_resolved: 'https://x/noisy', stationuuid: 'a' },
{ name: 'Jazz 24', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'b' },
{ name: 'Jazz 24 dup', codec: 'MP3', country: 'Switzerland', url_resolved: 'https://x/jazz24', stationuuid: 'c' },
{ name: 'Jazz FM', codec: 'MP3', country: 'United Kingdom', url_resolved: 'http://x/jazzfm', stationuuid: 'd' }
]) };
if (url.includes('sonicuniverse.pls')) return { ok: true, text: async () => '[playlist]\nFile1=https://ice2.somafm.com/sonicuniverse-128-mp3' };
return { ok: false, status: 404, text: async () => '' };
};
const stations = await searchStations('jazz', { fetchImpl });
// The curated channel is the first answer: no advertising, and a stream known to work.
assert.equal(stations[0].src, 'soma');
assert.equal(stations[0].id, 'sonicuniverse');
assert.equal(stations[0].url, 'https://ice2.somafm.com/sonicuniverse-128-mp3');
const search = asked.find(u => u.includes('/stations/search'));
assert.ok(search, 'the directory was asked');
const q = new URL(search).searchParams;
assert.equal(q.get('name'), 'jazz');
assert.equal(q.get('hidebroken'), 'true');
assert.equal(q.get('is_https'), 'true', 'an http stream is a row the browser will refuse to play');
assert.equal(q.get('order'), 'clickcount', 'ordered by what people actually listen to');
// The http station never makes it, the duplicate never makes it, the noisy name does not outrank
// the station actually called Jazz, and nothing from the directory outranks the curated channel.
assert.deepEqual(stations.map(s => s.name), ['Sonic Universe', 'Jazz 24', 'Smooth Jazz Worldwide Radio Charts Network']);
assert.ok(stations.every(s => /^https:\/\//.test(s.url)));
});
test('a one-letter search answers nothing and asks nobody', async () => {
clearRadioCache();
let called = 0;
const fetchImpl = async () => { called++; return { ok: true, text: async () => '[]' } };
assert.deepEqual(await searchStations('j', { fetchImpl }), []);
assert.deepEqual(await searchStations(' ', { fetchImpl }), []);
assert.equal(called, 0);
});
test('the same query twice is one request to the directory', async () => {
clearRadioCache();
let called = 0;
const fetchImpl = async url => {
if (url.includes('/stations/search')) { called++; return { ok: true, text: async () => JSON.stringify([{ name: 'Jazz', codec: 'MP3', url_resolved: 'https://x/1', stationuuid: 'a' }]) } }
if (url.includes('channels.json')) return { ok: true, text: async () => JSON.stringify({ channels: [] }) };
return { ok: false, status: 404, text: async () => '' };
};
await rbSearch('jazz', { fetchImpl });
await rbSearch('jazz', { fetchImpl });
assert.equal(called, 1);
});
+91
View File
@@ -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(','));
});
+82
View File
@@ -0,0 +1,82 @@
/* The two radio routes, against the real server: who may call them, and what `/now` agrees to look
up. What a genre actually returns is api/test/radio.test.js, which owns the directory logic and
stubs the network — this file is the guards, because a guard is exactly the thing that quietly
stops guarding.
The second one matters more than it looks. `/api/radio/now` takes a source and an id *from the
request* and uses them to build a URL this process then fetches; if the source stopped being
checked, the api container (which sits on the owner's own network) would become a request proxy
for anyone holding a session. */
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-radio-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_r', 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 station list needs a session', async t => {
const h = await startServer(t);
// Not an open station directory: the list is what this instance's owner pays attention to, and
// the audio itself never passes through here.
const r = await fetch(`${h.api}/api/radio`);
assert.equal(r.status, 401);
});
test('what is playing needs a session too', async t => {
const h = await startServer(t);
const r = await fetch(`${h.api}/api/radio/now?src=soma&id=beatblender`);
assert.equal(r.status, 401);
});
test('a station that is not one of the two known sources is refused, unfetched', async t => {
const h = await startServer(t);
for (const q of [
'src=http://127.0.0.1:3000&id=health', // a source that is not one of ours
'src=soma', // no id at all
'src=soma&id=' + encodeURIComponent('../../x'),// an id that would walk out of the path
'src=soma&id=' + encodeURIComponent('a b c'),
'id=beatblender' // no source
]) {
const r = await fetch(`${h.api}/api/radio/now?${q}`, { headers: cookie('u_r') });
assert.equal(r.status, 400, `${q} should be refused`);
assert.match((await r.json()).error, /no such station/);
}
});
-70
View File
@@ -1,73 +1,3 @@
# Build-from-source stack for a host that builds at deploy time (Dokploy and friends).
#
# This is the same five-service shape the instance at gym.dploy.lol runs: `source` clones the
# repository into a volume, `api` installs and runs the backend from that clone, `web-build`
# compiles the frontend, and `web` serves the result with nginx. Nothing is pulled from a
# registry, so `scripts/build-images.sh` and `.gitea/workflows/docker-publish.yml` are not part
# of this path at all.
#
# Five things here are easy to get wrong, and all five are load-bearing:
#
# 1. `web-build` copies the WHOLE repository into /app and builds from /app/frontend, not
# frontend/ on its own. The frontend imports the Coach's core from outside its own directory
# (`frontend/src/lib/coach-local.js` and `views/CoachSetup.jsx` reach into
# `../../../api/coach/core/`), so a build stage that only has frontend/ fails with nine
# UNRESOLVED_IMPORT errors. The repo's own web/Dockerfile copies api/coach/core/ into its
# build stage for the same reason.
#
# 2. The volumes are pinned with `name:`. They hold the users, passkeys, workouts and weigh-ins
# — `kuentagym-data` above all. Those names are this deployment's existing volumes; they are
# spelled out so a restyled stack keeps pointing at the same data instead of silently
# creating empty ones. Never change them without moving the data first, and never run
# `docker compose down -v` — `-v` deletes the volumes, which is every logged set and every
# weigh-in. A plain `docker compose down` is safe. Check yours with `docker volume ls`.
#
# 3. nginx needs `client_max_body_size`, and needs it in two sizes. Its default request limit is
# 1 MB, and the app PUTs the whole profile to /api/data on every change — a couple of years of
# training passes 1 MB and the sync then fails with a 413 the UI cannot explain. So the bulk
# of /api is 5m, matching the API's own MAX_BODY. But the Apple Health ingest takes whole
# exports: a first sync of a year of raw samples is tens of megabytes, and the API allows
# that one route 32 MB (VITALS_MAX_BODY in api/server.js). One global number cannot do both,
# which is why the generated config below has a second location for that one path — nginx
# picks the longest matching prefix, so /api/vitals/ingest gets 32m and everything else keeps
# 5m.
#
# This inline config is the one this deployment actually runs; web/nginx.conf.template is for
# the registry-image path (docker-compose.yml) and is NOT read here. A change to the limits
# has to be made in both, or the two deployment shapes diverge.
#
# 4. X-Forwarded-For uses the APPEND form here, unlike web/nginx.conf.template. In this shape
# nginx is NOT the edge: Traefik terminates TLS in front of it, so `$remote_addr` is Traefik's
# own address and the real client only survives in the header Traefik sends.
# `$proxy_add_x_forwarded_for` carries that one through as the first entry, which is exactly
# what the API reads (see clientIp in api/server.js). The registry template does the opposite
# for the opposite reason — there the web container answers the internet directly, so the
# incoming header can be forged and only $remote_addr can be trusted.
#
# 5. nginx resolves `api` through a VARIABLE, not by name. A plain `proxy_pass http://api:3000`
# is resolved once, when nginx starts, and the address is then pinned for the life of the
# container: recreate the api — a deploy that changes its configuration, a `--force-recreate`,
# a manual restart that gives it a new IP — and every /api call answers 502 until the web
# container is restarted too, including /api/config, so the app cannot even load. The
# `resolver` + `set $api_upstream` pair below makes nginx ask again on every request, which is
# the same fix web/nginx.conf.template carries (and explains at length) for the other shape.
#
# To deploy a change to the code, force the one-shot services to run again — `source` and
# `web-build` have `restart: "no"`, so compose leaves them alone when their configuration has not
# changed:
#
# docker compose up -d --force-recreate
#
# That is also how the `api` service picks up new code: it copies the clone into /app at container
# start, so an `api` that was not recreated keeps running the previous revision while `web-build`
# happily serves the new frontend. Recreate `web` in the same command, and not on its own: its
# `proxy_pass http://api:3000` is resolved once at start-up, so a recreated api means a new IP and
# an nginx still pointing at the old one answers 502 on every /api call.
#
# Set RP_ID, RP_NAME and ORIGIN in the host's environment (or its .env). RP_ID must be the exact
# hostname the app is served from — passkeys are bound to it — and RP_NAME is what the passkey
# prompt shows, so set it to KuentaGYM.
name: kuentagym
services:
+19
View File
@@ -159,6 +159,25 @@ a Mac and nothing more; nobody here does it for you. A signed build (TestFlight,
additionally need an Apple Developer Program membership, the distribution certificate and profile,
and an `-exportArchive` step — none of that is set up.
### Audio with the screen locked (the shells only)
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.
- **Android** (`frontend/android`) — a WebView needs a foreground service (with a
`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 **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
- Bump `versionName`/`versionCode` in `android/app/build.gradle` per release; keep them in
+142
View File
@@ -0,0 +1,142 @@
# Podcasts
Radio, but the other half of it: episodes, in Spanish, that you can resume.
Open **Música → Podcasts** (the middle tab; the screen shows one list at a time, ten shows with a
"show more"), search by name if you know what you are looking for, or 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.
## A search is not a weaker way in
Typing in the box above the tabs asks Apple's podcast search, both storefronts, and the results go
through **the same feed check and the same Spanish filter** as a category's chart entries — one
function on the server, used by both, so "Spanish only" cannot quietly stop applying to a search.
That is the shape worth keeping: a second, cheaper path into a catalogue is how a rule like this
gets lost.
## 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 full player
Tap the bar — the cover and the text, not the buttons — and it opens the full player, the way tapping
Spotify's bar does: artwork at size, the whole episode title, the show, the author, the episode number
and date, a **scrubber you can drag**, elapsed and **remaining**, −15 / +30, previous and next, and a
line that names **what plays next** ("Then: …") or says that this is the last one in the list.
It opens as a **sheet**, not a route, for the same reason the bar lives above the router: a screen
inside the router is unmounted by navigating, and this must never be the thing that stops the audio.
Swipe down (or Android back) closes it and playback continues.
A station gets the same sheet without the scrubber: a live stream has no position and no end, and
saying so is better than a slider that does nothing.
## When an episode ends
The next one in the list you tapped from plays, with nobody touching the phone. "Next" is literally
the next row of that list — the order you can see — and at the end of it playback stops, which the
full player says *before* it happens. The finished episode is marked heard first, so what you have
listened to stays that way.
The lock screen's next/previous buttons do the same thing, which is the point: that is where somebody
with their hands on a bar is going to press it.
## 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.
+144
View File
@@ -0,0 +1,144 @@
# Radio
Live stations, for the hour you're in the gym. Open **Música → Radio**, pick a genre, press a
station, and it plays while you train — across screens, with the screen locked and the phone in your
pocket.
It is radio, not a music library: you don't pick the song, and nobody has to. That is the whole
reason it exists next to the Apple Music playlists on the same screen — one is what you listen to on
purpose, the other is what plays while you count reps.
## What is playing
There is also a **search box** above the tabs, and it searches the directory rather than the page
you are looking at: *jazz* is every jazz station radio-browser knows, not the jazz stations that
happened to be in the genre on screen. Results are ordered by the name first — a station *called*
"Jazz 24" comes before one with "jazz" buried in a forty-character marketing name — and then by how
many people listen. The curated channels and mixes that match come first of all: no advertising, and
a stream already known to work.
Chips pick a genre. Ten of them: **Workout / Rave, Techno / House, R&B / Soul, Latina, Hip-Hop,
Reggae, Chill, Jazz, Rock, Electrónica**. Each one is a list of **SomaFM** channels (curated by hand
— a machine cannot know that *Seven Inch Soul* is the R&B one), the **Radio Paradise** mixes that
fit, and the **radio-browser** tags that fill in the rest.
The ad-free ones come first in every genre: SomaFM is a listener-supported, commercial-free network
of 46 channels, and Radio Paradise is four hand-mixed ones. Both publish their stream as a playlist
`.pls`, which `api/radio.js` reads rather than guessing a bitrate into a URL — that is what makes the
same code work for every channel, including the ones added after this was written.
Behind them is [radio-browser](https://www.radio-browser.info), a public, community-run directory of
tens of thousands of stations. It is filtered hard: **HTTPS only** (a page served over HTTPS cannot
play an `http://` stream at all — the browser blocks it as mixed content, so offering one would be
offering a station that silently does nothing), `hidebroken=true`, ordered by how many people
actually listen to it.
## Where the audio goes
**From the station to your phone. Never through this server.**
The api hands out the list — each station with its stream URL already resolved — and after that it
sees nothing: no traffic, no disk, no byte of audio. On a small VPS that is the difference between a
feature and a bandwidth bill, and it is also why nothing here ever downloads, records or keeps a
copy of anything.
Two kinds of request *do* reach out from the server, and both are for the list and its caption:
| Call | To | Why |
|---|---|---|
| channel list + `.pls` | somafm.com | to resolve a channel into a stream URL |
| `bytagexact` search | all.api.radio-browser.info | the directory's stations per genre |
| `now_playing` | api.radioparadise.com | the cover and the track for the bar |
All of them are cached for ten minutes, so opening the screen twice is one round of requests. Every
outgoing call goes through one function with a **host allowlist** (`RADIO_HOSTS`) — the api container
sits on the owner's own network, so the set of hosts it will talk to is a security boundary, not a
convenience.
So the server does see something: which genre chip was pressed, and — only for the two sources that
publish what they play — which station the bar is asking about, once every 45 seconds while it
plays. Nothing is written down: those are requests, not records, and there is no table, log or file
where listening would accumulate. (The request log in the admin dashboard is the activity log, and it
carries sign-ins and admin actions, not this.)
## Why the stream URL arrives in the list
iOS only lets audio start **inside the gesture** that asked for it. Anything asynchronous between the
finger and the `play()` — a `fetch`, a state update, a re-render — is a press that does nothing, with
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/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.
## The bar, and the lock screen
While something is playing, a bar sits above the tab bar (the same place and the same glass as the
rest timer, on purpose — a second floating bar with its own look reads as a second app):
- the station, and what it says it is playing
- **pause** — keeps the station, so the same one is still there after the rest
- **stop** — takes the bar and the station away
Tapping the bar itself opens the full player — the logo at size, the station, its genre, what it
says it is playing, and pause/stop — with **no scrubber and no clock**, because a live stream has no
position and no end, and a slider that does nothing is worse than a sentence that says so.
**Media Session** is what puts the station, the track and the controls on the lock screen and in the
car, and it is what makes "screen off, phone in pocket" work: the audio is played by the browser
underneath the page, not by the page's timers. Those timers — the 45-second poll for what is playing —
are suspended while the screen is locked, so the caption simply stops moving until you look again. It
is a caption; the music is unaffected.
On the **native Android/iOS shells** the same rules apply, with one addition: keeping audio alive
under a locked screen in a WebView needs `UIBackgroundModes: audio` (iOS) and a foreground service
(Android) in the shell's own config. Neither is set today — that is described in
[docs/MOBILE.md](docs/MOBILE.md), and it only affects the packaged builds, not the PWA.
## When the radio isn't there
Two situations look like a bug and are not, so the screen says which one it is instead of showing a
request that failed:
- **Nobody is signed in.** Guest mode is client-side only and never talks to the api, and the station
list is the server's job — so the section says the radio needs a profile. No request is made.
- **The api is older than the app.** They ship separately: `web` is rebuilt from source on every
deploy, while the api's code lives inside its container, so a deploy can leave a new screen on top
of an api that has never heard of `/api/radio`. `GET /api/config` lists what that api can do
(`features`, and this build answers `radio`), so "old server" is detectable — the section says so,
quietly, rather than offering chips that 404. The same list is what keeps the Salud screen from
blaming the data when it is really the container.
## Saving a station
The star on a row saves the station to your profile (`music.stations`), and saved ones are pinned
above the list. They are stored with the rest of your profile's client state — they contain nothing
about your listening, just the station you liked.
## What this deliberately is not
- **Not a YouTube/Spotify front end.** Ripping streams or playing someone else's catalogue through
an unofficial API breaks those services' terms and this project's licence is AGPL; the honest
version of "radio" is radio.
- **Not a proxy.** No endpoint here relays audio. Every `/api/radio` response is JSON, and the
routes are session-gated so the list cannot be borrowed by somebody else's page.
- **Not a downloader.** There is no record button and no cache of audio anywhere.
- **Not HLS.** Stations that only stream HLS are skipped: playing them in a browser needs `hls.js`,
and a dependency-light project does not take a media stack on for a feature whose whole point is
that it makes no new dependency necessary.
## Credits and licences
- [SomaFM](https://somafm.com) — listener-supported, commercial-free; the channels used here are
theirs, and their stream URLs are resolved through their own public `.pls`.
- [Radio Paradise](https://radioparadise.com) — listener-supported, and the `now_playing` endpoint
that gives the bar its cover art.
- [radio-browser](https://www.radio-browser.info) — the directory itself is **AGPL-3.0**, same
family as this project, and it is the reason the long tail of stations is reachable at all.
These are third-party services this app does not control: a station that goes off the air disappears
from the list on the next refresh, and a genre that comes back thin is the directory having a bad
day, not the app.
+5
View File
@@ -20,6 +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 PlayerBar from './components/PlayerBar.jsx'
import TimerFlash from './components/TimerFlash.jsx'
import Login from './views/Login.jsx'
import MobileOnboarding from './views/MobileOnboarding.jsx'
@@ -216,6 +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 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 />
+137
View File
@@ -0,0 +1,137 @@
/* The full player: what the bar opens when you tap it, the way tapping Spotify's bar does.
*
* The bar is a glance — one line, under a thumb, over whatever screen you were on. This is the other
* half: the artwork at size, the whole episode title instead of the truncated one, a bar you can
* actually drag, and the number that decides whether to start something else (how much is *left*).
*
* It is a **sheet**, not a route, and that is the same decision as the bar living above the router: a
* screen inside the router is unmounted by navigating, and this must never be the thing that stops
* the audio. A sheet brings the house behaviour with it — swipe down to dismiss, Android's back
* closes it, the page behind it does not scroll — and `data-nodrag` on the scrubber (the Slider
* component already carries it) is what keeps a sideways drag from being read as a dismissal.
*
* Nothing here owns the audio: every control goes to the store, which goes to the one element in
* lib/player.js.
*/
import { useEffect, useState } from 'react'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { fmtClock, nextEpisode, prevEpisode, progressPct } from '../lib/podcast-view.js'
import { Slider, Button } from './ui.jsx'
import Icon from './Icon.jsx'
export default function NowPlaying({ close }) {
const radio = useUI(s => s.radio)
const pod = useUI(s => s.pod)
const { togglePod, stopPod, podSeek, podSeekTo, podNext, podPrev, toggleRadio, stopRadio } = useUI()
/* Stopped from somewhere else — the bar's ✕, or the end of the queue with nothing after it — and
this closes itself rather than staying open on an empty screen. */
useEffect(() => { if (!radio && !pod) close() }, [radio, pod])
if (!radio && !pod) return null
if (pod) {
const { episode, show } = pod
const duration = Number(pod.duration) || Number(episode.duration) || 0
const next = nextEpisode(pod.queue, episode.id)
const prev = prevEpisode(pod.queue, episode.id)
return <div className="np">
<Head onClose={close} />
<Art image={episode.image || show?.image || null} />
<div className="np-meta">
<div className="np-show">{show?.name || t('Podcast')}</div>
<div className="np-title">{episode.title}</div>
<div className="np-sub">
{[show?.author, episode.episode ? t('Episode {0}', episode.episode) : null, episode.date?.slice(0, 10)]
.filter(Boolean).join(' · ')}
</div>
</div>
<div className="np-scrub">
<Slider value={Math.min(pod.position || 0, duration || 1)} min={0} max={duration || 1} step={1}
onChange={v => podSeekTo(v)} />
<div className="np-times">
<span>{fmtClock(pod.position)}</span>
{/* What is left, not the total: the total is on the bar and on the right of the scrubber
a moment ago, and the question here is whether there is time for another one. */}
<span>{duration ? '-' + fmtClock(Math.max(0, duration - (pod.position || 0))) : ''}</span>
</div>
</div>
<div className="np-controls">
<button className="np-skip" onClick={() => podSeek(-15)} disabled={!duration} aria-label={t('15 seconds back')}>−15</button>
<button className="np-main" onClick={togglePod} aria-label={pod.playing ? t('Pause') : t('Play')}>
<Icon name={pod.playing ? 'pause' : 'play'} />
</button>
<button className="np-skip" onClick={() => podSeek(30)} disabled={!duration} aria-label={t('30 seconds forward')}>+30</button>
</div>
<div className="np-foot">
<button className="np-nav" onClick={podPrev} disabled={!prev} aria-label={t('Previous episode')}>
<Icon name="chevronLeft" />{t('Previous')}
</button>
<span className="np-pct">{(() => {
const pct = progressPct({ pos: pod.position, dur: duration }, duration)
return pct == null ? '' : Math.round(pct) + '%'
})()}</span>
<button className="np-nav" onClick={podNext} disabled={!next} aria-label={t('Next episode')}>
{t('Next')}<Icon name="chevronRight" />
</button>
</div>
{/* What plays when this one ends — or that nothing will. The queue is the list the episode was
tapped in, in the order it was shown, so "next" is the row below the one you pressed. */}
<div className="np-nextline">
{next ? t('Then: {0}', next.title) : t('Last episode in this list.')}
</div>
<div className="np-actions">
<Button variant="plain" size="sm" onClick={stopPod}>{t('Stop')}</Button>
</div>
</div>
}
const station = radio.station
const cover = radio.now?.cover || station.image || null
return <div className="np">
<Head onClose={close} />
<Art image={cover} />
<div className="np-meta">
<div className="np-show">{t('Radio')}</div>
<div className="np-title">{station.name}</div>
<div className="np-sub">{[station.detail, station.genre].filter(Boolean).join(' · ')}</div>
</div>
<div className="np-meta">
<div className="np-sub">
{radio.now
? t('Playing now: {0}', [radio.now.artist, radio.now.title].filter(Boolean).join(' · '))
: t('This station does not publish what it is playing.')}
</div>
</div>
<div className="np-controls">
<button className="np-main" onClick={toggleRadio} aria-label={radio.playing ? t('Pause') : t('Play')}>
<Icon name={radio.playing ? 'pause' : 'play'} />
</button>
</div>
{/* No scrubber, no clock, and saying so is better than a slider that does nothing: a live stream
has no position, no end, and nothing to go back to. */}
<div className="np-nextline">{t('Live radio: there is nothing to seek and nothing to skip.')}</div>
<div className="np-actions">
<Button variant="plain" size="sm" onClick={stopRadio}>{t('Stop')}</Button>
</div>
</div>
}
const Head = ({ onClose }) => <div className="np-head">
<button className="iconbtn" onClick={onClose} aria-label={t('Close')}><Icon name="chevronDown" /></button>
<span className="np-head-t">{t('Now playing')}</span>
<span style={{ width: 34 }} />
</div>
/** The artwork at size — and the placeholder when there is none, which is a third of podcasts. */
const Art = ({ image }) => {
const [bad, setBad] = useState(null)
return image && image !== bad
? <img className="np-art" src={image} alt="" onError={() => setBad(image)} />
: <div className="np-art np-art-ph"><Icon name="music" /></div>
}
+191
View File
@@ -0,0 +1,191 @@
// @vitest-environment happy-dom
/* The full player: the sheet the bar opens.
*
* Worth a test because it is mostly *claims* — "this is what is playing", "this is how much is
* left", "this is what plays next" — and a claim that drifts from the store is worse than no player
* at all. Two of them are load-bearing here:
*
* - **What plays next is named**, so continuing is not a surprise and stopping is not either.
* - **A station gets no scrubber.** A live stream has no position and no end; a slider that does
* nothing is worse than saying so.
*
* The `<audio>` element lives in lib/player.js, outside React, and is mocked: this file is about what
* the sheet draws and which store action each control calls. */
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 seekBy = vi.fn(() => 100)
const seekTo = vi.fn(() => 900)
vi.mock('../lib/player.js', () => ({
playStream: vi.fn(() => true),
playFile: vi.fn(() => true),
pausePlayer: vi.fn(),
resumePlayer: vi.fn(() => true),
seekBy: (...a) => seekBy(...a),
seekTo: (...a) => seekTo(...a),
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: NowPlaying } = await import('./NowPlaying.jsx')
const show = { feed: 'https://a.example.com/feed', name: 'Tiene Sentido', author: 'Eli Romero', image: null }
const ep = (over = {}) => ({
id: 'ep-1', title: 'Experta en Inflamación: cómo sanar tu intestino',
url: 'https://audio.example.com/1.mp3', date: '2025-09-21T10:00:00.000Z', duration: 3600, image: null, ...over
})
const station = { src: 'soma', id: 'beatblender', name: 'Beat Blender', detail: 'A late night blend', genre: 'Electronic', url: 'https://ice2.somafm.com/x-128-mp3', image: null }
let host, root, closed
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
seekBy.mockClear(); seekTo.mockClear()
closed = vi.fn()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ pod: null, radio: null }) })
})
afterEach(() => {
act(() => root.unmount())
host.remove()
})
const mount = async (close = closed) => { await act(async () => { root.render(<NowPlaying close={close} />) }) }
const btn = label => [...host.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === label)
const text = () => host.textContent
describe('an episode in the full player', () => {
const open = async (over = {}, podOver = {}) => {
act(() => { useUI.getState().playEpisode(show, ep(over), podOver.queue || []) })
await mount()
if (podOver.position != null) act(() => { useUI.getState().setPodPlayback({ position: podOver.position, duration: podOver.duration || 3600 }) })
await act(async () => {})
}
it('shows the episode, the show, the author and the whole title', async () => {
await open()
expect(host.querySelector('.np-show').textContent).toBe('Tiene Sentido')
expect(host.querySelector('.np-title').textContent).toContain('Experta en Inflamación')
expect(text()).toContain('Eli Romero')
expect(text()).toContain('2025-09-21')
})
it('counts down what is left, which is the number that decides whether to start something else', async () => {
await open({ duration: 3600 }, { position: 900, duration: 3600 })
const [elapsed, left] = [...host.querySelectorAll('.np-times span')].map(s => s.textContent)
expect(elapsed).toBe('15:00')
expect(left).toBe('-45:00')
})
it('drags the scrubber to a position', async () => {
await open({ duration: 3600 }, { position: 900, duration: 3600 })
const sld = host.querySelector('.np-scrub .sld')
// The Slider is pointer-driven, so a press on the track is a seek to that fraction of the file.
sld.getBoundingClientRect = () => ({ left: 0, width: 200, top: 0, height: 20, right: 200, bottom: 20 })
act(() => {
const down = new window.PointerEvent('pointerdown', { bubbles: true, clientX: 100, pointerId: 1 })
sld.dispatchEvent(down)
})
await act(async () => {})
expect(seekTo).toHaveBeenCalled()
expect(seekTo.mock.calls[0][0]).toBeGreaterThan(1700)
expect(seekTo.mock.calls[0][0]).toBeLessThan(1900)
})
it('skips back and forward through the element', async () => {
await open()
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])
})
it('names what plays next, so continuing is not a surprise', async () => {
const first = ep(), second = ep({ id: 'ep-2', title: 'La crisis de la salud mental' })
await open(first, { queue: [first, second] })
expect(host.querySelector('.np-nextline').textContent).toBe('Then: La crisis de la salud mental')
expect(btn('Next episode').disabled).toBe(false)
})
it('says when there is nothing after this one, and disables the button', async () => {
const only = ep()
await open(only, { queue: [only] })
expect(host.querySelector('.np-nextline').textContent).toBe('Last episode in this list.')
expect(btn('Next episode').disabled).toBe(true)
expect(btn('Previous episode').disabled).toBe(true)
})
it('goes to the next episode, and back', async () => {
const first = ep(), second = ep({ id: 'ep-2', title: 'Dos' })
await open(first, { queue: [first, second] })
act(() => { btn('Next episode').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod.episode.id).toBe('ep-2')
act(() => { btn('Previous episode').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod.episode.id).toBe('ep-1')
})
it('pauses, and stops', async () => {
await open()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().pod.playing).toBe(false)
act(() => { [...host.querySelectorAll('button')].find(b => b.textContent.trim() === 'Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useUI.getState().pod).toBe(null)
// Stopping from the sheet closes it, instead of leaving an empty player on screen.
expect(closed).toHaveBeenCalled()
})
it('falls back to the placeholder when the artwork does not load', async () => {
await open({ image: 'https://x/not-an-image' })
expect(host.querySelector('.np-art').tagName).toBe('IMG')
act(() => { host.querySelector('.np-art').dispatchEvent(new Event('error')) })
await act(async () => {})
expect(host.querySelector('.np-art').className).toContain('np-art-ph')
})
})
describe('a station in the full player', () => {
const open = async (now = null) => {
act(() => {
useUI.getState().playRadio(station)
if (now) useUI.getState().setRadioNow(now)
})
await mount()
}
it('shows the station and what it says it is playing', async () => {
await open({ artist: 'Tycho', title: 'From Home' })
expect(host.querySelector('.np-title').textContent).toBe('Beat Blender')
expect(text()).toContain('A late night blend · Electronic')
expect(text()).toContain('Playing now: Tycho · From Home')
})
it('says so when the station publishes no track', async () => {
await open()
expect(text()).toContain('does not publish what it is playing')
})
it('offers no scrubber, because a live stream has nothing to seek', async () => {
await open({ artist: 'Tycho', title: 'From Home' })
expect(host.querySelector('.np-scrub')).toBe(null)
expect(text()).toContain('nothing to seek')
// And no next/previous: a station has no queue, and playing the next one is not a thing.
expect(btn('Next episode')).toBeUndefined()
})
it('pauses the station from here', async () => {
await open()
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(useUI.getState().radio.playing).toBe(false)
expect(useUI.getState().radio.station.id).toBe('beatblender')
})
})
+156
View File
@@ -0,0 +1,156 @@
/* 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'
import NowPlaying from './NowPlaying.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 openSheet = useUI(s => s.openSheet)
const { toggleRadio, stopRadio, setRadioNow, togglePod, stopPod, podSeek, podNext } = useUI()
const on = !!radio || !!pod
/* Tapping the bar opens the full player, the way tapping Spotify's bar does. A sheet and not a
route: a route would be unmounted by navigating, and this is one tap away from every screen in
the app. The sheet's own gestures (swipe down, Android back) come with it. */
const openFull = () => openSheet(close => <NowPlaying close={close} />)
// 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} onOpen={openFull} />
if (pod) return <EpisodeLine pod={pod} onToggle={togglePod} onStop={stopPod} onSeek={podSeek} onNext={podNext} onOpen={openFull} />
return null
}
/* ---------- radio ---------- */
function RadioLine({ radio, onToggle, onStop, onNow, onOpen }) {
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
onOpen={onOpen}
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, onOpen }) {
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
onOpen={onOpen}
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.
*
* The cover and the text are the button that opens the full player — the controls are buttons of
* their own, and a bar where the whole surface is one button cannot have a play button in it. */
function Bar({ onOpen, 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">
<button className="plr-open" onClick={onOpen} aria-label={t('Open the 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>
<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>
}
+210
View File
@@ -0,0 +1,210 @@
// @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)
const setStreamSession = vi.fn()
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: (...a) => setStreamSession(...a),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
clearSession: vi.fn(),
onPlayer: () => () => {}
}))
const { default: PlayerBar } = await import('./PlayerBar.jsx')
const { default: Modals } = await import('./Modals.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()
setStreamSession.mockClear()
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
act(() => { useUI.setState({ radio: null, pod: null, sheets: [] }) })
document.getElementById('modal-root')?.remove()
})
afterEach(() => {
act(() => root.unmount())
host.remove()
document.body.classList.remove('playing-media')
act(() => { useUI.setState({ sheets: [] }) })
document.getElementById('modal-root')?.remove()
})
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')
// The lock screen gets the track too, not just the station: the metadata has to be re-sent when
// the track changes, and this is the only place that knows it changed.
expect(setStreamSession).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'beatblender' }), expect.objectContaining({ title: 'Little Fluffy Clouds' }))
})
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 })
})
/* The bar is a glance and the full player is the detail, and the tap between them is the whole
interaction: tapping the bar must not pause, stop, or navigate anything. */
it('opens the full player when the bar itself is tapped', async () => {
act(() => { useUI.getState().playEpisode(show, episode({ duration: 3600 }), []) })
await act(async () => { root.render(<><PlayerBar /><Modals /></>) })
expect(document.querySelector('#modal-root .np')).toBe(null)
act(() => { host.querySelector('.plr-open').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
const sheet = document.querySelector('#modal-root .np')
expect(sheet).toBeTruthy()
expect(sheet.textContent).toContain('Nadie Sabe Nada')
expect(sheet.textContent).toContain('En el corazón del ajo')
// Still playing: opening the detail view is not a play/pause.
expect(useUI.getState().pod.playing).toBe(true)
expect(playFile).toHaveBeenCalledTimes(1)
})
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)
})
})
+130
View File
@@ -1117,6 +1117,136 @@ 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 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;
padding:9px 11px;border-radius:var(--r-md);background:var(--glass);border:var(--hair) solid var(--sep-op);
-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}
.mus-rad.on .mus-rad-main{border-color:color-mix(in srgb,var(--acc) 40%,transparent)}
.mus-rad-i{width:34px;height:34px;border-radius:8px;object-fit:cover;flex:0 0 auto}
.mus-rad-i-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
.mus-rad-i-ph .icn{font-size:16px}
.mus-rad-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
.mus-rad-n{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mus-rad-s{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.mus-rad-go{font-size:17px;color:var(--acc);flex:0 0 auto}
.mus-rad-save{color:var(--label-3)}
.mus-rad-save .icn{font-size:17px}
/* The screen's three lists, one at a time. The segmented control sits right under the search box and
above everything it switches between, so the screen reads top to bottom: what am I looking at,
which of the three, and then the list. */
.mus-tabs{margin:2px 0 12px}
.mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px}
/* 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 full player, inside a sheet: artwork at size, the whole title, a draggable bar.
It is the other half of the strip under the tab bar — that one is a glance, this one is where
somebody looks when the question is "what is this, and how much is left". */
.np{display:flex;flex-direction:column;gap:14px;padding-bottom:4px}
.np-head{display:flex;align-items:center;justify-content:space-between;gap:8px}
.np-head-t{font-size:12px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--label-3)}
.np-art{
width:min(62vw,240px);height:min(62vw,240px);border-radius:var(--r-lg);object-fit:cover;
align-self:center;box-shadow:0 18px 40px -14px rgba(0,0,0,.5);
}
.np-art-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3);box-shadow:none}
.np-art-ph .icn{font-size:52px}
.np-meta{display:flex;flex-direction:column;gap:3px;text-align:center;padding:0 4px}
.np-show{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--label-3)}
.np-title{font-size:17px;font-weight:650;color:var(--label);line-height:1.32}
.np-sub{font-size:12.5px;color:var(--label-3);line-height:1.4}
.np-scrub{display:flex;flex-direction:column;gap:6px;padding:0 2px}
.np-times{display:flex;justify-content:space-between;font-size:11.5px;color:var(--label-3);font-variant-numeric:tabular-nums}
.np-controls{display:flex;align-items:center;justify-content:center;gap:22px}
/* The one big button on the screen, and the two that are only ever pressed by feel. */
.np-main{
width:64px;height:64px;border-radius:50%;border:0;background:var(--acc);color:var(--on-acc);
display:flex;align-items:center;justify-content:center;cursor:pointer;
}
.np-main .icn{font-size:28px;--icon-stroke:2.4}
.np-skip{
min-width:52px;height:44px;border-radius:12px;border:0;background:var(--surface-3);color:var(--label);
font:650 14px/1 var(--font);font-variant-numeric:tabular-nums;cursor:pointer;
}
.np-skip:disabled{color:var(--label-4);background:transparent}
.np-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:0 2px}
.np-nav{
display:flex;align-items:center;gap:4px;border:0;background:transparent;color:var(--label);
font:600 13px/1 var(--font);padding:8px 6px;border-radius:10px;cursor:pointer;
}
.np-nav:disabled{color:var(--label-4)}
.np-nav .icn{font-size:17px}
.np-pct{font-size:11.5px;color:var(--label-3);font-variant-numeric:tabular-nums}
.np-nextline{font-size:12px;color:var(--label-3);text-align:center;line-height:1.45;padding:0 8px}
.np-actions{display:flex;justify-content:center}
/* 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.
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);
border-radius:var(--r-lg);padding:9px 12px;
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 #player{bottom:calc(190px + var(--sab))}
body.playing-media #app{padding-bottom:calc(146px + var(--sab))}
@media (min-width:1000px){
#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}
/* The cover and the text are one button: tapping them opens the full player, and the controls
beside them stay buttons of their own. */
.plr-open{display:flex;align-items:center;gap:10px;flex:1;min-width:0;border:0;background:transparent;padding:0;text-align:left;cursor:pointer}
.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;
}
/* 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. */
+29
View File
@@ -0,0 +1,29 @@
/* Showing ten of something instead of forty.
*
* The Música screen carries three lists — stations, podcasts, playlists — and a list that renders
* everything is a screen you scroll through looking for the thing you already know you want. Ten
* rows and a "show more" is the house style here (the exercise library and the admin activity log
* both work this way), and it is the reason the screen reads as three small lists rather than one
* long one.
*
* Pure and tested because the arithmetic has an edge that is easy to get wrong in a component: a
* list that *shrinks* — a new search, a station unstarred — must not leave the page size past its
* end, which reads as "show more" doing nothing. */
export const PAGE = 10
/** The first `shown` items. Never more than there are, and never a crash on a missing list. */
export const visible = (list, shown) => (Array.isArray(list) ? list : []).slice(0, Math.max(0, shown))
/** Whether there is anything left to reveal. */
export const hasMore = (list, shown) => (Array.isArray(list) ? list.length : 0) > Math.max(0, shown)
/**
* How many to show after "show more".
*
* Clamped to the list: the button is only ever pressed against a list that shrank since it was
* drawn, and growing past the end would leave it on screen doing nothing at all.
*/
export const nextShown = (shown, total, step = PAGE) => Math.min((Number(shown) || 0) + step, Math.max(0, Number(total) || 0))
/** How many are hidden — for a button that says how much it is hiding, or nothing at all. */
export const hiddenCount = (list, shown) => Math.max(0, (Array.isArray(list) ? list.length : 0) - Math.max(0, shown))
+46
View File
@@ -0,0 +1,46 @@
/* Ten at a time, and the edges of that. */
import { describe, expect, it } from 'vitest'
import { PAGE, visible, hasMore, nextShown, hiddenCount } from './paging.js'
const list = n => Array.from({ length: n }, (_, i) => i)
describe('showing a list in pages of ten', () => {
it('shows ten, not everything', () => {
expect(PAGE).toBe(10)
expect(visible(list(40), PAGE)).toHaveLength(10)
expect(visible(list(40), PAGE)[9]).toBe(9)
})
it('shows what there is when there is less than a page', () => {
expect(visible(list(4), PAGE)).toEqual([0, 1, 2, 3])
expect(hasMore(list(4), PAGE)).toBe(false)
})
it('says when there is more, and stops saying it at the end', () => {
expect(hasMore(list(11), PAGE)).toBe(true)
expect(hasMore(list(20), 20)).toBe(false)
// The bug this exists for: a list that shrank under a page size that was already past its end.
expect(hasMore([], PAGE)).toBe(false)
expect(hasMore(list(3), 10)).toBe(false)
})
it('grows by a page, and never past the end', () => {
expect(nextShown(PAGE, 40)).toBe(20)
expect(nextShown(30, 40)).toBe(40)
// "Show more" on a list that shrank to eight would otherwise leave the button there forever.
expect(nextShown(20, 8)).toBe(8)
})
it('counts what it is hiding', () => {
expect(hiddenCount(list(25), PAGE)).toBe(15)
expect(hiddenCount(list(3), PAGE)).toBe(0)
})
it('survives a list that is not there yet', () => {
expect(visible(null, PAGE)).toEqual([])
expect(visible(undefined, PAGE)).toEqual([])
expect(hasMore(null, PAGE)).toBe(false)
expect(hiddenCount(null, PAGE)).toBe(0)
expect(visible(list(5), null)).toEqual([])
})
})
+276
View File
@@ -0,0 +1,276 @@
/* 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.
*
* `next` and `previous` are passed in because only the store knows what a queue is — but they are
* kept in module state and read *late*, so the handler can be installed once and still follow the
* queue the current episode was started from. That is what puts "next episode" on the lock screen,
* which is where somebody with their hands on a bar is going to press it. */
let sessionWired = false
let sessionNext = null
let sessionPrev = null
export function wireSessionHandlers({ next = null, prev = null } = {}) {
if (next) sessionNext = next
if (prev) sessionPrev = prev
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) })
ms.setActionHandler?.('nexttrack', () => { sessionNext?.() })
ms.setActionHandler?.('previoustrack', () => { sessionPrev?.() })
} 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)
ms.setActionHandler?.('nexttrack', null)
ms.setActionHandler?.('previoustrack', 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
sessionNext = null
sessionPrev = null
}
+222
View File
@@ -0,0 +1,222 @@
// @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()
// Next and previous go through whichever queue the current episode came from, read late: the
// handlers are installed once, and the store swaps the callbacks as the queue changes.
const next = vi.fn(), prev = vi.fn()
wireSessionHandlers({ next, prev })
session.handlers.nexttrack()
session.handlers.previoustrack()
expect(next).toHaveBeenCalled()
expect(prev).toHaveBeenCalled()
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)
expect(session.handlers.nexttrack).toBe(null)
})
})
+127
View File
@@ -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)
}
+116
View File
@@ -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({})
})
})
+62
View File
@@ -1408,6 +1408,68 @@ 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}',
'Now playing': 'Sonando ahora',
'Open the player': 'Abrir el reproductor',
'Previous': 'Anterior',
'Previous episode': 'Episodio anterior',
'Episode {0}': 'Episodio {0}',
'Then: {0}': 'Después: {0}',
'Last episode in this list.': 'Es el último episodio de esta lista.',
'Playing now: {0}': 'Suena ahora: {0}',
'This station does not publish what it is playing.': 'Esta emisora no publica qué está sonando.',
'Live radio: there is nothing to seek and nothing to skip.': 'Radio en vivo: no hay nada que adelantar ni saltar.',
// podcasts
'Live radio, nothing downloaded': 'Radio en vivo, sin descargar nada',
'Spanish podcasts, remembered where you left off': 'Podcasts en español, que se acuerdan de dónde ibas',
'Search stations…': 'Buscar emisoras…',
'Search podcasts…': 'Buscar podcasts…',
'Search playlists…': 'Buscar listas…',
'Results for “{0}”': 'Resultados para “{0}”',
'No results for “{0}”.': 'Sin resultados para “{0}”.',
'Show more ({0})': 'Mostrar más ({0})',
'{0} shows': '{0} programas',
'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}',
'Paused: {0}': 'En pausa: {0}',
'Playlists': 'Listas',
'Live radio': 'Radio en vivo',
'Play': 'Reproducir',
'Pause': 'Pausar',
'Stop': 'Parar',
'Stations': 'Emisoras',
'no advertising': 'sin publicidad',
'Saved stations': 'Emisoras guardadas',
'{0} stations': '{0} emisoras',
'Loading stations…': 'Cargando emisoras…',
'That station is not answering. Try another one.': 'Esa emisora no está respondiendo. Probá con otra.',
'Save this station': 'Guardar esta emisora',
'Saved to your stations': 'Guardada en tus emisoras',
'Nothing playing. Pick a station below.': 'No hay nada sonando. Elegí una emisora abajo.',
'These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.': 'Son radios públicas: no se descarga nada y el audio va directo de la emisora a tu teléfono. Las primeras de cada género son emisoras sin publicidad.',
'The radio comes from your server, so it needs a profile: sign in and the stations appear here.': 'La radio viene de tu servidor, así que necesita un perfil: entrá a tu cuenta y las emisoras aparecen acá.',
'Your server has not been updated for the radio yet: it is the server that finds the stations, and this app is newer than it. Restarting it should be enough.': 'Tu servidor todavía no se actualizó para la radio: las emisoras las busca el servidor, y esta app es más nueva que él. Reiniciarlo debería alcanzar.',
'What arrived last': 'Qué llegó en el último envío',
'Datapoints in the last sync': 'Datos en el último envío',
'How they were stamped': 'Cómo vienen marcados',
+70 -4
View File
@@ -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
@@ -35,7 +36,11 @@ export const DEF = {
// somebody else's public playlists (see frontend/src/lib/music.js for the long version), so these
// 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: [] },
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
@@ -350,6 +355,65 @@ export const useStore = create((set, get) => {
// overwrite, not a change to merge: the push it arms goes without a baseRev.
replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) },
/* Radios saved per profile, next to the playlists: what one person listens to while training is
not what another does, and this document is already per profile and already synced. Keyed by
source + id for the same reason the playlists are keyed by theirs — starring the same station
twice is one row, and unstarring one never depends on its position in the list. */
addStation(station) {
if (!station || !station.url) return
get().update(st => {
const music = st.music || { user: '', playlists: [], stations: [] }
const list = music.stations || []
if (list.some(x => x.src === station.src && x.id === station.id)) return
st.music = {
...music,
stations: [...list, { src: station.src, id: station.id, name: station.name, url: station.url, genre: station.genre || '', detail: station.detail || '', image: station.image || null }]
}
})
},
removeStation(src, id) {
get().update(st => {
const music = st.music || { playlists: [], stations: [] }
st.music = { ...music, stations: (music.stations || []).filter(x => !(x.src === src && x.id === id)) }
})
},
/* 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. */
@@ -363,17 +427,19 @@ export const useStore = create((set, get) => {
get().update(s => {
const list = (s.music && s.music.playlists) || []
if (list.some(p => (p.id || p.url) === id)) return
s.music = { user: (s.music && s.music.user) || '', playlists: [...list, { ...item, id }] }
s.music = { ...s.music, user: (s.music && s.music.user) || '', playlists: [...list, { ...item, id }] }
})
},
removePlaylist(id) {
get().update(s => {
const list = (s.music && s.music.playlists) || []
s.music = { user: (s.music && s.music.user) || '', playlists: list.filter(p => p.id !== id) }
// Spread, not a fresh object: `music` also holds the saved radio stations, and rebuilding it
// from two known fields silently dropped them — the star said "saved", the list was empty.
s.music = { ...s.music, user: (s.music && s.music.user) || '', playlists: list.filter(p => p.id !== id) }
})
},
setMusicUser(user) {
get().update(s => { s.music = { user: String(user || '').replace(/^@/, '').trim().slice(0, 40), playlists: (s.music && s.music.playlists) || [] } })
get().update(s => { s.music = { ...s.music, user: String(user || '').replace(/^@/, '').trim().slice(0, 40), playlists: (s.music && s.music.playlists) || [] } })
},
// Fires after the moments where losing local data would actually hurt — a workout just
@@ -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'])
})
})
@@ -0,0 +1,85 @@
// @vitest-environment happy-dom
/* The stations a profile saves, and the neighbours that keep eating them.
*
* Two bugs this pins, both silent, both found by reading rather than by clicking:
*
* 1. `update(mut)` mutates the draft it is handed — the return value is discarded. The first
* version of addStation *returned* `{ music: … }`, so the star on a station did nothing at all:
* the toast said "saved to your stations" and the list stayed empty.
* 2. `music` holds playlists, the Apple Music username *and* these stations. The playlist methods
* rebuilt it from the two fields they cared about, so removing a playlist — or typing a
* username in Settings — dropped every saved station on the floor. Same class of bug as the
* add form that forgot an id: the screen keeps looking right while the data moves on.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../lib/api.js', () => ({ api: vi.fn().mockResolvedValue({}) }))
import { useStore } from './useStore.js'
const station = (over = {}) => ({
src: 'soma', id: 'beatblender', name: 'Beat Blender',
url: 'https://ice2.somafm.com/beatblender-128-mp3',
genre: 'Electronic', detail: 'A late night blend', image: null, ...over
})
const playlist = { id: 'pl.aaa', url: 'https://music.apple.com/us/playlist/leg-day/pl.aaa', kind: 'playlist', name: 'Leg Day' }
const stations = () => useStore.getState().S.music.stations
beforeEach(() => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [], stations: [] } } }))
})
describe('saved radio stations', () => {
it('saves one, with the stream URL, so the row can play without asking again', () => {
useStore.getState().addStation(station())
expect(stations()).toHaveLength(1)
expect(stations()[0]).toMatchObject({ src: 'soma', id: 'beatblender', name: 'Beat Blender' })
expect(stations()[0].url).toBe('https://ice2.somafm.com/beatblender-128-mp3')
})
it('starring the same station twice is one row', () => {
useStore.getState().addStation(station())
useStore.getState().addStation(station({ name: 'Beat Blender (again)' }))
expect(stations()).toHaveLength(1)
expect(stations()[0].name).toBe('Beat Blender')
})
it('refuses a station with no stream, which would be a row that cannot play', () => {
useStore.getState().addStation(station({ url: null }))
useStore.getState().addStation(null)
expect(stations()).toHaveLength(0)
})
it('unstars the one it was asked about, and only that one', () => {
useStore.getState().addStation(station())
useStore.getState().addStation(station({ src: 'paradise', id: 'mellow', name: 'Radio Paradise Mellow' }))
useStore.getState().removeStation('soma', 'beatblender')
expect(stations().map(s => s.id)).toEqual(['mellow'])
})
it('survives a state that predates the feature, where music has no stations at all', () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [] } } }))
useStore.getState().addStation(station())
expect(stations()).toHaveLength(1)
expect(useStore.getState().S.music.user).toBe('ana')
})
/* The playlists screen and Settings both rebuild `music`; the stations have to come out the other
side of that. */
it('is not dropped by the playlist mutations that share the same object', () => {
useStore.getState().addStation(station())
useStore.getState().addPlaylist(playlist)
expect(stations()).toHaveLength(1)
useStore.getState().removePlaylist('pl.aaa')
expect(useStore.getState().S.music.playlists).toHaveLength(0)
expect(stations()).toHaveLength(1)
useStore.getState().setMusicUser('@ana')
expect(useStore.getState().S.music.user).toBe('ana')
expect(stations()).toHaveLength(1)
useStore.getState().addPlaylist(playlist)
expect(stations()).toHaveLength(1)
})
})
+215
View File
@@ -2,6 +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, playFile, pausePlayer, resumePlayer, seekBy, seekTo, 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'
@@ -25,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
@@ -63,6 +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/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
@@ -87,6 +142,166 @@ export const useUI = create((set, get) => ({
toastTm = setTimeout(() => set({ toastMsg: '' }), 2200)
},
/* 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, 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 } })
setStreamSession(station, null)
wireSessionHandlers()
return ok
},
toggleRadio() {
const r = get().radio
if (!r) return
if (r.playing) { pausePlayer(); set({ radio: { ...r, playing: false } }) }
else { const ok = playStream(r.station.url, r.volume); set({ radio: { ...r, playing: ok } }) }
},
stopRadio() {
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)
// The lock screen's next/previous go through the queue this episode came from.
wireSessionHandlers({ next: () => get().podNext(), prev: () => get().podPrev() })
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()
},
/** Somewhere in particular: the scrubber in the full player, and the lock screen's own bar. */
podSeekTo(seconds) {
const p = get().pod
if (!p) return
const to = seekTo(seconds)
if (to == null) return
set({ pod: { ...p, position: to } })
setSessionPosition()
savePodPosition(true)
},
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 } })
},
startRest(sec, forIdx) {
get().stopRest()
// Rest timer set to Off. Stopping and returning rather than starting a zero-length timer
+215
View File
@@ -0,0 +1,215 @@
// @vitest-environment happy-dom
/* The podcast player's state machine: what happens when an episode ends, and where it starts.
*
* Two behaviours the user asked for in as many words, and both are the kind that only show up an
* hour into a workout — which is exactly when nobody wants to discover them:
*
* - **When an episode ends, the next one plays.** "Next" is the next row of the list the episode
* was tapped in, because that is what the person can see; at the end of that list it stops, and
* the full player says so before it happens.
* - **An episode starts where it was left off**, and if it was left within seconds of the end it
* starts over instead.
*
* The player module is mocked with a captured handler list, so the test can *emit* what a browser
* emits — `ended`, `time`, `paused` — instead of pretending the audio exists. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
/* `vi.hoisted` because the module under test registers its listener at *import* time: anything the
factory closes over has to exist before the imports are evaluated, which is what this is for. */
const mocks = vi.hoisted(() => ({
handlers: [],
/* What the element would answer if it were asked where it is. The store asks the *element*, not the
event that just arrived, so a test that wants a position saved has to move this too — which is
the honest shape of it: the audio is the truth and the store follows. */
time: { position: 0, duration: null },
playStream: vi.fn(() => true),
playFile: vi.fn(() => true),
pausePlayer: vi.fn(),
seekBy: vi.fn(() => 0)
}))
vi.mock('../lib/player.js', () => ({
playStream: (...a) => mocks.playStream(...a),
playFile: (...a) => mocks.playFile(...a),
pausePlayer: (...a) => mocks.pausePlayer(...a),
resumePlayer: vi.fn(() => true),
seekBy: (...a) => mocks.seekBy(...a),
seekTo: vi.fn(() => 0),
playerTime: () => mocks.time,
setPlayerVolume: vi.fn(),
setStreamSession: vi.fn(),
setEpisodeSession: vi.fn(),
setSessionPosition: vi.fn(),
wireSessionHandlers: vi.fn(),
clearSession: vi.fn(),
onPlayer: h => { mocks.handlers.push(h); return () => {} }
}))
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
const emit = (event, state = { position: 0, duration: null }) => mocks.handlers.forEach(h => h(event, state))
const ep = (over = {}) => ({
id: 'ep-1', title: 'Uno', 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: 'Tiene Sentido' }
beforeEach(() => {
vi.useFakeTimers()
mocks.playFile.mockClear(); mocks.pausePlayer.mockClear(); mocks.seekBy.mockClear()
mocks.time = { position: 0, duration: null }
useUI.setState({ pod: null, radio: null })
useStore.setState(s => ({ S: { ...s.S, podcasts: { shows: [], progress: {} } } }))
})
afterEach(() => { vi.useRealTimers() })
describe('playing an episode', () => {
it('starts it where it was left off, on this device or another', () => {
useStore.getState().savePodcastPosition('ep-1', 600, 3135)
useUI.getState().playEpisode(show, ep(), [ep()])
expect(mocks.playFile).toHaveBeenCalledWith('https://audio.example.com/1.mp3', { startAt: 600 })
expect(useUI.getState().pod.position).toBe(600)
})
it('starts a finished episode over instead of resuming into its last seconds', () => {
useStore.getState().savePodcastPosition('ep-1', 3130, 3135)
useUI.getState().playEpisode(show, ep(), [ep()])
expect(mocks.playFile).toHaveBeenCalledWith(expect.any(String), { startAt: 0 })
})
it('keeps the list it was tapped in as the queue, and a lone episode as a queue of one', () => {
const one = ep(), two = ep({ id: 'ep-2', title: 'Dos' })
useUI.getState().playEpisode(show, one, [one, two])
expect(useUI.getState().pod.queue.map(e => e.id)).toEqual(['ep-1', 'ep-2'])
useUI.getState().playEpisode(show, ep({ id: 'ep-9' }), [])
expect(useUI.getState().pod.queue.map(e => e.id)).toEqual(['ep-9'])
})
})
describe('when an episode ends', () => {
it('plays the next one in the list, without anybody touching the phone', () => {
const one = ep(), two = ep({ id: 'ep-2', title: 'Dos', url: 'https://audio.example.com/2.mp3' })
useUI.getState().playEpisode(show, one, [one, two])
mocks.playFile.mockClear()
mocks.time = { position: 3135, duration: 3135 }
emit('ended', { position: 3135, duration: 3135 })
expect(mocks.playFile).toHaveBeenCalledWith('https://audio.example.com/2.mp3', { startAt: 0 })
expect(useUI.getState().pod.episode.id).toBe('ep-2')
expect(useUI.getState().pod.show.name).toBe('Tiene Sentido')
})
it('marks the finished one as heard before moving on', () => {
const one = ep(), two = ep({ id: 'ep-2' })
useUI.getState().playEpisode(show, one, [one, two])
mocks.time = { position: 3135, duration: 3135 }
emit('ended', { position: 3135, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1'].pos).toBe(3135)
// And the next one is not "heard" just because it started.
expect(useStore.getState().S.podcasts.progress['ep-2']).toBeUndefined()
})
it('stops at the end of the list, because there is nothing after it', () => {
const one = ep(), two = ep({ id: 'ep-2' })
useUI.getState().playEpisode(show, two, [one, two])
mocks.pausePlayer.mockClear()
emit('ended', { position: 3135, duration: 3135 })
expect(mocks.pausePlayer).toHaveBeenCalled()
expect(useUI.getState().pod.playing).toBe(false)
// The episode stays on screen: it is still what you were listening to, and the sheet says
// "last episode in this list" rather than leaving a blank player.
expect(useUI.getState().pod.episode.id).toBe('ep-2')
})
it('stops a lone episode that ended, and does not invent a next one', () => {
const only = ep()
useUI.getState().playEpisode(show, only, [only])
mocks.playFile.mockClear()
emit('ended', { position: 100, duration: 3135 })
expect(mocks.playFile).not.toHaveBeenCalled()
expect(useUI.getState().pod.playing).toBe(false)
})
})
describe('what the player reports back', () => {
it('moves the clock on screen once per second, not four times', () => {
useUI.getState().playEpisode(show, ep(), [])
const before = useUI.getState().pod
emit('time', { position: 10.2, duration: 3135 })
expect(useUI.getState().pod.position).toBe(10.2)
// Same second: the store object is not replaced, so nothing re-renders for it.
const same = useUI.getState().pod
emit('time', { position: 10.7, duration: 3135 })
expect(useUI.getState().pod).toBe(same)
emit('time', { position: 11.1, duration: 3135 })
expect(useUI.getState().pod).not.toBe(before)
})
it('writes the position into the profile when the episode is paused', () => {
vi.setSystemTime(1000)
useUI.getState().playEpisode(show, ep(), [])
vi.setSystemTime(1000 + 8000)
mocks.time = { position: 620, duration: 3135 }
emit('paused', { position: 620, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1']).toMatchObject({ pos: 620, dur: 3135 })
expect(useUI.getState().pod.playing).toBe(false)
})
it('does not write down a two-second listen', () => {
vi.setSystemTime(1000)
useUI.getState().playEpisode(show, ep(), [])
vi.setSystemTime(2000)
mocks.time = { position: 2, duration: 3135 }
emit('paused', { position: 2, duration: 3135 })
expect(useStore.getState().S.podcasts.progress['ep-1']).toBeUndefined()
})
it('takes the length from the loaded file, so the bar has a clock', () => {
useUI.getState().playEpisode(show, ep({ duration: null }), [])
emit('meta', { position: 0, duration: 2480 })
expect(useUI.getState().pod.duration).toBe(2480)
})
it('says it stopped when the file dies, instead of claiming to play', () => {
useUI.getState().playEpisode(show, ep(), [])
emit('error', { position: 12, duration: 3135 })
expect(useUI.getState().pod.playing).toBe(false)
})
})
describe('the controls the full player uses', () => {
it('seeks to a position when the scrubber is dragged', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().podSeekTo(900)
expect(useUI.getState().pod.position).toBe(0) // the mocked element answers 0
// The real call went to the element; the store keeps whatever it says it landed on.
expect(mocks.seekBy).not.toHaveBeenCalled()
})
it('skips by seconds through the element, and follows what it answers', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().podSeek(-15)
expect(mocks.seekBy).toHaveBeenCalledWith(-15)
useUI.getState().podSeek(30)
expect(mocks.seekBy).toHaveBeenLastCalledWith(30)
})
it('stops everything and forgets the station when the podcast is stopped', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().stopPod()
expect(useUI.getState().pod).toBe(null)
expect(mocks.pausePlayer).toHaveBeenCalled()
})
it('never lets a station and an episode play at once', () => {
useUI.getState().playEpisode(show, ep(), [])
useUI.getState().playRadio({ src: 'soma', id: 'x', name: 'X', url: 'https://ice2.somafm.com/x-128-mp3' })
expect(useUI.getState().pod).toBe(null)
expect(useUI.getState().radio.station.id).toBe('x')
useUI.getState().playEpisode(show, ep(), [])
expect(useUI.getState().radio).toBe(null)
expect(useUI.getState().pod.episode.id).toBe('ep-1')
})
})
+28 -7
View File
@@ -157,19 +157,38 @@ function InvitesCard({ invites, reload, inviteOnly }) {
// Who signed in, who tried and failed, what an admin changed. A card rather than its own route:
// the dashboard is deliberately one page of cards, and the 95 % use of this is a glance at the
// last twenty events. Paging follows Library.jsx's house style — "Show more", not page numbers.
/* How many events the card shows before somebody asks for more.
*
* The log is history and history is long: twenty-five rows is a wall of text that pushes the rest of
* the dashboard off the screen, and a cleared log is a full one again the next day. The count in the
* lead line says how much there is — the newest ten are shown, and one button reveals the rest, ten
* at a time, fetching from the server once everything already loaded is on screen. */
const AUDIT_PAGE = 10
function AuditCard({ tick }) {
const toast = useUI(s => s.toast)
const [meta, setMeta] = useState(null) // last response minus the rows: total, retention, …
const [rows, setRows] = useState([])
const [cat, setCat] = useState('')
const [shown, setShown] = useState(AUDIT_PAGE)
const load = (c, before) => api('/api/admin/audit?limit=50&cat=' + c + (before ? '&before=' + before : ''))
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events) : r.events)) })
// `|| []` because a response without events is a response with no events, not a crash: an
// admin card that throws takes the whole dashboard with it.
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events || []) : (r.events || []))) })
.catch(e => toast(e.message))
const pick = c => { setCat(c); setRows([]); setMeta(null); load(c) }
const pick = c => { setCat(c); setRows([]); setMeta(null); setShown(AUDIT_PAGE); load(c) }
// Reloads on mount and whenever the header's ↻ bumps the tick. Deliberately not on the 15s
// poll that drives "training now": this is history, not presence.
useEffect(() => { load(cat) }, [tick])
// poll that drives "training now": this is history, not presence. A reload starts folded again,
// which is the point of folding it.
useEffect(() => { setShown(AUDIT_PAGE); load(cat) }, [tick])
const hidden = rows.length - shown
const more = () => {
setShown(n => n + AUDIT_PAGE)
// Everything already fetched is on screen: the next ten come from the server.
if (hidden <= 0 && meta?.nextBefore) load(cat, meta.nextBefore)
}
const clear = () => confirmSheet({
title: 'Clear the activity log?',
@@ -194,7 +213,7 @@ function AuditCard({ tick }) {
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
</div>
{rows.map(e => {
{rows.slice(0, shown).map(e => {
const line = auditLine(e)
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }}>
<div className="grow">
@@ -208,8 +227,10 @@ function AuditCard({ tick }) {
</div>
})}
{meta && !rows.length && <div className="adm-empty">Nothing logged yet.</div>}
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
{(hidden > 0 || meta?.nextBefore) && <div className="row" style={{ marginTop: 10, gap: 10, alignItems: 'center' }}>
<Button size="sm" onClick={more}>Show more</Button>
{meta && <span className="small muted">{fmtNum(Math.min(shown, rows.length))} of {fmtNum(meta.total)}</span>}
</div>}
</div>
}
+68 -1
View File
@@ -9,9 +9,10 @@ import Admin from './Admin.jsx'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] }))
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [], calls: [] }))
vi.mock('../lib/api.js', () => ({
api: path => {
mocks.calls.push(path)
const key = path.split('?')[0]
return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found'))
}
@@ -48,6 +49,7 @@ const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61
beforeEach(() => {
document.body.innerHTML = ''
mocks.sheets.length = 0
mocks.calls.length = 0
mocks.answers = {
'/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 2, lastSync: null, disabled: false }], invite_only: false },
'/api/admin/invites': { invites: [] },
@@ -63,6 +65,71 @@ beforeEach(() => {
})
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
/* The activity log is history, and history grows: one line per sign-in, per failed attempt, per
admin action. Reported as a wall of twenty-five rows pushing the rest of the dashboard off the
screen. It opens folded to the newest ten with the total in the lead line, and one button reveals
the rest — from what is already loaded first, and from the server once that runs out. */
describe('the activity log', () => {
const withLog = (n, extra = {}) => {
mocks.answers['/api/admin/audit'] = {
events: Array.from({ length: n }, (_, i) => ({ id: n - i, ts: Date.now() - i * 60000, ev: 'auth.login.ok', uid: 'u1', name: 'Daniel', ok: true })),
total: n, nextBefore: null, enabled: true, ip_mode: 'off', retention: { days: 90, max: 5000 }, now: Date.now(), ...extra
}
}
const auditCard = page => [...page.querySelectorAll('.card')].find(c => c.textContent.includes('Activity log'))
const auditRows = card => [...card.querySelectorAll('.row.between')].filter(r => r.querySelector('.small.muted'))
const showMore = card => [...card.querySelectorAll('button')].find(b => b.textContent.trim() === 'Show more')
it('opens with the newest ten and reveals the rest on demand', async () => {
withLog(25)
const page = render(<Admin />)
await settle()
const card = auditCard(page)
expect(auditRows(card).length).toBe(10);
expect(card.textContent).toContain('25 events')
expect(card.textContent).toContain('10 of 25')
act(() => showMore(card).click())
await settle()
expect(auditRows(card).length).toBe(20)
expect(card.textContent).toContain('20 of 25')
act(() => showMore(card).click())
await settle()
expect(auditRows(card).length).toBe(25)
// Everything is on screen and nothing is left on the server: the button goes away rather than
// sitting there inviting a click that does nothing.
expect(showMore(card)).toBeFalsy()
})
it('asks the server for the next page once what it has is shown', async () => {
// A page of fifty with more behind it: revealing past the fifty asks for the next page rather
// than sitting on a button that does nothing.
withLog(50, { total: 80, nextBefore: 3 })
const page = render(<Admin />)
await settle()
const card = auditCard(page)
// Four clicks reveal the fifty that were already loaded — and none of them asks the server.
for (let i = 0; i < 4; i++) { act(() => showMore(card).click()); await settle() }
expect(auditRows(card).length).toBe(50)
expect(mocks.calls.some(c => c.includes('before=3'))).toBe(false, 'a page already here is not re-fetched')
expect(showMore(card)).toBeTruthy()
// The fifth has nothing left to reveal, so it goes and gets the next page.
act(() => showMore(card).click())
await settle()
expect(mocks.calls.some(c => c.includes('before=3'))).toBe(true, 'and then it fetches');
})
it('says nothing to show on an empty log, and no button', async () => {
withLog(0)
const page = render(<Admin />)
await settle()
const card = auditCard(page)
expect(card.textContent).toContain('Nothing logged yet.')
expect(showMore(card)).toBeFalsy()
})
})
describe('Admin user drill-down', () => {
it('opens a profile with malformed workout entries and still offers "Disable account"', async () => {
const page = render(<Admin />)
+412 -31
View File
@@ -1,4 +1,19 @@
/* Música — the playlists a profile keeps, and the way to open them in Apple Music.
/* Música — three lists behind one search box: live radio, Spanish podcasts, and the Apple Music
* playlists a profile keeps.
*
* ── Why it is split into tabs at all ───────────────────────────────────────────────────────────
*
* It used to be one column: the radio, then the podcasts, then the playlists. Three lists of twenty
* rows each is a screen you scroll through looking for the thing you already knew you wanted — and
* the thing you wanted was usually at the bottom. So the screen asks first (Radio | Podcasts |
* Playlists) and shows one list at a time, ten rows long, with the search box above it and a
* "show more" under it. Nothing is hidden that cannot be reached in one tap, and nothing else is on
* screen while you are deciding.
*
* The search box searches whatever tab is open, and it searches the *source*, not the page: typing
* "jazz" asks the station directory, and typing "crimen" asks Apple's podcast directory — filtered,
* as always, to Spanish. The rows it returns are the same rows a category shows, so a station found
* by search is starred, played and cached exactly like one found by browsing.
*
* ── Why this is a list of links and not a MusicKit integration ─────────────────────────────────
*
@@ -16,16 +31,18 @@
* artwork and track count so the list looks like a list, and a page that says nothing leaves the
* card showing the name its owner typed — which is why nothing here depends on it.
*/
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { t } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { confirmSheet } from '../sheets.jsx'
import { Button } from '../components/ui.jsx'
import { Button, Segmented, SearchField } 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'
import { PAGE, visible, hasMore, nextShown, hiddenCount } from '../lib/paging.js'
/** A playlist tile: artwork when the public page gave us some, a note when it did not. */
function PlaylistCard({ item, onRemove }) {
@@ -86,6 +103,320 @@ function AddPlaylistSheet({ close }) {
</>
}
/* ---------- radio ----------
*
* 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/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
* thousands are mostly commercial broadcasters that may air ads.
*/
function RadioSection({ q }) {
const radio = useUI(s => s.radio)
const playRadio = useUI(s => s.playRadio)
const toast = useUI(s => s.toast)
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const cfg = useStore(s => s.config)
const addStation = useStore(s => s.addStation)
const removeStation = useStore(s => s.removeStation)
/* The list comes from the server, so two situations have to be told apart from a bug rather than
shown as one: nobody is signed in (guest mode never talks to the api at all), and the api is
older than the app — they ship separately, so a deploy that refreshed `web` and not the api
container leaves a screen whose every request is a 401/404. Both are quiet lines instead of a
toast, and no request is made in either case. */
const staleApi = !!cfg && Array.isArray(cfg.features) && !cfg.features.includes('radio')
const canRadio = !!user && !staleApi
const [genres, setGenres] = useState(null)
const [genre, setGenre] = useState(null)
const [stations, setStations] = useState(null)
const [busy, setBusy] = useState(false)
/* Logos that did not load. The directory is community-run: a station's `favicon` field is
sometimes a homepage rather than an image, which renders as a broken-image icon mid-list. A
row that fails falls back to the same placeholder as a row that never had one. */
const [noArt, setNoArt] = useState(() => new Set())
const [shown, setShown] = useState(PAGE)
const saved = (S.music && S.music.stations) || []
const load = key => {
setBusy(true)
api('/api/radio' + (key ? '?genre=' + encodeURIComponent(key) : ''))
.then(r => {
setGenres(r.genres)
setGenre(r.genre)
setStations(r.stations)
setShown(PAGE)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { if (canRadio && !q) load(null) }, [canRadio])
/* A search replaces the list rather than filtering the twenty rows already on screen: the answer
to "jazz" is every jazz station in the directory, not the jazz stations that happened to be in
the genre you were looking at. Debounced, because every letter is a request. */
useEffect(() => {
if (!canRadio || !q) return
let live = true
setBusy(true)
api('/api/radio?q=' + encodeURIComponent(q))
.then(r => { if (live) { setStations(r.stations); setShown(PAGE) } })
.catch(e => { if (live) toast(e.message) })
.finally(() => { if (live) setBusy(false) })
return () => { live = false }
}, [canRadio, q])
const play = station => {
// Synchronous on purpose: `play()` has to happen inside this tap for iOS to allow it.
if (!playRadio(station)) toast(t('That station is not answering. Try another one.'))
}
const isSaved = station => saved.some(x => x.src === station.src && x.id === station.id)
const row = station => <div key={station.src + ':' + station.id}
className={'mus-rad' + (radio?.station && radio.station.id === station.id ? ' on' : '')}>
<button className="mus-rad-main" onClick={() => play(station)} aria-label={t('Play')}>
{station.image && !noArt.has(station.image)
? <img className="mus-rad-i" src={station.image} alt=""
onError={() => setNoArt(prev => new Set(prev).add(station.image))} />
: <span className="mus-rad-i mus-rad-i-ph"><Icon name="music" /></span>}
<span className="mus-rad-meta">
<span className="mus-rad-n">{station.name}</span>
<span className="mus-rad-s">{[station.detail, station.genre].filter(Boolean).join(' · ')}</span>
</span>
<Icon name={radio?.station && radio.station.id === station.id && radio.playing ? 'pause' : 'play'} className="mus-rad-go" />
</button>
<button className="iconbtn mus-rad-save" onClick={() => isSaved(station) ? removeStation(station.src, station.id) : (addStation(station), toast(t('Saved to your stations')))}
aria-label={isSaved(station) ? t('Remove') : t('Save this station')}>
<Icon name={isSaved(station) ? 'starFill' : 'star'} />
</button>
</div>
const list = stations || []
return <>
<h4 className="sec">{q ? t('Results for “{0}”', q) : t('Radio')}
{stations ? <span className="vh-window"> · {t('{0} stations', stations.length)}</span> : null}</h4>
{!canRadio
? <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{staleApi
? t('Your server has not been updated for the radio yet: it is the server that finds the stations, and this app is newer than it. Restarting it should be enough.')
: t('The radio comes from your server, so it needs a profile: sign in and the stations appear here.')}
</div>
: <>
{!q && <div className="small dim" style={{ margin: '0 2px 8px', lineHeight: 1.45 }}>
{t('These are public radio streams: nothing is downloaded, and the audio goes straight from the station to your phone. The first four of each genre are stations with no advertising at all.')}
</div>}
{!q && <div className="chips" style={{ marginBottom: 10 }}>
{(genres || []).map(g => <button key={g.key}
className={'chip' + (genre === g.key ? ' on' : '')}
onClick={() => load(g.key)}>{g.label}</button>)}
</div>}
{!q && saved.length > 0 && <>
<div className="mus-sub-h">{t('Saved stations')}</div>
{saved.map(st => row(st))}
</>}
{busy && !stations && <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('Loading stations…')}</div>}
{visible(list, shown).map(st => row(st))}
<More list={list} shown={shown} onMore={() => setShown(n => nextShown(n, list.length))} />
{stations && !list.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{q ? t('No results for “{0}”.', q) : t('That station is not answering. Try another one.')}
</div>}
{!q && (radio
? <div className="small dim" style={{ margin: '8px 2px 0' }}>
{radio.playing ? t('Playing {0}', radio.station.name) : t('Paused: {0}', radio.station.name)}
</div>
: <div className="small dim" style={{ margin: '8px 2px 0' }}>{t('Nothing playing. Pick a station below.')}</div>)}
</>}
</>
}
/** The house "show more": ten rows, then ten more, and the button says how many it is hiding. */
function More({ list, shown, onMore }) {
if (!hasMore(list, shown)) return null
return <div style={{ marginTop: 8, display: 'flex', justifyContent: 'center' }}>
<Button size="sm" onClick={onMore}>{t('Show more ({0})', hiddenCount(list, shown))}</Button>
</div>
}
/* ---------- 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({ q }) {
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 [shown, setShown] = useState(PAGE)
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)
setShown(PAGE)
})
.catch(e => toast(e.message))
.finally(() => setBusy(false))
}
useEffect(() => { if (canPodcasts && !q) load(null) }, [canPodcasts])
/* Searching shows the same catalogue a category does, filtered by the same rules — the Spanish
check runs on a search result exactly as it does on a chart entry, which is the whole reason
both go through one function on the server. */
useEffect(() => {
if (!canPodcasts || !q) return
let live = true
setBusy(true)
api('/api/podcasts?q=' + encodeURIComponent(q))
.then(r => { if (live) { setShows(r.shows); setShown(PAGE) } })
.catch(e => { if (live) toast(e.message) })
.finally(() => { if (live) setBusy(false) })
return () => { live = false }
}, [canPodcasts, q])
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>
const list = shows || []
return <>
<h4 className="sec">{q ? t('Results for “{0}”', q) : t('Podcasts')}
{shows ? <span className="vh-window"> · {t('{0} shows', shows.length)}</span> : null}</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>
: <>
{!q && <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>}
{!q && <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>}
{!q && 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>}
{visible(list, shown).map(st => row(st))}
<More list={list} shown={shown} onMore={() => setShown(n => nextShown(n, list.length))} />
{shows && !list.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
{q ? t('No results for “{0}”.', q) : 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('')
// Forty episodes in a sheet is a wall with a scrollbar; ten and "show more" is a list.
const [shown, setShown] = useState(PAGE)
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">
{visible(data.episodes, shown).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>)}
<More list={data.episodes} shown={shown} onMore={() => setShown(n => nextShown(n, data.episodes.length))} />
</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)
@@ -93,6 +424,22 @@ export default function Music() {
const removePlaylist = useStore(s => s.removePlaylist)
const list = (S.music && S.music.playlists) || []
const profile = profileUrl(S.music && S.music.user)
/* Radio first: it is the one that needs no account, no Apple Music, and no decision. */
const [tab, setTab] = useState('radio')
const [q, setQ] = useState('')
/* What the sections actually search on. Four hundred milliseconds: long enough that typing
"entrenamiento" is one request instead of fourteen, short enough that it feels like typing. */
const typed = q.trim()
const query = useDebounced(typed, 400)
/* One letter is not a search: it matches everything, and asking the directory to prove it costs a
request per keystroke for an answer nobody can use. Below two characters the screen keeps
showing what it was showing, which is also what makes the transition into a search calm. */
const searching = query.length >= 2
// The playlists are local links, so their search is local too — no request, no debounce needed.
const playlists = searching
? list.filter(p => [p.name, p.curator].filter(Boolean).join(' ').toLowerCase().includes(query.toLowerCase()))
: list
const [shownPlaylists, setShownPlaylists] = useState(PAGE)
const askRemove = item => confirmSheet({
title: t('Remove “{0}”?', item.name),
@@ -101,43 +448,77 @@ export default function Music() {
onConfirm: () => removePlaylist(item.id)
})
const placeholder = tab === 'radio' ? t('Search stations…') : tab === 'podcasts' ? t('Search podcasts…') : t('Search playlists…')
return <>
<div className="hdr">
<div style={{ flex: 1 }}>
<h1>{t('Music')}</h1>
<div className="sub">{list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}</div>
<div className="sub">{tab === 'radio' ? t('Live radio, nothing downloaded')
: tab === 'podcasts' ? t('Spanish podcasts, remembered where you left off')
: list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}</div>
</div>
<button className="iconbtn" onClick={() => openSheet(close => <AddPlaylistSheet close={close} />)} aria-label={t('Add a playlist')}><Icon name="plus" /></button>
<button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Settings')}><Icon name="gear" /></button>
</div>
{profile
? <a className="card mus-profile" href={profile} target="_blank" rel="noopener noreferrer">
<Icon name="personCircle" className="mus-profile-i" />
<span className="mus-meta">
<span className="mus-name">@{S.music.user}</span>
<span className="mus-sub">{t('Your public Apple Music profile')}</span>
</span>
<Icon name="chevronRight" className="mus-go" />
</a>
: <div className="card mus-hint">
<Icon name="music" className="mus-hint-i" />
<div>
<div className="mus-name">{t('Add your Apple Music profile')}</div>
<div className="small dim" style={{ lineHeight: 1.45 }}>
{t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')}
</div>
</div>
</div>}
<div style={{ marginBottom: 10 }}>
<SearchField value={q} onChange={e => setQ(e.target.value)} onClear={() => setQ('')} placeholder={placeholder} />
</div>
<Segmented className="mus-tabs" options={[
{ value: 'radio', label: t('Radio'), icon: 'music' },
{ value: 'podcasts', label: t('Podcasts'), icon: 'personCircle' },
{ value: 'playlists', label: t('Playlists'), icon: 'list' }
]} value={tab} onChange={v => { setTab(v); setQ('') }} />
{list.length === 0
? <div className="empty">
<div className="ico"><Icon name="music" /></div>
{t('No playlists yet.')}<br />
<span className="small dim">{t('Add one from the + above.')}</span>
</div>
: list.map(item => <PlaylistCard key={item.id} item={item} onRemove={() => askRemove(item)} />)}
{/* One list at a time. Switching tabs clears the search box, because a query typed for the
stations ("jazz") means nothing for the playlists, and a box that keeps it looks stuck. */}
{tab === 'radio' && <RadioSection q={searching ? query : ''} />}
{tab === 'podcasts' && <PodcastSection q={searching ? query : ''} />}
{tab === 'playlists' && <>
{profile
? <a className="card mus-profile" href={profile} target="_blank" rel="noopener noreferrer">
<Icon name="personCircle" className="mus-profile-i" />
<span className="mus-meta">
<span className="mus-name">@{S.music.user}</span>
<span className="mus-sub">{t('Your public Apple Music profile')}</span>
</span>
<Icon name="chevronRight" className="mus-go" />
</a>
: <div className="card mus-hint">
<Icon name="music" className="mus-hint-i" />
<div>
<div className="mus-name">{t('Add your Apple Music profile')}</div>
<div className="small dim" style={{ lineHeight: 1.45 }}>
{t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')}
</div>
</div>
</div>}
<h4 className="sec">{searching ? t('Results for “{0}”', query) : t('Playlists')}
{playlists.length ? <span className="vh-window"> · {t('{0} playlists', playlists.length)}</span> : null}</h4>
{playlists.length === 0
? (searching
? <div className="small dim" style={{ margin: '0 2px 10px' }}>{t('No results for “{0}”.', query)}</div>
: <div className="empty">
<div className="ico"><Icon name="music" /></div>
{t('No playlists yet.')}<br />
<span className="small dim">{t('Add one from the + above.')}</span>
</div>)
: visible(playlists, shownPlaylists).map(item => <PlaylistCard key={item.id} item={item} onRemove={() => askRemove(item)} />)}
<More list={playlists} shown={shownPlaylists} onMore={() => setShownPlaylists(n => nextShown(n, playlists.length))} />
</>}
<div style={{ height: 16 }} />
</>
}
/** A value, delayed: the search box types on every keystroke and the server should not hear them all. */
function useDebounced(value, ms) {
const [slow, setSlow] = useState(value)
useEffect(() => {
const id = setTimeout(() => setSlow(value), ms)
return () => clearTimeout(id)
}, [value, ms])
return slow
}
+349 -2
View File
@@ -7,12 +7,35 @@ import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
const nav = vi.fn()
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/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)
const playFile = vi.fn(() => true)
vi.mock('../lib/player.js', () => ({
playStream: (...a) => playStream(...a),
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')
const { default: Modals } = await import('../components/Modals.jsx')
@@ -23,19 +46,65 @@ let host, root
beforeEach(() => {
globalThis.IS_REACT_ACT_ENVIRONMENT = true
nav.mockClear()
/* The screen now mounts the radio section too, and that one asks the server for the genre list
as soon as it appears. Every test here starts from a server that answers with nothing, and a
test that cares about a request sets its own implementation. */
api.mockReset()
api.mockResolvedValue({ genres: [], genre: null, stations: [] })
playStream.mockClear()
playFile.mockClear()
/* The UI store is module-level, so a sheet left open by one test is still open for the next one:
`sheets` is part of the state that has to be reset, not just the player. */
act(() => { useUI.setState({ radio: null, pod: null, sheets: [] }) })
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] } } }))
useStore.setState(s => ({
S: { ...s.S, music: { user: '', playlists: [] } },
// The radio section is server-backed: it draws nothing for a guest or against an api older
// than the app. Every test here starts signed in, on a server that answers.
user: { id: 'u1', name: 'Test' },
config: null
}))
})
afterEach(() => { act(() => root.unmount()); host.remove() })
/* `#modal-root` is created once by Modals and lives on the body, so a sheet left open by one test
is still in the DOM for the next one. */
afterEach(() => { act(() => root.unmount()); host.remove(); document.getElementById('modal-root')?.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 />) }) }
/* The screen shows one list at a time now, so a test says which one it means. */
const openTab = async name => {
const btn = [...host.querySelectorAll('.seg button')].find(b => b.textContent.includes(name))
act(() => { btn.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => { await Promise.resolve() })
}
/* Typing in a search box that is debounced by 400 ms, and waiting it out. */
const type = async text => {
const input = host.querySelector('.searchf input')
act(() => {
const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set
set.call(input, text)
input.dispatchEvent(new Event('input', { bubbles: true }))
})
await act(async () => { await new Promise(r => setTimeout(r, 450)) })
}
const links = () => [...host.querySelectorAll('a')]
describe('Música', () => {
it('says how to get a playlist when there are none', async () => {
await mount()
await openTab('Playlists')
expect(host.textContent).toContain('No playlists yet.')
expect(host.textContent).toContain('Add your Apple Music profile')
expect(links().length).toBe(0)
@@ -44,6 +113,7 @@ describe('Música', () => {
it('makes each playlist a link to its own Apple Music page', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [item()] } } }))
await mount()
await openTab('Playlists')
const [profile, playlist] = links()
expect(profile.getAttribute('href')).toBe('https://music.apple.com/profile/ana')
expect(playlist.getAttribute('href')).toBe('https://music.apple.com/us/playlist/leg-day/pl.aaa')
@@ -58,6 +128,7 @@ describe('Música', () => {
it('removes one without touching the others', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day' })] } } }))
await mount()
await openTab('Playlists')
expect(host.textContent).toContain('Leg Day')
act(() => { useStore.getState().removePlaylist('pl.aaa') })
await act(async () => {})
@@ -71,6 +142,7 @@ describe('Música', () => {
it('adds what the form was given, all the way through the sheet', async () => {
api.mockResolvedValue({ ok: true, meta: { title: 'Leg Day', artwork: 'https://is1-ssl.mzstatic.com/x/600x600bb.jpg', tracks: 42, curator: 'Ana' } })
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Playlists')
act(() => { [...document.querySelectorAll('button')].find(b => b.getAttribute('aria-label') === 'Add a playlist').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
const fields = [...document.querySelectorAll('#modal-root input')]
expect(fields.length).toBe(2) // the link, then the optional name
@@ -92,12 +164,287 @@ describe('Música', () => {
expect(host.textContent).toContain('Leg Day')
})
/* Radio lives on this screen, and its one non-obvious rule is that the row *is* the play button:
iOS only lets audio start inside the tap that asked for it, so the stream URL arrives with the
station and nothing asynchronous may sit between the finger and the play(). A refactor that
moved the play behind a fetch would look identical and play nothing on an iPhone. */
it('plays a station from its row, inside the same tap', async () => {
const beat = {
src: 'soma', id: 'beatblender', name: 'Beat Blender', genre: 'Electronic',
detail: 'A late night blend', image: null, url: 'https://ice2.somafm.com/beatblender-128-mp3'
}
api.mockResolvedValue({ genres: [{ key: 'techno', label: 'Techno / House' }], genre: 'techno', stations: [beat] })
await mount()
const row = host.querySelector('.mus-rad-main')
expect(row.textContent).toContain('Beat Blender')
expect(row.textContent).toContain('A late night blend · Electronic')
// The chips came from the server too, so the screen never hard-codes the genres it offers.
expect([...host.querySelectorAll('.chips .chip')].map(c => c.textContent)).toEqual(['Techno / House'])
act(() => { row.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(playStream).toHaveBeenCalledWith(beat.url, 1)
expect(useUI.getState().radio.station.id).toBe('beatblender')
expect(useUI.getState().radio.playing).toBe(true)
})
/* The star, all the way to the store and back on screen. It was a no-op for a while: the store
method *returned* the new `music` object and `update()` only reads mutations, so the toast
appeared, the list stayed empty, and nothing said why. */
it('saves a station with the star, and it comes back as a saved row', async () => {
const beat = {
src: 'soma', id: 'beatblender', name: 'Beat Blender', genre: 'Electronic',
detail: 'A late night blend', image: null, url: 'https://ice2.somafm.com/beatblender-128-mp3'
}
api.mockResolvedValue({ genres: [], genre: 'workout', stations: [beat] })
await mount()
const star = host.querySelector('.mus-rad-save')
expect(star.getAttribute('aria-label')).toBe('Save this station')
act(() => { star.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useStore.getState().S.music.stations.map(s => s.id)).toEqual(['beatblender'])
expect(host.textContent).toContain('Saved stations')
// Starred, so the same button now offers to take it away — and the row is on screen twice:
// once in the saved block, once in the genre list.
expect(host.querySelectorAll('.mus-rad-save')[0].getAttribute('aria-label')).toBe('Remove')
expect(host.querySelectorAll('.mus-rad').length).toBe(2)
act(() => { host.querySelectorAll('.mus-rad-save')[0].dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
expect(useStore.getState().S.music.stations).toEqual([])
expect(host.textContent).not.toContain('Saved stations')
})
/* Two situations that are not bugs, and used to look like one: nothing signed in (guest mode
never talks to the api), and an api older than the app — they ship separately, so a deploy that
refreshed the frontend and not the api container is a screen whose every request fails. Both
are a quiet line, and neither makes a request. */
it('tells a guest where the radio comes from, without asking the server', async () => {
useStore.setState({ user: null })
await mount()
expect(host.textContent).toContain('The radio comes from your server, so it needs a profile')
expect(api).not.toHaveBeenCalled()
})
it('says the server is older when it does not offer the radio yet', async () => {
useStore.setState({ config: { features: ['vitals', 'insights'] } })
await mount()
expect(host.textContent).toContain('Your server has not been updated for the radio yet')
expect(api).not.toHaveBeenCalled()
})
it('saving the same link twice does not duplicate the card', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] } } }))
act(() => { useStore.getState().addPlaylist(item()) })
act(() => { useStore.getState().addPlaylist(item({ name: 'Leg Day (again)' })) })
await mount()
await openTab('Playlists')
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()
await openTab('Podcasts')
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()
await openTab('Podcasts')
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 /></>) })
await openTab('Podcasts')
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 /></>) })
await openTab('Podcasts')
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()
await openTab('Podcasts')
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()
await openTab('Podcasts')
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)
})
/* ---------- one list at a time, ten rows at a time, and a search box ---------- */
const station = i => ({
src: 'rb', id: 's' + i, name: 'Emisora ' + i, genre: 'jazz', detail: 'Argentina · MP3',
url: 'https://stream.example.com/' + i, image: null
})
const moreBtn = () => [...host.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more'))
it('shows one list at a time, and the tab is what decides which', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1)] }, podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
expect(host.textContent).toContain('Emisora 1')
expect(host.querySelectorAll('.mus-rad')).toHaveLength(1)
await openTab('Podcasts')
// The stations are gone, not merely below the fold: that was the whole complaint about this
// screen — three long lists in one column, with what you wanted at the bottom.
expect(host.textContent).not.toContain('Emisora 1')
expect(host.textContent).toContain('Tiene Sentido')
expect(api.mock.calls.some(c => String(c[0]).startsWith('/api/podcasts'))).toBe(true)
})
it('shows ten rows and says how many it is hiding', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: Array.from({ length: 25 }, (_, i) => station(i)) } })
await mount()
expect(host.querySelectorAll('.mus-rad')).toHaveLength(10)
expect(host.textContent).toContain('Emisora 9')
expect(host.textContent).not.toContain('Emisora 10')
expect(moreBtn().textContent).toBe('Show more (15)')
act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(host.querySelectorAll('.mus-rad')).toHaveLength(20)
expect(moreBtn().textContent).toBe('Show more (5)')
act(() => moreBtn().dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(host.querySelectorAll('.mus-rad')).toHaveLength(25)
// Nothing left to reveal, so the button is gone rather than sitting there doing nothing.
expect(moreBtn()).toBeUndefined()
})
it('pages the episodes of a show too, because forty rows is a wall', async () => {
const episodes = Array.from({ length: 23 }, (_, i) => ({ ...ep({ id: 'ep-' + i, title: 'Episodio ' + i }) }))
stubApi({
podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] },
show: { feed: 'https://a.example.com/feed', spanish: true, show: { title: 'Tiene Sentido' }, episodes }
})
await act(async () => { root.render(<><Music /><Modals /></>) })
await openTab('Podcasts')
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 sheet = document.querySelector('#modal-root')
expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(10)
const more = [...sheet.querySelectorAll('button')].find(b => b.textContent.startsWith('Show more'))
expect(more.textContent).toBe('Show more (13)')
act(() => more.dispatchEvent(new MouseEvent('click', { bubbles: true })))
await act(async () => {})
expect(sheet.querySelectorAll('.pod-ep')).toHaveLength(20)
})
it('searches the station directory, not the page it is showing', async () => {
stubApi({ radio: { genres: [], genre: 'workout', stations: [station(1), station(2)] } })
await mount()
expect(host.querySelectorAll('.mus-rad')).toHaveLength(2)
api.mockImplementation(path => {
if (String(path).startsWith('/api/radio?q=')) return Promise.resolve({ ok: true, query: 'jazz', stations: [station(7)] })
return Promise.resolve({ ok: true })
})
await type('jazz')
// It asked the server for "jazz" — the answer is every jazz station in the directory, not the
// jazz stations that happened to be in the genre on screen.
expect(api.mock.calls.some(c => c[0] === '/api/radio?q=jazz')).toBe(true)
expect(host.textContent).toContain('Results for “jazz”')
expect(host.textContent).toContain('Emisora 7')
expect(host.textContent).not.toContain('Emisora 1')
// The genre chips step aside: they are for browsing, and this is not browsing.
expect(host.querySelectorAll('.chips .chip')).toHaveLength(0)
})
it('searches the podcast directory the same way, and says when there is nothing', async () => {
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Podcasts')
api.mockImplementation(path => {
if (String(path).startsWith('/api/podcasts?q=')) return Promise.resolve({ ok: true, query: 'zzz', shows: [] })
return Promise.resolve({ ok: true })
})
await type('zzz')
expect(api.mock.calls.some(c => c[0] === '/api/podcasts?q=zzz')).toBe(true)
expect(host.textContent).toContain('No results for “zzz”.')
// A query too short to search is not sent at all: one letter matches everything.
api.mockClear()
await type('z')
expect(api).not.toHaveBeenCalled()
})
it('searches the playlists locally, since they are links and not a directory', async () => {
useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day', curator: null })] } } }))
stubApi({ podcasts: { categories: [cat], category: 'fitness', shows: [showRow()] } })
await mount()
await openTab('Playlists')
expect(host.querySelectorAll('.mus-card')).toHaveLength(2)
await type('push')
expect(host.querySelectorAll('.mus-card')).toHaveLength(1)
expect(host.textContent).toContain('Push Day')
expect(host.textContent).not.toContain('Leg Day')
// No request: this list is in the profile already.
expect(api.mock.calls.some(c => String(c[0]).includes('música'))).toBe(false)
await type('nada de nada')
expect(host.querySelectorAll('.mus-card')).toHaveLength(0)
expect(host.textContent).toContain('No results for “nada de nada”.')
})
})
+8
View File
@@ -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 &amp; public config' },
auth: { title: 'Auth', side: 'Passkeys &amp; sessions' },
pairing: { title: 'Pairing', side: 'Connect the mobile app' },
data: { title: 'Data', side: 'State sync' },
health: { title: 'Health', side: 'Apple Health metrics &amp; the second opinion' },
music: { title: 'Música', side: 'Playlists, radio &amp; podcasts' },
push: { title: 'Push', side: 'Notifications &amp; rest timer' },
activity: { title: 'Activity', side: 'Live presence' },
admin: { title: 'Admin', side: 'Users, invites, audit log' }
+669 -2
View File
@@ -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 &amp; 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 &amp; the second opinion</span></a>
<a class="side-link" href="#music"><b>Música</b><span>Playlists, radio &amp; podcasts</span></a>
<a class="side-link" href="#push"><b>Push</b><span>Notifications &amp; 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>38 endpoints</span>
<span>43 endpoints</span>
<span>AGPL-3.0-or-later</span>
</p>
@@ -309,6 +311,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
</summary>
<div class="ep-body">
<p>The flags the login screen needs before anyone is signed in. Both reflect environment variables on the server (<code>INVITE_ONLY</code>, <code>ALLOW_GUEST</code>).</p>
<p><code>features</code> is the one that exists because the app and the api are deployed separately: the frontend is rebuilt from source on every deploy while the api's code lives inside its container, so a deploy can leave a new screen on top of an older api. Naming what this server can do lets a screen say &quot;this server is older than the app&quot; instead of showing a request that quietly fails — or, worse, a number that never moves.</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>Public — no authentication required.</span></p>
@@ -316,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 }</span></span>
<span class="p-desc">Instance flags.<span class="r-sig">{ invite_only: boolean, allow_guest: boolean, features: (&quot;vitals&quot; | &quot;vitals.hours&quot; | &quot;vitals.receipt&quot; | &quot;music.lookup&quot; | &quot;radio&quot; | &quot;podcasts&quot; | &quot;insights&quot;)[], coach: object }</span></span>
</div>
</div>
</div>
@@ -714,6 +717,516 @@ 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 &quot;steps today&quot; 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 &lt;token&gt;</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&ndash;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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &quot;these numbers look wrong, start this one over&quot;. 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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &quot;what did the hours look like&quot; 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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;token&gt;</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">&quot;1&quot;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &quot;bad shoulder&quot; 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 &quot;bad shoulder&quot; 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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;ingest key&gt;</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 &lt;token&gt;</code> from mobile-app pairing.</span></p>
<p class="ep-h">Request body <span class="p-hint">(JSON)</span></p>
<pre><code>{
&quot;data&quot;: {
&quot;metrics&quot;: [
{
&quot;name&quot;: &quot;step_count&quot;,
&quot;units&quot;: &quot;count&quot;,
&quot;data&quot;: [
{
&quot;qty&quot;: 12481,
&quot;date&quot;: &quot;2026-09-03 00:00:00 +0200&quot;
}
]
}
]
}
}</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>{&quot;error&quot;:&quot;not a Health Auto Export JSON export&quot;}</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>{&quot;error&quot;:&quot;invalid ingest key&quot;}</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>{&quot;error&quot;:&quot;body too large&quot;}</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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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>&lt;audio&gt;</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><b><code>?q=</code> searches instead of browsing</b>, and it is the same route on purpose: the screen has one list, and what fills it changes. A query is matched against the curated channels and Radio Paradise mixes locally, and the directory is asked by name — ordered by how many people listen, then re-ordered so a station <i>called</i> &quot;Jazz 24&quot; comes before one with &quot;jazz&quot; buried in a forty-character marketing name. A query shorter than two characters is not a search and answers an empty list without asking anybody.</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 &lt;token&gt;</code> from mobile-app pairing.</span></p>
<p class="ep-h">Query parameters</p><div class="ptab">
<div class="prow">
<span class="p-name">q</span>
<span class="p-type">string <span class="p-hint">(&le; 60 chars)</span></span>
<span class="p-desc">A name search. Two characters or more; when present, <code>genre</code> is ignored.</span>
</div>
<div class="prow">
<span class="p-name">genre</span>
<span class="p-type">&quot;workout&quot; | &quot;techno&quot; | &quot;rnb&quot; | &quot;latin&quot; | &quot;hiphop&quot; | &quot;reggae&quot; | &quot;chill&quot; | &quot;jazz&quot; | &quot;rock&quot; | &quot;electronic&quot;</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, query: 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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;token&gt;</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">&quot;soma&quot; | &quot;paradise&quot;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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>&lt;language&gt;</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 &lt;token&gt;</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">&quot;fitness&quot; | &quot;sports&quot; | &quot;comedy&quot; | &quot;news&quot; | &quot;history&quot; | &quot;truecrime&quot; | &quot;science&quot; | &quot;tech&quot; | &quot;society&quot; | &quot;business&quot; | &quot;fiction&quot; | &quot;education&quot; | &quot;music&quot; | &quot;leisure&quot;</span>
<span class="p-desc">Category key. Missing or unrecognised falls back to <code>fitness</code>.</span>
</div>
<div class="prow">
<span class="p-name">q</span>
<span class="p-type">string <span class="p-hint">(&le; 80 chars)</span></span>
<span class="p-desc">A search by name. Two characters or more; when present, <code>category</code> is ignored and the same Spanish-language check runs on the results as on a category's chart entries — a search is not a second, weaker way into the catalogue.</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, query: 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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;token&gt;</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">(&le; 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">(&le; 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>{&quot;error&quot;:&quot;not signed in&quot;}</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 &lt;token&gt;</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>{&quot;error&quot;:&quot;not signed in&quot;}</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>
@@ -1384,6 +1897,160 @@ 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 &quot;kept, unconfirmed&quot; and not a &quot;not Spanish&quot;.</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>
<span class="ep-chev" aria-hidden="true"></span>
<span class="ep-sum">One row in the Radio section: everything the screen needs to draw the station <i>and</i> to start playing it, because the <code>play()</code> has to happen inside the tap that chose it.</span>
</summary>
<div class="ep-body">
<div class="ptab">
<div class="prow">
<span class="p-name">src<em class="p-req" title="required">required</em></span>
<span class="p-type">&quot;soma&quot; | &quot;paradise&quot; | &quot;rb&quot;</span>
<span class="p-desc">Where it came from — <code>soma</code> (SomaFM, commercial-free), <code>paradise</code> (Radio Paradise, four hand-mixed channels) or <code>rb</code> (the public radio-browser directory). <code>src</code> + <code>id</code> is what <code>GET /api/radio/now</code> is asked about, and only the first two answer.</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 source.</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">genre</span>
<span class="p-type">string</span>
<span class="p-desc">Free-form tags or the channel's own genre.</span>
</div>
<div class="prow">
<span class="p-name">detail</span>
<span class="p-type">string</span>
<span class="p-desc">The second line — country, codec, bitrate for the directory, or &quot;no advertising&quot; for the curated ones.</span>
</div>
<div class="prow">
<span class="p-name">image</span>
<span class="p-type">string</span>
<span class="p-desc">HTTPS logo</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 stream, already resolved to an HTTPS URL a browser plays natively. For SomaFM this comes from the channel's own <code>.pls</code> rather than a guessed bitrate URL.</span>
</div>
</div>
</div>
</details>
<details class="ep sch" id="schema-SessionUser">
<summary>
<span class="sch-name"><code>SessionUser</code></span>