Merge pull request 'feat(web): admin area with libraries and scanning (F3a)' (#70) from feat/admin-libraries into main
This commit is contained in:
commit
0b9d158f2b
18 changed files with 1155 additions and 12 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
111
web/src/api/libraries.test.tsx
Normal file
111
web/src/api/libraries.test.tsx
Normal file
|
|
@ -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 }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>
|
||||
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)
|
||||
})
|
||||
69
web/src/api/libraries.ts
Normal file
69
web/src/api/libraries.ts
Normal file
|
|
@ -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<Library>('/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<Library>(`/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<ScanStatus>('/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 }),
|
||||
})
|
||||
}
|
||||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<nav
|
||||
aria-label={t('nav.main')}
|
||||
|
|
@ -28,7 +32,7 @@ export default function Sidebar() {
|
|||
<span className="text-[22px] font-extrabold tracking-tight">{t('app.name')}</span>
|
||||
</div>
|
||||
<ul className="flex flex-col gap-1 max-sm:flex-row max-sm:flex-wrap">
|
||||
{LINKS.map((link) => (
|
||||
{links.map((link) => (
|
||||
<li key={link.to}>
|
||||
<NavLink
|
||||
to={link.to}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"artists": "Artists",
|
||||
"albums": "Albums",
|
||||
"songs": "Songs",
|
||||
"admin": "Admin",
|
||||
"settings": "Settings"
|
||||
},
|
||||
"common": {
|
||||
|
|
@ -59,6 +60,66 @@
|
|||
"currentPasswordWrong": "The current password is wrong.",
|
||||
"changePassword": "Change password"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Admin",
|
||||
"sections": "Admin sections",
|
||||
"adminOnly": "Only admins can see this page.",
|
||||
"sectionLibraries": "Libraries",
|
||||
"cancel": "Cancel",
|
||||
"save": "Save",
|
||||
"errors": {
|
||||
"scan_running": "A scan is already running.",
|
||||
"no_libraries": "Add a library first.",
|
||||
"admin_required": "Only an admin can do this."
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Libraries",
|
||||
"empty": "No libraries yet. Add one below.",
|
||||
"addTitle": "Add a library",
|
||||
"name": "Name",
|
||||
"folder": "Folder on the server",
|
||||
"folderHint": "The folder must exist on the machine that runs Sonda, not on this computer.",
|
||||
"add": "Add library",
|
||||
"scan": "Scan",
|
||||
"scanOne": "Scan {{name}}",
|
||||
"edit": "Edit",
|
||||
"editOne": "Edit {{name}}",
|
||||
"editTitle": "Edit {{name}}",
|
||||
"remove": "Remove",
|
||||
"removeOne": "Remove {{name}}",
|
||||
"removeTitle": "Remove {{name}}?",
|
||||
"removeBody": "Sonda stops listing this library. Tracks and listening history stay, and the music on disk is never touched.",
|
||||
"removeConfirm": "Remove library",
|
||||
"errors": {
|
||||
"invalid_input": "The folder must be an existing directory on the server, not the root, and not inside or around another library.",
|
||||
"library_exists": "Another library already has this name or folder."
|
||||
}
|
||||
},
|
||||
"scan": {
|
||||
"title": "Scan",
|
||||
"all": "Scan all libraries",
|
||||
"full": "Read every file again",
|
||||
"fullHint": "Slower. Use it to read tags that earlier scans skipped, such as MusicBrainz ids and genres.",
|
||||
"running": "A scan is running.",
|
||||
"never": "No scan has run yet.",
|
||||
"last": "Last scan",
|
||||
"finished": "Finished {{when}}",
|
||||
"unsupported_one": "{{count}} file is in a format Sonda cannot read yet (such as m4a, ogg or wav).",
|
||||
"unsupported_other": "{{count}} files are in formats Sonda cannot read yet (such as m4a, ogg or wav).",
|
||||
"counts": {
|
||||
"found_one": "{{count}} audio file found",
|
||||
"found_other": "{{count}} audio files found",
|
||||
"added": "{{count}} added",
|
||||
"updated": "{{count}} updated",
|
||||
"unchanged": "{{count}} unchanged",
|
||||
"renamed": "{{count}} moved",
|
||||
"restored": "{{count}} back again",
|
||||
"missing": "{{count}} missing",
|
||||
"failed": "{{count}} could not be read",
|
||||
"skipped": "{{count}} skipped (links and special files)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"lidarr": {
|
||||
"request": "Request on Lidarr",
|
||||
"checkAgain": "Check again",
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"artists": "Artisti",
|
||||
"albums": "Album",
|
||||
"songs": "Brani",
|
||||
"admin": "Admin",
|
||||
"settings": "Impostazioni"
|
||||
},
|
||||
"common": {
|
||||
|
|
@ -59,6 +60,66 @@
|
|||
"currentPasswordWrong": "La password attuale è sbagliata.",
|
||||
"changePassword": "Cambia password"
|
||||
},
|
||||
"admin": {
|
||||
"title": "Admin",
|
||||
"sections": "Sezioni admin",
|
||||
"adminOnly": "Solo gli admin possono vedere questa pagina.",
|
||||
"sectionLibraries": "Librerie",
|
||||
"cancel": "Annulla",
|
||||
"save": "Salva",
|
||||
"errors": {
|
||||
"scan_running": "Una scansione è già in corso.",
|
||||
"no_libraries": "Aggiungi prima una libreria.",
|
||||
"admin_required": "Solo un admin può farlo."
|
||||
},
|
||||
"libraries": {
|
||||
"title": "Librerie",
|
||||
"empty": "Ancora nessuna libreria. Aggiungine una qui sotto.",
|
||||
"addTitle": "Aggiungi una libreria",
|
||||
"name": "Nome",
|
||||
"folder": "Cartella sul server",
|
||||
"folderHint": "La cartella deve esistere sulla macchina che esegue Sonda, non su questo computer.",
|
||||
"add": "Aggiungi libreria",
|
||||
"scan": "Scansiona",
|
||||
"scanOne": "Scansiona {{name}}",
|
||||
"edit": "Modifica",
|
||||
"editOne": "Modifica {{name}}",
|
||||
"editTitle": "Modifica {{name}}",
|
||||
"remove": "Rimuovi",
|
||||
"removeOne": "Rimuovi {{name}}",
|
||||
"removeTitle": "Rimuovere {{name}}?",
|
||||
"removeBody": "Sonda smette di elencare questa libreria. Brani e cronologia degli ascolti restano, e la musica sul disco non viene mai toccata.",
|
||||
"removeConfirm": "Rimuovi libreria",
|
||||
"errors": {
|
||||
"invalid_input": "La cartella deve essere una directory esistente sul server, non la radice, e non dentro o attorno a un'altra libreria.",
|
||||
"library_exists": "Un'altra libreria ha già questo nome o questa cartella."
|
||||
}
|
||||
},
|
||||
"scan": {
|
||||
"title": "Scansione",
|
||||
"all": "Scansiona tutte le librerie",
|
||||
"full": "Rileggi ogni file",
|
||||
"fullHint": "Più lenta. Serve a leggere i tag che le scansioni precedenti hanno saltato, come gli id MusicBrainz e i generi.",
|
||||
"running": "Una scansione è in corso.",
|
||||
"never": "Nessuna scansione eseguita finora.",
|
||||
"last": "Ultima scansione",
|
||||
"finished": "Finita il {{when}}",
|
||||
"unsupported_one": "{{count}} file è in un formato che Sonda non legge ancora (come m4a, ogg o wav).",
|
||||
"unsupported_other": "{{count}} file sono in formati che Sonda non legge ancora (come m4a, ogg o wav).",
|
||||
"counts": {
|
||||
"found_one": "{{count}} file audio trovato",
|
||||
"found_other": "{{count}} file audio trovati",
|
||||
"added": "{{count}} aggiunti",
|
||||
"updated": "{{count}} aggiornati",
|
||||
"unchanged": "{{count}} invariati",
|
||||
"renamed": "{{count}} spostati",
|
||||
"restored": "{{count}} tornati",
|
||||
"missing": "{{count}} mancanti",
|
||||
"failed": "{{count}} illeggibili",
|
||||
"skipped": "{{count}} saltati (collegamenti e file speciali)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"lidarr": {
|
||||
"request": "Richiedi su Lidarr",
|
||||
"checkAgain": "Controlla di nuovo",
|
||||
|
|
|
|||
81
web/src/pages/admin/AddLibraryForm.test.tsx
Normal file
81
web/src/pages/admin/AddLibraryForm.test.tsx
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch } from '@/test/mockFetch'
|
||||
import AddLibraryForm from './AddLibraryForm'
|
||||
|
||||
const created = () =>
|
||||
new Response(JSON.stringify({ id: 9, name: 'Jazz', path: '/srv/jazz', created_at: '2026-11-12T10:00:00Z' }), {
|
||||
status: 201,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
function renderForm() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<AddLibraryForm />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
const name = () => screen.getByLabelText('Name')
|
||||
const folder = () => screen.getByLabelText('Folder on the server')
|
||||
const add = () => screen.getByRole('button', { name: 'Add library' })
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } })
|
||||
})
|
||||
|
||||
test('it says the folder is on the machine that runs Sonda, not on this computer', () => {
|
||||
mockFetch({})
|
||||
renderForm()
|
||||
expect(screen.getByText(/on the machine that runs Sonda, not on this computer/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('nothing is sent while the name or the folder is empty', async () => {
|
||||
const { calls } = mockFetch({})
|
||||
renderForm()
|
||||
expect(add()).toBeDisabled()
|
||||
await userEvent.type(name(), 'Jazz')
|
||||
expect(add()).toBeDisabled()
|
||||
await userEvent.type(folder(), ' ')
|
||||
expect(add()).toBeDisabled()
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
|
||||
test('adding sends the trimmed name and folder, then empties the form', async () => {
|
||||
const { calls } = mockFetch({ 'POST /api/v1/libraries': created })
|
||||
renderForm()
|
||||
await userEvent.type(name(), ' Jazz ')
|
||||
await userEvent.type(folder(), ' /srv/jazz ')
|
||||
await userEvent.click(add())
|
||||
await waitFor(() => expect(name()).toHaveValue(''))
|
||||
expect(folder()).toHaveValue('')
|
||||
expect(JSON.parse(String(calls[0].init.body))).toEqual({ name: 'Jazz', path: '/srv/jazz' })
|
||||
})
|
||||
|
||||
test.each([
|
||||
[400, 'invalid_input', 'The folder must be an existing directory on the server, not the root, and not inside or around another library.'],
|
||||
[409, 'library_exists', 'Another library already has this name or folder.'],
|
||||
])('a refusal (%i %s) is explained and what was typed stays', async (status, code, text) => {
|
||||
mockFetch({ 'POST /api/v1/libraries': () => apiError(status, code) })
|
||||
renderForm()
|
||||
await userEvent.type(name(), 'Jazz')
|
||||
await userEvent.type(folder(), '/srv/jazz')
|
||||
await userEvent.click(add())
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(text)
|
||||
expect(name()).toHaveValue('Jazz')
|
||||
expect(folder()).toHaveValue('/srv/jazz')
|
||||
})
|
||||
|
||||
test('the name is limited to the 100 characters the server accepts', () => {
|
||||
mockFetch({})
|
||||
renderForm()
|
||||
expect(name()).toHaveAttribute('maxlength', '100')
|
||||
})
|
||||
57
web/src/pages/admin/AddLibraryForm.tsx
Normal file
57
web/src/pages/admin/AddLibraryForm.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
import { useState, type FormEvent } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useAddLibrary } from '@/api/libraries'
|
||||
import Section from '@/components/Section'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { errorText } from './errorText'
|
||||
|
||||
/** What the server accepts as a library name. */
|
||||
const MAX_NAME = 100
|
||||
|
||||
export default function AddLibraryForm() {
|
||||
const { t } = useTranslation()
|
||||
const add = useAddLibrary()
|
||||
const [name, setName] = useState('')
|
||||
const [path, setPath] = useState('')
|
||||
const ready = name.trim() !== '' && path.trim() !== ''
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (!ready) return
|
||||
add.mutate(
|
||||
{ name: name.trim(), path: path.trim() },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setName('')
|
||||
setPath('')
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Section title={t('admin.libraries.addTitle')}>
|
||||
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="library-name">{t('admin.libraries.name')}</Label>
|
||||
<Input id="library-name" value={name} maxLength={MAX_NAME} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="library-path">{t('admin.libraries.folder')}</Label>
|
||||
<Input id="library-path" value={path} onChange={(e) => setPath(e.target.value)} autoCapitalize="off" spellCheck={false} />
|
||||
<p className="text-sm text-muted-foreground">{t('admin.libraries.folderHint')}</p>
|
||||
</div>
|
||||
{add.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, add.error, ['admin.libraries.errors', 'admin.errors'])}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={!ready || add.isPending} className="self-start">
|
||||
{t('admin.libraries.add')}
|
||||
</Button>
|
||||
</form>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
44
web/src/pages/admin/AdminLayout.test.tsx
Normal file
44
web/src/pages/admin/AdminLayout.test.tsx
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { render, screen } from '@testing-library/react'
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { mockFetch } from '@/test/mockFetch'
|
||||
import AdminLayout from './AdminLayout'
|
||||
|
||||
function renderAdmin(path = '/admin/libraries') {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[path]}>
|
||||
<Routes>
|
||||
<Route path="/admin" element={<AdminLayout />}>
|
||||
<Route path="libraries" element={<p>the libraries page</p>} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</MemoryRouter>,
|
||||
)
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
})
|
||||
|
||||
test('an admin gets the admin page with its sections and the page of the section', () => {
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } })
|
||||
renderAdmin()
|
||||
expect(screen.getByRole('heading', { level: 1, name: 'Admin' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('navigation', { name: 'Admin sections' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'Libraries' })).toHaveAttribute('aria-current', 'page')
|
||||
expect(screen.getByText('the libraries page')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('anyone else sees a notice, not the section, and nothing is asked of the server', async () => {
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 2, username: 'ann', is_admin: false } })
|
||||
const { calls } = mockFetch({})
|
||||
renderAdmin()
|
||||
expect(screen.getByText('Only admins can see this page.')).toBeInTheDocument()
|
||||
expect(screen.queryByText('the libraries page')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('navigation', { name: 'Admin sections' })).not.toBeInTheDocument()
|
||||
await new Promise((r) => setTimeout(r, 30))
|
||||
expect(calls).toHaveLength(0)
|
||||
})
|
||||
41
web/src/pages/admin/AdminLayout.tsx
Normal file
41
web/src/pages/admin/AdminLayout.tsx
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { NavLink, Outlet } from 'react-router-dom'
|
||||
import { useSession } from '@/auth/session'
|
||||
import { EmptyMessage } from '@/components/Status'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
/** The sections of the admin area; each is a route under `/admin`. */
|
||||
const SECTIONS = [{ to: '/admin/libraries', key: 'admin.sectionLibraries' }]
|
||||
|
||||
/**
|
||||
* The frame of the admin area. Only an admin gets the sections: anyone else gets a notice, and since the
|
||||
* section pages are never rendered for them, nothing is asked of the server (which would say 403 anyway).
|
||||
*/
|
||||
export default function AdminLayout() {
|
||||
const { t } = useTranslation()
|
||||
const { user } = useSession()
|
||||
if (!user?.is_admin) return <EmptyMessage>{t('admin.adminOnly')}</EmptyMessage>
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<h1 className="text-3xl font-extrabold tracking-tight">{t('admin.title')}</h1>
|
||||
<nav aria-label={t('admin.sections')} className="flex flex-wrap gap-2">
|
||||
{SECTIONS.map((section) => (
|
||||
<NavLink
|
||||
key={section.to}
|
||||
to={section.to}
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'flex min-h-11 items-center rounded-lg px-4 font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring',
|
||||
isActive ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)
|
||||
}
|
||||
>
|
||||
{t(section.key)}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<Outlet />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
16
web/src/pages/admin/LibrariesPage.tsx
Normal file
16
web/src/pages/admin/LibrariesPage.tsx
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { useState } from 'react'
|
||||
import AddLibraryForm from './AddLibraryForm'
|
||||
import LibraryList from './LibraryList'
|
||||
import ScanPanel from './ScanPanel'
|
||||
|
||||
/** Libraries and scanning. "Read every file again" is shared by the scan of everything and of one library. */
|
||||
export default function LibrariesPage() {
|
||||
const [full, setFull] = useState(false)
|
||||
return (
|
||||
<div className="flex flex-col gap-10">
|
||||
<LibraryList full={full} />
|
||||
<AddLibraryForm />
|
||||
<ScanPanel full={full} onFullChange={setFull} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
174
web/src/pages/admin/LibraryList.test.tsx
Normal file
174
web/src/pages/admin/LibraryList.test.tsx
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
|
||||
import LibraryList from './LibraryList'
|
||||
|
||||
const lib = (id: number, name: string, path: string) => ({ id, name, path, created_at: '2026-11-12T10:00:00Z' })
|
||||
const none = () => new Response(null, { status: 204 })
|
||||
const started = () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } })
|
||||
|
||||
function renderList(full = false) {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<LibraryList full={full} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
function routes(over: MockRoutes = {}): MockRoutes {
|
||||
return {
|
||||
'GET /api/v1/libraries': () => ({ libraries: [lib(1, 'Music', '/srv/music'), lib(2, 'Jazz', '/srv/jazz')] }),
|
||||
'GET /api/v1/library/scan': () => ({ running: false }),
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
const row = async (name: string) => (await screen.findByText(name)).closest('li') as HTMLElement
|
||||
const bodies = (calls: RecordedCall[], key: string) => calls.filter((c) => c.key === key).map((c) => JSON.parse(String(c.init.body)))
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } })
|
||||
})
|
||||
|
||||
test('each library shows its name and its folder on the server', async () => {
|
||||
mockFetch(routes())
|
||||
renderList()
|
||||
const music = await row('Music')
|
||||
expect(music).toHaveTextContent('/srv/music')
|
||||
expect(await row('Jazz')).toHaveTextContent('/srv/jazz')
|
||||
})
|
||||
|
||||
test('with no library it says how to start', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/libraries': () => ({ libraries: [] }) }))
|
||||
renderList()
|
||||
expect(await screen.findByText('No libraries yet. Add one below.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a failure to read the list is said in words with a way to try again', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/libraries': () => apiError(500, 'internal') }))
|
||||
renderList()
|
||||
const alert = await screen.findByRole('alert')
|
||||
expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('"Scan" starts a scan of that library only', async () => {
|
||||
const { calls } = mockFetch(routes({ 'POST /api/v1/libraries/2/scan': started }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Jazz')).getByRole('button', { name: 'Scan Jazz' }))
|
||||
const post = calls.find((c) => c.key === 'POST /api/v1/libraries/2/scan')
|
||||
expect(post).toBeDefined()
|
||||
expect(post?.url.searchParams.has('full')).toBe(false)
|
||||
})
|
||||
|
||||
test('with "read every file again" the scan of a library is a full one', async () => {
|
||||
const { calls } = mockFetch(routes({ 'POST /api/v1/libraries/1/scan': started }))
|
||||
renderList(true)
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Scan Music' }))
|
||||
expect(calls.find((c) => c.key === 'POST /api/v1/libraries/1/scan')?.url.searchParams.get('full')).toBe('true')
|
||||
})
|
||||
|
||||
test('a scan that is already running is explained', async () => {
|
||||
mockFetch(routes({ 'POST /api/v1/libraries/1/scan': () => apiError(409, 'scan_running') }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Scan Music' }))
|
||||
expect(await screen.findByText('A scan is already running.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('while a scan runs no library can be scanned, edited or removed', async () => {
|
||||
mockFetch(routes({ 'GET /api/v1/library/scan': () => ({ running: true }) }))
|
||||
renderList()
|
||||
const music = await row('Music')
|
||||
await waitFor(() => expect(within(music).getByRole('button', { name: 'Scan Music' })).toBeDisabled())
|
||||
expect(within(music).getByRole('button', { name: 'Edit Music' })).toBeDisabled()
|
||||
expect(within(music).getByRole('button', { name: 'Remove Music' })).toBeDisabled()
|
||||
})
|
||||
|
||||
test('removing asks first, and says the music on disk is never touched', async () => {
|
||||
const { calls } = mockFetch(routes({ 'DELETE /api/v1/libraries/1': none }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Remove Music' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(dialog).toHaveTextContent('Remove Music?')
|
||||
expect(dialog).toHaveTextContent('Tracks and listening history stay, and the music on disk is never touched.')
|
||||
expect(calls.map((c) => c.key)).not.toContain('DELETE /api/v1/libraries/1')
|
||||
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(calls.map((c) => c.key)).not.toContain('DELETE /api/v1/libraries/1')
|
||||
})
|
||||
|
||||
test('confirming removes the library and it leaves the list', async () => {
|
||||
let libs = [lib(1, 'Music', '/srv/music'), lib(2, 'Jazz', '/srv/jazz')]
|
||||
mockFetch(
|
||||
routes({
|
||||
'GET /api/v1/libraries': () => ({ libraries: libs }),
|
||||
'DELETE /api/v1/libraries/1': () => {
|
||||
libs = libs.filter((l) => l.id !== 1)
|
||||
return none()
|
||||
},
|
||||
}),
|
||||
)
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Remove Music' }))
|
||||
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Remove library' }))
|
||||
await waitFor(() => expect(screen.queryByText('Music')).not.toBeInTheDocument())
|
||||
expect(screen.getByText('Jazz')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a removal refused because a scan started is explained', async () => {
|
||||
mockFetch(routes({ 'DELETE /api/v1/libraries/1': () => apiError(409, 'scan_running') }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Remove Music' }))
|
||||
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Remove library' }))
|
||||
expect(await screen.findByText('A scan is already running.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('editing starts from what the library has now, and sends only what changed', async () => {
|
||||
const { calls } = mockFetch(routes({ 'PATCH /api/v1/libraries/1': () => lib(1, 'Main', '/srv/music') }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Edit Music' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
expect(within(dialog).getByLabelText('Name')).toHaveValue('Music')
|
||||
expect(within(dialog).getByLabelText('Folder on the server')).toHaveValue('/srv/music')
|
||||
expect(within(dialog).getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
|
||||
await userEvent.clear(within(dialog).getByLabelText('Name'))
|
||||
await userEvent.type(within(dialog).getByLabelText('Name'), 'Main')
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(bodies(calls, 'PATCH /api/v1/libraries/1')).toEqual([{ name: 'Main' }])
|
||||
})
|
||||
|
||||
test('moving a library sends only the folder', async () => {
|
||||
const { calls } = mockFetch(routes({ 'PATCH /api/v1/libraries/1': () => lib(1, 'Music', '/mnt/music') }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Edit Music' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
await userEvent.clear(within(dialog).getByLabelText('Folder on the server'))
|
||||
await userEvent.type(within(dialog).getByLabelText('Folder on the server'), '/mnt/music')
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
expect(bodies(calls, 'PATCH /api/v1/libraries/1')).toEqual([{ path: '/mnt/music' }])
|
||||
})
|
||||
|
||||
test.each([
|
||||
[409, 'library_exists', 'Another library already has this name or folder.'],
|
||||
[409, 'scan_running', 'A scan is already running.'],
|
||||
[400, 'invalid_input', 'The folder must be an existing directory on the server, not the root, and not inside or around another library.'],
|
||||
])('an edit refused with %i %s is explained in the dialog, which stays open', async (status, code, text) => {
|
||||
mockFetch(routes({ 'PATCH /api/v1/libraries/1': () => apiError(status, code) }))
|
||||
renderList()
|
||||
await userEvent.click(within(await row('Music')).getByRole('button', { name: 'Edit Music' }))
|
||||
const dialog = await screen.findByRole('dialog')
|
||||
await userEvent.type(within(dialog).getByLabelText('Name'), 'x')
|
||||
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
|
||||
expect(await within(dialog).findByRole('alert')).toHaveTextContent(text)
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument()
|
||||
})
|
||||
156
web/src/pages/admin/LibraryList.tsx
Normal file
156
web/src/pages/admin/LibraryList.tsx
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
import { useState, type FormEvent } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useLibraries, useRemoveLibrary, useScanStatus, useStartScan, useUpdateLibrary, type Library } from '@/api/libraries'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { errorText } from './errorText'
|
||||
|
||||
const SCOPES = ['admin.libraries.errors', 'admin.errors']
|
||||
/** What the server accepts as a library name. */
|
||||
const MAX_NAME = 100
|
||||
|
||||
/** Rename and move: the dialog starts from what the library has, and only what changed is sent. */
|
||||
function EditDialog({ library, onClose }: { library: Library; onClose: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const update = useUpdateLibrary()
|
||||
const [name, setName] = useState(library.name)
|
||||
const [path, setPath] = useState(library.path)
|
||||
|
||||
const changes: { name?: string; path?: string } = {}
|
||||
if (name.trim() !== library.name) changes.name = name.trim()
|
||||
if (path.trim() !== library.path) changes.path = path.trim()
|
||||
const ready = Object.keys(changes).length > 0 && name.trim() !== '' && path.trim() !== ''
|
||||
|
||||
function submit(event: FormEvent) {
|
||||
event.preventDefault()
|
||||
if (ready) update.mutate({ id: library.id, ...changes }, { onSuccess: onClose })
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<form onSubmit={submit} className="flex flex-col gap-4">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('admin.libraries.editTitle', { name: library.name })}</DialogTitle>
|
||||
<DialogDescription>{t('admin.libraries.folderHint')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="edit-name">{t('admin.libraries.name')}</Label>
|
||||
<Input id="edit-name" value={name} maxLength={MAX_NAME} onChange={(e) => setName(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="edit-path">{t('admin.libraries.folder')}</Label>
|
||||
<Input id="edit-path" value={path} onChange={(e) => setPath(e.target.value)} autoCapitalize="off" spellCheck={false} />
|
||||
</div>
|
||||
{update.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, update.error, SCOPES)}
|
||||
</p>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={onClose}>
|
||||
{t('admin.cancel')}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!ready || update.isPending}>
|
||||
{t('admin.save')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function RemoveDialog({ library, onClose, onConfirm }: { library: Library; onClose: () => void; onConfirm: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<Dialog open onOpenChange={(open) => !open && onClose()}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('admin.libraries.removeTitle', { name: library.name })}</DialogTitle>
|
||||
<DialogDescription>{t('admin.libraries.removeBody')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={onClose}>
|
||||
{t('admin.cancel')}
|
||||
</Button>
|
||||
<Button onClick={onConfirm}>{t('admin.libraries.removeConfirm')}</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
/** The libraries, each with what an admin can do to it. Nothing can be changed or scanned while a scan runs. */
|
||||
export default function LibraryList({ full }: { full: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
const libraries = useLibraries()
|
||||
const status = useScanStatus()
|
||||
const scan = useStartScan()
|
||||
const remove = useRemoveLibrary()
|
||||
const [editing, setEditing] = useState<Library | null>(null)
|
||||
const [removing, setRemoving] = useState<Library | null>(null)
|
||||
const busy = status.data?.running === true || scan.isPending || remove.isPending
|
||||
const failure = scan.error ?? remove.error
|
||||
|
||||
return (
|
||||
<Section title={t('admin.libraries.title')}>
|
||||
{libraries.isError ? (
|
||||
<ErrorMessage error={libraries.error} onRetry={() => void libraries.refetch()} />
|
||||
) : libraries.isPending ? (
|
||||
<Loading />
|
||||
) : libraries.data.length === 0 ? (
|
||||
<EmptyMessage>{t('admin.libraries.empty')}</EmptyMessage>
|
||||
) : (
|
||||
<ul className="flex flex-col gap-3">
|
||||
{libraries.data.map((library) => (
|
||||
<li key={library.id} className="flex flex-wrap items-center gap-4 rounded-lg bg-card p-4 text-card-foreground">
|
||||
<div className="flex min-w-40 flex-1 flex-col">
|
||||
<span className="text-lg font-bold break-words">{library.name}</span>
|
||||
<span className="font-mono text-sm break-all text-muted-foreground">{library.path}</span>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
aria-label={t('admin.libraries.scanOne', { name: library.name })}
|
||||
onClick={() => scan.mutate({ libraryId: library.id, full })}
|
||||
>
|
||||
{t('admin.libraries.scan')}
|
||||
</Button>
|
||||
<Button variant="outline" disabled={busy} aria-label={t('admin.libraries.editOne', { name: library.name })} onClick={() => setEditing(library)}>
|
||||
{t('admin.libraries.edit')}
|
||||
</Button>
|
||||
<Button variant="outline" disabled={busy} aria-label={t('admin.libraries.removeOne', { name: library.name })} onClick={() => setRemoving(library)}>
|
||||
{t('admin.libraries.remove')}
|
||||
</Button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{failure ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, failure, SCOPES)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{editing && <EditDialog key={editing.id} library={editing} onClose={() => setEditing(null)} />}
|
||||
{removing && (
|
||||
<RemoveDialog
|
||||
library={removing}
|
||||
onClose={() => setRemoving(null)}
|
||||
onConfirm={() => {
|
||||
remove.mutate(removing.id)
|
||||
setRemoving(null)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
122
web/src/pages/admin/ScanPanel.test.tsx
Normal file
122
web/src/pages/admin/ScanPanel.test.tsx
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
|
||||
import ScanPanel from './ScanPanel'
|
||||
|
||||
const started = () => new Response(JSON.stringify({ status: 'started' }), { status: 202, headers: { 'Content-Type': 'application/json' } })
|
||||
|
||||
const summary = (over: object = {}) => ({
|
||||
libraries: 2,
|
||||
found: 120,
|
||||
added: 10,
|
||||
updated: 3,
|
||||
unchanged: 100,
|
||||
renamed: 1,
|
||||
restored: 0,
|
||||
missing: 2,
|
||||
failed: 1,
|
||||
skipped: 0,
|
||||
unsupported: 7,
|
||||
...over,
|
||||
})
|
||||
|
||||
function Harness() {
|
||||
const [full, setFull] = useState(false)
|
||||
return <ScanPanel full={full} onFullChange={setFull} />
|
||||
}
|
||||
|
||||
function renderPanel() {
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={client}>
|
||||
<Harness />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
|
||||
function routes(status: object, over: MockRoutes = {}): MockRoutes {
|
||||
return { 'GET /api/v1/library/scan': () => status, ...over }
|
||||
}
|
||||
|
||||
const posts = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'POST /api/v1/library/scan')
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } })
|
||||
})
|
||||
|
||||
test('after a scan it shows how it went, and the files Sonda cannot read yet stand out', async () => {
|
||||
mockFetch(routes({ running: false, last_finished_at: '2026-11-12T10:00:00Z', last: summary() }))
|
||||
renderPanel()
|
||||
const list = await screen.findByRole('list', { name: 'Last scan' })
|
||||
expect(list).toHaveTextContent('120 audio files found')
|
||||
expect(list).toHaveTextContent('10 added')
|
||||
expect(list).toHaveTextContent('2 missing')
|
||||
expect(list).toHaveTextContent('1 could not be read')
|
||||
expect(screen.getByText('7 files are in formats Sonda cannot read yet (such as m4a, ogg or wav).')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('with nothing unsupported it does not mention formats', async () => {
|
||||
mockFetch(routes({ running: false, last_finished_at: '2026-11-12T10:00:00Z', last: summary({ unsupported: 0 }) }))
|
||||
renderPanel()
|
||||
await screen.findByRole('list', { name: 'Last scan' })
|
||||
expect(screen.queryByText(/cannot read yet/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('before any scan it says so', async () => {
|
||||
mockFetch(routes({ running: false }))
|
||||
renderPanel()
|
||||
expect(await screen.findByText('No scan has run yet.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a scan that ended in an error shows the reason', async () => {
|
||||
mockFetch(routes({ running: false, last_error: 'library "Music" is empty or unreadable' }))
|
||||
renderPanel()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('library "Music" is empty or unreadable')
|
||||
})
|
||||
|
||||
test('"Scan all" starts a scan of everything, reading only what changed', async () => {
|
||||
const { calls } = mockFetch(routes({ running: false }, { 'POST /api/v1/library/scan': started }))
|
||||
renderPanel()
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Scan all libraries' }))
|
||||
expect(posts(calls)).toHaveLength(1)
|
||||
expect(posts(calls)[0].url.searchParams.has('full')).toBe(false)
|
||||
})
|
||||
|
||||
test('"Read every file again" makes the scan a full one', async () => {
|
||||
const { calls } = mockFetch(routes({ running: false }, { 'POST /api/v1/library/scan': started }))
|
||||
renderPanel()
|
||||
await userEvent.click(await screen.findByRole('checkbox', { name: 'Read every file again' }))
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Scan all libraries' }))
|
||||
expect(posts(calls)[0].url.searchParams.get('full')).toBe('true')
|
||||
})
|
||||
|
||||
test('while a scan runs the button waits and the page says so', async () => {
|
||||
mockFetch(routes({ running: true, started_at: '2026-11-12T10:00:00Z' }))
|
||||
renderPanel()
|
||||
expect(await screen.findByText('A scan is running.')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Scan all libraries' })).toBeDisabled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
['scan_running', 'A scan is already running.'],
|
||||
['no_libraries', 'Add a library first.'],
|
||||
])('a refusal (%s) is explained', async (code, text) => {
|
||||
mockFetch(routes({ running: false }, { 'POST /api/v1/library/scan': () => apiError(409, code) }))
|
||||
renderPanel()
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Scan all libraries' }))
|
||||
expect(await screen.findByText(text)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an unexpected failure to start is said in words', async () => {
|
||||
mockFetch(routes({ running: false }, { 'POST /api/v1/library/scan': () => apiError(500, 'internal') }))
|
||||
renderPanel()
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Scan all libraries' }))
|
||||
expect(await screen.findByText('Something went wrong. Try again.')).toBeInTheDocument()
|
||||
})
|
||||
91
web/src/pages/admin/ScanPanel.tsx
Normal file
91
web/src/pages/admin/ScanPanel.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { useScanStatus, useStartScan, type ScanSummary } from '@/api/libraries'
|
||||
import Section from '@/components/Section'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { errorText } from './errorText'
|
||||
|
||||
/** The counts of a scan, leaving out what is zero (except what was found). */
|
||||
function Summary({ summary, finishedAt }: { summary: ScanSummary; finishedAt?: string }) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const rows: [string, number][] = [
|
||||
['found', summary.found],
|
||||
['added', summary.added],
|
||||
['updated', summary.updated],
|
||||
['unchanged', summary.unchanged],
|
||||
['renamed', summary.renamed],
|
||||
['restored', summary.restored],
|
||||
['missing', summary.missing],
|
||||
['failed', summary.failed],
|
||||
['skipped', summary.skipped],
|
||||
]
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<ul aria-label={t('admin.scan.last')} className="flex flex-wrap gap-2">
|
||||
{rows
|
||||
.filter(([key, count]) => key === 'found' || count > 0)
|
||||
.map(([key, count]) => (
|
||||
<li key={key} className="rounded-md bg-secondary px-3 py-1 text-sm font-semibold">
|
||||
{t(`admin.scan.counts.${key}`, { count })}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{summary.unsupported > 0 && (
|
||||
<p className="text-sm font-semibold">{t('admin.scan.unsupported', { count: summary.unsupported })}</p>
|
||||
)}
|
||||
{finishedAt && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('admin.scan.finished', { when: new Date(finishedAt).toLocaleString(i18n.language) })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Scan everything, and how the last scan went. The status follows the scan by itself while one runs. */
|
||||
export default function ScanPanel({ full, onFullChange }: { full: boolean; onFullChange: (full: boolean) => void }) {
|
||||
const { t } = useTranslation()
|
||||
const status = useScanStatus()
|
||||
const start = useStartScan()
|
||||
const running = status.data?.running === true
|
||||
|
||||
return (
|
||||
<Section title={t('admin.scan.title')}>
|
||||
<div className="flex flex-col items-start gap-3">
|
||||
<label className="flex min-h-11 items-center gap-3 font-semibold">
|
||||
<input type="checkbox" checked={full} onChange={(e) => onFullChange(e.target.checked)} className="size-5 accent-primary" />
|
||||
{t('admin.scan.full')}
|
||||
</label>
|
||||
<p className="max-w-xl text-sm text-muted-foreground">{t('admin.scan.fullHint')}</p>
|
||||
<Button disabled={running || start.isPending} onClick={() => start.mutate({ full })}>
|
||||
{t('admin.scan.all')}
|
||||
</Button>
|
||||
{start.isError && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{errorText(t, start.error)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{status.isError ? (
|
||||
<ErrorMessage error={status.error} onRetry={() => void status.refetch()} />
|
||||
) : status.isPending ? (
|
||||
<Loading />
|
||||
) : running ? (
|
||||
<p role="status" className="font-semibold">
|
||||
{t('admin.scan.running')}
|
||||
</p>
|
||||
) : (
|
||||
<>
|
||||
{status.data.last && <Summary summary={status.data.last} finishedAt={status.data.last_finished_at} />}
|
||||
{status.data.last_error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{status.data.last_error}
|
||||
</p>
|
||||
)}
|
||||
{!status.data.last && !status.data.last_error && <EmptyMessage>{t('admin.scan.never')}</EmptyMessage>}
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
16
web/src/pages/admin/errorText.ts
Normal file
16
web/src/pages/admin/errorText.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import type { TFunction } from 'i18next'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { errorMessageKey, i18n } from '@/i18n'
|
||||
|
||||
/**
|
||||
* An API error in words. The first scope that has a text for its code wins, so a section can say its own
|
||||
* thing for a code (a bad folder) and leave the rest to the shared texts; then the generic ones.
|
||||
*/
|
||||
export function errorText(t: TFunction, error: unknown, scopes: string[] = ['admin.errors']): string {
|
||||
const code = error instanceof ApiError ? error.code : 'unknown'
|
||||
for (const scope of scopes) {
|
||||
const key = `${scope}.${code}`
|
||||
if (i18n.exists(key)) return t(key)
|
||||
}
|
||||
return t(errorMessageKey(code))
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import type { RouteObject } from 'react-router-dom'
|
||||
import { Navigate, type RouteObject } from 'react-router-dom'
|
||||
import Shell from '@/components/layout/Shell'
|
||||
import AlbumPage from '@/pages/AlbumPage'
|
||||
import AlbumsPage from '@/pages/AlbumsPage'
|
||||
|
|
@ -6,6 +6,8 @@ import ArtistPage from '@/pages/ArtistPage'
|
|||
import ArtistsPage from '@/pages/ArtistsPage'
|
||||
import DiscoverPage from '@/pages/DiscoverPage'
|
||||
import HomePage from '@/pages/HomePage'
|
||||
import AdminLayout from '@/pages/admin/AdminLayout'
|
||||
import LibrariesPage from '@/pages/admin/LibrariesPage'
|
||||
import NotFoundPage from '@/pages/NotFoundPage'
|
||||
import SearchPage from '@/pages/SearchPage'
|
||||
import SettingsPage from '@/pages/SettingsPage'
|
||||
|
|
@ -24,6 +26,14 @@ export const routes: RouteObject[] = [
|
|||
{ path: '/albums/:id', element: <AlbumPage /> },
|
||||
{ path: '/songs', element: <SongsPage /> },
|
||||
{ path: '/settings', element: <SettingsPage /> },
|
||||
{
|
||||
path: '/admin',
|
||||
element: <AdminLayout />,
|
||||
children: [
|
||||
{ index: true, element: <Navigate to="/admin/libraries" replace /> },
|
||||
{ path: 'libraries', element: <LibrariesPage /> },
|
||||
],
|
||||
},
|
||||
{ path: '*', element: <NotFoundPage /> },
|
||||
],
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in a new issue