diff --git a/CLAUDE.md b/CLAUDE.md index ad80e0b..b446677 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -86,6 +86,8 @@ would catch is a change nothing checks here. - `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined). - `vitals-view.js` — the Apple Health metric catalogue and card model (labels, units, which aggregate a card shows, workout rows). The server 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. - `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 @@ -119,10 +121,12 @@ 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` sits beside `server.js` as the only non-`server.js` module 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. `server.js` owns the bytes; that file owns the arithmetic, which is why it is -testable without a phone. +`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. ### MCP server (`mcp/src`) diff --git a/api/Dockerfile b/api/Dockerfile index d352c70..4ce520c 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -53,10 +53,10 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force # Every local module server.js imports, listed rather than `COPY . .` so a stray file in api/ # (a test, a script, a stray JSON) cannot reach the published image. vitals.js joined the list -# with the Apple Health ingest — 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 ./ +# 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 ./ COPY coach ./coach ENV NODE_ENV=production ENV PORT=3000 diff --git a/api/music.js b/api/music.js new file mode 100644 index 0000000..7c33dfb --- /dev/null +++ b/api/music.js @@ -0,0 +1,81 @@ +/* music.js — what a public Apple Music page says about itself. + * + * This is the API half of the Música screen. The client keeps the links (frontend/src/lib/music.js + * owns reading and validating those); this fetches one and reads its title, artwork and track count + * so the list looks like a list of playlists instead of a column of URLs. + * + * It lives beside server.js, exported and tested on its own, for the reason vitals.js does: it is + * the only part of the route with logic in it, and it is much easier to test against real markup + * than to watch a phone do it. server.js owns the socket, this owns the parsing. + * + * ── Two things that are not negotiable here ────────────────────────────────────────────────── + * + * HOST-ALLOWLISTED. The URL comes from a signed-in user and the request is made from the api + * container, which sits on the same network as everything else the owner runs — so a route that + * fetches whatever it is handed is a request-forgery lever. Only Apple's own music hosts are + * reachable, which is a set nobody can point at the LAN. `hostAllowed` is used both before the + * request and again on the final URL, because a redirect must not be a way around it. + * + * BEST EFFORT. Apple's markup is theirs to change; a page that yields nothing costs the reader the + * artwork and the track count, never the playlist (the card falls back to the name its owner + * typed). Apple publishes a schema.org MusicPlaylist block for previews to read, which is the part + * this leans on; the Open Graph tags are the fallback. + */ +export const MUSIC_HOSTS = new Set(['music.apple.com', 'itunes.apple.com', 'geo.music.apple.com']); +export const MUSIC_TIMEOUT_MS = 8000; +export const MUSIC_MAX_HTML = 1024 * 1024; // a playlist page is a few hundred KB; more is not one + +/** Is this URL one we are willing to fetch? https, and one of Apple's music hosts. */ +export function hostAllowed(url) { + try { + const u = new URL(String(url)); + return u.protocol === 'https:' && MUSIC_HOSTS.has(u.hostname.toLowerCase()); + } catch { return false } +} + +/** Read at most `max` bytes of a response, as text. */ +export async function readCapped(res, max = MUSIC_MAX_HTML) { + const chunks = []; + let size = 0; + for await (const chunk of res.body || []) { + size += chunk.length; + if (size > max) break; + chunks.push(chunk); + } + return Buffer.concat(chunks).toString('utf8'); +} + +const decode = s => String(s || '') + .replace(/"/g, '"').replace(/�?39;/g, "'").replace(/'/g, "'") + .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/ /g, ' '); + +/** @returns {{title:string|null, artwork:string|null, tracks:number|null, curator:string|null}} */ +export function parseMusicPage(html) { + const text = String(html || ''); + const out = { title: null, artwork: null, tracks: null, curator: null }; + const meta = prop => { + const m = new RegExp(`]+(?:property|name)=["']${prop}["'][^>]+content=["']([^"']*)["']`, 'i').exec(text) + || new RegExp(`]+content=["']([^"']*)["'][^>]+(?:property|name)=["']${prop}["']`, 'i').exec(text); + return m ? decode(m[1]) : null; + }; + for (const m of text.matchAll(/]+application\/ld\+json[^>]*>([\s\S]*?)<\/script>/gi)) { + let data; + try { data = JSON.parse(m[1].trim()); } catch { continue } + for (const node of Array.isArray(data) ? data : [data]) { + if (!node || node['@type'] !== 'MusicPlaylist') continue; + if (node.name) out.title = decode(node.name); + if (typeof node.numTracks === 'number') out.tracks = node.numTracks; + const img = node.image; + if (typeof img === 'string') out.artwork = img; + else if (img && typeof img === 'object' && img.url) out.artwork = img.url; + const by = node.byArtist || node.author || node.creator; + if (by && typeof by === 'object' && by.name) out.curator = decode(by.name); + } + } + if (!out.title) out.title = meta('og:title') || meta('twitter:title'); + if (!out.artwork) out.artwork = meta('og:image') || meta('twitter:image'); + // Apple serves the preview image at whatever size it likes; asking their own CDN template for a + // bigger one is a string substitution, and harmless when the path does not match. + if (out.artwork) out.artwork = out.artwork.replace(/\/\d+x\d+(bb)?\.(jpg|png|webp)$/i, '/600x600bb.jpg'); + return out; +} diff --git a/api/server.js b/api/server.js index 9d6f1f2..df7bc69 100644 --- a/api/server.js +++ b/api/server.js @@ -20,6 +20,7 @@ import { startWarmup } from './coach/warmup.js'; import { dayReminderPush, restTimerPush, testPush } from './push-messages.js'; import { verifyError } from './verify-error.js'; import { parsePayload, mergeVitals, vitalsSeries, emptyVitals, RETENTION_DAYS } from './vitals.js'; +import { hostAllowed, readCapped, parseMusicPage } from './music.js'; const PORT = +(process.env.PORT || 3000); const DATA = process.env.DATA_DIR || '/data'; @@ -1100,6 +1101,43 @@ const routes = { json(res, 200, { ok: true }); }, + /* ---------- Apple Music: reading a link's public page ---------- + * + * The client keeps the links; this only fills in what a link can say about itself — its title, + * its artwork, how many tracks — so the list looks like a list of playlists instead of a column + * of URLs. Apple publishes a schema.org MusicPlaylist block for previews; it is read here and + * anything unexpected degrades to the name the person typed (see lib/music.js). + * + * HOST-ALLOWLISTED, and that is a security boundary rather than tidiness: the URL comes from a + * signed-in user, the request is made from this container, and this container sits on the same + * network as everything else the owner runs — a route that fetches whatever it is handed is a + * request-forgery lever (the same reasoning as PUSH_AGENT below, which is why it exists). Only + * Apple's own music hosts are reachable, which is a set no attacker can point at the LAN. */ + 'POST /api/music/lookup': async (req, res) => { + const user = readSession(req); + if (!user) return json(res, 401, { error: 'not signed in' }); + const body = await readBody(req); + const target = text(body.url).trim(); + if (!hostAllowed(target)) return json(res, 400, { error: 'not an Apple Music link' }); + let r; + try { + r = await fetch(target, { + redirect: 'follow', + signal: AbortSignal.timeout(MUSIC_TIMEOUT_MS), + headers: { 'User-Agent': 'KuentaGYM (self-hosted)' } + }); + } catch { + return json(res, 200, { ok: true, meta: null, error: 'unreachable' }); + } + // Where we ended up is checked too, not only where we were pointed: a redirect is otherwise a + // way around the allowlist. + if (!r.ok || !hostAllowed(r.url)) { + return json(res, 200, { ok: true, meta: null, error: r.ok ? 'off-host' : 'http-' + r.status }); + } + const html = await readCapped(r, MUSIC_MAX_HTML); + json(res, 200, { ok: true, meta: parseMusicPage(html) }); + }, + 'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }), 'POST /api/push/subscribe': async (req, res) => { diff --git a/api/test/music.test.js b/api/test/music.test.js new file mode 100644 index 0000000..2ccd763 --- /dev/null +++ b/api/test/music.test.js @@ -0,0 +1,69 @@ +/* What a public Apple Music page says about itself, and which links this API is willing to fetch. + * + * The parser is best-effort by design — Apple's markup is theirs to change — so these tests are + * about the two things that must not wobble: the schema block is read when it is there, the Open + * Graph tags take over when it is not, and a page that is not a playlist at all returns nothing + * rather than throwing. The allowlist gets the same treatment, because that one is a boundary + * rather than a convenience. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseMusicPage, hostAllowed } from '../music.js'; + +const PAGE = ` + + + Leg Day`; + +test('reads the schema block first, and asks Apple\'s CDN for one useful size', () => { + const m = parseMusicPage(PAGE); + assert.equal(m.title, "Leg Day '24"); + assert.equal(m.tracks, 42); + assert.equal(m.curator, 'Ana'); + assert.equal(m.artwork, 'https://is1-ssl.mzstatic.com/image/thumb/Feature/abc/600x600bb.jpg'); +}); + +test('falls back to Open Graph, and never invents what it cannot read', () => { + const noSchema = PAGE.replace(//, ''); + const m = parseMusicPage(noSchema); + assert.equal(m.title, 'Leg Day — Playlist by Ana'); + assert.ok(m.artwork.endsWith('600x600bb.jpg')); + assert.equal(m.tracks, null); + assert.equal(m.curator, null); + + // A schema block that is there but unparseable is the same as one that is not: half a JSON object + // must not take the title down with it. + const broken = parseMusicPage(PAGE.replace('"numTracks":42,', '"numTracks":,')); + assert.equal(broken.title, 'Leg Day — Playlist by Ana'); + assert.equal(broken.tracks, null); +}); + +test('says nothing rather than throwing when the page is not a playlist', () => { + const empty = { title: null, artwork: null, tracks: null, curator: null }; + assert.deepEqual(parseMusicPage('Sign in to Apple Music'), empty); + assert.deepEqual(parseMusicPage(''), empty); + assert.deepEqual(parseMusicPage(null), empty); + // The `content` before `property` order is real markup too, and is matched. + assert.equal(parseMusicPage('').title, 'X'); +}); + +test('only Apple\'s own music hosts, over https — this is a boundary, not a preference', () => { + assert.equal(hostAllowed('https://music.apple.com/us/playlist/x/pl.1'), true); + assert.equal(hostAllowed('https://itunes.apple.com/us/album/x/1'), true); + assert.equal(hostAllowed('https://geo.music.apple.com/us/playlist/x/pl.1'), true); + // The interesting ones: the api container sits on the owner's network, so anything that could + // name a machine on it is refused — a lookalike domain, a LAN address, localhost, plain http, and + // a scheme that is not http at all. + assert.equal(hostAllowed('https://music.apple.com.evil.test/us/playlist/x/pl.1'), false); + assert.equal(hostAllowed('http://music.apple.com/us/playlist/x/pl.1'), false); + assert.equal(hostAllowed('http://127.0.0.1:3000/api/health'), false); + assert.equal(hostAllowed('http://192.168.1.1/'), false); + assert.equal(hostAllowed('http://169.254.169.254/latest/meta-data/'), false); + assert.equal(hostAllowed('file:///etc/passwd'), false); + assert.equal(hostAllowed('gopher://music.apple.com/'), false); + assert.equal(hostAllowed('not a url'), false); + assert.equal(hostAllowed(''), false); +}); diff --git a/api/test/server-music.test.js b/api/test/server-music.test.js new file mode 100644 index 0000000..5b873c8 --- /dev/null +++ b/api/test/server-music.test.js @@ -0,0 +1,80 @@ +/* POST /api/music/lookup, against the real server: who may call it, and what it will agree to + fetch. The fetch itself is Apple's, so the happy path is covered by api/test/music.test.js — + these are the two guards, and a guard is exactly the kind of thing that quietly stops guarding. */ +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-music-')); + fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 }); + fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u_m', 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; +} + +const lookup = (h, url, headers = cookie('u_m')) => fetch(`${h.api}/api/music/lookup`, { + method: 'POST', headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', ...headers }, + body: JSON.stringify({ url }) +}); + +test('the lookup needs a session', async t => { + const h = await startServer(t); + const r = await fetch(`${h.api}/api/music/lookup`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ url: 'https://music.apple.com/us/playlist/x/pl.1' }) + }); + assert.equal(r.status, 401); +}); + +test('it refuses anything that is not an Apple Music link, before any request is made', async t => { + const h = await startServer(t); + // The api container sits on the owner's network. Every one of these would be a request forged + // from the container if the host were not checked, so each is a 400 and none of them is fetched. + for (const url of [ + 'http://127.0.0.1:3000/api/health', + 'http://169.254.169.254/latest/meta-data/', + 'http://192.168.1.1/', + 'https://music.apple.com.evil.test/us/playlist/x/pl.1', + 'http://music.apple.com/us/playlist/x/pl.1', // plain http, even on the right host + 'https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M', + 'not a url', '', null + ]) { + const r = await lookup(h, url); + assert.equal(r.status, 400, `${url} should be refused`); + assert.match((await r.json()).error, /Apple Music/); + } +}); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 541326a..f4a1726 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -30,6 +30,7 @@ import RoutineEdit from './views/RoutineEdit.jsx' import Workout from './views/Workout.jsx' import Stats from './views/Stats.jsx' import Health from './views/Health.jsx' +import Music from './views/Music.jsx' import History from './views/History.jsx' import Library from './views/Library.jsx' import Muscles from './views/Muscles.jsx' @@ -191,6 +192,10 @@ function Shell() { per profile: the route is reachable by guest mode too, where it explains how to connect rather than pretending there is data. */} } /> + {/* Apple Music: the playlists this profile keeps as share links (views/Music.jsx). + Reached from Home's header, next to Salud, for the same reason — a place you go on + purpose, not a drawer in the tab bar, which has to keep an odd number of tabs. */} + } /> } /> } /> } /> diff --git a/frontend/src/components/Icon.jsx b/frontend/src/components/Icon.jsx index e8c1e79..d189d8f 100644 --- a/frontend/src/components/Icon.jsx +++ b/frontend/src/components/Icon.jsx @@ -80,6 +80,7 @@ const P = { reset: <>, bell: <>, bellSlash: <>, + music: <>, chevronRight: , chevronLeft: , chevronDown: , diff --git a/frontend/src/index.css b/frontend/src/index.css index 0b7b032..e7fd0af 100644 --- a/frontend/src/index.css +++ b/frontend/src/index.css @@ -1368,6 +1368,31 @@ body.chips-dragging *{cursor:inherit} .vh-when{margin-top:3px;font-size:11px;color:var(--label-3);letter-spacing:0} .vh-when .vh-ago::before{content:' · '} +/* A labelled block inside a grouped section: the title, a full-width field, and the note under it. + Same padding as a `.lrow` so it lines up with the rows around it inside the same card. */ +.set-field{padding:12px 14px} +.set-field .field{background:var(--surface-2)} + +/* --- Música (Apple Music playlists) ---------------------------------------- + A playlist is a card that is really one big link: the whole row opens Apple Music, so the tap + target is the artwork and the title together rather than a small chevron, and the only button + inside it is the one that removes it (offset from the link so a thumb aiming at a playlist + cannot delete it). */ +.mus-card{position:relative;padding:10px} +.mus-link{display:flex;align-items:center;gap:12px;text-decoration:none;color:inherit;min-width:0} +.mus-art{width:56px;height:56px;border-radius:9px;flex:none;object-fit:cover;background:var(--surface-2)} +.mus-art-ph{display:grid;place-items:center;font-size:24px;color:var(--label-2)} +.mus-meta{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1;padding-right:30px} +.mus-name{font-size:16px;font-weight:600;letter-spacing:-.014em;overflow-wrap:anywhere} +.mus-sub{font-size:12.5px;color:var(--label-2)} +.mus-go{font-size:16px;color:var(--acc);flex:none} +.mus-del{position:absolute;top:50%;right:10px;transform:translateY(-50%);width:32px;height:32px;font-size:15px;color:var(--label-2)} +.mus-del:active{transform:translateY(-50%) scale(.92)} +.mus-profile{display:flex;align-items:center;gap:12px;text-decoration:none;color:inherit} +.mus-profile-i{font-size:28px;color:var(--acc);flex:none} +.mus-hint{display:flex;gap:12px;align-items:flex-start} +.mus-hint-i{font-size:24px;color:var(--label-2);flex:none;margin-top:2px} + /* --- the chart panels ----------------------------------------------------- Full-width panels for the few metrics people open this screen for. Same `--tint` contract as the tiles, so a panel and its card are recognisably the same metric. */ diff --git a/frontend/src/lib/music.js b/frontend/src/lib/music.js new file mode 100644 index 0000000..2bd9840 --- /dev/null +++ b/frontend/src/lib/music.js @@ -0,0 +1,85 @@ +/* music.js — the Apple Music half of the app: turn a share link into something worth showing, and + * send it to the right place when it is tapped. + * + * ── What this is not ───────────────────────────────────────────────────────────────────────── + * + * It is not a MusicKit integration, and that is a decision forced by Apple rather than a shortcut. + * There is no API for "the public playlists of somebody else": the request is answered in Apple's + * own developer forums (threads 692941 and 123894) with "you can't", and a public profile page is + * rendered by JavaScript with no endpoint behind it. What MusicKit does offer is two other things — + * the catalog, and the *signed-in* user's own library — and the second needs an Apple Developer + * Program membership for a developer token, plus a Music-User-Token per person, plus a script from + * Apple's CDN. That would list YOUR library, not a profile you typed, and it would put a private + * key in an app whose whole point is holding no third-party secrets. + * + * So a profile keeps links. Every Apple Music playlist has a public share link (Music → Share → + * Copy Link), and on an iPhone that link opens the Music app directly. The link is the data; the + * title, artwork and track count are a best-effort bonus the API reads from the public page — + * `api/music.js`, which owns that parsing for both sides rather than keeping two copies of it in + * step by hand. + */ + +const APPLE_HOSTS = new Set(['music.apple.com', 'itunes.apple.com', 'geo.music.apple.com']) + +/** + * Read an Apple Music share link. + * + * Accepts the link the Music app copies (with its `?l=`, `at=` and `itscg` tracking parameters) and + * returns the parts this app cares about. The storefront is kept because it belongs in the path — + * a link to a playlist in one country's catalogue should open that playlist, not a guess at the + * reader's. + * + * @returns {{kind:'playlist'|'album'|'song'|'artist'|'profile', id:string, storefront:string, + * username?:string, trackId?:string, url:string}|null} null for anything that is not one of them, + * which is what the form shows as "that is not an Apple Music link". + */ +export function parseMusicUrl(input) { + const raw = String(input || '').trim() + if (!raw) return null + let u + try { + u = new URL(raw) + } catch { return null } + if (u.protocol !== 'https:' && u.protocol !== 'http:') return null + if (!APPLE_HOSTS.has(u.hostname.toLowerCase())) return null + + const parts = u.pathname.split('/').filter(Boolean) + // The first segment is the storefront, with /profile/ the one exception. + if (parts[0] === 'profile') { + const username = (parts[1] || '').replace(/^@/, '') + if (!username) return null + return { kind: 'profile', id: username, username, storefront: '', url: `https://music.apple.com/profile/${encodeURIComponent(username)}` } + } + if (parts.length < 2) return null + const storefront = parts[0].toLowerCase() + if (!/^[a-z]{2}$/.test(storefront)) return null + + const kind = { playlist: 'playlist', album: 'album', song: 'song', artist: 'artist' }[parts[1]] + if (!kind) return null + // The id is the last segment, which is the `pl.…`/numeric identifier Apple puts there. + const id = parts[parts.length - 1] + if (!id) return null + + // `i` is the track within an album and is the difference between "listen to this song" and + // "listen to this album" — the other parameters are tracking and are dropped. + const trackId = u.searchParams.get('i') || null + const base = `https://music.apple.com/${storefront}/${parts.slice(1).join('/')}` + return { + kind, id, storefront, + ...(trackId ? { trackId } : {}), + url: trackId ? `${base}?i=${encodeURIComponent(trackId)}` : base + } +} + +/** A public profile page from a username, with or without the `@` people write it with. */ +export function profileUrl(username) { + const name = String(username || '').trim().replace(/^@/, '') + return name ? `https://music.apple.com/profile/${encodeURIComponent(name)}` : null +} + +/** The name to show a link under when nobody has given it one. */ +export function fallbackName(parsed) { + if (!parsed) return '' + if (parsed.kind === 'profile') return '@' + parsed.username + return parsed.id +} diff --git a/frontend/src/lib/music.test.js b/frontend/src/lib/music.test.js new file mode 100644 index 0000000..f7c8314 --- /dev/null +++ b/frontend/src/lib/music.test.js @@ -0,0 +1,49 @@ +import { describe, it, expect } from 'vitest' +import { parseMusicUrl, profileUrl, fallbackName } from './music.js' + +/* The links the Music app copies are long and full of tracking, and the storefront is part of the + path — so the tests are mostly about not losing the parts that matter and not trusting the rest. */ + +describe('parseMusicUrl', () => { + it('reads a playlist share link and keeps the storefront', () => { + const p = parseMusicUrl('https://music.apple.com/us/playlist/leg-day/pl.u-1Z4aGvT4hWA?l=es') + expect(p).toEqual({ + kind: 'playlist', id: 'pl.u-1Z4aGvT4hWA', storefront: 'us', + url: 'https://music.apple.com/us/playlist/leg-day/pl.u-1Z4aGvT4hWA' + }) + }) + + it('keeps `i` — the difference between a song and the album it sits on — and drops the rest', () => { + const p = parseMusicUrl('https://music.apple.com/es/album/random-access-memories/617154241?i=617154337&at=1000l&itscg=30200&l=es') + expect(p.kind).toBe('album') + expect(p.storefront).toBe('es') + expect(p.trackId).toBe('617154337') + expect(p.url).toBe('https://music.apple.com/es/album/random-access-memories/617154241?i=617154337') + }) + + it('reads profiles, with or without the @ people write them with', () => { + const p = parseMusicUrl('https://music.apple.com/profile/@dj.kuenta') + expect(p).toEqual({ kind: 'profile', id: 'dj.kuenta', username: 'dj.kuenta', storefront: '', url: 'https://music.apple.com/profile/dj.kuenta' }) + expect(profileUrl('@dj.kuenta')).toBe('https://music.apple.com/profile/dj.kuenta') + expect(profileUrl(' ')).toBeNull() + }) + + it('accepts the legacy itunes host, and refuses everything else', () => { + expect(parseMusicUrl('https://itunes.apple.com/us/song/x/1440833098')?.kind).toBe('song') + // A lookalike host, an unrelated site, a bare id, a storefront-less path — all refused, because + // the alternative is storing something that silently does nothing when tapped. + expect(parseMusicUrl('https://music.apple.com.evil.test/us/playlist/x/pl.1')).toBeNull() + expect(parseMusicUrl('https://open.spotify.com/playlist/37i9dQZF1DXcBWIGoYBM5M')).toBeNull() + expect(parseMusicUrl('pl.u-1Z4aGvT4hWA')).toBeNull() + expect(parseMusicUrl('https://music.apple.com/us/')).toBeNull() + expect(parseMusicUrl('https://music.apple.com/playlist/x/pl.1')).toBeNull() + expect(parseMusicUrl('')).toBeNull() + expect(parseMusicUrl(null)).toBeNull() + }) + + it('has a name to fall back on before anybody types one', () => { + expect(fallbackName(parseMusicUrl('https://music.apple.com/us/playlist/x/pl.abc'))).toBe('pl.abc') + expect(fallbackName(parseMusicUrl('https://music.apple.com/profile/@ana'))).toBe('@ana') + expect(fallbackName(null)).toBe('') + }) +}) diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index 7b7cce3..9f40cbb 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1428,4 +1428,34 @@ export default { 'low {0}': 'mín {0}', 'avg {0}': 'media {0}', 'high {0}': 'máx {0}', -} + // Música (Apple Music) + 'Music': 'Música', + 'Your Apple Music, one tap away': 'Tu Apple Music, a un toque', + '{0} playlists': '{0} listas', + 'Apple Music': 'Apple Music', + 'Your Apple Music username': 'Tu usuario de Apple Music', + 'Shown as a link to your public profile on the Música screen.': 'Se muestra como enlace a tu perfil público en la pantalla Música.', + "Apple publishes no list of somebody else's playlists, so the ones you want on the Música screen are the ones you add there.": 'Apple no publica una lista de las listas de otra persona, así que las que quieras ver en la pantalla Música son las que agregues ahí.', + 'Your playlists': 'Tus listas', + '{0} saved': '{0} guardadas', + 'Add a playlist': 'Agregar una lista', + 'In Apple Music, open the playlist → Share → Copy Link, and paste it here. Tapping it in this app opens it in Apple Music.': 'En Apple Music, abrí la lista → Compartir → Copiar enlace, y pegalo acá. Al tocarla en esta app se abre en tu Apple Music.', + 'That is not an Apple Music link.': 'Ese no es un enlace de Apple Music.', + 'Playlist': 'Lista', + 'Album': 'Álbum', + 'Track': 'Canción', + 'Open in Apple Music': 'Abrir en Apple Music', + '{0} songs': '{0} canciones', + 'Name (optional)': 'Nombre (opcional)', + 'Reading the link…': 'Leyendo el enlace…', + 'Add': 'Agregar', + 'Playlist added': 'Lista agregada', + 'Remove “{0}”?': '¿Quitar «{0}»?', + 'It is removed from this list. Nothing happens to the playlist itself — it is still in your Apple Music.': 'Se quita de esta lista. A la lista en sí no le pasa nada: sigue en tu Apple Music.', + 'Your public Apple Music profile': 'Tu perfil público de Apple Music', + 'Add your Apple Music profile': 'Agregá tu perfil de Apple Music', + 'Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.': 'Poné tu usuario en Ajustes y se convierte en un enlace acá. Apple no permite publicar tus listas automáticamente, así que las que quieras en esta pantalla son las que agregues.', + 'No playlists yet.': 'Todavía no hay listas.', + 'Add one from the + above.': 'Agregá una con el + de arriba.', + '{0} link': 'Enlace de {0}', +} \ No newline at end of file diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js index 7f75d7b..09fbba1 100644 --- a/frontend/src/store/useStore.js +++ b/frontend/src/store/useStore.js @@ -30,6 +30,12 @@ export const DEF = { theme: 'dark', accent: 'lime', body: 'male', targetW: null, bodyweight: [], routines: [], week: {}, dayPlan: {}, exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full', + // Apple Music, per profile: the username shown as a link to the public profile, and the playlists + // this person keeps. Links rather than a MusicKit integration on purpose — Apple has no API for + // 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: [] }, // 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 @@ -344,6 +350,27 @@ export const useStore = create((set, get) => { // overwrite, not a change to merge: the push it arms goes without a baseRev. replaceState(S, push = false) { if (push) forceNext = true; persist(clone(S), push) }, + /* 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) { + if (!item || !item.id) return + get().update(s => { + const list = (s.music && s.music.playlists) || [] + if (list.some(p => p.id === item.id)) return + s.music = { user: (s.music && s.music.user) || '', playlists: [...list, item] } + }) + }, + removePlaylist(id) { + get().update(s => { + const list = (s.music && s.music.playlists) || [] + s.music = { user: (s.music && s.music.user) || '', playlists: list.filter(p => p.id !== id) } + }) + }, + setMusicUser(user) { + get().update(s => { s.music = { user: String(user || '').replace(/^@/, '').trim().slice(0, 40), playlists: (s.music && s.music.playlists) || [] } }) + }, + // Fires after the moments where losing local data would actually hurt — a workout just // logged, a routine just edited — not on every keystroke. No-op off mobile or with the // setting off; the private file mirror (nativePersist, above) already covers every change. diff --git a/frontend/src/views/Home.health-door.test.jsx b/frontend/src/views/Home.health-door.test.jsx index 73271c1..e2b86b7 100644 --- a/frontend/src/views/Home.health-door.test.jsx +++ b/frontend/src/views/Home.health-door.test.jsx @@ -29,10 +29,10 @@ const headerButtons = () => [...host.querySelectorAll('.hdr button')] const click = el => act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) describe('Home\'s header', () => { - it('offers Salud next to the gear, in that order', () => { + it('offers Salud and Música next to the gear, in that order', () => { act(() => root.render()) const labels = headerButtons().map(b => b.getAttribute('aria-label')) - expect(labels).toEqual(['Health', 'Settings']) + expect(labels).toEqual(['Health', 'Music', 'Settings']) // Same container, or they end up on separate lines / far apart on a narrow phone. expect(headerButtons()[0].parentElement).toBe(headerButtons()[1].parentElement) // ...and that container must not shrink. The CSSOM rewrites `flex: none` to `0 0 auto`, so @@ -41,11 +41,11 @@ describe('Home\'s header', () => { expect([wrap.style.flexGrow, wrap.style.flexShrink]).toEqual(['0', '0']) }) - it('takes Salud to /health', () => { + it('takes each of the three somewhere, and none of them is the same place', () => { act(() => root.render()) - click(headerButtons()[0]) - expect(nav).toHaveBeenCalledWith('/health') - click(headerButtons()[1]) - expect(nav).toHaveBeenCalledWith('/settings') + const [health, music, gear] = headerButtons() + click(health); expect(nav).toHaveBeenCalledWith('/health') + click(music); expect(nav).toHaveBeenCalledWith('/music') + click(gear); expect(nav).toHaveBeenCalledWith('/settings') }) }) diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx index ff0d8b7..a92d102 100644 --- a/frontend/src/views/Home.jsx +++ b/frontend/src/views/Home.jsx @@ -72,6 +72,7 @@ export default function Home() { the title gives way on a narrow phone, these two do not. */}
+
diff --git a/frontend/src/views/Music.jsx b/frontend/src/views/Music.jsx new file mode 100644 index 0000000..8b085d5 --- /dev/null +++ b/frontend/src/views/Music.jsx @@ -0,0 +1,143 @@ +/* Música — the playlists a profile keeps, and the way to open them in Apple Music. + * + * ── Why this is a list of links and not a MusicKit integration ───────────────────────────────── + * + * The idea was "each person types their Apple Music username and their public playlists appear". + * Apple does not allow that: there is no API for another person's public playlists (their own + * developer forums answer the request with "you can't"), and a profile page is rendered by + * JavaScript with nothing behind it to call. MusicKit would give the *signed-in* user's own + * library, which needs an Apple Developer Program membership for a developer token plus a + * Music-User-Token per person — a private key and a third-party secret in an app that holds none, + * to fetch the wrong thing. + * + * What works today, with no Apple account and no secrets: the share link every playlist has + * (Music → Share → Copy Link). On an iPhone that link opens the Music app; anywhere else it opens + * the web player. The link is the data. `POST /api/music/lookup` reads the public page for a title, + * 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 { useNavigate } from 'react-router-dom' +import { useStore } from '../store/useStore.js' +import { t } from '../lib/i18n.js' +import { api } from '../lib/api.js' +import { useUI } from '../store/useUI.js' +import { confirmSheet } from '../sheets.jsx' +import { Button } from '../components/ui.jsx' +import Icon from '../components/Icon.jsx' +import { parseMusicUrl, profileUrl } from '../lib/music.js' + +/** A playlist tile: artwork when the public page gave us some, a note when it did not. */ +function PlaylistCard({ item, onRemove }) { + return +} + +/** The form: paste a link, we read what it can tell us, done. */ +function AddPlaylistSheet({ close }) { + const toast = useUI(s => s.toast) + const add = useStore(s => s.addPlaylist) + const [url, setUrl] = useState('') + const [name, setName] = useState('') + const [busy, setBusy] = useState(false) + const parsed = parseMusicUrl(url) + const bad = url.trim().length > 0 && !parsed + + const save = async () => { + if (!parsed) return + setBusy(true) + // The lookup is a bonus, never a gate: `meta` is null when the page could not be read, and the + // playlist is saved either way under whatever name is in the field. + let meta = null + try { meta = (await api('/api/music/lookup', { method: 'POST', body: JSON.stringify({ url: parsed.url }) })).meta } catch { /* offline, or the route is older than the app */ } + add({ url: parsed.url, kind: parsed.kind, name: name.trim() || (meta && meta.title) || parsed.id, artwork: (meta && meta.artwork) || null, tracks: (meta && meta.tracks) || null, curator: (meta && meta.curator) || null }) + toast(t('Playlist added')) + close() + } + + return <> +

{t('Add a playlist')}

+
+ {t('In Apple Music, open the playlist → Share → Copy Link, and paste it here. Tapping it in this app opens it in Apple Music.')} +
+ setUrl(e.target.value)} placeholder="https://music.apple.com/…" inputMode="url" autoCapitalize="off" autoCorrect="off" spellCheck={false} /> + {bad &&
{t('That is not an Apple Music link.')}
} + {parsed &&
{t('{0} link', parsed.kind === 'playlist' ? t('Playlist') : parsed.kind === 'album' ? t('Album') : t('Track'))}
} +
+ setName(e.target.value)} placeholder={t('Name (optional)')} maxLength={60} /> +
+ +
+ + +} + +export default function Music() { + const nav = useNavigate() + const S = useStore(s => s.S) + const openSheet = useUI(s => s.openSheet) + const removePlaylist = useStore(s => s.removePlaylist) + const list = (S.music && S.music.playlists) || [] + const profile = profileUrl(S.music && S.music.user) + + const askRemove = item => confirmSheet({ + title: t('Remove “{0}”?', item.name), + message: t('It is removed from this list. Nothing happens to the playlist itself — it is still in your Apple Music.'), + confirmText: t('Remove'), danger: true, + onConfirm: () => removePlaylist(item.id) + }) + + return <> +
+
+

{t('Music')}

+
{list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}
+
+ + +
+ + {profile + ? + + + @{S.music.user} + {t('Your public Apple Music profile')} + + + + :
+ +
+
{t('Add your Apple Music profile')}
+
+ {t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')} +
+
+
} + + {list.length === 0 + ?
+
+ {t('No playlists yet.')}
+ {t('Add one from the + above.')} +
+ : list.map(item => askRemove(item)} />)} + +
+ +} diff --git a/frontend/src/views/Music.test.jsx b/frontend/src/views/Music.test.jsx new file mode 100644 index 0000000..2427709 --- /dev/null +++ b/frontend/src/views/Music.test.jsx @@ -0,0 +1,75 @@ +// @vitest-environment happy-dom +/* The Música screen: a list of playlists a profile keeps, each one a link out to Apple Music. + Worth a render test because the whole feature is "the tile is the link" — if the href stops + being the playlist's own URL, or the tap target stops being the row, the screen still looks + right and does nothing. */ +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' + +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) })) + +const { default: Music } = await import('./Music.jsx') + +const item = (over = {}) => ({ id: 'pl.aaa', url: 'https://music.apple.com/us/playlist/leg-day/pl.aaa', kind: 'playlist', name: 'Leg Day', artwork: null, tracks: 42, curator: 'Ana', ...over }) + +let host, root +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + nav.mockClear() + host = document.createElement('div') + document.body.appendChild(host) + root = createRoot(host) + useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] } } })) +}) +afterEach(() => { act(() => root.unmount()); host.remove() }) + +const mount = async () => { await act(async () => { root.render() }) } +const links = () => [...host.querySelectorAll('a')] + +describe('Música', () => { + it('says how to get a playlist when there are none', async () => { + await mount() + expect(host.textContent).toContain('No playlists yet.') + expect(host.textContent).toContain('Add your Apple Music profile') + expect(links().length).toBe(0) + }) + + it('makes each playlist a link to its own Apple Music page', async () => { + useStore.setState(s => ({ S: { ...s.S, music: { user: 'ana', playlists: [item()] } } })) + await mount() + const [profile, playlist] = links() + expect(profile.getAttribute('href')).toBe('https://music.apple.com/profile/ana') + expect(playlist.getAttribute('href')).toBe('https://music.apple.com/us/playlist/leg-day/pl.aaa') + // Opening in a new context, and never handing the referrer to the target. + expect(playlist.getAttribute('rel')).toBe('noopener noreferrer') + expect(host.textContent).toContain('Leg Day') + // The track count, in whatever language is loaded (the tests run on the English keys) and + // under the curator's name when the page told us who made it. + expect(host.textContent).toContain('Ana · 42 songs') + }) + + it('removes one without touching the others', async () => { + useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [item(), item({ id: 'pl.bbb', name: 'Push Day' })] } } })) + await mount() + expect(host.textContent).toContain('Leg Day') + act(() => { useStore.getState().removePlaylist('pl.aaa') }) + await act(async () => {}) + expect(host.textContent).not.toContain('Leg Day') + expect(host.textContent).toContain('Push Day') + }) + + it('saving the same link twice does not duplicate the card', async () => { + useStore.setState(s => ({ S: { ...s.S, music: { user: '', playlists: [] } } })) + act(() => { useStore.getState().addPlaylist(item()) }) + act(() => { useStore.getState().addPlaylist(item({ name: 'Leg Day (again)' })) }) + await mount() + expect(host.querySelectorAll('.mus-card').length).toBe(1) + expect(host.textContent).toContain('Leg Day') + }) +}) diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index a9d5e0d..cb8fb06 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -22,6 +22,7 @@ import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '. export default function Settings() { const nav = useNavigate() + const setMusicUser = useStore(s => s.setMusicUser) const S = useStore(s => s.S) const user = useStore(s => s.user) const coachLocal = useStore(s => s.coachLocal) @@ -382,6 +383,19 @@ export default function Settings() { {/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */} +
+ {/* The username gets the field's own row rather than sharing one with its label: a 17px + input squeezed beside a title is a control you cannot read what you typed into. */} +
+
{t('Your Apple Music username')}
+ setMusicUser(e.target.value)} /> +
{t('Shown as a link to your public profile on the Música screen.')}
+
+ nav('/music')} /> +
+
{/* Above the file imports on purpose: this one keeps working after today, while the rows below it are one-shot reads of an export. */}