feat(federation): play a friend's music and show its covers through this server

A listener can now play the music of a friend from the web app.

- GET /friends/{friend}/tracks/{id}/stream and /friends/{friend}/albums/{id}/cover,
  in the group that accepts the access token in the query, like the local ones.
  This server asks the friend with a signed request and passes the bytes on,
  forwarding Range and the conditional headers, so a player can seek. The
  friend sees this server and never the listener.
- Only audio (for a stream) and a JPEG (for a cover) are passed on, with a
  fixed set of headers: Content-Type, Content-Length, Content-Range,
  Accept-Ranges, Last-Modified and ETag. Anything else a friend sends, or
  what a listener's request carries (cookies, authorization), is not passed
  either way, so a friend cannot make this server serve anything else.
- The client of friends can open a streaming answer: no limit on its whole
  length, one only on its beginning, no redirect followed, and it ends when
  the listener leaves.
- The player holds a friend's track next to the local ones. It streams
  through this server, shows the friend's cover, links to the music of the
  friend and not to a local page, is told apart from a local track with the
  same id, and is never reported as a listen: it does not feed taste.
- The songs of a friend have play buttons, the albums their covers.
- OpenAPI paths, contract test, and two real servers checked end to end: the
  bytes of the file arrive unchanged, with ranges, and a song plays in a
  browser from the friend's server through the other one.
This commit is contained in:
tgiachi 2026-11-13 16:11:59 +01:00
commit 7f38ae038e
18 changed files with 1093 additions and 62 deletions

View file

@ -81,3 +81,8 @@ test('a very long or empty artist name does not break the photo', () => {
fireEvent.error(container.querySelector('img')!)
expect(screen.getByText('?')).toBeInTheDocument()
})
test('the cover of a friend’s album comes through this server, from the friend’s route', () => {
const { container } = render(<Cover albumId={12} friend={3} size={64} />)
expect(container.querySelector('img')!.getAttribute('src')).toBe('/api/v1/friends/3/albums/12/cover')
})

View file

