diff --git a/README.md b/README.md index 584a6fc..81a94b4 100644 --- a/README.md +++ b/README.md @@ -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:` 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. | diff --git a/web/src/api/radio.ts b/web/src/api/radio.ts new file mode 100644 index 0000000..73a803c --- /dev/null +++ b/web/src/api/radio.ts @@ -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(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) }) +} diff --git a/web/src/components/layout/NowPlaying.tsx b/web/src/components/layout/NowPlaying.tsx index 1eff8d3..99348f3 100644 --- a/web/src/components/layout/NowPlaying.tsx +++ b/web/src/components/layout/NowPlaying.tsx @@ -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(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} )} + {radio &&

{t('radio.now', { name: radio.title })}

} diff --git a/web/src/components/layout/PhoneTabs.tsx b/web/src/components/layout/PhoneTabs.tsx index 549df1a..20f846d 100644 --- a/web/src/components/layout/PhoneTabs.tsx +++ b/web/src/components/layout/PhoneTabs.tsx @@ -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}/`)) diff --git a/web/src/components/layout/Player.test.tsx b/web/src/components/layout/Player.test.tsx index ed81e2c..3dccbb3 100644 --- a/web/src/components/layout/Player.test.tsx +++ b/web/src/components/layout/Player.test.tsx @@ -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() +}) diff --git a/web/src/components/layout/Shell.tsx b/web/src/components/layout/Shell.tsx index c491ff2..79069f5 100644 --- a/web/src/components/layout/Shell.tsx +++ b/web/src/components/layout/Shell.tsx @@ -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 (
{/* The first stop of the Tab key: it jumps over the sidebar. It moves the focus itself, so the address does not change. */} diff --git a/web/src/components/layout/Sidebar.test.tsx b/web/src/components/layout/Sidebar.test.tsx index 1dfbe28..33c7bbf 100644 --- a/web/src/components/layout/Sidebar.test.tsx +++ b/web/src/components/layout/Sidebar.test.tsx @@ -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. diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 89846b3..2ffdb1f 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -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 }, ], }, { diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 12aff00..c0a6bcd 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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}}" } } diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 3e99b05..2f1a9d1 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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}}" } } diff --git a/web/src/pages/ArtistPage.tsx b/web/src/pages/ArtistPage.tsx index 7f4fcee..33997d5 100644 --- a/web/src/pages/ArtistPage.tsx +++ b/web/src/pages/ArtistPage.tsx @@ -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 }) { {t('player.play')} +
)} diff --git a/web/src/pages/LibraryPage.test.tsx b/web/src/pages/LibraryPage.test.tsx index b188ff8..101a6d8 100644 --- a/web/src/pages/LibraryPage.test.tsx +++ b/web/src/pages/LibraryPage.test.tsx @@ -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'], diff --git a/web/src/pages/LibraryPage.tsx b/web/src/pages/LibraryPage.tsx index 71f9395..b1b7be9 100644 --- a/web/src/pages/LibraryPage.tsx +++ b/web/src/pages/LibraryPage.tsx @@ -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') }, ]} />
diff --git a/web/src/pages/RadioPage.test.tsx b/web/src/pages/RadioPage.test.tsx new file mode 100644 index 0000000..e49d2c1 --- /dev/null +++ b/web/src/pages/RadioPage.test.tsx @@ -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( + + + + + , + ) + 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() +}) diff --git a/web/src/pages/RadioPage.tsx b/web/src/pages/RadioPage.tsx new file mode 100644 index 0000000..f1bc371 --- /dev/null +++ b/web/src/pages/RadioPage.tsx @@ -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 ( + + ) +} + +/** + * 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 && ( +
+
+ {list.map((s) => ( + play(s)} /> + ))} +
+
+ ) + + return ( +
+ {t('nav.radio')} +

{t('radio.intro')}

+ {start.isError && } + {query.isError ? ( + query.refetch()} /> + ) : query.isPending ? ( + + ) : query.data.length === 0 ? ( + {t('radio.empty')} + ) : ( + <> + {group(t('mixes.forYou'), of('favourites', 'rediscover', 'unheard', 'all'))} + {group(t('mixes.byGenre'), of('genre'))} + {group(t('radio.byDecade'), of('decade'))} + + )} +
+ ) +} diff --git a/web/src/pages/pages.test.tsx b/web/src/pages/pages.test.tsx index 1f82e38..b848ffb 100644 --- a/web/src/pages/pages.test.tsx +++ b/web/src/pages/pages.test.tsx @@ -500,3 +500,17 @@ test('a song with no album and no artists is listed', async () => { renderPage(, '/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(, '/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' }) +}) diff --git a/web/src/pages/radioTitle.ts b/web/src/pages/radioTitle.ts new file mode 100644 index 0000000..004587a --- /dev/null +++ b/web/src/pages/radioTitle.ts @@ -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): 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}`) + } +} diff --git a/web/src/player/radio.test.tsx b/web/src/player/radio.test.tsx new file mode 100644 index 0000000..49ebf09 --- /dev/null +++ b/web/src/player/radio.test.tsx @@ -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 }) => {children} + 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 +}) diff --git a/web/src/player/radio.ts b/web/src/player/radio.ts new file mode 100644 index 0000000..d89a269 --- /dev/null +++ b/web/src/player/radio.ts @@ -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) + }, []) +} diff --git a/web/src/player/store.test.ts b/web/src/player/store.test.ts index 5a53897..153a462 100644 --- a/web/src/player/store.test.ts +++ b/web/src/player/store.test.ts @@ -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) +}) diff --git a/web/src/player/store.ts b/web/src/player/store.ts index ebb47af..504e677 100644 --- a/web/src/player/store.ts +++ b/web/src/player/store.ts @@ -4,6 +4,14 @@ import type { QueuedTrack } from './media' export type Repeat = 'off' | 'all' | 'one' +/** A radio station that is playing: the queue is refilled with other songs of it before it runs out. */ +export interface Station { + /** What the server calls it: `all`, `decade:1990`, `genre:rock`, `artist:12`. */ + id: string + /** Its name, in the language of the page when it was started. */ + title: string +} + export interface PlayerState { queue: QueuedTrack[] index: number @@ -21,8 +29,13 @@ export interface PlayerState { /** From 0 to 1. Kept while muted, so that unmuting brings it back. Remembered in the browser. */ volume: number muted: boolean + /** The station that plays, or null for any other list. */ + radio: Station | null - playTracks(tracks: QueuedTrack[], start?: number): void + /** Plays a list. With a station it is a radio, which gets more songs by itself (see useRadioRefill). */ + playTracks(tracks: QueuedTrack[], start?: number, station?: Station): void + /** Puts songs at the end of the queue. */ + appendTracks(tracks: QueuedTrack[]): void togglePlay(): void next(): void prev(): void @@ -81,12 +94,13 @@ export const usePlayer = create()((set, get) => ({ seekMs: null, seekId: 0, playId: 0, + radio: null, ...loadVolume(), - playTracks(tracks, start = 0) { + playTracks(tracks, start = 0, station) { set((s) => { if (tracks.length === 0) { - return { queue: [], original: [], index: 0, playing: false, positionMs: 0, playId: s.playId + 1 } + return { queue: [], original: [], index: 0, playing: false, positionMs: 0, playId: s.playId + 1, radio: null } } const i = Math.min(Math.max(start, 0), tracks.length - 1) const queue = s.shuffle ? [tracks[i], ...shuffled(tracks.filter((_, k) => k !== i))] : tracks @@ -97,10 +111,16 @@ export const usePlayer = create()((set, get) => ({ playing: true, positionMs: 0, playId: s.playId + 1, + radio: station ?? null, } }) }, + appendTracks(tracks) { + if (tracks.length === 0) return + set((s) => ({ queue: [...s.queue, ...tracks], original: [...s.original, ...tracks] })) + }, + togglePlay() { set((s) => (currentTrack(s) ? { playing: !s.playing } : s)) }, diff --git a/web/src/router.tsx b/web/src/router.tsx index 2049f78..18f9514 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -27,6 +27,7 @@ export const routes: RouteObject[] = [ { path: '/friends', lazy: page(() => import('@/pages/FriendsPage')) }, { path: '/friends/:friend', lazy: page(() => import('@/pages/FriendPage')) }, { path: '/mixes', lazy: page(() => import('@/pages/MixesPage')) }, + { path: '/radio', lazy: page(() => import('@/pages/RadioPage')) }, { path: '/mixes/:id', lazy: page(() => import('@/pages/MixPage')) }, { path: '/playlists', lazy: page(() => import('@/pages/PlaylistsPage')) }, { path: '/playlists/:id', lazy: page(() => import('@/pages/PlaylistPage')) },