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
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.
This commit is contained in:
1 parent
e1d28f971d
commit
48cf976635
22 files changed
+1662
-15
No files matched your search
@@ -1,5 +1,45 @@
|
||||
# Changelog
|
||||
|
||||
## 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** (`lib/radio-player.js`), 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
|
||||
|
||||
@@ -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).
|
||||
```
|
||||
|
||||
## Commands
|
||||
@@ -89,6 +90,10 @@ would catch is a change nothing checks here.
|
||||
stores numbers; this decides how they read.
|
||||
- `music.js` — reading and validating the Apple Music share links a profile keeps. Apple has no
|
||||
API for somebody else's public playlists, so a playlist here is a link, not an integration.
|
||||
- `radio-player.js` — the single `<audio>` element and Media Session, held **outside React** on
|
||||
purpose: an element owned by a component unmounts with it, which is how a player stops when
|
||||
somebody changes screens. `play()` is called synchronously from the tap because iOS only allows
|
||||
audio to start inside a gesture — see `docs/RADIO.md` before touching any of it.
|
||||
- `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 +127,15 @@ 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` and `radio.js` sit beside `server.js` as the modules with real logic on the
|
||||
API side: HAE parsing, the idempotent merge (the reason a 5-minute automation does not double a day
|
||||
of steps) and retention in the first; reading what a public Apple Music page says about itself,
|
||||
behind a host allowlist, in the second; the live-station directory — SomaFM, Radio Paradise and
|
||||
radio-browser — in the third, which is also where the rule lives that **audio is never proxied**: the
|
||||
api hands out a resolved stream URL and the phone talks to the station directly. `server.js` owns the
|
||||
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`)
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ 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)
|
||||
- ❤️ **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
|
||||
|
||||
+2
-2
@@ -55,8 +55,8 @@ 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.
|
||||
COPY server.js push-messages.js verify-error.js vitals.js music.js radio.js jev.js insights.js ./
|
||||
COPY coach ./coach
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
|
||||
@@ -88,6 +88,11 @@ 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, and the live radio
|
||||
station directory. Audio is never proxied by this server: the list carries resolved stream
|
||||
URLs and the phone talks to the station directly.
|
||||
- name: admin
|
||||
description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`)
|
||||
|
||||
@@ -909,6 +914,158 @@ 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.
|
||||
parameters:
|
||||
- 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. }
|
||||
label: { type: string, description: That genre's human label. }
|
||||
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/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 +1784,42 @@ components:
|
||||
properties:
|
||||
ok: { type: boolean, const: true }
|
||||
|
||||
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.
|
||||
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
/* 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;
|
||||
|
||||
/* 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 []; }
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------- 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;
|
||||
}
|
||||
@@ -21,6 +21,7 @@ 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 } from './radio.js';
|
||||
import { jevConfig, jevEndpoint, stateHash, insightFreshness, budgetFor } from './jev.js';
|
||||
import {
|
||||
readInsight, clearInsight, runInsight, stateFor, summarizeState, endpointHost
|
||||
@@ -133,6 +134,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 +1277,30 @@ 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 key = new URL(req.url, 'http://x').searchParams.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) });
|
||||
},
|
||||
|
||||
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
|
||||
|
||||
'POST /api/push/subscribe': async (req, res) => {
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
/* 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
|
||||
} 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);
|
||||
});
|
||||
@@ -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/);
|
||||
}
|
||||
});
|
||||
@@ -159,6 +159,21 @@ 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 fine with the phone locked: **Safari and Chrome keep the audio alive
|
||||
underneath the page**, and Media Session puts the station and its controls on the lock screen. The
|
||||
packaged shells are a different story, and it is a config gap rather than a code one:
|
||||
|
||||
- **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 **radio in a packaged build stops when the screen locks** — install the PWA
|
||||
instead (Add to Home Screen) if that matters, which is the recommended path here anyway.
|
||||
|
||||
### Release notes for maintainers
|
||||
|
||||
- Bump `versionName`/`versionCode` in `android/app/build.gradle` per release; keep them in
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
# 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
|
||||
|
||||
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/radio-player.js`, **outside React**, as a
|
||||
module-level singleton. 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
|
||||
|
||||
**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.
|
||||
|
||||
## 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.
|
||||
@@ -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 RadioBar from './components/RadioBar.jsx'
|
||||
import TimerFlash from './components/TimerFlash.jsx'
|
||||
import Login from './views/Login.jsx'
|
||||
import MobileOnboarding from './views/MobileOnboarding.jsx'
|
||||
@@ -216,6 +217,9 @@ function Shell() {
|
||||
{/* The chat owns the bottom of the screen: its composer sits where the tabs would be. */}
|
||||
{loc.pathname !== '/coach' && <TabBar onStart={startFlow} />}
|
||||
<RestTimer />
|
||||
{/* The radio lives here, not in the Música screen: a player inside a route is unmounted when
|
||||
somebody navigates away, and that is how music stops mid-set. */}
|
||||
<RadioBar />
|
||||
<Modals />
|
||||
<Toast />
|
||||
<TimerFlash />
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/* The radio bar: one line above the tab bar, while something is playing.
|
||||
*
|
||||
* It follows the rest timer's shape on purpose — same place, same glass, same slide-up — because a
|
||||
* second floating bar with its own look would read as a second app. What it adds is the station,
|
||||
* what the station says it is playing, and a pause button.
|
||||
*
|
||||
* The `<audio>` element is *not* here: it lives in lib/radio-player.js, outside React, so that
|
||||
* changing screens cannot unmount it and stop the music. This component reads the store, draws the
|
||||
* line, and asks it to poll the station for what is playing.
|
||||
*/
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import Icon from './Icon.jsx'
|
||||
|
||||
/* How often the station is asked what it is playing.
|
||||
*
|
||||
* Forty-five seconds: long enough to be polite to two community services that run on donations,
|
||||
* short enough that the line is usually right by the time a song ends. Not zero — a station's
|
||||
* current track is the thing that makes a radio feel alive — and not per second, which would be
|
||||
* abusing somebody else's bandwidth for a caption.
|
||||
*
|
||||
* While the screen is locked iOS suspends these timers, so the line simply stops moving and the
|
||||
* music keeps playing. When the person looks again the next tick fixes it. */
|
||||
const NOW_EVERY_MS = 45000
|
||||
|
||||
export default function RadioBar() {
|
||||
const radio = useUI(s => s.radio)
|
||||
const { toggleRadio, stopRadio, setRadioNow } = useUI()
|
||||
const station = radio?.station
|
||||
/* A cover that did not load. A directory station's "logo" is sometimes a homepage URL rather than
|
||||
an image, and a broken image in the bar is worse than the placeholder — so whatever failed is
|
||||
remembered and never asked for twice. */
|
||||
const [noArt, setNoArt] = useState(null)
|
||||
|
||||
// Poll for what is playing, only for the sources that publish it (the api answers null for the
|
||||
// rest, which costs one small request and shows nothing).
|
||||
useEffect(() => {
|
||||
if (!radio?.playing || !station) return
|
||||
let live = true
|
||||
const ask = () => api('/api/radio/now?src=' + encodeURIComponent(station.src) + '&id=' + encodeURIComponent(station.id))
|
||||
.then(r => { if (live && r?.now) setRadioNow(r.now) })
|
||||
.catch(() => {})
|
||||
ask()
|
||||
const id = setInterval(ask, NOW_EVERY_MS)
|
||||
return () => { live = false; clearInterval(id) }
|
||||
}, [radio?.playing, station?.src, station?.id])
|
||||
|
||||
// The page makes room for the bar while it is there, the same class trick the rest timer uses.
|
||||
useEffect(() => {
|
||||
document.body.classList.toggle('radioing', !!radio)
|
||||
return () => document.body.classList.remove('radioing')
|
||||
}, [!!radio])
|
||||
|
||||
if (!radio) return null
|
||||
const now = radio.now
|
||||
const cover = now?.cover || station.image || null
|
||||
const line = now ? [now.artist, now.title].filter(Boolean).join(' · ') : (station.detail || station.genre || t('Live radio'))
|
||||
|
||||
return <div id="radio">
|
||||
{cover && cover !== noArt
|
||||
? <img className="rad-cover" src={cover} alt="" onError={() => setNoArt(cover)} />
|
||||
: <span className="rad-cover rad-cover-ph"><Icon name="music" /></span>}
|
||||
<span className="rad-meta">
|
||||
<span className="rad-name">{station.name}</span>
|
||||
<span className="rad-now">{line}</span>
|
||||
</span>
|
||||
<button className="iconbtn rad-btn" onClick={toggleRadio}
|
||||
aria-label={radio.playing ? t('Pause') : t('Play')}>
|
||||
<Icon name={radio.playing ? 'pause' : 'play'} />
|
||||
</button>
|
||||
<button className="iconbtn rad-btn" onClick={stopRadio} aria-label={t('Stop')}>
|
||||
<Icon name="xmark" />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// @vitest-environment happy-dom
|
||||
/* The radio bar, and the two things about it that are easy to get wrong and invisible when wrong.
|
||||
*
|
||||
* One: it has to disappear completely when nothing is playing — a bar that renders empty would sit
|
||||
* over the tab bar and eat taps. Two: the pause button has to *pause*, not stop: stopping drops the
|
||||
* station, and the whole point of listening while training is that the same station is still there
|
||||
* after the rest.
|
||||
*
|
||||
* The `<audio>` element itself lives in lib/radio-player.js, outside React (see the comment there),
|
||||
* so it is mocked here — this file is about what the bar draws and what it asks the store to do. */
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
|
||||
const api = vi.fn()
|
||||
vi.mock('../lib/api.js', () => ({ api: (...a) => api(...a) }))
|
||||
const playStream = vi.fn(() => true)
|
||||
vi.mock('../lib/radio-player.js', () => ({
|
||||
playStream: (...a) => playStream(...a),
|
||||
pauseStream: vi.fn(),
|
||||
setStreamVolume: vi.fn(),
|
||||
setMediaSession: vi.fn(),
|
||||
clearMediaSession: vi.fn()
|
||||
}))
|
||||
|
||||
const { default: RadioBar } = await import('./RadioBar.jsx')
|
||||
|
||||
const station = (over = {}) => ({
|
||||
src: 'somafm', id: 'beatblender', name: 'Beat Blender',
|
||||
detail: 'A late night blend', genre: 'Electronic',
|
||||
url: 'https://ice2.somafm.com/beatblender-128-mp3', image: null, ...over
|
||||
})
|
||||
|
||||
let host, root
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
api.mockReset()
|
||||
api.mockResolvedValue({ ok: true, now: null })
|
||||
playStream.mockClear()
|
||||
host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
|
||||
act(() => { useUI.setState({ radio: null }) })
|
||||
})
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
host.remove()
|
||||
document.body.classList.remove('radioing')
|
||||
})
|
||||
|
||||
const mount = async () => { await act(async () => { root.render(<RadioBar />) }) }
|
||||
const btn = label => [...host.querySelectorAll('#radio button')].find(b => b.getAttribute('aria-label') === label)
|
||||
|
||||
describe('the radio bar', () => {
|
||||
it('draws nothing at all before something is playing', async () => {
|
||||
await mount()
|
||||
expect(host.querySelector('#radio')).toBe(null)
|
||||
expect(document.body.classList.contains('radioing')).toBe(false)
|
||||
})
|
||||
|
||||
it('names the station and what it says it is playing', async () => {
|
||||
api.mockResolvedValue({ ok: true, now: { artist: 'The Orb', title: 'Little Fluffy Clouds' } })
|
||||
act(() => { useUI.getState().playRadio(station()) })
|
||||
await mount()
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
|
||||
expect(host.querySelector('.rad-now').textContent).toBe('The Orb · Little Fluffy Clouds')
|
||||
// The page makes room for the bar, the same class trick the rest timer uses.
|
||||
expect(document.body.classList.contains('radioing')).toBe(true)
|
||||
// And it asked the station what is playing, instead of inventing a caption.
|
||||
expect(api.mock.calls[0][0]).toBe('/api/radio/now?src=somafm&id=beatblender')
|
||||
})
|
||||
|
||||
it('falls back to what the station is when it publishes no track', async () => {
|
||||
act(() => { useUI.getState().playRadio(station({ genre: 'Techno' })) })
|
||||
await mount()
|
||||
await act(async () => { await Promise.resolve() })
|
||||
expect(host.querySelector('.rad-now').textContent).toBe('A late night blend')
|
||||
})
|
||||
|
||||
it('pause keeps the station, so the same one is still there after the rest', async () => {
|
||||
act(() => { useUI.getState().playRadio(station()) })
|
||||
await mount()
|
||||
act(() => { btn('Pause').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
expect(useUI.getState().radio.playing).toBe(false)
|
||||
expect(useUI.getState().radio.station.id).toBe('beatblender')
|
||||
// Still on screen, still named, and the button now offers to start it again.
|
||||
expect(host.querySelector('.rad-name').textContent).toBe('Beat Blender')
|
||||
expect(btn('Play')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('stop takes the bar away with the station', async () => {
|
||||
act(() => { useUI.getState().playRadio(station()) })
|
||||
await mount()
|
||||
act(() => { btn('Stop').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
await act(async () => {})
|
||||
expect(useUI.getState().radio).toBe(null)
|
||||
expect(host.querySelector('#radio')).toBe(null)
|
||||
expect(document.body.classList.contains('radioing')).toBe(false)
|
||||
})
|
||||
|
||||
it('shows the station logo when the station publishes no track', async () => {
|
||||
act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
|
||||
await mount()
|
||||
expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/logo.png')
|
||||
})
|
||||
|
||||
it('prefers the cover of the track it is playing over the station logo', async () => {
|
||||
api.mockResolvedValue({ ok: true, now: { artist: 'A', title: 'B', cover: 'https://x/cover.jpg' } })
|
||||
act(() => { useUI.getState().playRadio(station({ image: 'https://x/logo.png' })) })
|
||||
await mount()
|
||||
expect(host.querySelector('.rad-cover').getAttribute('src')).toBe('https://x/cover.jpg')
|
||||
})
|
||||
|
||||
/* A directory station's "logo" is sometimes a homepage rather than an image, and a broken image
|
||||
in the bar looks worse than no artwork at all. */
|
||||
it('falls back to the placeholder when the artwork does not load', async () => {
|
||||
act(() => { useUI.getState().playRadio(station({ image: 'https://x/not-an-image' })) })
|
||||
await mount()
|
||||
expect(host.querySelector('.rad-cover').tagName).toBe('IMG')
|
||||
act(() => { host.querySelector('.rad-cover').dispatchEvent(new Event('error')) })
|
||||
await act(async () => {})
|
||||
const art = host.querySelector('.rad-cover')
|
||||
expect(art.tagName).toBe('SPAN')
|
||||
expect(art.classList.contains('rad-cover-ph')).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1117,6 +1117,51 @@ body.chips-dragging *{cursor:inherit}
|
||||
#timer .t{font-size:26px;font-weight:600;letter-spacing:-.026em;font-variant-numeric:tabular-nums;min-width:66px}
|
||||
#timer .bar{flex:1;height:4px;background:var(--surface-3);border-radius:99px;overflow:hidden}
|
||||
#timer .bar i{display:block;height:100%;background:var(--acc);transition:width 1s linear}
|
||||
/* A station row: the whole row plays it, and a star saves it for this profile. */
|
||||
.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}
|
||||
.mus-sub-h{font-size:12px;font-weight:600;color:var(--label-3);text-transform:uppercase;letter-spacing:.04em;margin:2px 2px 6px}
|
||||
|
||||
/* The radio bar: the rest timer's shape, lower in the stack. It sits above the tab bar and, when
|
||||
a rest countdown is also on screen, above that too — the countdown is the one you act on seconds
|
||||
from now, so it keeps the lower slot. */
|
||||
#radio{
|
||||
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);
|
||||
}
|
||||
body.resting #radio{bottom:calc(190px + var(--sab))}
|
||||
body.radioing #app{padding-bottom:calc(146px + var(--sab))}
|
||||
@media (min-width:1000px){
|
||||
#radio{left:50%;right:auto;margin-left:-260px;width:520px;bottom:112px}
|
||||
body.resting #radio{bottom:200px}
|
||||
body.radioing #app{padding-bottom:calc(186px + var(--sab))}
|
||||
}
|
||||
.rad-cover{width:38px;height:38px;border-radius:8px;object-fit:cover;flex:0 0 auto;display:block}
|
||||
.rad-cover-ph{display:flex;align-items:center;justify-content:center;background:var(--surface-3);color:var(--label-3)}
|
||||
.rad-cover-ph .icn{font-size:18px}
|
||||
.rad-meta{display:flex;flex-direction:column;min-width:0;flex:1;gap:1px}
|
||||
.rad-name{font-size:13.5px;font-weight:600;color:var(--label);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.rad-now{font-size:11.5px;color:var(--label-3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.rad-btn{flex:0 0 auto;color:var(--label-2)}
|
||||
.rad-btn .icn{font-size:20px}
|
||||
/* rest variant: −15/+15/Skip and the clock won't share one line on a phone, so the clock and
|
||||
bar take the top row and the controls take their own. The work timer keeps a single row —
|
||||
it only ever has two buttons. */
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/* radio-player.js — the one `<audio>` element, and the lock screen.
|
||||
*
|
||||
* A module of its own, and a module-level element, for one reason that decides whether this feature
|
||||
* works at all on an iPhone: **`play()` has to be called inside the tap's own task.** iOS only lets
|
||||
* audio start from a gesture, so anything asynchronous between the press and the play — a fetch, a
|
||||
* state update, a re-render — is a press that does nothing. The stream URL therefore arrives with
|
||||
* the station (the api resolves it when it builds the list), the press calls `play()` synchronously
|
||||
* on this element, and the store only records what happened afterwards.
|
||||
*
|
||||
* The element lives outside React on purpose. An `<audio>` owned by a component is unmounted when
|
||||
* that component is, which is how a player stops the moment somebody changes screens; this one
|
||||
* survives every navigation, which is what makes listening while training possible.
|
||||
*
|
||||
* Media Session is the other half: with metadata and action handlers set, iOS and Android show the
|
||||
* station, the track and the controls on the lock screen, and the music keeps playing with the
|
||||
* phone in a pocket.
|
||||
*/
|
||||
const MEDIA_METADATA = typeof MediaMetadata !== 'undefined' ? MediaMetadata : null
|
||||
|
||||
let audio = null
|
||||
/** The element, created on first use — there is no audio before somebody presses play. */
|
||||
export function radioAudio() {
|
||||
if (audio) return audio
|
||||
if (typeof Audio === 'undefined') return null
|
||||
audio = new Audio()
|
||||
audio.preload = 'none'
|
||||
// Radio has no end, and no seeking: those two defaults are for files, and they make a stream
|
||||
// misbehave on some browsers.
|
||||
audio.loop = false
|
||||
return audio
|
||||
}
|
||||
|
||||
/** Start a stream. Returns false when the browser refused, which the caller reports. */
|
||||
export function playStream(url, volume = 1) {
|
||||
const el = radioAudio()
|
||||
if (!el || !url) return false
|
||||
el.volume = volume
|
||||
if (el.src !== url) el.src = url
|
||||
try {
|
||||
const p = el.play()
|
||||
// A rejected promise is the autoplay policy or a dead stream; either way the screen should not
|
||||
// claim it is playing.
|
||||
if (p && typeof p.catch === 'function') p.catch(() => {})
|
||||
return true
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
export function pauseStream() {
|
||||
try { audio?.pause() } catch { /* nothing playing */ }
|
||||
}
|
||||
|
||||
export function setStreamVolume(volume) {
|
||||
if (audio) audio.volume = Math.max(0, Math.min(1, Number(volume) || 0))
|
||||
}
|
||||
|
||||
/**
|
||||
* What the lock screen shows. `now` is whatever the station publishes — SomaFM and Radio Paradise
|
||||
* do, the directory's stations do not — and when there is none the station itself is the answer
|
||||
* rather than an invented track.
|
||||
*/
|
||||
export function setMediaSession(station, now) {
|
||||
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
|
||||
if (!ms || !station) return
|
||||
try {
|
||||
if (MEDIA_METADATA) {
|
||||
ms.metadata = new MEDIA_METADATA({
|
||||
title: now?.title || station.name || '',
|
||||
artist: now?.artist || station.genre || station.detail || '',
|
||||
album: 'KuentaGYM Radio',
|
||||
artwork: station.image || now?.cover
|
||||
? [{ src: (station.image || now?.cover), sizes: '512x512', type: 'image/jpeg' }]
|
||||
: []
|
||||
})
|
||||
}
|
||||
// The handlers are how the lock screen's buttons reach this element.
|
||||
ms.setActionHandler?.('play', () => playStream(audio?.src))
|
||||
ms.setActionHandler?.('pause', () => pauseStream())
|
||||
ms.setActionHandler?.('stop', () => pauseStream())
|
||||
} catch { /* a browser without Media Session simply shows nothing */ }
|
||||
}
|
||||
|
||||
export function clearMediaSession() {
|
||||
const ms = typeof navigator !== 'undefined' ? navigator.mediaSession : null
|
||||
if (!ms) return
|
||||
try {
|
||||
ms.metadata = null
|
||||
ms.setActionHandler?.('play', null)
|
||||
ms.setActionHandler?.('pause', null)
|
||||
ms.setActionHandler?.('stop', null)
|
||||
} catch { /* as above */ }
|
||||
}
|
||||
|
||||
/** Only for tests: forget the element so each one starts clean. */
|
||||
export function __resetRadioAudio() { audio = null }
|
||||
@@ -1408,6 +1408,25 @@ 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}',
|
||||
// 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.',
|
||||
'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',
|
||||
|
||||
@@ -35,7 +35,7 @@ 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: [] },
|
||||
// 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
|
||||
@@ -353,7 +353,25 @@ export const useStore = create((set, get) => {
|
||||
/* 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. */
|
||||
addPlaylist(item) {
|
||||
/* 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. */
|
||||
addStation(station) {
|
||||
if (!station || !station.url) return
|
||||
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 {}
|
||||
return { 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) {
|
||||
update(st => {
|
||||
const music = st.music || { playlists: [], stations: [] }
|
||||
return { music: { ...music, stations: (music.stations || []).filter(x => !(x.src === src && x.id === id)) } }
|
||||
})
|
||||
},
|
||||
|
||||
addPlaylist(item) {
|
||||
if (!item || !item.url) return
|
||||
// Falls back to the URL for the key rather than refusing the item: this guard used to be
|
||||
// `if (!item.id) return`, and when the add form forgot to pass one the sheet said "playlist
|
||||
|
||||
@@ -2,6 +2,7 @@ import { create } from 'zustand'
|
||||
import { uid } from '../lib/format.js'
|
||||
import { beep, vibrate } from '../lib/sound.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { playStream, pauseStream, setStreamVolume, setMediaSession, clearMediaSession } from '../lib/radio-player.js'
|
||||
import { t } from '../lib/i18n.js'
|
||||
import { deviceId } from '../lib/push.js'
|
||||
import { useStore } from './useStore.js'
|
||||
@@ -63,6 +64,7 @@ export const useUI = create((set, get) => ({
|
||||
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
|
||||
toastMsg: '',
|
||||
timer: null, // rest countdown between sets — { left, total, endsAt, forIdx }
|
||||
radio: null, // { station, playing, volume, now } — the audio element lives in lib/radio-player.js
|
||||
// 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 +89,41 @@ 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. */
|
||||
playRadio(station, { volume } = {}) {
|
||||
if (!station || !station.url) return false
|
||||
const v = volume != null ? volume : (get().radio?.volume ?? 1)
|
||||
const ok = playStream(station.url, v)
|
||||
set({ radio: { station, playing: ok, volume: v, now: null } })
|
||||
setMediaSession(station, null)
|
||||
return ok
|
||||
},
|
||||
toggleRadio() {
|
||||
const r = get().radio
|
||||
if (!r) return
|
||||
if (r.playing) { pauseStream(); set({ radio: { ...r, playing: false } }) }
|
||||
else { const ok = playStream(r.station.url, r.volume); set({ radio: { ...r, playing: ok } }) }
|
||||
},
|
||||
stopRadio() {
|
||||
pauseStream()
|
||||
clearMediaSession()
|
||||
set({ radio: null })
|
||||
},
|
||||
setRadioVolume(volume) {
|
||||
const r = get().radio
|
||||
setStreamVolume(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 } })
|
||||
setMediaSession(r.station, now)
|
||||
},
|
||||
|
||||
startRest(sec, forIdx) {
|
||||
get().stopRest()
|
||||
// Rest timer set to Off. Stopping and returning rather than starting a zero-length timer
|
||||
|
||||
@@ -16,12 +16,12 @@
|
||||
* 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 Icon from '../components/Icon.jsx'
|
||||
@@ -86,6 +86,98 @@ 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/radio-player.js.
|
||||
*
|
||||
* 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() {
|
||||
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 addStation = useStore(s => s.addStation)
|
||||
const removeStation = useStore(s => s.removeStation)
|
||||
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 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)
|
||||
})
|
||||
.catch(e => toast(e.message))
|
||||
.finally(() => setBusy(false))
|
||||
}
|
||||
useEffect(() => { load(null) }, [])
|
||||
|
||||
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>
|
||||
|
||||
return <>
|
||||
<h4 className="sec">{t('Radio')}{stations ? <span className="vh-window"> · {t('{0} stations', stations.length)}</span> : null}</h4>
|
||||
<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>
|
||||
<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>
|
||||
{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>}
|
||||
{stations && stations.map(st => row(st))}
|
||||
{stations && !stations.length && <div className="small dim" style={{ margin: '0 2px 10px' }}>
|
||||
{t('That station is not answering. Try another one.')}
|
||||
</div>}
|
||||
{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>}
|
||||
{!radio && <div className="small dim" style={{ margin: '8px 2px 0' }}>{t('Nothing playing. Pick a station below.')}</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
export default function Music() {
|
||||
const nav = useNavigate()
|
||||
const S = useStore(s => s.S)
|
||||
@@ -130,6 +222,9 @@ export default function Music() {
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
<RadioSection />
|
||||
|
||||
<h4 className="sec">{t('Playlists')}</h4>
|
||||
{list.length === 0
|
||||
? <div className="empty">
|
||||
<div className="ico"><Icon name="music" /></div>
|
||||
|
||||
@@ -7,12 +7,23 @@ 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/radio-player.js, outside React; the radio section reaches it
|
||||
through the store. Mocked so a test can assert *when* it was asked to play — see the row test. */
|
||||
const playStream = vi.fn(() => true)
|
||||
vi.mock('../lib/radio-player.js', () => ({
|
||||
playStream: (...a) => playStream(...a),
|
||||
pauseStream: vi.fn(),
|
||||
setStreamVolume: vi.fn(),
|
||||
setMediaSession: vi.fn(),
|
||||
clearMediaSession: vi.fn()
|
||||
}))
|
||||
|
||||
const { default: Music } = await import('./Music.jsx')
|
||||
const { default: Modals } = await import('../components/Modals.jsx')
|
||||
@@ -23,6 +34,13 @@ 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()
|
||||
act(() => { useUI.setState({ radio: null }) })
|
||||
host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
root = createRoot(host)
|
||||
@@ -92,6 +110,28 @@ 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)
|
||||
})
|
||||
|
||||
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()) })
|
||||
|
||||
+49
-1
@@ -232,7 +232,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>41 endpoints</span>
|
||||
<span>AGPL-3.0-or-later</span>
|
||||
</p>
|
||||
|
||||
@@ -1384,6 +1384,54 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
|
||||
</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">"soma" | "paradise" | "rb"</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 "no advertising" 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>
|
||||
|
||||
Reference in new issue
Block a user