Música: a playlist screen per profile, with Apple's limits stated plainly
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
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers 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: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be.
This commit is contained in:
1 parent
45183c725f
commit
caed0cbaa0
18 files changed
+743
-16
No files matched your search
@@ -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. */}
|
||||
<Route path="/health" element={<Health />} />
|
||||
{/* 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. */}
|
||||
<Route path="/music" element={<Music />} />
|
||||
<Route path="/history" element={<History />} />
|
||||
<Route path="/library" element={<Library />} />
|
||||
<Route path="/muscles" element={<Muscles />} />
|
||||
|
||||
@@ -80,6 +80,7 @@ const P = {
|
||||
reset: <><path d="M4.4 12a7.6 7.6 0 1 0 2.3-5.4" /><path d="M4 4.4v4.4h4.4" /></>,
|
||||
bell: <><path d="M6.6 10.4a5.4 5.4 0 0 1 10.8 0c0 4 1.4 5.6 1.4 5.6H5.2s1.4-1.6 1.4-5.6Z" /><path d="M10.1 19.2a2.1 2.1 0 0 0 3.8 0" /></>,
|
||||
bellSlash: <><path d="M8.1 6.6a5.4 5.4 0 0 1 9.3 3.8c0 4 1.4 5.6 1.4 5.6H9.4M6.6 16H5.2s1.4-1.6 1.4-5.6v-.6" /><path d="M10.1 19.2a2.1 2.1 0 0 0 3.8 0M4 3.6l16 16.8" /></>,
|
||||
music: <><path d="M9.2 17.6V6.9l8-1.7v10.6" /><ellipse cx="6.9" cy="17.7" rx="2.3" ry="2" /><ellipse cx="14.9" cy="15.9" rx="2.3" ry="2" /></>,
|
||||
chevronRight: <path d="m9.6 5.6 6.6 6.4-6.6 6.4" />,
|
||||
chevronLeft: <path d="m14.4 5.6-6.6 6.4 6.6 6.4" />,
|
||||
chevronDown: <path d="m5.6 9.4 6.4 6.2 6.4-6.2" />,
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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('')
|
||||
})
|
||||
})
|
||||
@@ -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}',
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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(<Home />))
|
||||
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(<Home />))
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -72,6 +72,7 @@ export default function Home() {
|
||||
the title gives way on a narrow phone, these two do not. */}
|
||||
<div style={{ display: 'flex', gap: 8, flex: 'none' }}>
|
||||
<button className="iconbtn" onClick={() => nav('/health')} aria-label={t('Health')} title={t('Health')}><Icon name="heart" /></button>
|
||||
<button className="iconbtn" onClick={() => nav('/music')} aria-label={t('Music')} title={t('Music')}><Icon name="music" /></button>
|
||||
<button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Settings')}><Icon name="gear" /></button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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 <div className="card mus-card">
|
||||
<a className="mus-link" href={item.url} target="_blank" rel="noopener noreferrer">
|
||||
{item.artwork
|
||||
? <img className="mus-art" src={item.artwork} alt="" loading="lazy" />
|
||||
: <span className="mus-art mus-art-ph"><Icon name="music" /></span>}
|
||||
<span className="mus-meta">
|
||||
<span className="mus-name">{item.name}</span>
|
||||
<span className="mus-sub">
|
||||
{item.curator ? item.curator + ' · ' : ''}
|
||||
{item.tracks ? t('{0} songs', item.tracks) : t('Open in Apple Music')}
|
||||
</span>
|
||||
</span>
|
||||
<Icon name="play" className="mus-go" />
|
||||
</a>
|
||||
<button className="iconbtn mus-del" onClick={onRemove} aria-label={t('Remove')}><Icon name="trash" /></button>
|
||||
</div>
|
||||
}
|
||||
|
||||
/** 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 <>
|
||||
<h3>{t('Add a playlist')}</h3>
|
||||
<div className="small dim" style={{ lineHeight: 1.5, marginBottom: 12 }}>
|
||||
{t('In Apple Music, open the playlist → Share → Copy Link, and paste it here. Tapping it in this app opens it in Apple Music.')}
|
||||
</div>
|
||||
<input className="field" value={url} onChange={e => setUrl(e.target.value)} placeholder="https://music.apple.com/…" inputMode="url" autoCapitalize="off" autoCorrect="off" spellCheck={false} />
|
||||
{bad && <div className="small" style={{ color: 'var(--orange)', marginTop: 6 }}>{t('That is not an Apple Music link.')}</div>}
|
||||
{parsed && <div className="small dim" style={{ marginTop: 6 }}>{t('{0} link', parsed.kind === 'playlist' ? t('Playlist') : parsed.kind === 'album' ? t('Album') : t('Track'))}</div>}
|
||||
<div style={{ height: 10 }} />
|
||||
<input className="field" value={name} onChange={e => setName(e.target.value)} placeholder={t('Name (optional)')} maxLength={60} />
|
||||
<div style={{ height: 14 }} />
|
||||
<Button variant="primary" icon="check" disabled={!parsed || busy} onClick={save}>{busy ? t('Reading the link…') : t('Add')}</Button>
|
||||
<div style={{ height: 8 }} />
|
||||
<Button variant="ghost" className="dim" onClick={close}>{t('Cancel')}</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
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 <>
|
||||
<div className="hdr">
|
||||
<div style={{ flex: 1 }}>
|
||||
<h1>{t('Music')}</h1>
|
||||
<div className="sub">{list.length ? t('{0} playlists', list.length) : t('Your Apple Music, one tap away')}</div>
|
||||
</div>
|
||||
<button className="iconbtn" onClick={() => openSheet(close => <AddPlaylistSheet close={close} />)} aria-label={t('Add a playlist')}><Icon name="plus" /></button>
|
||||
<button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Settings')}><Icon name="gear" /></button>
|
||||
</div>
|
||||
|
||||
{profile
|
||||
? <a className="card mus-profile" href={profile} target="_blank" rel="noopener noreferrer">
|
||||
<Icon name="personCircle" className="mus-profile-i" />
|
||||
<span className="mus-meta">
|
||||
<span className="mus-name">@{S.music.user}</span>
|
||||
<span className="mus-sub">{t('Your public Apple Music profile')}</span>
|
||||
</span>
|
||||
<Icon name="chevronRight" className="mus-go" />
|
||||
</a>
|
||||
: <div className="card mus-hint">
|
||||
<Icon name="music" className="mus-hint-i" />
|
||||
<div>
|
||||
<div className="mus-name">{t('Add your Apple Music profile')}</div>
|
||||
<div className="small dim" style={{ lineHeight: 1.45 }}>
|
||||
{t('Put your username in Settings and it becomes a link here. Apple has no way to publish your playlists automatically, so the ones you want on this screen are the ones you add.')}
|
||||
</div>
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{list.length === 0
|
||||
? <div className="empty">
|
||||
<div className="ico"><Icon name="music" /></div>
|
||||
{t('No playlists yet.')}<br />
|
||||
<span className="small dim">{t('Add one from the + above.')}</span>
|
||||
</div>
|
||||
: list.map(item => <PlaylistCard key={item.id} item={item} onRemove={() => askRemove(item)} />)}
|
||||
|
||||
<div style={{ height: 16 }} />
|
||||
</>
|
||||
}
|
||||
@@ -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(<Music />) }) }
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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() {
|
||||
</Section>
|
||||
|
||||
{/* ---------- data: fill it, bring things over, back it up, wipe it ---------- */}
|
||||
<Section title={t('Apple Music')} footer={t("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.")}>
|
||||
{/* 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. */}
|
||||
<div className="set-field">
|
||||
<div className="sect-t" style={{ padding: 0 }}>{t('Your Apple Music username')}</div>
|
||||
<TextField value={(S.music && S.music.user) || ''} placeholder="@username" maxLength={40}
|
||||
autoCapitalize="off" autoCorrect="off" spellCheck={false}
|
||||
onChange={e => setMusicUser(e.target.value)} />
|
||||
<div className="small dim" style={{ marginTop: 6 }}>{t('Shown as a link to your public profile on the Música screen.')}</div>
|
||||
</div>
|
||||
<Row icon="list" title={t('Your playlists')} subtitle={t('{0} saved', ((S.music && S.music.playlists) || []).length)} accessory="chevron" onClick={() => nav('/music')} />
|
||||
</Section>
|
||||
|
||||
<Section title={t('Data')}>
|
||||
{/* Above the file imports on purpose: this one keeps working after today, while the rows
|
||||
below it are one-shot reads of an export. */}
|
||||
|
||||
Reference in new issue
Block a user