@ -1,17 +1,20 @@
import { useState } from 'react'
import { mediaUrl, useAccessToken } from '@/auth/session'
import { coverPath } from '@/player/media'
interface CoverProps {
albumId: number | null
/** The friend whose album it is, when it is not one of this server's. */
friend?: number
/** Pixels. With `fluid` it is the largest size: the cover shrinks to fit a narrow screen. */
size: number
fluid?: boolean
}
/** The cover of an album, or concentric rings when there is none (or it cannot be loaded). */
export default function Cover({ albumId, size, fluid = false }: CoverProps) {
export default function Cover({ albumId, friend, size, fluid = false }: CoverProps) {
useAccessToken() // the URL carries the token, so it has to follow a renewal
const src = albumId === null ? null : mediaUrl(`/albums/${albumId}/cover`)
const src = albumId === null ? null : mediaUrl(coverPath(friend, albumId))
// A failure is remembered for this URL only: a renewed token makes a new URL, which is tried again.
const [failed, setFailed] = useState<string | null>(null)
const showImage = src !== null && failed !== src

View file

@ -6,7 +6,11 @@ import TrackRow from './TrackRow'
/** The songs of a list. Clicking one plays the whole list from that song. */
export default function TrackList({ tracks }: { tracks: Track[] }) {
const playTracks = usePlayer((s) => s.playTracks)
const playingId = usePlayer((s) => currentTrack(s)?.id)
// Only a track of this server: a friend's may share the id.
const playingId = usePlayer((s) => {
const now = currentTrack(s)
return now && !now.friend ? now.id : undefined
})
return (
<div className="flex flex-col">
{tracks.map((track, i) => (

View file

@ -10,6 +10,7 @@ import VolumeControl from '@/components/VolumeControl'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'
import { formatTime } from '@/lib/time'
import { albumHref, artistHref } from '@/player/media'
import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import PlayerControls from './PlayerControls'
@ -65,7 +66,7 @@ export default function NowPlaying() {
<div className="mx-auto flex w-full max-w-5xl flex-wrap items-center justify-center gap-x-16 gap-y-8 pt-10">
<div className="flex min-w-0 flex-[1_1_320px] justify-center">
<Cover albumId={track.album?.id ?? null} size={520} fluid />
<Cover albumId={track.album?.id ?? null} friend={track.friend} size={520} fluid />
</div>
<div className="flex min-w-0 flex-[1_1_380px] flex-col gap-7">
@ -79,7 +80,7 @@ export default function NowPlaying() {
: track.artists.map((a, i) => (
<span key={a.id}>
{i > 0 && ', '}
<Link to={`/artists/${a.id}`} onClick={() => setOpen(false)} className="hover:underline">
<Link to={artistHref(track, a)} onClick={() => setOpen(false)} className="hover:underline">
{a.name}
</Link>
</span>
@ -87,7 +88,7 @@ export default function NowPlaying() {
</p>
{track.album && (
<Link
to={`/albums/${track.album.id}`}
to={albumHref(track, track.album)}
onClick={() => setOpen(false)}
className="text-muted-foreground hover:underline"
>

View file

@ -6,6 +6,7 @@ import { beforeEach, expect, test, vi } from 'vitest'
import type { Track } from '@/api/catalog'
import { sessionStore } from '@/auth/session'
import Scrubber from '@/components/Scrubber'
import TrackList from '@/components/TrackList'
import TrackRow from '@/components/TrackRow'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
@ -326,3 +327,31 @@ test('the seek bar of the player bar is 44 pixels high to take a thumb', () => {
render(<Scrubber positionMs={0} durationMs={1000} onSeek={() => {}} variant="line" />)
expect(screen.getByRole('slider')).toHaveClass('h-11')
})
const theirs = (n: number) => ({ ...track(n), friend: 3, album: { id: 10, title: 'Their Album' }, artists: [{ id: 5, name: 'Their Band' }] })
test('the bar shows a friend’s track with its cover and links to the music of the friend, not to a local page', () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
const { container } = renderBar()
expect(container.querySelector('img')!.getAttribute('src')).toContain('/api/v1/friends/3/albums/10/cover')
expect(screen.getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
})
test('the full-screen player links a friend’s track to the music of the friend', async () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
renderBar()
await userEvent.click(screen.getByRole('button', { name: 'Open the full-screen player' }))
const dialog = screen.getByRole('dialog')
expect(within(dialog).getByRole('link', { name: 'Their Album' })).toHaveAttribute('href', '/friends/3?tab=songs&album=10&of=Their+Album')
expect(within(dialog).getByRole('link', { name: 'Their Band' })).toHaveAttribute('href', '/friends/3?tab=albums&artist=5&of=Their+Band')
})
test('a local list does not mark a row because a friend’s track with the same id is playing', () => {
act(() => usePlayer.getState().playTracks([theirs(1)]))
render(
<MemoryRouter>
<TrackList tracks={[a]} />
</MemoryRouter>,
)
expect(screen.getByRole('button', { name: /Song 1/ })).not.toHaveAttribute('aria-current')
})

View file

@ -9,6 +9,7 @@ import Scrubber from '@/components/Scrubber'
import VolumeControl from '@/components/VolumeControl'
import { Button } from '@/components/ui/button'
import { formatTime } from '@/lib/time'
import { artistHref } from '@/player/media'
import { currentTrack, usePlayer } from '@/player/store'
import { useNowPlayingUi } from '@/player/ui'
import NowPlaying from './NowPlaying'
@ -60,7 +61,7 @@ export default function PlayerBar() {
{track ? (
<>
<button type="button" aria-label={t('player.open')} onClick={() => setOpen(true)} className="rounded-md">
<Cover albumId={track.album?.id ?? null} size={56} />
<Cover albumId={track.album?.id ?? null} friend={track.friend} size={56} />
</button>
<div className="flex min-w-0 flex-col">
<button type="button" onClick={() => setOpen(true)} className="truncate text-left font-bold">
@ -72,7 +73,7 @@ export default function PlayerBar() {
: track.artists.map((a, i) => (
<span key={a.id}>
{i > 0 && ', '}
<Link to={`/artists/${a.id}`} className="hover:underline">
<Link to={artistHref(track, a)} className="hover:underline">
{a.name}
</Link>
</span>

View file

@ -550,7 +550,6 @@
"noneYet": "You have no friends yet. An admin makes friends in Admin → Federation.",
"musicOf": "Music of {{name}}",
"whose": "{{name}}’s server shares this music. It is asked for when you open a page and is never copied here.",
"noPlayYet": "For now you can browse this music; playing it comes next.",
"searchLabel": "Search the music of {{name}}",
"searchPlaceholder": "Artists, albums and songs",
"tabsLabel": "Sections of {{name}}’s music",

View file

@ -550,7 +550,6 @@
"noneYet": "Non hai ancora amici. Un admin li crea in Admin → Federazione.",
"musicOf": "Musica di {{name}}",
"whose": "Questa musica la condivide il server di {{name}}. Viene chiesta quando apri una pagina e qui non viene mai copiata.",
"noPlayYet": "Per ora puoi solo sfogliare questa musica; l'ascolto arriva dopo.",
"searchLabel": "Cerca nella musica di {{name}}",
"searchPlaceholder": "Artisti, album e brani",
"tabsLabel": "Sezioni della musica di {{name}}",

View file

@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
import { createMemoryRouter, RouterProvider } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
import FriendPage from './FriendPage'
@ -40,6 +41,7 @@ function renderAt(url = '/friends/3') {
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0, shuffle: false, repeat: 'off', playId: 0 })
})
test('it is headed with the name of the friend and says whose music this is', async () => {
@ -155,3 +157,30 @@ test('a friend that is not in the list is not there', async () => {
renderAt()
expect(await screen.findByText('This friend is not there any more.')).toBeInTheDocument()
})
test('a song of a friend plays when it is clicked, with the rest of the page after it, as the friend’s tracks', async () => {
const user = userEvent.setup()
mockFetch(routes())
renderAt('/friends/3?tab=songs')
await user.click(await screen.findByRole('button', { name: /Second Song/ }))
const state = usePlayer.getState()
expect(state.playing).toBe(true)
expect(state.index).toBe(1)
expect(state.queue.map((t) => [t.id, t.friend])).toEqual([[1, 3], [2, 3]])
expect(screen.getByRole('button', { name: /Second Song/ })).toHaveAttribute('aria-current', 'true')
expect(screen.getByRole('button', { name: /Shared Song/ })).not.toHaveAttribute('aria-current')
})
test('a local song with the same id is not the one that is marked as playing', async () => {
mockFetch(routes())
usePlayer.getState().playTracks([{ ...track(2, 'Local'), album: null, artists: [] }])
renderAt('/friends/3?tab=songs')
expect(await screen.findByRole('button', { name: /Second Song/ })).not.toHaveAttribute('aria-current')
})
test('the albums of a friend show their covers from this server’s route for that friend', async () => {
mockFetch(routes())
renderAt('/friends/3?tab=albums')
const row = (await screen.findByText('Shared Album')).closest('li') as HTMLElement
expect(row.querySelector('img')!.getAttribute('src')).toContain('/api/v1/friends/3/albums/7/cover')
})

View file

@ -3,11 +3,15 @@ import { useTranslation } from 'react-i18next'
import { useParams, useSearchParams } from 'react-router-dom'
import { ApiError } from '@/api/client'
import { useFriendAlbums, useFriendArtists, useFriends, useFriendTracks } from '@/api/friends'
import Cover from '@/components/Cover'
import LoadMore from '@/components/LoadMore'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { Button } from '@/components/ui/button'
import TrackRow from '@/components/TrackRow'
import { Input } from '@/components/ui/input'
import { formatTime } from '@/lib/time'
import { trackKey } from '@/player/media'
import { currentTrack, usePlayer } from '@/player/store'
import { cn } from '@/lib/utils'
const TABS = ['artists', 'albums', 'songs'] as const
@ -60,6 +64,11 @@ export default function FriendPage() {
const [text, setText] = useState(params.get('q') ?? '')
const q = Array.from(text.trim()).slice(0, MAX_QUERY_LENGTH).join('')
const buttons = useRef<Record<string, HTMLButtonElement | null>>({})
const playTracks = usePlayer((st) => st.playTracks)
const playingKey = usePlayer((st) => {
const now = currentTrack(st)
return now ? trackKey(now) : null
})
// The search is kept in the address, but only once typing stops: the friend is asked once, not for every letter.
const [typed, setTyped] = useState(q)
@ -114,7 +123,6 @@ export default function FriendPage() {
<div className="flex flex-col gap-2">
<h1 className="text-3xl font-extrabold tracking-tight">{t('friends.musicOf', { name })}</h1>
<p className="text-sm text-muted-foreground">{t('friends.whose', { name })}</p>
<p className="text-sm text-muted-foreground">{t('friends.noPlayYet')}</p>
</div>
<div className="max-w-xl">
@ -188,6 +196,7 @@ export default function FriendPage() {
albums.data?.items.map((a) => (
<li key={a.id}>
<button type="button" className={cn(rowClass, 'hover:bg-secondary')} onClick={() => go({ tab: 'songs', album: String(a.id), of: a.title })}>
<Cover albumId={a.id} friend={friendId} size={48} />
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold">{a.title}</span>
<span className="block truncate text-sm text-muted-foreground">{a.artist?.name ?? '—'}</span>
@ -199,14 +208,14 @@ export default function FriendPage() {
</li>
))}
{tab === 'songs' &&
songs.data?.items.map((s, i) => (
<li key={s.id} className={cn(rowClass, 'grid grid-cols-[2.5rem_minmax(0,1fr)_4.5rem]')}>
<span className="tabular-nums text-muted-foreground">{s.track_no > 0 ? s.track_no : i + 1}</span>
<span className="min-w-0">
<span className="block truncate font-semibold">{s.title}</span>
<span className="block truncate text-sm text-muted-foreground">{s.artists.map((a) => a.name).join(', ') || '—'}</span>
</span>
<span className="text-right text-sm tabular-nums text-muted-foreground">{formatTime(s.duration_ms)}</span>
songs.data?.items.map((song, i) => (
<li key={song.id}>
<TrackRow
track={song}
index={i}
active={playingKey === trackKey({ id: song.id, friend: friendId })}
onPlay={() => playTracks((songs.data?.items ?? []).map((x) => ({ ...x, friend: friendId })), i)}
/>
</li>
))}
</ul>

View file

@ -46,7 +46,11 @@ function PlaylistView({ id }: { id: number }) {
const remove = useRemoveItem()
const del = useDeletePlaylist()
const playTracks = usePlayer((s) => s.playTracks)
const playingId = usePlayer((s) => currentTrack(s)?.id)
// Only a track of this server: a friend's may share the id.
const playingId = usePlayer((s) => {
const now = currentTrack(s)
return now && !now.friend ? now.id : undefined
})
const [renaming, setRenaming] = useState(false)
const [deleting, setDeleting] = useState(false)
const [started, setStarted] = useState<number | null>(null)

View file

@ -62,6 +62,8 @@ function track(n: number): Track {
}
const [t1, t2, t3] = [1, 2, 3].map(track)
/** A track of a friend's server: the same shape, the friend's own id, and the friend's number. */
const theirs = (n: number, friend = 3) => ({ ...track(n), friend })
function session(access: string) {
return {
@ -284,3 +286,58 @@ test('after destroy the engine no longer listens to anyone', async () => {
await login('tom', 'secret123')
expect(audio.src).toBe('')
})
test('a track of a friend is loaded through this server, from the stream of that friend', () => {
usePlayer.getState().playTracks([theirs(9)])
expect(audio.src).toBe('/api/v1/friends/3/tracks/9/stream?access_token=tok1')
expect(audio.paused).toBe(false)
})
test('a track of a friend is never reported as a listen', () => {
usePlayer.getState().playTracks([theirs(9), theirs(10)])
expect(hooks.onStart).not.toHaveBeenCalled()
audio.currentTime = 1.5
audio.emit('timeupdate')
expect(hooks.onPlayed).not.toHaveBeenCalled()
audio.emit('ended')
expect(usePlayer.getState().index).toBe(1)
expect(hooks.onFinish).not.toHaveBeenCalled()
usePlayer.getState().next()
expect(hooks.onFinish).not.toHaveBeenCalled()
})
test('leaving a local track for a friend’s still closes the local play, and coming back opens a new one', () => {
usePlayer.getState().playTracks([t1, theirs(9), t2])
expect(hooks.onStart).toHaveBeenCalledWith(1)
audio.currentTime = 2
audio.emit('timeupdate')
usePlayer.getState().next() // to the friend's
expect(hooks.onFinish).toHaveBeenCalledTimes(1)
expect(hooks.onFinish).toHaveBeenCalledWith('skip')
expect(hooks.onStart).toHaveBeenCalledTimes(1)
usePlayer.getState().next() // back to a local one
expect(audio.src).toBe('/api/v1/tracks/2/stream?access_token=tok1')
expect(hooks.onStart).toHaveBeenLastCalledWith(2)
expect(hooks.onFinish).toHaveBeenCalledTimes(1) // nothing was played of the friend's
})
test('a friend’s track and a local one with the same id are two tracks', () => {
usePlayer.getState().playTracks([t1, theirs(1)])
expect(audio.src).toBe('/api/v1/tracks/1/stream?access_token=tok1')
usePlayer.getState().next()
expect(audio.src).toBe('/api/v1/friends/3/tracks/1/stream?access_token=tok1')
usePlayer.getState().playTracks([theirs(1, 4)])
expect(audio.src).toBe('/api/v1/friends/4/tracks/1/stream?access_token=tok1')
})
test('a renewed token keeps a friend’s track playing from the same second', async () => {
usePlayer.getState().playTracks([theirs(9)])
audio.currentTime = 42
mockFetch({ 'POST /api/v1/auth/login': () => session('tok2') })
await login('tom', 'secret123')
expect(audio.src).toBe('/api/v1/friends/3/tracks/9/stream?access_token=tok2')
audio.emit('loadedmetadata')
expect(audio.currentTime).toBe(42)
expect(hooks.onStart).not.toHaveBeenCalled()
})

View file

@ -1,4 +1,5 @@
import { mediaUrl, onTokenChange } from '@/auth/session'
import { streamPath, trackKey, type QueuedTrack } from './media'
import { currentTrack, usePlayer, type PlayerState } from './store'
export type AudioEvent = 'timeupdate' | 'ended' | 'error' | 'loadedmetadata'
@ -32,7 +33,7 @@ export interface EngineHooks {
/** The largest step of `timeupdate` that counts as listening; a bigger one is a seek. */
const MAX_STEP_MS = 2000
const streamUrl = (trackId: number) => mediaUrl(`/tracks/${trackId}/stream`)
const streamUrl = (track: QueuedTrack) => mediaUrl(streamPath(track))
/**
* Drives an audio element from the player store: loads the current track, plays and pauses, seeks,
@ -40,7 +41,9 @@ const streamUrl = (trackId: number) => mediaUrl(`/tracks/${trackId}/stream`)
*/
export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destroy(): void } {
const initial = usePlayer.getState()
let loadedId: number | null = null
let loaded: QueuedTrack | null = null
// Only a track of this server is reported as a listen: what plays from a friend's is not this person's taste here.
let counts = false
let loadedPlayId = initial.playId
let loadedSeekId = initial.seekId
let finished = true
@ -53,7 +56,7 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
}
function load(state: PlayerState) {
if (loadedId !== null && !finished && playedMs > 0) hooks.onFinish?.('skip')
if (loaded !== null && counts && !finished && playedMs > 0) hooks.onFinish?.('skip')
const track = currentTrack(state)
loadedPlayId = state.playId
loadedSeekId = state.seekId
@ -63,14 +66,16 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
if (!track) {
audio.pause()
audio.src = ''
loadedId = null
loaded = null
counts = false
finished = true
return
}
audio.src = streamUrl(track.id)
loadedId = track.id
audio.src = streamUrl(track)
loaded = track
counts = !track.friend
finished = false
hooks.onStart?.(track.id)
if (counts) hooks.onStart?.(track.id)
if (state.playing) play()
}
@ -79,11 +84,11 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
const ms = state.seekMs ?? 0
audio.currentTime = ms / 1000
lastTime = ms
if (finished && ms === 0 && loadedId !== null) {
if (finished && ms === 0 && loaded !== null) {
// The track ran to its end and starts over: that is a new play.
finished = false
playedMs = 0
hooks.onStart?.(loadedId)
if (counts) hooks.onStart?.(loaded.id)
}
if (state.playing && state.playing === previous.playing) play()
}
@ -92,7 +97,7 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
if (state.volume !== previous.volume) audio.volume = state.volume
if (state.muted !== previous.muted) audio.muted = state.muted
const track = currentTrack(state)
if ((track?.id ?? null) !== loadedId || state.playId !== loadedPlayId) {
if ((track ? trackKey(track) : null) !== (loaded ? trackKey(loaded) : null) || state.playId !== loadedPlayId) {
load(state)
return
}
@ -110,9 +115,9 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
sync(initial, { ...initial, queue: [], playId: initial.playId - 1 })
const unsubscribeToken = onTokenChange(() => {
if (loadedId === null) return
if (loaded === null) return
pendingRestore = { time: audio.currentTime, resume: usePlayer.getState().playing }
audio.src = streamUrl(loadedId)
audio.src = streamUrl(loaded)
})
const onLoadedMetadata = () => {
@ -131,14 +136,14 @@ export function createEngine(audio: AudioLike, hooks: EngineHooks = {}): { destr
if (!audio.paused && delta > 0) {
const step = Math.min(delta, MAX_STEP_MS)
playedMs += step
hooks.onPlayed?.(step)
if (counts) hooks.onPlayed?.(step)
}
}
const onEnded = () => {
if (!finished) {
finished = true
hooks.onFinish?.('complete')
if (counts) hooks.onFinish?.('complete')
}
usePlayer.getState().trackEnded()
}

30
web/src/player/media.ts Normal file
View file

@ -0,0 +1,30 @@
import type { Track } from '@/api/catalog'
/**
* A track in the queue. A track of a friend's server has the friend's number: its id is the friend's own, so the
* two together are what names it, and it is played, shown and reported through that friend and not as a local track.
*/
export type QueuedTrack = Track & { friend?: number }
/** What tells two queued tracks apart: a friend's track and a local one may share an id. */
export const trackKey = (t: Pick<QueuedTrack, 'id' | 'friend'>): string => `${t.friend ?? 0}:${t.id}`
/** The API path of the audio of a track. A friend's goes through this server, which asks the friend. */
export const streamPath = (t: Pick<QueuedTrack, 'id' | 'friend'>): string =>
t.friend ? `/friends/${t.friend}/tracks/${t.id}/stream` : `/tracks/${t.id}/stream`
/** The API path of the cover of an album of this server (no friend) or of a friend. */
export const coverPath = (friend: number | undefined, albumId: number): string =>
friend ? `/friends/${friend}/albums/${albumId}/cover` : `/albums/${albumId}/cover`
/** Where a link to an artist of a track goes: its page here, or the albums of it in the music of the friend. */
export function artistHref(track: Pick<QueuedTrack, 'friend'>, artist: { id: number; name: string }): string {
if (!track.friend) return `/artists/${artist.id}`
return `/friends/${track.friend}?${new URLSearchParams({ tab: 'albums', artist: String(artist.id), of: artist.name })}`
}
/** Where a link to the album of a track goes: its page here, or the songs of it in the music of the friend. */
export function albumHref(track: Pick<QueuedTrack, 'friend'>, album: { id: number; title: string }): string {
if (!track.friend) return `/albums/${album.id}`
return `/friends/${track.friend}?${new URLSearchParams({ tab: 'songs', album: String(album.id), of: album.title })}`
}

View file

@ -83,3 +83,9 @@ test('nothing playing clears the lock screen', () => {
test('a browser without the Media Session API is left alone', () => {
expect(() => setMediaSession(track, handlers)).not.toThrow()
})
test('the lock screen shows the cover of a friend’s album from the friend’s route', () => {
const { mediaSession } = withMediaSession()
setMediaSession({ ...track, friend: 3, album: { id: 12, title: 'Their Album' } }, handlers)
expect(mediaSession.metadata?.artwork[0].src).toBe('/api/v1/friends/3/albums/12/cover')
})

View file

@ -1,5 +1,5 @@
import type { Track } from '@/api/catalog'
import { mediaUrl } from '@/auth/session'
import { coverPath, type QueuedTrack } from './media'
export interface MediaKeyHandlers {
play(): void
@ -9,7 +9,7 @@ export interface MediaKeyHandlers {
}
/** Tells the operating system what is playing (lock screen, media keys). Does nothing where the API is missing. */
export function setMediaSession(track: Track | null, handlers: MediaKeyHandlers): void {
export function setMediaSession(track: QueuedTrack | null, handlers: MediaKeyHandlers): void {
const session = navigator.mediaSession as MediaSession | undefined
if (!session) return
if (!track) {
@ -20,7 +20,7 @@ export function setMediaSession(track: Track | null, handlers: MediaKeyHandlers)
title: track.title,
artist: track.artists.map((a) => a.name).join(', '),
album: track.album?.title ?? '',
artwork: track.album ? [{ src: mediaUrl(`/albums/${track.album.id}/cover`) }] : [],
artwork: track.album ? [{ src: mediaUrl(coverPath(track.friend, track.album.id)) }] : [],
})
session.setActionHandler('play', handlers.play)
session.setActionHandler('pause', handlers.pause)

View file

@ -1,18 +1,18 @@
import { create } from 'zustand'
import type { Track } from '@/api/catalog'
import { loadVolume, saveVolume } from './volume'
import type { QueuedTrack } from './media'
export type Repeat = 'off' | 'all' | 'one'
export interface PlayerState {
queue: Track[]
queue: QueuedTrack[]
index: number
playing: boolean
positionMs: number
shuffle: boolean
repeat: Repeat
/** The queue in its own order, kept while it is shuffled so that turning shuffle off can restore it. */
original: Track[]
original: QueuedTrack[]
/** The audio engine moves to `seekMs` whenever `seekId` changes. */
seekMs: number | null
seekId: number
@ -22,15 +22,15 @@ export interface PlayerState {
volume: number
muted: boolean
playTracks(tracks: Track[], start?: number): void
playTracks(tracks: QueuedTrack[], start?: number): void
togglePlay(): void
next(): void
prev(): void
trackEnded(): void
seek(ms: number): void
tick(positionMs: number): void
enqueue(track: Track): void
playNext(track: Track): void
enqueue(track: QueuedTrack): void
playNext(track: QueuedTrack): void
removeAt(i: number): void
toggleShuffle(): void
cycleRepeat(): void
@ -61,7 +61,7 @@ function shuffled<T>(items: T[]): T[] {
return out
}
export function currentTrack(state: Pick<PlayerState, 'queue' | 'index'>): Track | null {
export function currentTrack(state: Pick<PlayerState, 'queue' | 'index'>): QueuedTrack | null {
return state.queue[state.index] ?? null
}

View file

@ -3,6 +3,7 @@ import { sendListen } from '@/api/listens'
import { uuid } from '@/lib/uuid'
import { createEngine } from './engine'
import { createListenReporter } from './listens'
import { trackKey } from './media'
import { setMediaSession } from './mediaSession'
import { currentTrack, usePlayer } from './store'
@ -36,7 +37,8 @@ export function usePlayerEngine(): void {
}
const stopMediaSession = usePlayer.subscribe((state, previous) => {
const track = currentTrack(state)
if (track?.id !== currentTrack(previous)?.id) setMediaSession(track, keys)
const before = currentTrack(previous)
if ((track ? trackKey(track) : null) !== (before ? trackKey(before) : null)) setMediaSession(track, keys)
})
return () => {