Merge pull request 'feat(web): web app with player, library browsing, themes and languages (F1)' (#55) from feat/web-f1 into main
This commit is contained in:
commit
2d478055f2
96 changed files with 17360 additions and 2 deletions
19
README.md
19
README.md
|
|
@ -4,7 +4,7 @@ Sonda is a privacy-first, self-hosted music server written in Go. It streams the
|
|||
|
||||
It is a single executable, one database (SQLite by default, PostgreSQL if you prefer) and the folders that hold your music. There is no Redis, no message broker and no cloud account.
|
||||
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Suggestions of new artists work too (Discover). Radio queues, a web client and OpenSubsonic compatibility are not built yet (see [What is not there yet](#what-is-not-there-yet)). The API may still change.
|
||||
> **Status: early.** The local-playback part works end to end: accounts, libraries, scanning, search, and streaming with HTTP Range. Suggestions of new artists work too (Discover). Radio queues and OpenSubsonic compatibility are not built yet, and the web client in `web/` is a work in progress (see [What is not there yet](#what-is-not-there-yet) and [Web app](#web-app)). The API may still change.
|
||||
|
||||
## What works today
|
||||
|
||||
|
|
@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr
|
|||
|
||||
## What is not there yet
|
||||
|
||||
Radio queues, a web client, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration.
|
||||
Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no Discover or admin screens yet.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
|
@ -295,6 +295,20 @@ Back up the database and `sonda.toml`. Your music stays wherever you keep it.
|
|||
- **PostgreSQL:** `pg_dump` the database.
|
||||
- `sonda.toml` holds the secret that signs tokens; treat the copy like a password.
|
||||
|
||||
## Web app
|
||||
|
||||
A web client lives in `web/` (React, Vite and shadcn/ui). It talks only to the Sonda server: no CDN, no external fonts, no analytics. `sondad` does not serve it yet, so for now it runs next to the server:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm install
|
||||
SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda
|
||||
```
|
||||
|
||||
What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings.
|
||||
|
||||
More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). Discover, the admin screens and serving the app from the binary come later.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
|
@ -333,6 +347,7 @@ internal/usersettings/ the settings that belong to one user
|
|||
internal/storage/ SQLite and PostgreSQL through bun, the repositories
|
||||
internal/streaming/ opening a track's file safely
|
||||
migrations/ SQL migrations, one folder per database
|
||||
web/ the web client (React, Vite, shadcn/ui)
|
||||
```
|
||||
|
||||
The API description is `internal/api/openapi/openapi.yaml`, written by hand and embedded in the binary. Two tests keep it in step with the code: one fails when a route and the spec disagree in either direction, and a contract test sends real requests through every operation and validates each response (status, headers, JSON body) against the spec. Adding or changing an endpoint therefore means updating the spec in the same change. Response objects are closed (`additionalProperties: false`), so a field added in the code and forgotten in the spec fails the build.
|
||||
|
|
|
|||
24
web/.gitignore
vendored
Normal file
24
web/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
8
web/.oxlintrc.json
Normal file
8
web/.oxlintrc.json
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
25
web/components.json
Normal file
25
web/components.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "base-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
13
web/index.html
Normal file
13
web/index.html
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Sonda</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
6212
web/package-lock.json
generated
Normal file
6212
web/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
47
web/package.json
Normal file
47
web/package.json
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
{
|
||||
"name": "sonda-web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview",
|
||||
"test": "vitest run",
|
||||
"gen:api": "node scripts/gen-api.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.9.0",
|
||||
"@fontsource/figtree": "^5.3.0",
|
||||
"@fontsource/fraunces": "^5.3.0",
|
||||
"@tanstack/react-query": "^5.107.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"cn": "^0.5.2",
|
||||
"i18next": "^27.1.1",
|
||||
"lucide-react": "^1.72.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-i18next": "^18.0.1",
|
||||
"react-router-dom": "^7.18.5",
|
||||
"shadcn": "^4.23.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"zustand": "^5.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@testing-library/jest-dom": "^7.0.1",
|
||||
"@testing-library/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.10",
|
||||
"@types/node": "^24.19.2",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"jsdom": "^31.0.0",
|
||||
"oxlint": "^1.90.0",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"typescript": "~7.0.2",
|
||||
"vite": "^8.3.6",
|
||||
"vitest": "^5.1.0"
|
||||
}
|
||||
}
|
||||
1
web/public/favicon.svg
Normal file
1
web/public/favicon.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
13
web/scripts/gen-api.mjs
Normal file
13
web/scripts/gen-api.mjs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
// Regenerates src/api/schema.d.ts from the API spec in the Go module.
|
||||
// openapi-typescript is run through npx because it still asks for TypeScript 5 as a peer.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url))
|
||||
const spec = fileURLToPath(new URL('../../internal/api/openapi/openapi.yaml', import.meta.url))
|
||||
|
||||
execFileSync(
|
||||
'npx',
|
||||
['--yes', 'openapi-typescript@7.13.0', spec, '-o', 'src/api/schema.d.ts'],
|
||||
{ cwd: root, stdio: 'inherit' },
|
||||
)
|
||||
17
web/src/App.tsx
Normal file
17
web/src/App.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
|
||||
import AuthGate from './auth/AuthGate'
|
||||
import { routes } from './router'
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 30_000, retry: 1 } } })
|
||||
const router = createBrowserRouter(routes)
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthGate>
|
||||
<RouterProvider router={router} />
|
||||
</AuthGate>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
101
web/src/api/catalog.test.tsx
Normal file
101
web/src/api/catalog.test.tsx
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { expect, test } from 'vitest'
|
||||
import { createWrapper } from '@/test/queryWrapper'
|
||||
import { mockFetch } from '@/test/mockFetch'
|
||||
import { useAlbum, useAlbumList, useArtist, useArtistList, useTrackList } from './catalog'
|
||||
|
||||
/** A page of `total` fake items, 50 at a time, as the server pages them. */
|
||||
function paged(total: number, make: (i: number) => object) {
|
||||
return ({ url }: { url: URL }) => {
|
||||
const limit = Number(url.searchParams.get('limit') ?? 50)
|
||||
const offset = Number(url.searchParams.get('offset') ?? 0)
|
||||
const items = Array.from({ length: Math.max(0, Math.min(limit, total - offset)) }, (_, i) => make(offset + i))
|
||||
return { items, total, limit, offset }
|
||||
}
|
||||
}
|
||||
|
||||
const artist = (i: number) => ({ id: i + 1, name: `Artist ${i}`, album_count: 1, track_count: 3 })
|
||||
|
||||
test('pages are asked for 50 at a time and the next one is offered until the end', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(120, artist) })
|
||||
const { result } = renderHook(() => useArtistList(), { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => expect(result.current.data?.items).toHaveLength(50))
|
||||
expect(result.current.data?.total).toBe(120)
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
expect(calls[0].url.searchParams.get('limit')).toBe('50')
|
||||
expect(calls[0].url.searchParams.get('offset')).toBe('0')
|
||||
|
||||
await act(() => result.current.fetchNextPage())
|
||||
await waitFor(() => expect(result.current.data?.items).toHaveLength(100))
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
|
||||
await act(() => result.current.fetchNextPage())
|
||||
await waitFor(() => expect(result.current.data?.items).toHaveLength(120))
|
||||
expect(result.current.hasNextPage).toBe(false)
|
||||
expect(calls.map((c) => c.url.searchParams.get('offset'))).toEqual(['0', '50', '100'])
|
||||
})
|
||||
|
||||
test('an empty library has no next page', async () => {
|
||||
mockFetch({ 'GET /api/v1/artists': paged(0, artist) })
|
||||
const { result } = renderHook(() => useArtistList(), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(result.current.data?.items).toEqual([])
|
||||
expect(result.current.hasNextPage).toBe(false)
|
||||
})
|
||||
|
||||
test('the search text goes to the server as typed', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(1, artist) })
|
||||
const { result } = renderHook(() => useArtistList('bjork'), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(calls[0].url.searchParams.get('q')).toBe('bjork')
|
||||
})
|
||||
|
||||
test('no search text sends no q', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(1, artist) })
|
||||
const { result } = renderHook(() => useArtistList(), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(calls[0].url.searchParams.has('q')).toBe(false)
|
||||
})
|
||||
|
||||
test('a list can ask for a smaller page', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(10, artist) })
|
||||
const { result } = renderHook(() => useArtistList('x', { pageSize: 6 }), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.data?.items).toHaveLength(6))
|
||||
expect(calls[0].url.searchParams.get('limit')).toBe('6')
|
||||
expect(result.current.hasNextPage).toBe(true)
|
||||
})
|
||||
|
||||
test('a list that is switched off asks for nothing', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': paged(1, artist) })
|
||||
const { result } = renderHook(() => useArtistList('x', { enabled: false }), { wrapper: createWrapper() })
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(calls).toHaveLength(0)
|
||||
expect(result.current.data).toBeUndefined()
|
||||
})
|
||||
|
||||
test('albums can be limited to an artist', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/albums': paged(1, (i) => ({ id: i + 1, title: 'A' })) })
|
||||
const { result } = renderHook(() => useAlbumList({ artistId: 7 }), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(calls[0].url.searchParams.get('artist_id')).toBe('7')
|
||||
})
|
||||
|
||||
test('tracks can be limited to an album', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/tracks': paged(1, (i) => ({ id: i + 1, title: 'T' })) })
|
||||
const { result } = renderHook(() => useTrackList({ albumId: 4 }), { wrapper: createWrapper() })
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(calls[0].url.searchParams.get('album_id')).toBe('4')
|
||||
})
|
||||
|
||||
test('one artist and one album are read by id', async () => {
|
||||
mockFetch({
|
||||
'GET /api/v1/artists/3': () => artist(2),
|
||||
'GET /api/v1/albums/9': () => ({ id: 9, title: 'Homogenic', artist: null, track_count: 10, duration_ms: 1 }),
|
||||
})
|
||||
const wrapper = createWrapper()
|
||||
const a = renderHook(() => useArtist(3), { wrapper })
|
||||
const b = renderHook(() => useAlbum(9), { wrapper })
|
||||
await waitFor(() => expect(a.result.current.data?.name).toBe('Artist 2'))
|
||||
await waitFor(() => expect(b.result.current.data?.title).toBe('Homogenic'))
|
||||
})
|
||||
63
web/src/api/catalog.ts
Normal file
63
web/src/api/catalog.ts
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query'
|
||||
import type { components } from './schema'
|
||||
import { api } from './client'
|
||||
|
||||
export type Artist = components['schemas']['Artist']
|
||||
export type Album = components['schemas']['Album']
|
||||
export type Track = components['schemas']['Track']
|
||||
|
||||
export interface Page<T> {
|
||||
items: T[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
type Params = Record<string, string | number | undefined>
|
||||
|
||||
export interface ListOptions {
|
||||
/** How many items one request asks for (default 50). */
|
||||
pageSize?: number
|
||||
/** False keeps the list from asking for anything yet (default true). */
|
||||
enabled?: boolean
|
||||
}
|
||||
|
||||
/** A list the server pages by `limit` and `offset`, read one page after the other. */
|
||||
function usePagedList<T>(path: string, params: Params, opts: ListOptions = {}) {
|
||||
const pageSize = opts.pageSize ?? PAGE_SIZE
|
||||
return useInfiniteQuery({
|
||||
queryKey: [path, params, pageSize],
|
||||
enabled: opts.enabled ?? true,
|
||||
initialPageParam: 0,
|
||||
queryFn: ({ pageParam }) => api.get<Page<T>>(path, { ...params, limit: pageSize, offset: pageParam }),
|
||||
getNextPageParam: (last) => {
|
||||
const next = last.offset + last.items.length
|
||||
return last.items.length > 0 && next < last.total ? next : undefined
|
||||
},
|
||||
select: (data) => ({ items: data.pages.flatMap((p) => p.items), total: data.pages[0]?.total ?? 0 }),
|
||||
})
|
||||
}
|
||||
|
||||
export function useArtistList(q?: string, list: ListOptions = {}) {
|
||||
return usePagedList<Artist>('/artists', { q: q || undefined }, list)
|
||||
}
|
||||
|
||||
export function useAlbumList(opts: { q?: string; artistId?: number } & ListOptions = {}) {
|
||||
const { q, artistId, ...list } = opts
|
||||
return usePagedList<Album>('/albums', { q: q || undefined, artist_id: artistId }, list)
|
||||
}
|
||||
|
||||
export function useTrackList(opts: { q?: string; artistId?: number; albumId?: number } & ListOptions = {}) {
|
||||
const { q, artistId, albumId, ...list } = opts
|
||||
return usePagedList<Track>('/tracks', { q: q || undefined, artist_id: artistId, album_id: albumId }, list)
|
||||
}
|
||||
|
||||
export function useArtist(id: number) {
|
||||
return useQuery({ queryKey: ['artist', id], queryFn: () => api.get<Artist>(`/artists/${id}`) })
|
||||
}
|
||||
|
||||
export function useAlbum(id: number) {
|
||||
return useQuery({ queryKey: ['album', id], queryFn: () => api.get<Album>(`/albums/${id}`) })
|
||||
}
|
||||
113
web/src/api/client.test.ts
Normal file
113
web/src/api/client.test.ts
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { apiError, mockFetch } from '@/test/mockFetch'
|
||||
import { api, ApiError, setAuthHooks } from './client'
|
||||
|
||||
const hooks = {
|
||||
getAccessToken: vi.fn(async () => 't1' as string | null),
|
||||
refresh: vi.fn(async () => 't2' as string | null),
|
||||
signOut: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
hooks.getAccessToken.mockClear().mockResolvedValue('t1')
|
||||
hooks.refresh.mockClear().mockResolvedValue('t2')
|
||||
hooks.signOut.mockClear()
|
||||
setAuthHooks(hooks)
|
||||
})
|
||||
|
||||
function authorization(call: { init: RequestInit }): string | undefined {
|
||||
return (call.init.headers as Record<string, string>).Authorization
|
||||
}
|
||||
|
||||
test('sends the access token as a bearer token', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': () => ({ items: [] }) })
|
||||
await api.get('/artists')
|
||||
expect(authorization(calls[0])).toBe('Bearer t1')
|
||||
})
|
||||
|
||||
test('an error response becomes an ApiError with the server code', async () => {
|
||||
mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input', 'bad limit') })
|
||||
const failure = await api.get('/artists').catch((e: unknown) => e)
|
||||
expect(failure).toBeInstanceOf(ApiError)
|
||||
expect(failure).toMatchObject({ status: 400, code: 'invalid_input', message: 'bad limit' })
|
||||
})
|
||||
|
||||
test('a 401 renews the session and retries once', async () => {
|
||||
let n = 0
|
||||
const { calls } = mockFetch({
|
||||
'GET /api/v1/artists': () => (++n === 1 ? apiError(401, 'unauthorized') : { items: ['ok'] }),
|
||||
})
|
||||
await expect(api.get('/artists')).resolves.toEqual({ items: ['ok'] })
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(hooks.refresh).toHaveBeenCalledTimes(1)
|
||||
expect(authorization(calls[1])).toBe('Bearer t2')
|
||||
expect(hooks.signOut).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('a second 401 signs the user out and the error reaches the caller', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') })
|
||||
await expect(api.get('/artists')).rejects.toMatchObject({ status: 401, code: 'unauthorized' })
|
||||
expect(calls).toHaveLength(2)
|
||||
expect(hooks.signOut).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('a 401 with nothing to renew signs out without a retry', async () => {
|
||||
hooks.refresh.mockResolvedValue(null)
|
||||
const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') })
|
||||
await expect(api.get('/artists')).rejects.toMatchObject({ status: 401 })
|
||||
expect(calls).toHaveLength(1)
|
||||
expect(hooks.signOut).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('a call that does not need a session sends no token and never renews', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') })
|
||||
await expect(api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false })).rejects.toMatchObject({
|
||||
code: 'invalid_credentials',
|
||||
})
|
||||
expect(hooks.getAccessToken).not.toHaveBeenCalled()
|
||||
expect(hooks.refresh).not.toHaveBeenCalled()
|
||||
expect(authorization(calls[0])).toBeUndefined()
|
||||
})
|
||||
|
||||
test('query values are sent, undefined ones are left out', async () => {
|
||||
const { calls } = mockFetch({ 'GET /api/v1/albums': () => ({ items: [] }) })
|
||||
await api.get('/albums', { q: 'björk', limit: 50, artist_id: undefined, counted: true })
|
||||
expect(calls[0].url.searchParams.get('q')).toBe('björk')
|
||||
expect(calls[0].url.searchParams.get('limit')).toBe('50')
|
||||
expect(calls[0].url.searchParams.has('artist_id')).toBe(false)
|
||||
expect(calls[0].url.searchParams.get('counted')).toBe('true')
|
||||
})
|
||||
|
||||
test('a JSON body is sent with its content type', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
|
||||
await api.post('/listens', { track_id: 3 })
|
||||
expect((calls[0].init.headers as Record<string, string>)['Content-Type']).toBe('application/json')
|
||||
expect(JSON.parse(calls[0].init.body as string)).toEqual({ track_id: 3 })
|
||||
})
|
||||
|
||||
test('keepalive lets a request outlive the page', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
|
||||
await api.post('/listens', { track_id: 3 }, { keepalive: true })
|
||||
expect(calls[0].init.keepalive).toBe(true)
|
||||
})
|
||||
|
||||
test('a request without keepalive does not ask for it', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
|
||||
await api.post('/listens', { track_id: 3 })
|
||||
expect(calls[0].init.keepalive).toBeUndefined()
|
||||
})
|
||||
|
||||
test('a 204 answer gives undefined', async () => {
|
||||
mockFetch({ 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }) })
|
||||
await expect(api.post('/auth/logout', { refresh_token: 'r' }, { auth: false })).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
test('a network failure becomes an ApiError with the code network', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new TypeError('Failed to fetch')
|
||||
}),
|
||||
)
|
||||
await expect(api.get('/artists')).rejects.toMatchObject({ status: 0, code: 'network' })
|
||||
})
|
||||
105
web/src/api/client.ts
Normal file
105
web/src/api/client.ts
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
/** What the server answers when a call fails: `{"error": {"code", "message"}}`. */
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
code: string
|
||||
|
||||
constructor(status: number, code: string, message: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
/** The session side of a call, injected so that this file never imports the session (which imports this). */
|
||||
export interface AuthHooks {
|
||||
getAccessToken(): Promise<string | null>
|
||||
/** Renews the session; resolves to the new access token, or null when there is nothing to renew. */
|
||||
refresh(): Promise<string | null>
|
||||
signOut(): void
|
||||
}
|
||||
|
||||
let hooks: AuthHooks = {
|
||||
getAccessToken: async () => null,
|
||||
refresh: async () => null,
|
||||
signOut: () => {},
|
||||
}
|
||||
|
||||
export function setAuthHooks(next: AuthHooks): void {
|
||||
hooks = next
|
||||
}
|
||||
|
||||
type Query = Record<string, string | number | boolean | undefined>
|
||||
|
||||
export interface CallOptions {
|
||||
/** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */
|
||||
auth?: boolean
|
||||
/** Lets the request finish after the page is closed (the browser allows it for small bodies). */
|
||||
keepalive?: boolean
|
||||
}
|
||||
|
||||
const BASE = '/api/v1'
|
||||
|
||||
function buildUrl(path: string, params?: Query): string {
|
||||
const query = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(params ?? {})) {
|
||||
if (value !== undefined) query.set(key, String(value))
|
||||
}
|
||||
const text = query.toString()
|
||||
return `${BASE}${path}${text ? `?${text}` : ''}`
|
||||
}
|
||||
|
||||
async function toApiError(res: Response): Promise<ApiError> {
|
||||
try {
|
||||
const body = (await res.json()) as { error?: { code?: string; message?: string } }
|
||||
return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText)
|
||||
} catch {
|
||||
return new ApiError(res.status, 'unknown', res.statusText)
|
||||
}
|
||||
}
|
||||
|
||||
async function send(
|
||||
method: string,
|
||||
url: string,
|
||||
body: unknown,
|
||||
token: string | null,
|
||||
keepalive: boolean | undefined,
|
||||
): Promise<Response> {
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
||||
if (token) headers.Authorization = `Bearer ${token}`
|
||||
try {
|
||||
return await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
keepalive: keepalive || undefined,
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'network', 'The server cannot be reached')
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise<T> {
|
||||
const auth = opts.auth ?? true
|
||||
const url = buildUrl(path, params)
|
||||
let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null, opts.keepalive)
|
||||
|
||||
if (res.status === 401 && auth) {
|
||||
const fresh = await hooks.refresh()
|
||||
if (fresh) res = await send(method, url, body, fresh, opts.keepalive)
|
||||
if (res.status === 401) hooks.signOut()
|
||||
}
|
||||
|
||||
if (!res.ok) throw await toApiError(res)
|
||||
if (res.status === 204) return undefined as T
|
||||
return (await res.json()) as T
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string, params?: Query, opts: CallOptions = {}) => request<T>('GET', path, params, undefined, opts),
|
||||
post: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('POST', path, undefined, body ?? {}, opts),
|
||||
patch: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PATCH', path, undefined, body ?? {}, opts),
|
||||
put: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PUT', path, undefined, body ?? {}, opts),
|
||||
del: <T>(path: string, opts: CallOptions = {}) => request<T>('DELETE', path, undefined, undefined, opts),
|
||||
}
|
||||
22
web/src/api/listens.ts
Normal file
22
web/src/api/listens.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api } from './client'
|
||||
import type { components } from './schema'
|
||||
|
||||
type Listen = components['schemas']['Listen']
|
||||
export type ListenItem = components['schemas']['ListenItem']
|
||||
type ListenPage = components['schemas']['ListenPage']
|
||||
|
||||
/** The last 30 listens that count, newest first. */
|
||||
export function useRecentListens() {
|
||||
return useQuery({
|
||||
queryKey: ['listens', 'recent'],
|
||||
queryFn: () => api.get<ListenPage>('/listens', { counted: true, limit: 30 }),
|
||||
})
|
||||
}
|
||||
|
||||
/** What `POST /listens` takes, with the fields the player always sends. */
|
||||
export type ListenBody = Required<Pick<Listen, 'track_id' | 'event_type' | 'occurred_at' | 'duration_played_ms' | 'idempotency_key'>>
|
||||
|
||||
export async function sendListen(body: ListenBody, opts?: { keepalive?: boolean }): Promise<void> {
|
||||
await api.post('/listens', body, { keepalive: opts?.keepalive })
|
||||
}
|
||||
47
web/src/api/providers.ts
Normal file
47
web/src/api/providers.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import { useQuery } from '@tanstack/react-query'
|
||||
import { api, ApiError } from './client'
|
||||
import type { components } from './schema'
|
||||
|
||||
export type ArtistDescription = components['schemas']['ArtistDescription']
|
||||
export type SimilarArtists = components['schemas']['SimilarArtists']
|
||||
export type ArtistTags = components['schemas']['ArtistTags']
|
||||
export type PictureCredit = components['schemas']['PictureCredit']
|
||||
|
||||
export function useArtistDescription(id: number) {
|
||||
return useQuery({
|
||||
queryKey: ['artist', id, 'description'],
|
||||
queryFn: () => api.get<ArtistDescription>(`/artists/${id}/description`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useSimilarArtists(id: number) {
|
||||
return useQuery({
|
||||
queryKey: ['artist', id, 'similar'],
|
||||
queryFn: () => api.get<SimilarArtists>(`/artists/${id}/similar`),
|
||||
})
|
||||
}
|
||||
|
||||
export function useArtistTags(id: number) {
|
||||
return useQuery({
|
||||
queryKey: ['artist', id, 'tags'],
|
||||
queryFn: () => api.get<ArtistTags>(`/artists/${id}/tags`),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The credit of the artist photo. There is no credit when there is no picture (provider off, no free
|
||||
* picture, no MusicBrainz id) or the picture provider is down: those answer `null`, not an error.
|
||||
*/
|
||||
export function useArtistImageCredit(id: number) {
|
||||
return useQuery({
|
||||
queryKey: ['artist', id, 'image-credit'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
return await api.get<PictureCredit>(`/artists/${id}/image/credit`)
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && (e.status === 404 || e.status === 502)) return null
|
||||
throw e
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
4016
web/src/api/schema.d.ts
vendored
Normal file
4016
web/src/api/schema.d.ts
vendored
Normal file
File diff suppressed because it is too large
Load diff
16
web/src/auth/AuthGate.tsx
Normal file
16
web/src/auth/AuthGate.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import type { ReactNode } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import LoginPage from './LoginPage'
|
||||
import { useSession } from './session'
|
||||
|
||||
/** Shows the app to a signed-in user and the sign-in form to everyone else. */
|
||||
export default function AuthGate({ children }: { children: ReactNode }) {
|
||||
const { status } = useSession()
|
||||
const { t } = useTranslation()
|
||||
|
||||
if (status === 'loading') {
|
||||
return <div role="status" aria-label={t('common.loading')} className="min-h-screen bg-background" />
|
||||
}
|
||||
if (status === 'anonymous') return <LoginPage />
|
||||
return <>{children}</>
|
||||
}
|
||||
94
web/src/auth/LoginPage.test.tsx
Normal file
94
web/src/auth/LoginPage.test.tsx
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch } from '@/test/mockFetch'
|
||||
import AuthGate from './AuthGate'
|
||||
import LoginPage from './LoginPage'
|
||||
import { sessionStore } from './session'
|
||||
|
||||
const user = { id: 1, username: 'tom', is_admin: true }
|
||||
const session = {
|
||||
access_token: 'a1',
|
||||
access_expires_at: new Date(Date.now() + 900_000).toISOString(),
|
||||
refresh_token: 'r1',
|
||||
refresh_expires_at: new Date(Date.now() + 86_400_000).toISOString(),
|
||||
user,
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null })
|
||||
})
|
||||
|
||||
async function fill(username: string, password: string) {
|
||||
await userEvent.type(screen.getByLabelText('Username'), username)
|
||||
await userEvent.type(screen.getByLabelText('Password'), password)
|
||||
}
|
||||
|
||||
test('a wrong password shows the translated message', async () => {
|
||||
mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') })
|
||||
render(<LoginPage />)
|
||||
await fill('tom', 'wrong-password')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Wrong username or password.')
|
||||
})
|
||||
|
||||
test('signing in sends what was typed', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session })
|
||||
render(<LoginPage />)
|
||||
await fill('tom', 'secret123')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
|
||||
await vi.waitFor(() => expect(sessionStore.getState().status).toBe('authenticated'))
|
||||
expect(JSON.parse(calls[0].init.body as string)).toEqual({ username: 'tom', password: 'secret123' })
|
||||
})
|
||||
|
||||
test('the first-account link switches to registration and says when one already exists', async () => {
|
||||
mockFetch({ 'POST /api/v1/auth/register': () => apiError(403, 'registration_closed') })
|
||||
render(<LoginPage />)
|
||||
await userEvent.click(screen.getByRole('button', { name: 'This is a new server: create the first account' }))
|
||||
await fill('tom', 'secret123')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('An account already exists.')
|
||||
})
|
||||
|
||||
test('an unreachable server is reported as such', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => {
|
||||
throw new TypeError('Failed to fetch')
|
||||
}),
|
||||
)
|
||||
render(<LoginPage />)
|
||||
await fill('tom', 'secret123')
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Cannot reach the server.')
|
||||
})
|
||||
|
||||
test('AuthGate shows nothing while loading, the form when signed out, the app when signed in', () => {
|
||||
sessionStore.setState({ status: 'loading' })
|
||||
const { rerender } = render(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.queryByText('the app')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Username')).not.toBeInTheDocument()
|
||||
|
||||
sessionStore.setState({ status: 'anonymous' })
|
||||
rerender(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument()
|
||||
|
||||
sessionStore.setState({ status: 'authenticated', user })
|
||||
rerender(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.getByText('the app')).toBeInTheDocument()
|
||||
})
|
||||
89
web/src/auth/LoginPage.tsx
Normal file
89
web/src/auth/LoginPage.tsx
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { useState, type FormEvent } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { errorMessageKey } from '@/i18n'
|
||||
import { login, register } from './session'
|
||||
|
||||
/** Sign in, or (on a new server) create the first account, which becomes the admin. */
|
||||
export default function LoginPage() {
|
||||
const { t } = useTranslation()
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
async function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
await (creating ? register : login)(username, password)
|
||||
} catch (e) {
|
||||
setError(t(errorMessageKey(e instanceof ApiError ? e.code : 'unknown')))
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||
<div className="flex w-full max-w-sm flex-col gap-6 rounded-xl bg-card p-8 text-card-foreground">
|
||||
<div className="flex items-center gap-3">
|
||||
<svg width="32" height="32" viewBox="0 0 28 28" fill="none" aria-hidden="true">
|
||||
<circle cx="14" cy="14" r="3" fill="var(--primary)" />
|
||||
<circle cx="14" cy="14" r="8" stroke="var(--primary)" strokeWidth="2" opacity="0.75" />
|
||||
<circle cx="14" cy="14" r="12.5" stroke="var(--primary)" strokeWidth="1.5" opacity="0.35" />
|
||||
</svg>
|
||||
<span className="text-2xl font-extrabold tracking-tight">{t('app.name')}</span>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">{creating ? t('auth.registerTitle') : t('auth.signInTitle')}</h1>
|
||||
<form onSubmit={submit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="username">{t('auth.username')}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="password">{t('auth.password')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete={creating ? 'new-password' : 'current-password'}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={busy}>
|
||||
{creating ? t('auth.createAccount') : t('auth.signIn')}
|
||||
</Button>
|
||||
</form>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto self-start p-0"
|
||||
onClick={() => {
|
||||
setCreating(!creating)
|
||||
setError(null)
|
||||
}}
|
||||
>
|
||||
{creating ? t('auth.haveAccount') : t('auth.firstUser')}
|
||||
</Button>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue