diff --git a/README.md b/README.md index f51be72..d359716 100644 --- a/README.md +++ b/README.md @@ -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, 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 admin screens yet. +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 its admin area only covers libraries and scanning so far (users, providers and the bulk jobs are still API-only). ## Requirements @@ -328,9 +328,9 @@ 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. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. +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. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). An admin also gets an Admin area to add, rename, move and remove libraries and to start a scan (of one library or all, optionally reading every file again) and follow it. 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). The admin screens and serving the app from the binary come later. +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). The rest of the admin screens (users, providers, bulk jobs) and serving the app from the binary come later. ## Development diff --git a/web/src/api/libraries.test.tsx b/web/src/api/libraries.test.tsx new file mode 100644 index 0000000..37c0f43 --- /dev/null +++ b/web/src/api/libraries.test.tsx @@ -0,0 +1,111 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act, renderHook, waitFor } from '@testing-library/react' +import type { ReactNode } from 'react' +import { expect, test } from 'vitest' +import { mockFetch } from '@/test/mockFetch' +import { useAddLibrary, useLibraries, useRemoveLibrary, useScanStatus, useStartScan, useUpdateLibrary } from './libraries' + +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => {children} + return { client, wrapper } +} + +const lib = (id: number, name = `Lib ${id}`) => ({ id, name, path: `/music/${id}`, created_at: '2026-11-12T10:00:00Z' }) +const none = () => new Response(null, { status: 204 }) + +test('the libraries are listed', async () => { + mockFetch({ 'GET /api/v1/libraries': () => ({ libraries: [lib(1), lib(2)] }) }) + const { result } = renderHook(() => useLibraries(), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data).toHaveLength(2)) + expect(result.current.data?.[0].name).toBe('Lib 1') +}) + +test('adding sends the name and the folder, and the list is read again', async () => { + let libs = [lib(1)] + const { calls } = mockFetch({ + 'GET /api/v1/libraries': () => ({ libraries: libs }), + 'POST /api/v1/libraries': ({ init }) => { + const body = JSON.parse(String(init.body)) + libs = [...libs, { ...lib(2), ...body }] + return new Response(JSON.stringify(libs[1]), { status: 201, headers: { 'Content-Type': 'application/json' } }) + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ list: useLibraries(), add: useAddLibrary() }), { wrapper }) + await waitFor(() => expect(result.current.list.data).toHaveLength(1)) + await act(() => result.current.add.mutateAsync({ name: 'Jazz', path: '/music/jazz' })) + await waitFor(() => expect(result.current.list.data).toHaveLength(2)) + expect(JSON.parse(String(calls.find((c) => c.key === 'POST /api/v1/libraries')?.init.body))).toEqual({ name: 'Jazz', path: '/music/jazz' }) +}) + +test('renaming sends only the name, moving only the folder', async () => { + const { calls } = mockFetch({ 'PATCH /api/v1/libraries/3': () => lib(3), 'GET /api/v1/libraries': () => ({ libraries: [] }) }) + const { result } = renderHook(() => useUpdateLibrary(), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync({ id: 3, name: 'New name' })) + await act(() => result.current.mutateAsync({ id: 3, path: '/music/new' })) + const bodies = calls.filter((c) => c.key === 'PATCH /api/v1/libraries/3').map((c) => JSON.parse(String(c.init.body))) + expect(bodies).toEqual([{ name: 'New name' }, { path: '/music/new' }]) +}) + +test('removing asks the server to delete that library and the list is read again', async () => { + const { calls } = mockFetch({ 'DELETE /api/v1/libraries/3': none, 'GET /api/v1/libraries': () => ({ libraries: [] }) }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ list: useLibraries(), remove: useRemoveLibrary() }), { wrapper }) + await waitFor(() => expect(result.current.list.isSuccess).toBe(true)) + await act(() => result.current.remove.mutateAsync(3)) + await waitFor(() => expect(calls.filter((c) => c.key === 'GET /api/v1/libraries')).toHaveLength(2)) + expect(calls.map((c) => c.key)).toContain('DELETE /api/v1/libraries/3') +}) + +test('a scan of everything is a POST to /library/scan, and "full" is sent only when asked', async () => { + const { calls } = mockFetch({ + 'POST /api/v1/library/scan': () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } }), + 'GET /api/v1/library/scan': () => ({ running: true }), + }) + const { result } = renderHook(() => useStartScan(), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync({ full: false })) + await act(() => result.current.mutateAsync({ full: true })) + const posts = calls.filter((c) => c.key === 'POST /api/v1/library/scan') + expect(posts[0].url.searchParams.has('full')).toBe(false) + expect(posts[1].url.searchParams.get('full')).toBe('true') +}) + +test('a scan of one library names it', async () => { + const { calls } = mockFetch({ + 'POST /api/v1/libraries/3/scan': () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } }), + 'GET /api/v1/library/scan': () => ({ running: true }), + }) + const { result } = renderHook(() => useStartScan(), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync({ libraryId: 3, full: true })) + const post = calls.find((c) => c.key === 'POST /api/v1/libraries/3/scan') + expect(post?.url.searchParams.get('full')).toBe('true') +}) + +test('while a scan runs the status is read again and again, and it stops by itself when the scan ends', async () => { + let n = 0 + const { calls } = mockFetch({ 'GET /api/v1/library/scan': () => (++n < 3 ? { running: true } : { running: false }) }) + const { result } = renderHook(() => useScanStatus({ intervalMs: 20 }), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data?.running).toBe(false), { timeout: 2000 }) + const seen = calls.length + await new Promise((r) => setTimeout(r, 120)) + expect(calls).toHaveLength(seen) + expect(seen).toBe(3) +}) + +test('starting a scan makes the status be read at once, so the page follows it', async () => { + let running = false + const { calls } = mockFetch({ + 'GET /api/v1/library/scan': () => ({ running }), + 'POST /api/v1/library/scan': () => { + running = true + return new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } }) + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ status: useScanStatus({ intervalMs: 20 }), start: useStartScan() }), { wrapper }) + await waitFor(() => expect(result.current.status.data?.running).toBe(false)) + await act(() => result.current.start.mutateAsync({ full: false })) + await waitFor(() => expect(result.current.status.data?.running).toBe(true)) + expect(calls.filter((c) => c.key === 'GET /api/v1/library/scan').length).toBeGreaterThanOrEqual(2) +}) diff --git a/web/src/api/libraries.ts b/web/src/api/libraries.ts new file mode 100644 index 0000000..f021b18 --- /dev/null +++ b/web/src/api/libraries.ts @@ -0,0 +1,69 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api } from './client' +import type { components } from './schema' + +export type Library = components['schemas']['Library'] +export type ScanStatus = components['schemas']['ScanStatus'] +export type ScanSummary = components['schemas']['ScanSummary'] + +const LIBRARIES = ['libraries'] +const SCAN = ['library', 'scan'] + +/** Every library, oldest first. Admins only. */ +export function useLibraries() { + return useQuery({ + queryKey: LIBRARIES, + queryFn: () => api.get<{ libraries: Library[] }>('/libraries'), + select: (data) => data.libraries, + }) +} + +export function useAddLibrary() { + const client = useQueryClient() + return useMutation({ + mutationFn: (body: { name: string; path: string }) => api.post('/libraries', body), + onSuccess: () => client.invalidateQueries({ queryKey: LIBRARIES }), + }) +} + +/** Rename, move, or both: only the fields given are sent. */ +export function useUpdateLibrary() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ id, ...changes }: { id: number; name?: string; path?: string }) => api.patch(`/libraries/${id}`, changes), + onSuccess: () => client.invalidateQueries({ queryKey: LIBRARIES }), + }) +} + +/** Removes the library from Sonda; the tracks, the history and the music on disk stay. */ +export function useRemoveLibrary() { + const client = useQueryClient() + return useMutation({ + mutationFn: (id: number) => api.del(`/libraries/${id}`), + onSuccess: () => client.invalidateQueries({ queryKey: LIBRARIES }), + }) +} + +/** Whether a scan runs and how the last one ended. While one runs it is read again every `intervalMs`. */ +export function useScanStatus({ intervalMs = 2000 }: { intervalMs?: number } = {}) { + return useQuery({ + queryKey: SCAN, + queryFn: () => api.get('/library/scan'), + refetchInterval: (query) => (query.state.data?.running ? intervalMs : false), + }) +} + +/** + * Starts a scan in the background: of one library, or of all. `full` reads every file again. Whatever the + * answer (also "a scan is already running"), the status is read at once so the page follows the scan. + */ +export function useStartScan() { + const client = useQueryClient() + return useMutation({ + mutationFn: ({ libraryId, full }: { libraryId?: number; full: boolean }) => { + const path = libraryId === undefined ? '/library/scan' : `/libraries/${libraryId}/scan` + return api.post<{ status: 'started' }>(full ? `${path}?full=true` : path) + }, + onSettled: () => client.invalidateQueries({ queryKey: SCAN }), + }) +} diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index 49d0547..700674f 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { render, screen, within } from '@testing-library/react' import { createMemoryRouter, RouterProvider } from 'react-router-dom' import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' import { initI18n } from '@/i18n' import { routes } from '@/router' import { mockFetch } from '@/test/mockFetch' @@ -33,6 +34,34 @@ test('at /artists the Artists link is the current page and the others are not', } }) +const adminRoutes = { + 'GET /api/v1/libraries': () => ({ libraries: [] }), + 'GET /api/v1/library/scan': () => ({ running: false }), +} + +test('an admin has an Admin link, and a user who is not one has none', () => { + sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: false } }) + renderAt('/artists') + expect(within(mainNav()).queryByRole('link', { name: 'Admin' })).not.toBeInTheDocument() +}) + +test('the Admin link opens the libraries and stays current inside the admin area', async () => { + sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } }) + mockFetch(adminRoutes) + renderAt('/admin') + expect(await screen.findByRole('region', { name: 'Libraries' })).toBeInTheDocument() + expect(within(mainNav()).getByRole('link', { name: 'Admin' })).toHaveAttribute('aria-current', 'page') +}) + +test('someone who is not an admin who opens the admin address gets a notice and no request', async () => { + sessionStore.setState({ status: 'authenticated', user: { id: 2, username: 'ann', is_admin: false } }) + const { calls } = mockFetch(adminRoutes) + renderAt('/admin/libraries') + expect(screen.getByText('Only admins can see this page.')).toBeInTheDocument() + await new Promise((r) => setTimeout(r, 30)) + expect(calls.filter((c) => c.url.pathname.includes('librar'))).toHaveLength(0) +}) + test('Home is the current page only on /', () => { renderAt('/') expect(within(mainNav()).getByRole('link', { name: 'Home' })).toHaveAttribute('aria-current', 'page') diff --git a/web/src/components/layout/Sidebar.tsx b/web/src/components/layout/Sidebar.tsx index 3b1c16f..6937ac8 100644 --- a/web/src/components/layout/Sidebar.tsx +++ b/web/src/components/layout/Sidebar.tsx @@ -1,19 +1,23 @@ import { NavLink } from 'react-router-dom' import { useTranslation } from 'react-i18next' +import { useSession } from '@/auth/session' import { cn } from '@/lib/utils' const LINKS = [ - { to: '/', key: 'nav.home', end: true }, - { to: '/search', key: 'nav.search', end: false }, - { to: '/discover', key: 'nav.discover', end: false }, - { to: '/artists', key: 'nav.artists', end: false }, - { to: '/albums', key: 'nav.albums', end: false }, - { to: '/songs', key: 'nav.songs', end: false }, - { to: '/settings', key: 'nav.settings', end: false }, + { to: '/', key: 'nav.home', end: true, adminOnly: false }, + { to: '/search', key: 'nav.search', end: false, adminOnly: false }, + { to: '/discover', key: 'nav.discover', end: false, adminOnly: false }, + { to: '/artists', key: 'nav.artists', end: false, adminOnly: false }, + { to: '/albums', key: 'nav.albums', end: false, adminOnly: false }, + { to: '/songs', key: 'nav.songs', end: false, adminOnly: false }, + { to: '/admin', key: 'nav.admin', end: false, adminOnly: true }, + { to: '/settings', key: 'nav.settings', end: false, adminOnly: false }, ] export default function Sidebar() { const { t } = useTranslation() + const { user } = useSession() + const links = LINKS.filter((link) => !link.adminOnly || user?.is_admin) return (