Radio in the web app #30

Merged
squid merged 1 commit from feat/radio-web into main 2026-11-16 11:19:29 +00:00
22 changed files with 518 additions and 12 deletions

View file

@ -37,6 +37,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
- **Similar artists.** With Last.fm turned on, `GET /artists/{id}/similar` lists artists similar to an artist, and says which of them you already have. See [External providers](#external-providers). Without it, Sonda makes no outbound network requests at all.
- **Friends (federation).** Two Sonda servers can become friends, and the listeners of one can read what the other chose to share. `PUT /federation` (admin) turns federation on, which is off by default, and gives this server a name and a public address (`https`; plain `http` only on a network of your own); the server then makes its own Ed25519 key, kept in the database and never returned. `POST /federation/invites` makes an invite that works once and expires in 24 hours (only a hash of its code is kept). The other admin uses it with `POST /federation/friends`: that server is asked to accept this one, the key it answers with must be the one named in the invite, and the friend waits as `outgoing` until the first admin approves it with `POST /federation/friends/{id}/approve` (`POST /federation/friends/{id}/check` lets the waiting side find out). Either side can remove a friend with `DELETE /federation/friends/{id}`. Nothing is shared until an admin turns on `shared` for a library (`PATCH /libraries/{id}`). A friend's server then reads, with requests signed by its key (the method, the path and query, a date, a nonce and the hash of the body), the routes under `/peer`: the artists, albums and songs that have a file in a shared library, their covers once they are built, and the audio itself with `Range`. A friend never sees a path, a library id, a listen, a taste or a user, never makes this server build a cover or ask a provider, and has a few streams at a time and a number of KiB a second to share (`max_streams`, `max_kib_per_sec`); the admin sees the last requests it made (`GET /federation/requests`, the route and the size, never what was searched for). Sharing a library lets friends play it and, in practice, copy its files. A listener browses the music of a friend with `GET /friends` (the names of the friends whose friendship both admins agreed to, never an address or a key) and `GET /friends/{friend}/artists`, `albums` and `tracks` with `q`, `limit` and `offset`, and one item at a time: this server asks the friend with a signed request, checks the shape of the answer and passes it on, and nothing is kept; the ids are the friend's own. A friend that cannot be reached or no longer takes this server for a friend is told in words. The web app has a Friends section for it, shown only when there is a friend to browse. A listener plays it with `GET /friends/{friend}/tracks/{id}/stream` and sees its covers with `GET /friends/{friend}/albums/{id}/cover`, which accept the access token in the query like the local ones: this server asks the friend with a signed request, forwards `Range` and the conditional headers, and passes on only audio (or a JPEG for a cover) with `Content-Type`, `Content-Length`, `Content-Range`, `Accept-Ranges`, `Last-Modified` and `ETag`, so the friend sees this server and never the listener, and a friend cannot make this server serve anything else. A friend's song plays in the same player as the others but is never reported as a listen and does not feed taste. The admin area has a Federation section for all of it.
- **Radio.** Stations that Sonda makes by itself from your music, with nothing to set up, and without end: *Everything*, one for each decade that has at least 30 songs by 4 artists (from the year in the tags), and the mixes you have (one for each genre, *Your favourites*, *Rediscover*, *New to you*), plus the radio of an artist from its page. `GET /radio` lists the stations and `GET /radio/{id}` gives up to 50 songs of one, **other songs every time it is asked**, picked like a mix (your taste and your hearts count, nothing skipped lately, at most 3 by one artist); `artist:<id>` is the station of an artist (their songs weigh four times as much, with the songs of the two genres most of theirs have). The web app has a Radio page and a *Start radio* button on every artist, and its player asks for more songs by itself before the queue runs out. Apps that speak OpenSubsonic see each station as a playlist called *Radio · Rock*, with other songs every time it is opened (an app has no way to play a radio that never ends). Nothing is stored and nothing leaves the server.
- **Favourites.** `PUT /me/favorites/{kind}/{id}` marks a song, an album or an artist (`kind` is `tracks`, `albums` or `artists`) as a favourite and `DELETE` takes it back; `GET /me/favorites/{kind}` lists them, the newest first, and `GET /me/favorites/ids` gives every id for the hearts of a list. They are yours alone: never shown to a friend and never sent anywhere. Favourites also teach Sonda your taste: a favourite artist counts as much as three complete listens, a favourite album for its artist 1.5, a favourite song 1 (at most 6 for one artist), and the mixes of what you like give a favourite song more chance (and a song of a favourite album a little more). That feeds Discover, the mixes and the smart playlists that use your taste, and `GET /me/taste`. The web app has a heart on every song, album and artist (and in the player) and a Favourites page. Apps that speak OpenSubsonic see them as starred things.
- **Other apps.** Apps that speak OpenSubsonic (Symfonium, Feishin, Amperfy, Supersonic and others) can browse, search, play, show covers, use your playlists and report what you listened to, with a password of their own for each app (see [Other apps](#other-apps-opensubsonic)).
@ -307,7 +308,7 @@ A device password opens your music in that app and nothing else: it cannot sign
| `getAlbumList2` | Random, newest, frequent, recent, by name, by artist, by year, by genre. |
| `getRandomSongs`, `getSongsByGenre`, `search3` | Find songs, albums and artists. |
| `stream`, `download`, `getCoverArt` | The original file (with Range), and covers of albums, artists and songs. |
| `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `deletePlaylist` | Your playlists, the same ones as in the web app. |
| `getPlaylists`, `getPlaylist`, `createPlaylist`, `updatePlaylist`, `deletePlaylist` | Your playlists, the same ones as in the web app. After them, each station of the radio is a playlist (`rd-…`, *Radio · Rock*) with other songs every time it is opened; they cannot be changed or deleted. |
| `scrobble` | A listen is recorded like one made in the web app (and shared on Mastodon if you connected it). A "now playing" message is not recorded. |
| `star`, `unstar`, `getStarred2` | Your favourites (see **Favourites**): songs, albums and artists, with the `starred` date on each, and `getAlbumList2` of type `starred`. |
| `setRating`, `getNowPlaying` | Answered with nothing: there are no ratings, and what you play is nobody else's business. |

22
web/src/api/radio.ts Normal file
View file

@ -0,0 +1,22 @@
import { useMutation, useQuery } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
export type RadioStation = components['schemas']['RadioStation']
export type RadioStationWithTracks = components['schemas']['RadioStationWithTracks']
/** The id goes in the path, and a genre station has the genre in it (`genre:hard rock`). */
export const radioPath = (id: string) => `/radio/${encodeURIComponent(id)}`
/** The stations Sonda makes for me. */
export function useRadioStations() {
return useQuery({ queryKey: ['radio'], queryFn: () => api.get<{ items: RadioStation[] }>('/radio').then((r) => r.items) })
}
/** Asks for the songs of a station: other ones every time. */
export const fetchRadio = (id: string) => api.get<RadioStationWithTracks>(radioPath(id))
/** Starts a station: its songs are asked for and played, and the player asks for more by itself. */
export function useStartRadio() {
return useMutation({ mutationFn: (id: string) => fetchRadio(id) })
}

View file

@ -58,6 +58,7 @@ export default function NowPlaying() {
const queue = usePlayer((s) => s.queue)
const index = usePlayer((s) => s.index)
const jumpTo = usePlayer((s) => s.jumpTo)
const radio = usePlayer((s) => s.radio)
const upNextRef = useRef<HTMLElement>(null)
const milkdrop = useVisualizerPref((s) => s.mode) === 'milkdrop'
const milkdropRunning = useMilkdrop((s) => s.running)
@ -144,6 +145,7 @@ export default function NowPlaying() {
{track.album.title}
</Link>
)}
{radio && <p className="text-sm font-semibold text-primary">{t('radio.now', { name: radio.title })}</p>}
</div>
<Visualizer size="full" friend={track.friend !== undefined} className="h-20 w-full sm:h-36" />

View file

@ -6,7 +6,7 @@ import { cn } from '@/lib/utils'
/** The pages the Home tab leads to (Home itself ends the list of them with links to Discover and, for an admin, Requests). */
const HOME = ['/discover', '/requests']
/** The pages the Library tab leads to: it is the current tab on all of them. */
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/favorites', '/playlists', '/smart-playlists', '/mixes', '/history', '/stats', '/import']
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/favorites', '/playlists', '/smart-playlists', '/mixes', '/radio', '/history', '/stats', '/import']
const MORE = ['/more', '/settings', '/admin']
const under = (path: string, prefixes: string[]) => prefixes.some((p) => path === p || path.startsWith(`${p}/`))

View file

@ -525,3 +525,12 @@ test('the seek bar of a friend’s track is its shape too, asked of the friend',
expect(calls.some((c) => c.key === 'GET /api/v1/friends/3/tracks/1/peaks')).toBe(true)
expect(calls.some((c) => c.key === 'GET /api/v1/tracks/1/peaks')).toBe(false)
})
test('the full-screen player says which station is playing, and says nothing for any other list', async () => {
act(() => usePlayer.getState().playTracks([a, b], 0, { id: 'genre:jazz', title: 'Jazz Radio' }))
renderBar()
const { dialog } = await openNowPlaying()
expect(within(dialog).getByText('Radio: Jazz Radio')).toBeInTheDocument()
act(() => usePlayer.getState().playTracks([a, b]))
expect(within(dialog).queryByText(/^Radio:/)).not.toBeInTheDocument()
})

View file

@ -2,6 +2,7 @@ import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Outlet, useLocation } from 'react-router-dom'
import SearchBox from '@/components/SearchBox'
import { useRadioRefill } from '@/player/radio'
import { usePlayerEngine } from '@/player/usePlayer'
import UpdateNotice from '@/pwa/UpdateNotice'
import PhoneTabs from './PhoneTabs'
@ -15,6 +16,7 @@ export default function Shell() {
// The search page has its own box, and a phone has the Search tab.
const searching = useLocation().pathname.startsWith('/search')
usePlayerEngine()
useRadioRefill()
return (
<div className="flex min-h-screen flex-col bg-background text-foreground">
{/* The first stop of the Tab key: it jumps over the sidebar. It moves the focus itself, so the address does not change. */}

View file

@ -28,7 +28,7 @@ function renderSidebar(friends: { id: number; name: string }[] = [], path = '/al
test('the menu has a link for each page, and the page that is open is the current one', () => {
const nav = renderSidebar()
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Favourites', 'Mixes', 'Playlists', 'Smart playlists', 'History', 'Statistics', 'Import', 'Admin', 'Settings']) {
for (const name of ['Home', 'Search', 'Discover', 'Artists', 'Albums', 'Songs', 'Favourites', 'Mixes', 'Radio', 'Playlists', 'Smart playlists', 'History', 'Statistics', 'Import', 'Admin', 'Settings']) {
expect(within(nav).getByRole('link', { name })).toBeInTheDocument()
}
expect(within(nav).getByRole('link', { name: 'Albums' })).toHaveAttribute('aria-current', 'page')
@ -157,7 +157,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
await within(nav).findByRole('link', { name: 'Friends' })
expect(names(nav)).toEqual([
'Home', 'Search', 'Discover', 'Requests',
'Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes',
'Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes', 'Radio',
'History', 'Statistics', 'Import',
'Friends',
'Settings', 'Admin',
@ -167,7 +167,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
test('the library and the listening have a quiet heading, and the groups that explain themselves have none', () => {
const nav = renderSidebar()
const library = within(nav).getByRole('list', { name: 'Library' })
expect(within(library).getAllByRole('link').map((a) => a.textContent)).toEqual(['Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes'])
expect(within(library).getAllByRole('link').map((a) => a.textContent)).toEqual(['Artists', 'Albums', 'Songs', 'Favourites', 'Playlists', 'Smart playlists', 'Mixes', 'Radio'])
const listening = within(nav).getByRole('list', { name: 'Your listening' })
expect(within(listening).getAllByRole('link').map((a) => a.textContent)).toEqual(['History', 'Statistics', 'Import'])
// The headings are words, not links, and not headings of the page.

View file

@ -1,5 +1,5 @@
import { useState } from 'react'
import { Blend, ChartNoAxesColumn, Compass, Disc3, Heart, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
import { Blend, ChartNoAxesColumn, Compass, Disc3, Heart, History, House, Inbox, ListMusic, MicVocal, Music, PanelLeftClose, PanelLeftOpen, Radio, Search, Settings, ShieldCheck, Upload, Users, WandSparkles } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { NavLink } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
@ -47,6 +47,7 @@ const GROUPS: Group[] = [
{ to: '/playlists', key: 'nav.playlists', icon: ListMusic },
{ to: '/smart-playlists', key: 'nav.smartPlaylists', icon: WandSparkles },
{ to: '/mixes', key: 'nav.mixes', icon: Blend },
{ to: '/radio', key: 'nav.radio', icon: Radio },
],
},
{

View file

@ -28,7 +28,8 @@
"expand": "Expand menu",
"tabs": "Tabs",
"stats": "Statistics",
"favorites": "Favourites"
"favorites": "Favourites",
"radio": "Radio"
},
"common": {
"loading": "Loading",
@ -1169,5 +1170,18 @@
"overTime": "Genres over time",
"timelineNone": "{{label}}: no listens",
"timelineIn": "{{label}}: {{parts}}"
},
"radio": {
"intro": "Stations that Sonda makes by itself from your music. Press one and it plays, with other songs every time and no end.",
"forever": "Without end",
"playing": "Playing",
"byDecade": "By decade",
"empty": "No station yet. They appear when your library has songs.",
"genre": "{{genre}} Radio",
"decade": "{{decade}}s",
"artist": "{{name}} Radio",
"all": "Everything",
"start": "Start radio",
"now": "Radio: {{name}}"
}
}

View file

@ -28,7 +28,8 @@
"expand": "Espandi il menu",
"tabs": "Schede",
"stats": "Statistiche",
"favorites": "Preferiti"
"favorites": "Preferiti",
"radio": "Radio"
},
"common": {
"loading": "Caricamento",
@ -1169,5 +1170,18 @@
"overTime": "Generi nel tempo",
"timelineNone": "{{label}}: nessun ascolto",
"timelineIn": "{{label}}: {{parts}}"
},
"radio": {
"intro": "Stazioni che Sonda crea da sola con la tua musica. Premine una e suona, con brani diversi ogni volta e senza fine.",
"forever": "Senza fine",
"playing": "In riproduzione",
"byDecade": "Per decennio",
"empty": "Ancora nessuna stazione. Compaiono quando la libreria ha dei brani.",
"genre": "Radio {{genre}}",
"decade": "Anni {{short}}",
"artist": "Radio {{name}}",
"all": "Tutto",
"start": "Avvia radio",
"now": "Radio: {{name}}"
}
}

View file

@ -1,8 +1,9 @@
import { Play } from 'lucide-react'
import { Play, Radio } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useParams } from 'react-router-dom'
import { useAlbumList, useArtist, useTrackList } from '@/api/catalog'
import { ApiError } from '@/api/client'
import { useStartRadio } from '@/api/radio'
import ArtistPhoto from '@/components/ArtistPhoto'
import FavoriteButton from '@/components/FavoriteButton'
import { AlbumCard, CARD_GRID } from '@/components/cards'
@ -28,6 +29,7 @@ function ArtistView({ id }: { id: number }) {
const albums = useAlbumList({ artistId: id })
const tracks = useTrackList({ artistId: id })
const playTracks = usePlayer((s) => s.playTracks)
const radio = useStartRadio()
const songs = tracks.data?.items ?? []
if (artist.isError) {
@ -58,6 +60,19 @@ function ArtistView({ id }: { id: number }) {
<Play />
{t('player.play')}
</Button>
<Button
variant="outline"
className="h-12 gap-2 rounded-md px-6"
disabled={radio.isPending}
onClick={() =>
radio.mutate(`artist:${a.id}`, {
onSuccess: (data) => playTracks(data.tracks, 0, { id: data.id, title: t('radio.artist', { name: a.name }) }),
})
}
>
<Radio />
{t('radio.start')}
</Button>
<FavoriteButton kind="artists" id={a.id} className="size-12" />
</div>
)}

View file

@ -28,6 +28,7 @@ test('Library is a list of the places of the music, each a row that leads there'
['Playlists', '/playlists'],
['Smart playlists', '/smart-playlists'],
['Mixes', '/mixes'],
['Radio', '/radio'],
['History', '/history'],
['Statistics', '/stats'],
['Import', '/import'],

View file

@ -18,6 +18,7 @@ export default function LibraryPage() {
{ to: '/playlists', label: t('nav.playlists') },
{ to: '/smart-playlists', label: t('nav.smartPlaylists') },
{ to: '/mixes', label: t('nav.mixes') },
{ to: '/radio', label: t('nav.radio') },
]}
/>
<Section title={t('nav.listening')}>

View file

@ -0,0 +1,97 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } 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 RadioPage from './RadioPage'
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0, radio: null })
})
const station = (id: string, kind: string, title: string, over: object = {}) => ({ id, kind, title, genre: null, decade: null, artists: [], album_ids: [], ...over })
const stations = [
station('favourites', 'favourites', 'Your favourites'),
station('unheard', 'unheard', 'New to you'),
station('genre:hard rock', 'genre', 'Hard Rock Mix', { genre: 'hard rock' }),
station('genre:jazz', 'genre', 'Jazz Mix', { genre: 'jazz' }),
station('all', 'all', 'Everything'),
station('decade:1990', 'decade', '1990s', { decade: 1990 }),
station('decade:2000', 'decade', '2000s', { decade: 2000 }),
]
const song = (id: number) => ({ id, title: `Song ${id}`, duration_ms: 1000, track_no: 1, disc_no: 1, album: null, artists: [{ id: 1, name: 'Björk' }], format: 'mp3', replay_gain: null })
const played = (id: string, title: string, kind = 'all', over: object = {}) => ({ ...station(id, kind, title, over), tracks: [song(1), song(2), song(3)] })
function setup(over: MockRoutes = {}) {
const mocked = mockFetch({ 'GET /api/v1/radio': () => ({ items: stations }), ...over })
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })}>
<MemoryRouter>
<RadioPage />
</MemoryRouter>
</QueryClientProvider>,
)
return mocked
}
test('the page has the stations that Sonda made, in groups, with names in the language of the page', async () => {
setup()
expect(screen.getByRole('heading', { level: 1, name: 'Radio' })).toBeInTheDocument()
const forYou = await screen.findByRole('region', { name: 'Made for you' })
expect(within(forYou).getAllByRole('button').map((b) => b.textContent)).toEqual([
expect.stringContaining('Your favourites'),
expect.stringContaining('New to you'),
expect.stringContaining('Everything'),
])
const genres = screen.getByRole('region', { name: 'By genre' })
expect(within(genres).getByRole('button', { name: /Hard Rock Radio/ })).toBeInTheDocument()
expect(within(genres).getByRole('button', { name: /Jazz Radio/ })).toBeInTheDocument()
const decades = screen.getByRole('region', { name: 'By decade' })
expect(within(decades).getAllByRole('button').map((b) => b.textContent)).toEqual([expect.stringContaining('1990s'), expect.stringContaining('2000s')])
})
test('a click starts the station: its songs play, and the player knows it is a radio', async () => {
const { calls } = setup({ 'GET /api/v1/radio/genre%3Ajazz': () => played('genre:jazz', 'Jazz Mix', 'genre', { genre: 'jazz' }) })
await userEvent.click(await screen.findByRole('button', { name: /Jazz Radio/ }))
await vi.waitFor(() => expect(usePlayer.getState().queue).toHaveLength(3))
expect(usePlayer.getState().radio).toEqual({ id: 'genre:jazz', title: 'Jazz Radio' })
expect(usePlayer.getState().playing).toBe(true)
expect(calls.filter((c) => c.url.pathname.startsWith('/api/v1/radio/'))).toHaveLength(1)
})
test('the station that plays is marked', async () => {
setup({ 'GET /api/v1/radio/all': () => played('all', 'Everything') })
await userEvent.click(await screen.findByRole('button', { name: /Everything/ }))
await vi.waitFor(() => expect(screen.getByRole('button', { name: /Everything/ })).toHaveAttribute('aria-pressed', 'true'))
expect(screen.getByRole('button', { name: /Jazz Radio/ })).toHaveAttribute('aria-pressed', 'false')
expect(within(screen.getByRole('button', { name: /Everything/ })).getByText('Playing')).toBeInTheDocument()
})
test('a station that cannot start says so and can be tried again', async () => {
let fail = true
setup({ 'GET /api/v1/radio/all': () => (fail ? apiError(500, 'internal', 'x') : played('all', 'Everything')) })
await userEvent.click(await screen.findByRole('button', { name: /Everything/ }))
expect(await screen.findByRole('alert')).toBeInTheDocument()
fail = false
await userEvent.click(screen.getByRole('button', { name: /Everything/ }))
await vi.waitFor(() => expect(usePlayer.getState().queue).toHaveLength(3))
})
test('a list that cannot be read has a way to try again', async () => {
let fail = true
setup({ 'GET /api/v1/radio': () => (fail ? apiError(500, 'internal', 'x') : { items: stations }) })
const retry = await screen.findByRole('button', { name: 'Try again' })
fail = false
await userEvent.click(retry)
expect(await screen.findByRole('region', { name: 'Made for you' })).toBeInTheDocument()
})
test('with no station at all it says why', async () => {
setup({ 'GET /api/v1/radio': () => ({ items: [] }) })
expect(await screen.findByText(/no station/i)).toBeInTheDocument()
})

View file

@ -0,0 +1,81 @@
import { useTranslation } from 'react-i18next'
import { type RadioStation, useRadioStations, useStartRadio } from '@/api/radio'
import PageTitle from '@/components/PageTitle'
import Section from '@/components/Section'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { TONES, toneOfText } from '@/components/tones'
import { cn } from '@/lib/utils'
import { usePlayer } from '@/player/store'
import { radioTitle } from './radioTitle'
/** Tiles are wide, a few in a row: the name needs room. */
const TILES = 'grid grid-cols-[repeat(auto-fit,minmax(min(250px,100%),1fr))] gap-4'
function StationCard({ station, playing, busy, onStart }: { station: RadioStation; playing: boolean; busy: boolean; onStart(): void }) {
const { t } = useTranslation()
const tone = toneOfText(station.id)
return (
<button
type="button"
aria-pressed={playing}
disabled={busy}
onClick={onStart}
data-tone={tone}
style={{ background: TONES[tone].bg }}
className={cn(
'flex min-h-36 flex-col justify-between gap-6 rounded-md p-5 text-left text-white lift focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:opacity-70',
playing && 'outline-2 outline-offset-2 outline-primary',
)}
>
<span className="text-3xl leading-[1.05] font-extrabold tracking-tight">{radioTitle(t, station)}</span>
<span className="text-[13px]">{playing ? t('radio.playing') : t('radio.forever')}</span>
</button>
)
}
/**
* The radio: stations that Sonda makes by itself from the music, each one playing songs without end. A click starts one;
* the player asks for more before it runs out (see useRadioRefill).
*/
export default function RadioPage() {
const { t } = useTranslation()
const query = useRadioStations()
const start = useStartRadio()
const playing = usePlayer((s) => s.radio?.id)
const play = (station: RadioStation) =>
start.mutate(station.id, {
onSuccess: (data) => usePlayer.getState().playTracks(data.tracks, 0, { id: data.id, title: radioTitle(t, data) }),
})
const of = (...kinds: string[]) => query.data?.filter((s) => kinds.includes(s.kind)) ?? []
const group = (title: string, list: RadioStation[]) =>
list.length > 0 && (
<Section title={title}>
<div className={TILES}>
{list.map((s) => (
<StationCard key={s.id} station={s} playing={playing === s.id} busy={start.isPending} onStart={() => play(s)} />
))}
</div>
</Section>
)
return (
<div className="flex flex-col gap-8">
<PageTitle>{t('nav.radio')}</PageTitle>
<p className="max-w-xl text-muted-foreground">{t('radio.intro')}</p>
{start.isError && <ErrorMessage error={start.error} />}
{query.isError ? (
<ErrorMessage error={query.error} onRetry={() => query.refetch()} />
) : query.isPending ? (
<Loading />
) : query.data.length === 0 ? (
<EmptyMessage>{t('radio.empty')}</EmptyMessage>
) : (
<>
{group(t('mixes.forYou'), of('favourites', 'rediscover', 'unheard', 'all'))}
{group(t('mixes.byGenre'), of('genre'))}
{group(t('radio.byDecade'), of('decade'))}
</>
)}
</div>
)
}

View file

@ -500,3 +500,17 @@ test('a song with no album and no artists is listed', async () => {
renderPage(<SongsPage />, '/songs')
expect(await screen.findByRole('button', { name: /Song 1/ })).toHaveTextContent('—')
})
test('the artist page has a button that starts the radio of the artist', async () => {
mockFetch({
...artistRoutes(),
'GET /api/v1/radio/artist%3A5': () => ({
id: 'artist:5', kind: 'artist', title: 'Radiohead', genre: null, decade: null, artists: ['Radiohead'], album_ids: [],
tracks: [track(1), track(2), track(3)],
}),
})
renderPage(<ArtistPage />, '/artists/5', '/artists/:id')
await userEvent.click(await screen.findByRole('button', { name: 'Start radio' }))
await vi.waitFor(() => expect(usePlayer.getState().queue).toHaveLength(3))
expect(usePlayer.getState().radio).toEqual({ id: 'artist:5', title: 'Radiohead Radio' })
})

View file

@ -0,0 +1,22 @@
import type { TFunction } from 'i18next'
import type { RadioStation } from '@/api/radio'
const capitalize = (text: string) => text.replace(/(^|\s)\S/gu, (c) => c.toLocaleUpperCase())
/** The name of a station in the language of the page: the server's title is always English. */
export function radioTitle(t: TFunction, s: Pick<RadioStation, 'kind' | 'genre' | 'decade' | 'title'>): string {
switch (s.kind) {
case 'genre':
return t('radio.genre', { genre: capitalize(s.genre ?? s.title) })
case 'decade': {
const decade = s.decade ?? 0
return t('radio.decade', { decade, short: String(decade % 100).padStart(2, '0') })
}
case 'artist':
return t('radio.artist', { name: s.title })
case 'all':
return t('radio.all')
default:
return t(`mixes.kind.${s.kind}`)
}
}

View file

@ -0,0 +1,113 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import type { ReactNode } from 'react'
import { beforeEach, expect, test, vi } from 'vitest'
import type { Track } from '@/api/catalog'
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
import { useRadioRefill } from './radio'
import { usePlayer } from './store'
const track = (n: number): Track => ({
id: n,
title: `t${n}`,
duration_ms: 200_000,
track_no: n,
disc_no: 1,
album: { id: 1, title: 'Album' },
artists: [{ id: 1, name: 'Artist' }],
format: 'flac',
replay_gain: null,
})
const station = (tracks: Track[]) => ({ id: 'all', kind: 'all', title: 'Everything', genre: null, decade: null, artists: [], album_ids: [], tracks })
beforeEach(() => {
vi.useRealTimers()
usePlayer.setState({ queue: [], original: [], index: 0, playing: false, positionMs: 0, radio: null })
})
function mount(routes: MockRoutes) {
const mocked = mockFetch(routes)
const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={new QueryClient()}>{children}</QueryClientProvider>
renderHook(() => useRadioRefill(), { wrapper })
return mocked
}
const queued = () => usePlayer.getState().queue.map((t) => t.id)
test('a radio that is nearly over gets other songs, and not the ones already in the queue', async () => {
const { calls } = mount({ 'GET /api/v1/radio/all': () => station([track(2), track(10), track(11)]) })
act(() => usePlayer.getState().playTracks([track(1), track(2)], 0, { id: 'all', title: 'Everything' }))
await waitFor(() => expect(queued()).toEqual([1, 2, 10, 11]))
expect(calls.filter((c) => c.key === 'GET /api/v1/radio/all')).toHaveLength(1)
})
test('a radio that has plenty left asks for nothing', async () => {
const { calls } = mount({ 'GET /api/v1/radio/all': () => station([track(99)]) })
act(() => usePlayer.getState().playTracks(Array.from({ length: 10 }, (_, i) => track(i + 1)), 0, { id: 'all', title: 'Everything' }))
await new Promise((r) => setTimeout(r, 50))
expect(calls).toHaveLength(0)
})
test('what is not a radio asks for nothing, however short', async () => {
const { calls } = mount({ 'GET /api/v1/radio/all': () => station([track(99)]) })
act(() => usePlayer.getState().playTracks([track(1)]))
await new Promise((r) => setTimeout(r, 50))
expect(calls).toHaveLength(0)
})
test('the id of a station goes in the path, percent-encoded', async () => {
const { calls } = mount({ 'GET /api/v1/radio/genre%3Ahard%20rock': () => ({ ...station([track(5)]), id: 'genre:hard rock' }) })
act(() => usePlayer.getState().playTracks([track(1)], 0, { id: 'genre:hard rock', title: 'Hard Rock' }))
await waitFor(() => expect(queued()).toEqual([1, 5]))
expect(calls[0].url.pathname).toBe('/api/v1/radio/genre%3Ahard%20rock')
})
test('it does not ask again while it is waiting for an answer', async () => {
let resolve: (r: object) => void = () => undefined
const { calls } = mount({ 'GET /api/v1/radio/all': () => new Promise((r) => (resolve = r)) as never })
act(() => usePlayer.getState().playTracks([track(1)], 0, { id: 'all', title: 'Everything' }))
await waitFor(() => expect(calls).toHaveLength(1))
act(() => usePlayer.setState({ positionMs: 1000 })) // any change of the player
act(() => usePlayer.setState({ positionMs: 2000 }))
expect(calls).toHaveLength(1)
resolve(station([track(7), track(8), track(9), track(10)]))
await waitFor(() => expect(queued()).toEqual([1, 7, 8, 9, 10]))
})
test('songs that come after the listener went to another list or another station are left out', async () => {
let resolve: (r: object) => void = () => undefined
mount({ 'GET /api/v1/radio/all': () => new Promise((r) => (resolve = r)) as never })
act(() => usePlayer.getState().playTracks([track(1)], 0, { id: 'all', title: 'Everything' }))
await waitFor(() => expect(resolve).not.toBeUndefined())
act(() => usePlayer.getState().playTracks([track(50), track(51), track(52), track(53), track(54)])) // an album
resolve(station([track(7)]))
await new Promise((r) => setTimeout(r, 50))
expect(queued()).toEqual([50, 51, 52, 53, 54])
})
test('a radio that cannot be reached is tried again later, not at once', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
let fail = true
const { calls } = mount({ 'GET /api/v1/radio/all': () => (fail ? apiError(500, 'internal', 'x') : station([track(7), track(8), track(9), track(10)])) })
act(() => usePlayer.getState().playTracks([track(1)], 0, { id: 'all', title: 'Everything' }))
await vi.waitFor(() => expect(calls).toHaveLength(1))
act(() => usePlayer.setState({ positionMs: 1000 }))
expect(calls).toHaveLength(1)
fail = false
await act(async () => {
await vi.advanceTimersByTimeAsync(11_000)
})
await vi.waitFor(() => expect(queued()).toEqual([1, 7, 8, 9, 10]))
vi.useRealTimers()
})
test('a station with so few songs that all of them are queued starts them over, and is not asked for all the time', async () => {
const { calls } = mount({ 'GET /api/v1/radio/all': () => station([track(1), track(2)]) })
act(() => usePlayer.getState().playTracks([track(1), track(2)], 0, { id: 'all', title: 'Everything' }))
await waitFor(() => expect(queued()).toEqual([1, 2, 1, 2]))
await new Promise((r) => setTimeout(r, 300))
act(() => usePlayer.setState({ index: 3, positionMs: 1000 })) // nearly over again
act(() => usePlayer.setState({ positionMs: 2000 }))
expect(calls).toHaveLength(1) // less than two seconds since the last question
})

53
web/src/player/radio.ts Normal file
View file

@ -0,0 +1,53 @@
import { useEffect } from 'react'
import { fetchRadio } from '@/api/radio'
import { trackKey } from './media'
import { usePlayer } from './store'
/** A radio is asked for more songs when this many or fewer are left after the one that plays. */
const LOW = 3
/** How long to wait before asking again when the server could not answer. */
const RETRY_MS = 10_000
/** The least time between two questions: a station with few songs must not be asked for all the time. */
const PAUSE_MS = 2000
/**
* Keeps a radio from ending: when the queue of a station that plays is nearly over, it asks the server for other
* songs of the same station and puts them at the end, leaving out the ones that are already in the queue (a station with
* so few songs that all of them are there starts them over: a radio does not end). It asks one thing at a time, never
* twice within two seconds, and, when the server cannot answer, again after ten. Songs that arrive after the listener
* went to another list or station are thrown away.
*/
export function useRadioRefill(): void {
useEffect(() => {
let busy = false
let waitUntil = 0
const check = () => {
const s = usePlayer.getState()
if (!s.radio || busy || Date.now() < waitUntil) return
if (s.queue.length - s.index - 1 > LOW) return
const asked = s.radio
busy = true
fetchRadio(asked.id)
.then((station) => {
const now = usePlayer.getState()
if (now.radio?.id !== asked.id) return // another list or station started meanwhile
const have = new Set(now.queue.map(trackKey))
const fresh = station.tracks.filter((t) => !have.has(trackKey(t)))
now.appendTracks(fresh.length > 0 ? fresh : station.tracks)
waitUntil = Date.now() + PAUSE_MS
setTimeout(check, PAUSE_MS)
})
.catch(() => {
waitUntil = Date.now() + RETRY_MS
setTimeout(check, RETRY_MS)
})
.finally(() => {
busy = false
})
}
check()
return usePlayer.subscribe(check)
}, [])
}

View file

@ -32,6 +32,7 @@ beforeEach(() => {
repeat: 'off',
seekMs: null,
seekId: 0,
radio: null,
})
setRandom(() => 0)
})
@ -308,3 +309,25 @@ test('with shuffle on, playTracks starts at the chosen track and shuffles the re
expect(ids().slice().sort()).toEqual([1, 2, 3, 4, 5])
expect(ids()[0]).toBe(3)
})
// ---- radio ----
test('a radio is a list that is played as a station, and any other list takes the station away', () => {
const station = { id: 'all', title: 'Everything' }
usePlayer.getState().playTracks([track(1), track(2)], 0, station)
expect(usePlayer.getState().radio).toEqual(station)
usePlayer.getState().playTracks([track(3)])
expect(usePlayer.getState().radio).toBeNull()
usePlayer.getState().playTracks([track(1)], 0, station)
usePlayer.getState().playTracks([])
expect(usePlayer.getState().radio).toBeNull()
})
test('songs can be added to the end of the queue all at once, and the order of a shuffled list keeps them', () => {
usePlayer.getState().playTracks([track(1), track(2)])
usePlayer.getState().appendTracks([track(3), track(4)])
expect(usePlayer.getState().queue.map((x) => x.id)).toEqual([1, 2, 3, 4])
expect(usePlayer.getState().original.map((x) => x.id)).toEqual([1, 2, 3, 4])
usePlayer.getState().appendTracks([])
expect(usePlayer.getState().queue).toHaveLength(4)
})

Some files were not shown because too many files have changed in this diff Show more