Merge pull request 'feat(web): external providers in the admin area (F3c)' (#76) from feat/admin-providers into main

This commit is contained in:
squidd 2026-11-12 15:16:56 +01:00
commit dd128a315f
20 changed files with 1566 additions and 39 deletions

View file

@ -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 its admin area covers libraries, scanning and users so far (providers and the bulk jobs are still API-only).
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 covers libraries, scanning, users and the external providers so far (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). 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, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. 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, and to manage accounts: add one by email, give or take away the admin role, reset a password (which ends that person's sessions) and delete an account. The last admin cannot be changed, and your own account has no buttons there. Providers have a card each that says what the provider is sent: turning one on asks first, the API key is write-only (never shown, and gone from the page once saved), and there are a test of the key, the contact or address, removing what a provider gave, and, for Lidarr, the profiles and root folder to use when an artist is added. 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 rest of the admin screens (providers, bulk jobs) 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 bulk jobs screen and serving the app from the binary come later.
## Development

View file

@ -0,0 +1,92 @@
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 { apiError, mockFetch } from '@/test/mockFetch'
import { useLidarrOffers, useProviders, usePurgeProvider, useTestProvider, useUpdateProvider } from './adminProviders'
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 provider = (name: string, over: object = {}) => ({
name,
enabled: false,
needs_api_key: false,
needs_url: false,
has_api_key: false,
contact: '',
url: '',
sends: 'Nothing.',
notes: 'Terms.',
updated_at: null,
...over,
})
test('the providers are listed in the order the server gives them', async () => {
mockFetch({ 'GET /api/v1/providers': () => ({ providers: [provider('lastfm'), provider('musicbrainz')] }) })
const { result } = renderHook(() => useProviders(), { wrapper: setup().wrapper })
await waitFor(() => expect(result.current.data?.map((p) => p.name)).toEqual(['lastfm', 'musicbrainz']))
})
test('an update names the provider, sends only the fields given, and the list is read again', async () => {
let enabled = false
const { calls } = mockFetch({
'GET /api/v1/providers': () => ({ providers: [provider('lastfm', { enabled })] }),
'PUT /api/v1/providers/lastfm': ({ init }) => {
enabled = JSON.parse(String(init.body)).enabled
return provider('lastfm', { enabled })
},
})
const { wrapper } = setup()
const { result } = renderHook(() => ({ list: useProviders(), update: useUpdateProvider() }), { wrapper })
await waitFor(() => expect(result.current.list.data?.[0].enabled).toBe(false))
await act(() => result.current.update.mutateAsync({ name: 'lastfm', enabled: true }))
await waitFor(() => expect(result.current.list.data?.[0].enabled).toBe(true))
expect(JSON.parse(String(calls.find((c) => c.key === 'PUT /api/v1/providers/lastfm')?.init.body))).toEqual({ enabled: true })
})
test('a key is sent as api_key and nothing else with it', async () => {
const { calls } = mockFetch({ 'PUT /api/v1/providers/lastfm': () => provider('lastfm', { has_api_key: true }), 'GET /api/v1/providers': () => ({ providers: [] }) })
const { result } = renderHook(() => useUpdateProvider(), { wrapper: setup().wrapper })
await act(() => result.current.mutateAsync({ name: 'lastfm', api_key: '0123456789abcdef0123456789abcdef' }))
expect(JSON.parse(String(calls.find((c) => c.key === 'PUT /api/v1/providers/lastfm')?.init.body))).toEqual({
api_key: '0123456789abcdef0123456789abcdef',
})
})
test('a test gives the outcome, which is not an error when the provider says no', async () => {
mockFetch({ 'POST /api/v1/providers/lastfm/test': () => ({ ok: false, status: 'key_refused' }) })
const { result } = renderHook(() => useTestProvider(), { wrapper: setup().wrapper })
await act(() => result.current.mutateAsync('lastfm'))
await waitFor(() => expect(result.current.data).toEqual({ ok: false, status: 'key_refused' }))
})
test('removing a provider data gives what was removed', async () => {
const counts = { similar_artists: 4, tags: 9, descriptions: 0, images: 0, artists: 2 }
const { calls } = mockFetch({ 'DELETE /api/v1/providers/lastfm/data': () => counts })
const { result } = renderHook(() => usePurgeProvider(), { wrapper: setup().wrapper })
await act(() => result.current.mutateAsync('lastfm'))
await waitFor(() => expect(result.current.data).toEqual(counts))
expect(calls.map((c) => c.key)).toEqual(['DELETE /api/v1/providers/lastfm/data'])
})
test('what Lidarr offers is asked for only when wanted', async () => {
const offers = { quality_profiles: [{ id: 1, name: 'Any' }], metadata_profiles: [], root_folders: [{ path: '/music', accessible: true }] }
const { calls } = mockFetch({ 'GET /api/v1/providers/lidarr/options': () => offers })
const { wrapper } = setup()
const { result, rerender } = renderHook(({ on }) => useLidarrOffers(on), { wrapper, initialProps: { on: false } })
await new Promise((r) => setTimeout(r, 30))
expect(calls).toHaveLength(0)
rerender({ on: true })
await waitFor(() => expect(result.current.data).toEqual(offers))
})
test('when Lidarr is not set up the offers fail with the error to show', async () => {
mockFetch({ 'GET /api/v1/providers/lidarr/options': () => apiError(409, 'lidarr_not_configured') })
const { result } = renderHook(() => useLidarrOffers(true), { wrapper: setup().wrapper })
await waitFor(() => expect(result.current.isError).toBe(true))
expect(result.current.error).toMatchObject({ status: 409, code: 'lidarr_not_configured' })
})

View file

@ -0,0 +1,68 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from './client'
import type { components } from './schema'
export type Provider = components['schemas']['Provider']
export type ProviderName = Provider['name']
export type ProviderTest = components['schemas']['ProviderTest']
export type ProviderPurge = components['schemas']['ProviderPurge']
export type LidarrOptions = components['schemas']['LidarrOptions']
export type LidarrOffers = components['schemas']['LidarrOffers']
/**
* What `PUT /providers/{name}` takes: any of these, and what is left out is kept. (The generated type of the
* body is an "at least one of" that the generator cannot express, so the fields are listed here.)
*/
export interface ProviderChanges {
enabled?: boolean
/** Write-only. An empty one clears the key, and turns off a provider that needs one. */
api_key?: string
contact?: string
/** Only Lidarr. An empty one clears the address and turns Lidarr off. */
url?: string
/** Only Lidarr. Replaces all its options at once. */
lidarr?: LidarrOptions
}
const PROVIDERS = ['providers']
/** Every external provider with whether it is on and what it would send. The key is never in the answer. */
export function useProviders() {
return useQuery({
queryKey: PROVIDERS,
queryFn: () => api.get<{ providers: Provider[] }>('/providers'),
select: (data) => data.providers,
})
}
/**
* Changes a provider: only the fields given are sent and the rest is kept. An `api_key` is write-only; it
* stays in the mutation's variables until `reset()` is called, so whoever sends one resets the mutation.
*/
export function useUpdateProvider() {
const client = useQueryClient()
return useMutation({
mutationFn: ({ name, ...changes }: { name: ProviderName } & ProviderChanges) => api.put<Provider>(`/providers/${name}`, changes),
onSuccess: () => client.invalidateQueries({ queryKey: PROVIDERS }),
})
}
/** Asks the provider one cheap question with the stored key. A "no" is an answer (`ok` false), not an error. */
export function useTestProvider() {
return useMutation({ mutationFn: (name: ProviderName) => api.post<ProviderTest>(`/providers/${name}/test`) })
}
/** Removes everything a provider told Sonda, and says how much that was. The provider is not switched off. */
export function usePurgeProvider() {
return useMutation({ mutationFn: (name: ProviderName) => api.del<ProviderPurge>(`/providers/${name}/data`) })
}
/** What Lidarr offers to choose from. It is asked only when `enabled`: it contacts the admin's own Lidarr. */
export function useLidarrOffers(enabled: boolean) {
return useQuery({
queryKey: [...PROVIDERS, 'lidarr', 'options'],
enabled,
retry: false,
queryFn: () => api.get<LidarrOffers>('/providers/lidarr/options'),
})
}

View file

@ -63,6 +63,23 @@ test('the admin area has a Users section next to Libraries', async () => {
expect(sections.getByRole('link', { name: 'Libraries' })).not.toHaveAttribute('aria-current')
})
test('the admin area has a Providers section too', async () => {
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
mockFetch({ ...adminRoutes, 'GET /api/v1/providers': () => ({ providers: [] }) })
renderAt('/admin/providers')
expect(await screen.findByRole('region', { name: 'Providers' })).toBeInTheDocument()
expect(within(screen.getByRole('navigation', { name: 'Admin sections' })).getByRole('link', { name: 'Providers' })).toHaveAttribute('aria-current', 'page')
})
test('someone who is not an admin who opens the providers address gets a notice and no request', async () => {
sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } })
const { calls } = mockFetch({ 'GET /api/v1/providers': () => ({ providers: [] }) })
renderAt('/admin/providers')
expect(screen.getByText('Only admins can see this page.')).toBeInTheDocument()
await new Promise((r) => setTimeout(r, 30))
expect(calls).toHaveLength(0)
})
test('someone who is not an admin who opens the users address gets a notice and no request', async () => {
sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } })
const { calls } = mockFetch({ 'GET /api/v1/users': () => ({ users: [] }) })

View file

@ -66,6 +66,7 @@
"adminOnly": "Only admins can see this page.",
"sectionLibraries": "Libraries",
"sectionUsers": "Users",
"sectionProviders": "Providers",
"cancel": "Cancel",
"save": "Save",
"errors": {
@ -73,6 +74,125 @@
"no_libraries": "Add a library first.",
"admin_required": "Only an admin can do this."
},
"providers": {
"intro": "Providers are off until you turn one on, and nothing leaves this server before that. Each card says what the provider is sent.",
"on": "On",
"off": "Off",
"needKey": "Add a key to turn this on.",
"needUrl": "Set the address to turn this on.",
"needBoth": "Set the address and add a key to turn this on.",
"turnOnTitle": "Turn on {{name}}?",
"turnOnBody": "Once it is on, Sonda may contact {{name}}. What it sends: {{sends}}",
"turnOn": "Turn on",
"apiKey": "API key",
"keyStored": "A key is stored.",
"noKey": "No key is stored.",
"saveKey": "Save key",
"saveKeyOne": "Save key for {{name}}",
"removeKey": "Remove key",
"removeKeyOne": "Remove key from {{name}}",
"removeKeyTitle": "Remove the key of {{name}}?",
"removeKeyBody": "This also turns {{name}} off.",
"save": "Save",
"contact": "Contact",
"saveContactOne": "Save contact for {{name}}",
"contactHint": "A web address or an e-mail address, sent to the provider in the User-Agent. Empty uses the project address.",
"address": "Address",
"saveAddressOne": "Save address for {{name}}",
"addressHint": "Where your own {{name}} is, like http://lidarr.lan:8686. Clearing the address turns {{name}} off.",
"test": "Test",
"testOne": "Test {{name}}",
"testStatus": {
"ok": "It works.",
"no_api_key": "No key is stored, so nobody was asked.",
"no_address": "{{name}} has no address yet, so nobody was asked.",
"key_refused": "The provider does not accept this key.",
"rate_limited": "The provider asks to wait: try again later.",
"unreachable": "The provider did not answer.",
"error": "The test failed for another reason."
},
"purge": "Remove data",
"purgeOne": "Remove data from {{name}}",
"purgeTitle": "Remove what {{name}} gave?",
"purgeBody": "This removes everything it told Sonda (similar artists, tags, descriptions and pictures) and the artists that only that data named and nobody has files for. Your own music, listens and settings stay, and the provider is not turned off.",
"purgeConfirm": "Remove data",
"removed": {
"done": "Removed {{list}}.",
"nothing": "Nothing was removed: there was nothing from this provider.",
"and": "and",
"similar_one": "{{count}} similar-artist link",
"similar_other": "{{count}} similar-artist links",
"tags_one": "{{count}} tag",
"tags_other": "{{count}} tags",
"descriptions_one": "{{count}} description",
"descriptions_other": "{{count}} descriptions",
"images_one": "{{count}} picture",
"images_other": "{{count}} pictures",
"artists_one": "{{count}} artist",
"artists_other": "{{count}} artists"
},
"errors": {
"invalid_input": "{{name}} cannot be turned on yet: check that its key and address are set.",
"provider_not_found": "This provider does not exist."
},
"keyErrors": {
"invalid_input": "That key is not valid. A {{name}} key is 32 hexadecimal characters."
},
"contactErrors": {
"invalid_input": "Check the contact: a web address or an e-mail address, without parentheses."
},
"addressErrors": {
"invalid_input": "Check the address: it starts with http:// or https://, with no user, password, query or fragment."
},
"toolErrors": {
"invalid_input": "This provider has no test."
},
"lidarrErrors": {
"lidarr_not_configured": "Set Lidarr's address and a key first.",
"lidarr_key_refused": "Lidarr refused the API key.",
"lidarr_unavailable": "Lidarr could not be reached or gave an answer Sonda did not expect."
},
"lidarrSaveErrors": {
"invalid_input": "Lidarr did not accept these choices: check that the folder and the profiles still exist in Lidarr."
},
"lidarr": {
"title": "What is sent when an artist is added",
"nothing": "Nothing is chosen yet.",
"chosen": "Quality profile {{quality}}, metadata profile {{metadata}}, folder {{folder}}.",
"monitors": "Monitors: {{monitor}}. Starts searching at once: {{search}}.",
"yes": "yes",
"no": "no",
"needs": "Sending an artist to Lidarr needs a quality profile, a metadata profile and a root folder.",
"load": "Load choices from Lidarr",
"loadNeeds": "Set the address and a key first to load the choices.",
"choose": "Choose…",
"quality": "Quality profile",
"metadata": "Metadata profile",
"folder": "Root folder",
"notAccessible": "{{path}} (Lidarr cannot use it now)",
"monitor": "Which albums to monitor",
"search": "Start searching as soon as the artist is added",
"save": "Save Lidarr options",
"monitorOptions": {
"all": "All albums",
"future": "Future albums only",
"missing": "Missing albums only",
"existing": "Existing albums only",
"latest": "Latest album only",
"first": "First album only",
"none": "None, and no new albums"
},
"monitorWords": {
"all": "all albums",
"future": "future albums only",
"missing": "missing albums only",
"existing": "existing albums only",
"latest": "the latest album only",
"first": "the first album only",
"none": "none, and no new albums"
}
}
},
"users": {
"title": "Users",
"empty": "No users.",
@ -265,6 +385,9 @@
"wikipedia": "Wikipedia",
"lastfm": "Last.fm",
"musicbrainz": "MusicBrainz",
"commons": "Wikimedia Commons",
"coverartarchive": "Cover Art Archive",
"lidarr": "Lidarr",
"files": "your files"
},
"empty": {

View file

@ -66,6 +66,7 @@
"adminOnly": "Solo gli admin possono vedere questa pagina.",
"sectionLibraries": "Librerie",
"sectionUsers": "Utenti",
"sectionProviders": "Provider",
"cancel": "Annulla",
"save": "Salva",
"errors": {
@ -73,6 +74,125 @@
"no_libraries": "Aggiungi prima una libreria.",
"admin_required": "Solo un admin può farlo."
},
"providers": {
"intro": "I provider sono spenti finché non ne accendi uno, e prima di allora niente esce da questo server. Ogni scheda dice cosa viene mandato al provider.",
"on": "Acceso",
"off": "Spento",
"needKey": "Aggiungi una chiave per accenderlo.",
"needUrl": "Imposta l'indirizzo per accenderlo.",
"needBoth": "Imposta l'indirizzo e aggiungi una chiave per accenderlo.",
"turnOnTitle": "Accendere {{name}}?",
"turnOnBody": "Una volta acceso, Sonda può contattare {{name}}. Cosa manda: {{sends}}",
"turnOn": "Accendi",
"apiKey": "Chiave API",
"keyStored": "Una chiave è salvata.",
"noKey": "Nessuna chiave salvata.",
"saveKey": "Salva chiave",
"saveKeyOne": "Salva la chiave di {{name}}",
"removeKey": "Togli chiave",
"removeKeyOne": "Togli la chiave di {{name}}",
"removeKeyTitle": "Togliere la chiave di {{name}}?",
"removeKeyBody": "Questo spegne anche {{name}}.",
"save": "Salva",
"contact": "Contatto",
"saveContactOne": "Salva il contatto di {{name}}",
"contactHint": "Un indirizzo web o un indirizzo email, mandato al provider nello User-Agent. Se è vuoto si usa l'indirizzo del progetto.",
"address": "Indirizzo",
"saveAddressOne": "Salva l'indirizzo di {{name}}",
"addressHint": "Dove sta il tuo {{name}}, come http://lidarr.lan:8686. Se lo svuoti, {{name}} si spegne.",
"test": "Prova",
"testOne": "Prova {{name}}",
"testStatus": {
"ok": "Funziona.",
"no_api_key": "Nessuna chiave salvata, quindi non è stato chiesto a nessuno.",
"no_address": "{{name}} non ha ancora un indirizzo, quindi non è stato chiesto a nessuno.",
"key_refused": "Il provider non accetta questa chiave.",
"rate_limited": "Il provider chiede di aspettare: riprova più tardi.",
"unreachable": "Il provider non ha risposto.",
"error": "La prova è fallita per un altro motivo."
},
"purge": "Togli i dati",
"purgeOne": "Togli i dati di {{name}}",
"purgeTitle": "Togliere ciò che ha dato {{name}}?",
"purgeBody": "Questo toglie tutto ciò che ha detto a Sonda (artisti simili, tag, descrizioni e immagini) e gli artisti nominati solo da quei dati e di cui nessuno ha file. La tua musica, i tuoi ascolti e le tue impostazioni restano, e il provider non viene spento.",
"purgeConfirm": "Togli i dati",
"removed": {
"done": "Tolti {{list}}.",
"nothing": "Non è stato tolto niente: non c'era niente di questo provider.",
"and": "e",
"similar_one": "{{count}} collegamento tra artisti simili",
"similar_other": "{{count}} collegamenti tra artisti simili",
"tags_one": "{{count}} tag",
"tags_other": "{{count}} tag",
"descriptions_one": "{{count}} descrizione",
"descriptions_other": "{{count}} descrizioni",
"images_one": "{{count}} immagine",
"images_other": "{{count}} immagini",
"artists_one": "{{count}} artista",
"artists_other": "{{count}} artisti"
},
"errors": {
"invalid_input": "{{name}} non si può ancora accendere: controlla che la chiave e l'indirizzo siano impostati.",
"provider_not_found": "Questo provider non esiste."
},
"keyErrors": {
"invalid_input": "Questa chiave non è valida. Una chiave di {{name}} ha 32 cifre esadecimali."
},
"contactErrors": {
"invalid_input": "Controlla il contatto: un indirizzo web o un indirizzo email, senza parentesi."
},
"addressErrors": {
"invalid_input": "Controlla l'indirizzo: inizia con http:// o https://, senza utente, password, query o frammento."
},
"toolErrors": {
"invalid_input": "Questo provider non ha una prova."
},
"lidarrErrors": {
"lidarr_not_configured": "Imposta prima l'indirizzo e una chiave di Lidarr.",
"lidarr_key_refused": "Lidarr ha rifiutato la chiave API.",
"lidarr_unavailable": "Lidarr non è raggiungibile o ha dato una risposta che Sonda non si aspettava."
},
"lidarrSaveErrors": {
"invalid_input": "Lidarr non ha accettato queste scelte: controlla che la cartella e i profili esistano ancora in Lidarr."
},
"lidarr": {
"title": "Cosa viene mandato quando si aggiunge un artista",
"nothing": "Non è ancora stato scelto niente.",
"chosen": "Profilo qualità {{quality}}, profilo metadati {{metadata}}, cartella {{folder}}.",
"monitors": "Monitora: {{monitor}}. Comincia a cercare subito: {{search}}.",
"yes": "sì",
"no": "no",
"needs": "Per mandare un artista a Lidarr servono un profilo qualità, un profilo metadati e una cartella radice.",
"load": "Carica le scelte da Lidarr",
"loadNeeds": "Imposta prima l'indirizzo e una chiave per caricare le scelte.",
"choose": "Scegli…",
"quality": "Profilo qualità",
"metadata": "Profilo metadati",
"folder": "Cartella radice",
"notAccessible": "{{path}} (Lidarr non può usarla ora)",
"monitor": "Quali album monitorare",
"search": "Comincia a cercare appena l'artista è aggiunto",
"save": "Salva le opzioni di Lidarr",
"monitorOptions": {
"all": "Tutti gli album",
"future": "Solo gli album futuri",
"missing": "Solo gli album mancanti",
"existing": "Solo gli album esistenti",
"latest": "Solo l'ultimo album",
"first": "Solo il primo album",
"none": "Nessuno, e nessun nuovo album"
},
"monitorWords": {
"all": "tutti gli album",
"future": "solo gli album futuri",
"missing": "solo gli album mancanti",
"existing": "solo gli album esistenti",
"latest": "solo l'ultimo album",
"first": "solo il primo album",
"none": "nessuno, e nessun nuovo album"
}
}
},
"users": {
"title": "Utenti",
"empty": "Nessun utente.",
@ -265,6 +385,9 @@
"wikipedia": "Wikipedia",
"lastfm": "Last.fm",
"musicbrainz": "MusicBrainz",
"commons": "Wikimedia Commons",
"coverartarchive": "Cover Art Archive",
"lidarr": "Lidarr",
"files": "i tuoi file"
},
"empty": {

View file

@ -8,6 +8,7 @@ import { cn } from '@/lib/utils'
const SECTIONS = [
{ to: '/admin/libraries', key: 'admin.sectionLibraries' },
{ to: '/admin/users', key: 'admin.sectionUsers' },
{ to: '/admin/providers', key: 'admin.sectionProviders' },
]
/**

View file

@ -0,0 +1,36 @@
import { useTranslation } from 'react-i18next'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
/** A question with two answers, for what cannot be taken back, takes something away, or sends data out. */
export default function Confirm({
title,
body,
confirm,
onConfirm,
onClose,
}: {
title: string
body: string
confirm: string
onConfirm: () => void
onClose: () => void
}) {
const { t } = useTranslation()
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{body}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{t('admin.cancel')}
</Button>
<Button onClick={onConfirm}>{confirm}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}

View file

@ -0,0 +1,199 @@
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 { useProviders } from '@/api/adminProviders'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
import ProviderCard from './ProviderCard'
type P = Record<string, unknown>
const DEFAULTS = { quality_profile_id: 0, metadata_profile_id: 0, root_folder_path: '', monitor: 'all', search_missing: true }
const lidarr = (over: P = {}): P => ({
name: 'lidarr',
enabled: false,
needs_api_key: true,
needs_url: true,
has_api_key: true,
contact: '',
url: 'http://lidarr.lan:8686',
lidarr: DEFAULTS,
sends: 'Only the MusicBrainz id and the key go to your Lidarr.',
notes: 'Your own server.',
updated_at: null,
...over,
})
const OFFERS = {
quality_profiles: [
{ id: 1, name: 'Any' },
{ id: 2, name: 'Lossless' },
],
metadata_profiles: [{ id: 5, name: 'Standard' }],
root_folders: [
{ path: '/music', accessible: true },
{ path: '/unmounted', accessible: false },
],
}
function server(initial: P, over: MockRoutes = {}) {
let current = initial
return mockFetch({
'GET /api/v1/providers': () => ({ providers: [current] }),
'PUT /api/v1/providers/lidarr': ({ init }) => {
current = { ...current, ...(JSON.parse(String(init.body)) as P) }
return current
},
'GET /api/v1/providers/lidarr/options': () => OFFERS,
...over,
})
}
function Harness() {
const providers = useProviders()
const provider = providers.data?.find((p) => p.name === 'lidarr')
return provider ? <ProviderCard provider={provider} /> : null
}
function renderCard() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<Harness />
</QueryClientProvider>,
)
}
const card = () => screen.findByRole('region', { name: 'Lidarr' })
const puts = (calls: RecordedCall[]) => calls.filter((c) => c.key === 'PUT /api/v1/providers/lidarr').map((c) => JSON.parse(String(c.init.body)))
const load = async (c: HTMLElement) => userEvent.click(within(c).getByRole('button', { name: 'Load choices from Lidarr' }))
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
})
test('before anything is chosen the card says so and what is needed to add an artist', async () => {
server(lidarr())
renderCard()
const c = await card()
expect(c).toHaveTextContent('Nothing is chosen yet.')
expect(c).toHaveTextContent('Sending an artist to Lidarr needs a quality profile, a metadata profile and a root folder.')
})
test('what was chosen is summed up in words', async () => {
server(lidarr({ lidarr: { quality_profile_id: 2, metadata_profile_id: 5, root_folder_path: '/music', monitor: 'future', search_missing: false } }))
renderCard()
const c = await card()
expect(c).toHaveTextContent('Quality profile 2, metadata profile 5, folder /music.')
expect(c).toHaveTextContent('Monitors: future albums only. Starts searching at once: no.')
})
test('nothing is asked of Lidarr until the choices are loaded on purpose', async () => {
const { calls } = server(lidarr())
renderCard()
await card()
await new Promise((r) => setTimeout(r, 40))
expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/providers/lidarr/options')
})
test('the choices cannot be loaded before Lidarr has an address and a key, and the card says so', async () => {
server(lidarr({ url: '' }))
renderCard()
const c = await card()
expect(within(c).getByRole('button', { name: 'Load choices from Lidarr' })).toBeDisabled()
expect(c).toHaveTextContent('Set the address and a key first to load the choices.')
})
test('loading shows what Lidarr offers, and a folder it cannot use is marked and cannot be picked', async () => {
server(lidarr())
renderCard()
const c = await card()
await load(c)
const quality = await within(c).findByLabelText('Quality profile')
expect(within(quality).getAllByRole('option').map((o) => o.textContent)).toEqual(['Choose…', 'Any', 'Lossless'])
const folder = within(c).getByLabelText('Root folder')
const options = within(folder).getAllByRole('option')
expect(options.map((o) => o.textContent)).toEqual(['Choose…', '/music', '/unmounted (Lidarr cannot use it now)'])
expect(options[2]).toBeDisabled()
expect(within(c).getByLabelText('Which albums to monitor')).toHaveValue('all')
expect(within(c).getByRole('checkbox', { name: 'Start searching as soon as the artist is added' })).toBeChecked()
})
test('what is already chosen is selected once the choices are loaded', async () => {
server(lidarr({ lidarr: { ...DEFAULTS, quality_profile_id: 2, metadata_profile_id: 5, root_folder_path: '/music' } }))
renderCard()
const c = await card()
await load(c)
expect(await within(c).findByLabelText('Quality profile')).toHaveValue('2')
expect(within(c).getByLabelText('Metadata profile')).toHaveValue('5')
expect(within(c).getByLabelText('Root folder')).toHaveValue('/music')
})
test('saving needs the three choices, and sends all the options at once', async () => {
const { calls } = server(lidarr())
renderCard()
const c = await card()
await load(c)
const save = await within(c).findByRole('button', { name: 'Save Lidarr options' })
expect(save).toBeDisabled()
await userEvent.selectOptions(within(c).getByLabelText('Quality profile'), '2')
await userEvent.selectOptions(within(c).getByLabelText('Metadata profile'), '5')
expect(save).toBeDisabled()
await userEvent.selectOptions(within(c).getByLabelText('Root folder'), '/music')
await userEvent.selectOptions(within(c).getByLabelText('Which albums to monitor'), 'missing')
await userEvent.click(within(c).getByRole('checkbox', { name: 'Start searching as soon as the artist is added' }))
await userEvent.click(save)
await waitFor(() =>
expect(puts(calls)).toEqual([
{ lidarr: { quality_profile_id: 2, metadata_profile_id: 5, root_folder_path: '/music', monitor: 'missing', search_missing: false } },
]),
)
expect(await within(c).findByText('Quality profile 2, metadata profile 5, folder /music.')).toBeInTheDocument()
})
test.each([
[409, 'lidarr_not_configured', "Set Lidarr's address and a key first."],
[502, 'lidarr_key_refused', 'Lidarr refused the API key.'],
[502, 'lidarr_unavailable', 'Lidarr could not be reached or gave an answer Sonda did not expect.'],
])('when loading fails (%i %s) it says why and can be tried again', async (status, code, text) => {
server(lidarr(), { 'GET /api/v1/providers/lidarr/options': () => apiError(status, code) })
renderCard()
const c = await card()
await load(c)
expect(await within(c).findByRole('alert')).toHaveTextContent(text)
expect(within(c).getByRole('button', { name: 'Load choices from Lidarr' })).toBeEnabled()
})
test('a choice the server refuses is explained', async () => {
server(lidarr(), { 'PUT /api/v1/providers/lidarr': () => apiError(400, 'invalid_input') })
renderCard()
const c = await card()
await load(c)
await userEvent.selectOptions(await within(c).findByLabelText('Quality profile'), '1')
await userEvent.selectOptions(within(c).getByLabelText('Metadata profile'), '5')
await userEvent.selectOptions(within(c).getByLabelText('Root folder'), '/music')
await userEvent.click(within(c).getByRole('button', { name: 'Save Lidarr options' }))
expect(await within(c).findByRole('alert')).toHaveTextContent('Lidarr did not accept these choices: check that the folder and the profiles still exist in Lidarr.')
})
test('the other providers have no Lidarr options', async () => {
const other = { ...lidarr(), name: 'musicbrainz', needs_api_key: false, needs_url: false, lidarr: undefined }
mockFetch({ 'GET /api/v1/providers': () => ({ providers: [other] }) })
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
function Other() {
const providers = useProviders()
const provider = providers.data?.[0]
return provider ? <ProviderCard provider={provider} /> : null
}
render(
<QueryClientProvider client={client}>
<Other />
</QueryClientProvider>,
)
const c = await screen.findByRole('region', { name: 'MusicBrainz' })
expect(within(c).queryByRole('button', { name: 'Load choices from Lidarr' })).not.toBeInTheDocument()
})

View file

@ -0,0 +1,157 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useLidarrOffers, useUpdateProvider, type LidarrOffers, type LidarrOptions, type Provider } from '@/api/adminProviders'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { errorText } from './errorText'
const MONITOR = ['all', 'future', 'missing', 'existing', 'latest', 'first', 'none'] as const
const SELECT =
'h-9 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring'
/** The options as one sentence each: what is chosen now, or that nothing is. */
function Chosen({ options }: { options: LidarrOptions }) {
const { t } = useTranslation()
const nothing = options.quality_profile_id === 0 && options.metadata_profile_id === 0 && options.root_folder_path === ''
if (nothing) return <p className="text-sm font-semibold">{t('admin.providers.lidarr.nothing')}</p>
return (
<div className="flex flex-col gap-1 text-sm font-semibold">
<p>
{t('admin.providers.lidarr.chosen', {
quality: options.quality_profile_id,
metadata: options.metadata_profile_id,
folder: options.root_folder_path,
})}
</p>
<p>
{t('admin.providers.lidarr.monitors', {
monitor: t(`admin.providers.lidarr.monitorWords.${options.monitor}`),
search: t(options.search_missing ? 'admin.providers.lidarr.yes' : 'admin.providers.lidarr.no'),
})}
</p>
</div>
)
}
/** The choices Lidarr offers, as selects that start from what is already chosen. Saving replaces all the options. */
function Choices({ provider, offers, name }: { provider: Provider; offers: LidarrOffers; name: string }) {
const { t } = useTranslation()
const update = useUpdateProvider()
const current = provider.lidarr ?? { quality_profile_id: 0, metadata_profile_id: 0, root_folder_path: '', monitor: 'all', search_missing: true }
const pick = (id: number, list: { id: number }[]) => (list.some((item) => item.id === id) ? String(id) : '')
const [quality, setQuality] = useState(pick(current.quality_profile_id, offers.quality_profiles))
const [metadata, setMetadata] = useState(pick(current.metadata_profile_id, offers.metadata_profiles))
const [folder, setFolder] = useState(offers.root_folders.some((f) => f.path === current.root_folder_path) ? current.root_folder_path : '')
const [monitor, setMonitor] = useState<LidarrOptions['monitor']>(current.monitor)
const [search, setSearch] = useState(current.search_missing)
const ready = quality !== '' && metadata !== '' && folder !== ''
function submit(event: FormEvent) {
event.preventDefault()
if (!ready) return
update.mutate({
name: provider.name,
lidarr: {
quality_profile_id: Number(quality),
metadata_profile_id: Number(metadata),
root_folder_path: folder,
monitor,
search_missing: search,
},
})
}
const choose = t('admin.providers.lidarr.choose')
return (
<form onSubmit={submit} className="flex max-w-xl flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="lidarr-quality">{t('admin.providers.lidarr.quality')}</Label>
<select id="lidarr-quality" className={SELECT} value={quality} onChange={(e) => setQuality(e.target.value)}>
<option value="">{choose}</option>
{offers.quality_profiles.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="lidarr-metadata">{t('admin.providers.lidarr.metadata')}</Label>
<select id="lidarr-metadata" className={SELECT} value={metadata} onChange={(e) => setMetadata(e.target.value)}>
<option value="">{choose}</option>
{offers.metadata_profiles.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="lidarr-folder">{t('admin.providers.lidarr.folder')}</Label>
<select id="lidarr-folder" className={SELECT} value={folder} onChange={(e) => setFolder(e.target.value)}>
<option value="">{choose}</option>
{offers.root_folders.map((f) => (
<option key={f.path} value={f.path} disabled={!f.accessible}>
{f.accessible ? f.path : t('admin.providers.lidarr.notAccessible', { path: f.path })}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="lidarr-monitor">{t('admin.providers.lidarr.monitor')}</Label>
<select id="lidarr-monitor" className={SELECT} value={monitor} onChange={(e) => setMonitor(e.target.value as LidarrOptions['monitor'])}>
{MONITOR.map((m) => (
<option key={m} value={m}>
{t(`admin.providers.lidarr.monitorOptions.${m}`)}
</option>
))}
</select>
</div>
<label className="flex min-h-11 items-center gap-3 font-semibold">
<input type="checkbox" checked={search} onChange={(e) => setSearch(e.target.checked)} className="size-5 accent-primary" />
{t('admin.providers.lidarr.search')}
</label>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, update.error, ['admin.providers.lidarrSaveErrors', 'admin.errors'], { name })}
</p>
)}
<Button type="submit" className="self-start" disabled={!ready || update.isPending}>
{t('admin.providers.lidarr.save')}
</Button>
</form>
)
}
/**
* What is sent to Lidarr when an artist is added. Nothing is asked of Lidarr until the admin loads its choices
* on purpose, and that needs its address and a key first.
*/
export default function LidarrSetup({ provider, name }: { provider: Provider; name: string }) {
const { t } = useTranslation()
const [wanted, setWanted] = useState(false)
const offers = useLidarrOffers(wanted)
const ready = provider.url !== '' && provider.has_api_key
const options = provider.lidarr ?? { quality_profile_id: 0, metadata_profile_id: 0, root_folder_path: '', monitor: 'all' as const, search_missing: true }
return (
<div className="flex flex-col gap-3">
<h4 className="font-bold">{t('admin.providers.lidarr.title')}</h4>
<Chosen options={options} />
<p className="text-sm text-muted-foreground">{t('admin.providers.lidarr.needs')}</p>
<div className="flex flex-col items-start gap-2">
<Button variant="outline" disabled={!ready || offers.isFetching} onClick={() => (wanted ? void offers.refetch() : setWanted(true))}>
{t('admin.providers.lidarr.load')}
</Button>
{!ready && <p className="text-sm text-muted-foreground">{t('admin.providers.lidarr.loadNeeds')}</p>}
</div>
{offers.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, offers.error, ['admin.providers.lidarrErrors', 'admin.errors'])}
</p>
)}
{offers.data && <Choices key={JSON.stringify(options)} provider={provider} offers={offers.data} name={name} />}
</div>
)
}

View file

@ -0,0 +1,314 @@
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 { useProviders } from '@/api/adminProviders'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch'
import ProviderCard from './ProviderCard'
const KEY = '0123456789abcdef0123456789abcdef'
type P = Record<string, unknown>
const base = (name: string, over: P = {}): P => ({
name,
enabled: false,
needs_api_key: false,
needs_url: false,
has_api_key: false,
contact: '',
url: '',
sends: `What ${name} is sent.`,
notes: `Terms of ${name}.`,
updated_at: null,
...over,
})
const lastfm = (over: P = {}) => base('lastfm', { needs_api_key: true, sends: 'The names of artists go to Last.fm.', ...over })
/** A server that keeps the providers and applies what is put to them, like the real one. */
function server(initial: P, over: MockRoutes = {}) {
let current = initial
return mockFetch({
'GET /api/v1/providers': () => ({ providers: [current] }),
[`PUT /api/v1/providers/${initial.name}`]: ({ init }) => {
const body = JSON.parse(String(init.body)) as P
const { api_key, ...rest } = body
current = { ...current, ...rest }
if (api_key !== undefined) {
current.has_api_key = api_key !== ''
if (api_key === '') current.enabled = false
}
return current
},
...over,
})
}
function Harness({ name }: { name: string }) {
const providers = useProviders()
const provider = providers.data?.find((p) => p.name === name)
return provider ? <ProviderCard provider={provider} /> : null
}
function renderCard(name: string) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<Harness name={name} />
</QueryClientProvider>,
)
}
const card = (label: string) => screen.findByRole('region', { name: label })
const puts = (calls: RecordedCall[], name: string) => calls.filter((c) => c.key === `PUT /api/v1/providers/${name}`).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, email: 'tom@example.org', is_admin: true } })
})
// --- the card and the switch ----------------------------------------------------------------------
test('a card names the provider, says what it is sent and the terms, and shows whether it is on', async () => {
server(lastfm({ has_api_key: true }))
renderCard('lastfm')
const c = await card('Last.fm')
expect(c).toHaveTextContent('The names of artists go to Last.fm.')
expect(c).toHaveTextContent('Terms of lastfm.')
expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'false')
})
test('turning a provider on asks first and repeats what it will be sent', async () => {
const { calls } = server(lastfm({ has_api_key: true }))
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.click(within(c).getByRole('switch', { name: 'Last.fm' }))
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent('Turn on Last.fm?')
expect(dialog).toHaveTextContent('The names of artists go to Last.fm.')
expect(puts(calls, 'lastfm')).toHaveLength(0)
await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(puts(calls, 'lastfm')).toHaveLength(0)
await userEvent.click(within(c).getByRole('switch', { name: 'Last.fm' }))
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Turn on' }))
await waitFor(() => expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'true'))
expect(puts(calls, 'lastfm')).toEqual([{ enabled: true }])
})
test('turning a provider off needs no question', async () => {
const { calls } = server(lastfm({ has_api_key: true, enabled: true }))
renderCard('lastfm')
const c = await card('Last.fm')
await waitFor(() => expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'true'))
await userEvent.click(within(c).getByRole('switch', { name: 'Last.fm' }))
await waitFor(() => expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'false'))
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(puts(calls, 'lastfm')).toEqual([{ enabled: false }])
})
test('a provider that needs a key cannot be turned on without one, and the card says why', async () => {
server(lastfm())
renderCard('lastfm')
const c = await card('Last.fm')
expect(within(c).getByRole('switch', { name: 'Last.fm' })).toBeDisabled()
expect(c).toHaveTextContent('Add a key to turn this on.')
})
test('a provider that needs no key can be turned on at once, after the question', async () => {
const { calls } = server(base('musicbrainz'))
renderCard('musicbrainz')
const c = await card('MusicBrainz')
await userEvent.click(within(c).getByRole('switch', { name: 'MusicBrainz' }))
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Turn on' }))
await waitFor(() => expect(puts(calls, 'musicbrainz')).toEqual([{ enabled: true }]))
})
test('a refusal from the server is explained and the switch stays as it was', async () => {
server(lastfm({ has_api_key: true }), { 'PUT /api/v1/providers/lastfm': () => apiError(400, 'invalid_input') })
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.click(within(c).getByRole('switch', { name: 'Last.fm' }))
await userEvent.click(within(await screen.findByRole('dialog')).getByRole('button', { name: 'Turn on' }))
expect(await within(c).findByRole('alert')).toBeInTheDocument()
expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'false')
})
// --- the key, which is write-only -----------------------------------------------------------------
test('the key field is hidden, empty, and not remembered by the browser; the card only says whether one is stored', async () => {
server(lastfm({ has_api_key: true }))
renderCard('lastfm')
const c = await card('Last.fm')
const field = within(c).getByLabelText('API key')
expect(field).toHaveAttribute('type', 'password')
expect(field).toHaveAttribute('autocomplete', 'off')
expect(field).toHaveValue('')
expect(c).toHaveTextContent('A key is stored.')
})
test('with no key the card says so', async () => {
server(lastfm())
renderCard('lastfm')
expect(await card('Last.fm')).toHaveTextContent('No key is stored.')
})
test('saving a key sends it once, empties the field and leaves it nowhere on the page', async () => {
const { calls } = server(lastfm())
renderCard('lastfm')
const c = await card('Last.fm')
expect(within(c).getByRole('button', { name: 'Save key for Last.fm' })).toBeDisabled()
await userEvent.type(within(c).getByLabelText('API key'), KEY)
await userEvent.click(within(c).getByRole('button', { name: 'Save key for Last.fm' }))
await waitFor(() => expect(within(c).getByLabelText('API key')).toHaveValue(''))
expect(puts(calls, 'lastfm')).toEqual([{ api_key: KEY }])
expect(await within(c).findByText('A key is stored.')).toBeInTheDocument()
expect(document.body.innerHTML).not.toContain(KEY)
})
test('a key the server refuses is explained and the field keeps what was typed', async () => {
server(lastfm(), { 'PUT /api/v1/providers/lastfm': () => apiError(400, 'invalid_input') })
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.type(within(c).getByLabelText('API key'), 'nope')
await userEvent.click(within(c).getByRole('button', { name: 'Save key for Last.fm' }))
expect(await within(c).findByRole('alert')).toHaveTextContent('That key is not valid. A Last.fm key is 32 hexadecimal characters.')
})
test('removing a key asks first and says it also turns the provider off', async () => {
const { calls } = server(lastfm({ has_api_key: true, enabled: true }))
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.click(await within(c).findByRole('button', { name: 'Remove key from Last.fm' }))
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent('Remove the key of Last.fm?')
expect(dialog).toHaveTextContent('This also turns Last.fm off.')
expect(puts(calls, 'lastfm')).toHaveLength(0)
await userEvent.click(within(dialog).getByRole('button', { name: 'Remove key' }))
await waitFor(() => expect(puts(calls, 'lastfm')).toEqual([{ api_key: '' }]))
await waitFor(() => expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'false'))
expect(c).toHaveTextContent('No key is stored.')
})
test('there is nothing to remove when no key is stored', async () => {
server(lastfm())
renderCard('lastfm')
const c = await card('Last.fm')
expect(within(c).queryByRole('button', { name: 'Remove key from Last.fm' })).not.toBeInTheDocument()
})
test('a provider that needs no key has no key field', async () => {
server(base('musicbrainz'))
renderCard('musicbrainz')
const c = await card('MusicBrainz')
expect(within(c).queryByLabelText('API key')).not.toBeInTheDocument()
})
// --- contact and address --------------------------------------------------------------------------
test('the contact starts from what is stored and is sent when saved', async () => {
const { calls } = server(base('musicbrainz', { contact: 'me@example.org' }))
renderCard('musicbrainz')
const c = await card('MusicBrainz')
const field = within(c).getByLabelText('Contact')
expect(field).toHaveValue('me@example.org')
expect(within(c).getByRole('button', { name: 'Save contact for MusicBrainz' })).toBeDisabled()
await userEvent.clear(field)
await userEvent.type(field, 'https://example.org/sonda')
await userEvent.click(within(c).getByRole('button', { name: 'Save contact for MusicBrainz' }))
await waitFor(() => expect(puts(calls, 'musicbrainz')).toEqual([{ contact: 'https://example.org/sonda' }]))
})
test('an empty contact is saved too, and the hint says it restores the default', async () => {
const { calls } = server(base('musicbrainz', { contact: 'me@example.org' }))
renderCard('musicbrainz')
const c = await card('MusicBrainz')
expect(c).toHaveTextContent('Empty uses the project address.')
await userEvent.clear(within(c).getByLabelText('Contact'))
await userEvent.click(within(c).getByRole('button', { name: 'Save contact for MusicBrainz' }))
await waitFor(() => expect(puts(calls, 'musicbrainz')).toEqual([{ contact: '' }]))
})
test('Lidarr has an address instead of a contact, and a Lidarr that is cleared goes off', async () => {
const { calls } = server(base('lidarr', { needs_api_key: true, needs_url: true, has_api_key: true, url: 'http://lidarr.lan:8686', enabled: true }))
renderCard('lidarr')
const c = await card('Lidarr')
expect(within(c).queryByLabelText('Contact')).not.toBeInTheDocument()
const field = within(c).getByLabelText('Address')
expect(field).toHaveValue('http://lidarr.lan:8686')
expect(c).toHaveTextContent('Clearing the address turns Lidarr off.')
await userEvent.clear(field)
await userEvent.type(field, 'http://other.lan:8686')
await userEvent.click(within(c).getByRole('button', { name: 'Save address for Lidarr' }))
await waitFor(() => expect(puts(calls, 'lidarr')).toEqual([{ url: 'http://other.lan:8686' }]))
})
test('an address the server refuses is explained', async () => {
server(base('lidarr', { needs_api_key: true, needs_url: true }), { 'PUT /api/v1/providers/lidarr': () => apiError(400, 'invalid_input') })
renderCard('lidarr')
const c = await card('Lidarr')
await userEvent.type(within(c).getByLabelText('Address'), 'lidarr.lan')
await userEvent.click(within(c).getByRole('button', { name: 'Save address for Lidarr' }))
expect(await within(c).findByRole('alert')).toHaveTextContent('Check the address: it starts with http:// or https://, with no user, password, query or fragment.')
})
test('Lidarr cannot be turned on without an address and a key, and says which is missing', async () => {
server(base('lidarr', { needs_api_key: true, needs_url: true, has_api_key: true }))
renderCard('lidarr')
const c = await card('Lidarr')
expect(within(c).getByRole('switch', { name: 'Lidarr' })).toBeDisabled()
expect(c).toHaveTextContent('Set the address to turn this on.')
})
// --- test and removing what the provider gave ------------------------------------------------------
test.each([
[{ ok: true, status: 'ok' }, 'It works.'],
[{ ok: false, status: 'no_api_key' }, 'No key is stored, so nobody was asked.'],
[{ ok: false, status: 'key_refused' }, 'The provider does not accept this key.'],
[{ ok: false, status: 'rate_limited' }, 'The provider asks to wait: try again later.'],
[{ ok: false, status: 'unreachable' }, 'The provider did not answer.'],
[{ ok: false, status: 'error' }, 'The test failed for another reason.'],
])('a test that answers %j says it in words', async (answer, text) => {
server(lastfm({ has_api_key: true }), { 'POST /api/v1/providers/lastfm/test': () => answer })
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.click(within(c).getByRole('button', { name: 'Test Last.fm' }))
expect(await within(c).findByRole('status')).toHaveTextContent(text)
})
test('Lidarr with no address is told so by the test', async () => {
server(base('lidarr', { needs_api_key: true, needs_url: true, has_api_key: true }), {
'POST /api/v1/providers/lidarr/test': () => ({ ok: false, status: 'no_address' }),
})
renderCard('lidarr')
const c = await card('Lidarr')
await userEvent.click(within(c).getByRole('button', { name: 'Test Lidarr' }))
expect(await within(c).findByRole('status')).toHaveTextContent('Lidarr has no address yet, so nobody was asked.')
})
test('removing what a provider gave asks first, then says how much went', async () => {
const counts = { similar_artists: 4, tags: 9, descriptions: 1, images: 2, artists: 3 }
const { calls } = server(lastfm({ has_api_key: true }), { 'DELETE /api/v1/providers/lastfm/data': () => counts })
renderCard('lastfm')
const c = await card('Last.fm')
await userEvent.click(within(c).getByRole('button', { name: 'Remove data from Last.fm' }))
const dialog = await screen.findByRole('dialog')
expect(dialog).toHaveTextContent('Remove what Last.fm gave?')
expect(dialog).toHaveTextContent('Your own music, listens and settings stay, and the provider is not turned off.')
expect(calls.map((c) => c.key)).not.toContain('DELETE /api/v1/providers/lastfm/data')
await userEvent.click(within(dialog).getByRole('button', { name: 'Remove data' }))
expect(await within(c).findByRole('status')).toHaveTextContent('Removed 4 similar-artist links, 9 tags, 1 description, 2 pictures and 3 artists.')
})
test('Lidarr has nothing to remove: it gave Sonda no data', async () => {
server(base('lidarr', { needs_api_key: true, needs_url: true }))
renderCard('lidarr')
const c = await card('Lidarr')
expect(within(c).queryByRole('button', { name: /Remove data/ })).not.toBeInTheDocument()
})

View file

@ -0,0 +1,92 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useUpdateProvider, type Provider } from '@/api/adminProviders'
import { cn } from '@/lib/utils'
import Confirm from './Confirm'
import { errorText } from './errorText'
import LidarrSetup from './LidarrSetup'
import ProviderFields from './ProviderFields'
import ProviderKey from './ProviderKey'
import ProviderTools from './ProviderTools'
/** Why a provider cannot be turned on yet, or nothing when it can. */
function missingSetup(provider: Provider): string | null {
const noKey = provider.needs_api_key && !provider.has_api_key
const noUrl = provider.needs_url && provider.url === ''
if (noKey && noUrl) return 'admin.providers.needBoth'
if (noUrl) return 'admin.providers.needUrl'
if (noKey) return 'admin.providers.needKey'
return null
}
/**
* One provider: what it is sent and the terms, the switch (turning on asks first, off does not), and its settings.
* Providers are off until an admin turns one on, and nothing leaves the server before that.
*/
export default function ProviderCard({ provider }: { provider: Provider }) {
const { t } = useTranslation()
const update = useUpdateProvider()
const [asking, setAsking] = useState(false)
const name = t(`provider.${provider.name}`)
const missing = missingSetup(provider)
const on = provider.enabled
return (
<section aria-label={name} className="flex flex-col gap-4 rounded-lg bg-card p-5 text-card-foreground">
<div className="flex flex-wrap items-center gap-4">
<button
type="button"
role="switch"
aria-checked={on}
aria-label={name}
disabled={(missing !== null && !on) || update.isPending}
onClick={() => (on ? update.mutate({ name: provider.name, enabled: false }) : setAsking(true))}
className={cn(
'relative h-7 w-12 shrink-0 rounded-md border border-input transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring disabled:opacity-50',
on ? 'bg-primary' : 'bg-secondary',
)}
>
<span
aria-hidden="true"
className={cn(
'absolute top-0.5 left-0.5 size-5 rounded-sm transition-transform motion-reduce:transition-none',
on ? 'translate-x-5 bg-primary-foreground' : 'bg-muted-foreground',
)}
/>
</button>
<h3 className="text-xl font-bold">{name}</h3>
<span className="text-sm text-muted-foreground">{t(on ? 'admin.providers.on' : 'admin.providers.off')}</span>
</div>
{missing && !on && <p className="text-sm font-semibold">{t(missing)}</p>}
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, update.error, ['admin.providers.errors', 'admin.errors'], { name })}
</p>
)}
<div className="flex flex-col gap-1 text-sm">
<p>{provider.sends}</p>
<p className="text-muted-foreground">{provider.notes}</p>
</div>
{provider.needs_api_key && <ProviderKey provider={provider} name={name} />}
<ProviderFields provider={provider} name={name} />
{provider.name === 'lidarr' && <LidarrSetup provider={provider} name={name} />}
<ProviderTools provider={provider} name={name} />
{asking && (
<Confirm
title={t('admin.providers.turnOnTitle', { name })}
body={t('admin.providers.turnOnBody', { name, sends: provider.sends })}
confirm={t('admin.providers.turnOn')}
onClose={() => setAsking(false)}
onConfirm={() => {
update.mutate({ name: provider.name, enabled: true })
setAsking(false)
}}
/>
)}
</section>
)
}

View file

@ -0,0 +1,97 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useUpdateProvider, type Provider } from '@/api/adminProviders'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { errorText } from './errorText'
interface Setting {
field: 'contact' | 'url'
stored: string
label: string
saveLabel: string
hint: string
maxLength: number
/** Where the texts for what the server refuses in this field are. */
errors: string
}
/** One text setting of a provider: starts from what is stored, is saved on its own, and may be emptied. */
function TextSetting({ provider, setting }: { provider: Provider; setting: Setting }) {
const { t } = useTranslation()
const update = useUpdateProvider()
const [value, setValue] = useState(setting.stored)
const id = `${setting.field}-${provider.name}`
function submit(event: FormEvent) {
event.preventDefault()
update.mutate({ name: provider.name, [setting.field]: value.trim() })
}
return (
<form onSubmit={submit} className="flex max-w-xl flex-col gap-2">
<Label htmlFor={id}>{setting.label}</Label>
<div className="flex flex-wrap items-center gap-3">
<Input
id={id}
className="min-w-60 flex-1"
value={value}
maxLength={setting.maxLength}
autoCapitalize="off"
spellCheck={false}
onChange={(e) => setValue(e.target.value)}
/>
<Button type="submit" variant="outline" disabled={value.trim() === setting.stored || update.isPending} aria-label={setting.saveLabel}>
{t('admin.providers.save')}
</Button>
</div>
<p className="text-sm text-muted-foreground">{setting.hint}</p>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, update.error, [setting.errors, 'admin.errors'])}
</p>
)}
</form>
)
}
/**
* The contact sent in the User-Agent (every provider but Lidarr) or the address of the admin's own Lidarr.
* `key` remounts the field when the stored value changes, so it always starts from what the server has.
*/
export default function ProviderFields({ provider, name }: { provider: Provider; name: string }) {
const { t } = useTranslation()
if (provider.needs_url) {
return (
<TextSetting
key={provider.url}
provider={provider}
setting={{
field: 'url',
stored: provider.url,
label: t('admin.providers.address'),
saveLabel: t('admin.providers.saveAddressOne', { name }),
hint: t('admin.providers.addressHint', { name }),
maxLength: 300,
errors: 'admin.providers.addressErrors',
}}
/>
)
}
return (
<TextSetting
key={provider.contact}
provider={provider}
setting={{
field: 'contact',
stored: provider.contact,
label: t('admin.providers.contact'),
saveLabel: t('admin.providers.saveContactOne', { name }),
hint: t('admin.providers.contactHint'),
maxLength: 200,
errors: 'admin.providers.contactErrors',
}}
/>
)
}

View file

@ -0,0 +1,79 @@
import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { useUpdateProvider, type Provider } from '@/api/adminProviders'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import Confirm from './Confirm'
import { errorText } from './errorText'
/**
* The API key of a provider. It is write-only: the server never returns it, so the card only says whether
* one is stored; the field is never filled in, is hidden, is not remembered by the browser, and is emptied
* (and the mutation that carried it forgotten) as soon as the key is saved.
*/
export default function ProviderKey({ provider, name }: { provider: Provider; name: string }) {
const { t } = useTranslation()
const save = useUpdateProvider()
const clear = useUpdateProvider()
const [key, setKey] = useState('')
const [removing, setRemoving] = useState(false)
const id = `key-${provider.name}`
function submit(event: FormEvent) {
event.preventDefault()
const typed = key.trim()
if (typed === '') return
save.mutate(
{ name: provider.name, api_key: typed },
{
onSuccess: () => {
setKey('')
save.reset()
},
},
)
}
return (
<div className="flex flex-col gap-2">
<p className="text-sm font-semibold">{provider.has_api_key ? t('admin.providers.keyStored') : t('admin.providers.noKey')}</p>
<form onSubmit={submit} className="flex max-w-xl flex-wrap items-end gap-3">
<div className="flex min-w-60 flex-1 flex-col gap-2">
<Label htmlFor={id}>{t('admin.providers.apiKey')}</Label>
<Input id={id} type="password" autoComplete="off" autoCapitalize="off" spellCheck={false} value={key} onChange={(e) => setKey(e.target.value)} />
</div>
<Button type="submit" variant="outline" disabled={key.trim() === '' || save.isPending} aria-label={t('admin.providers.saveKeyOne', { name })}>
{t('admin.providers.saveKey')}
</Button>
{provider.has_api_key && (
<Button type="button" variant="outline" aria-label={t('admin.providers.removeKeyOne', { name })} onClick={() => setRemoving(true)}>
{t('admin.providers.removeKey')}
</Button>
)}
</form>
{save.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, save.error, ['admin.providers.keyErrors', 'admin.providers.errors', 'admin.errors'], { name })}
</p>
)}
{clear.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, clear.error, ['admin.providers.errors', 'admin.errors'])}
</p>
)}
{removing && (
<Confirm
title={t('admin.providers.removeKeyTitle', { name })}
body={t('admin.providers.removeKeyBody', { name })}
confirm={t('admin.providers.removeKey')}
onClose={() => setRemoving(false)}
onConfirm={() => {
clear.mutate({ name: provider.name, api_key: '' })
setRemoving(false)
}}
/>
)}
</div>
)
}

View file

@ -0,0 +1,78 @@
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { usePurgeProvider, useTestProvider, type Provider, type ProviderPurge } from '@/api/adminProviders'
import { Button } from '@/components/ui/button'
import Confirm from './Confirm'
import { errorText } from './errorText'
const SCOPES = ['admin.providers.toolErrors', 'admin.providers.errors', 'admin.errors']
/** What was removed, in words, leaving out what is zero. */
function purgeSummary(t: ReturnType<typeof useTranslation>['t'], done: ProviderPurge): string {
const parts = [
done.similar_artists > 0 && t('admin.providers.removed.similar', { count: done.similar_artists }),
done.tags > 0 && t('admin.providers.removed.tags', { count: done.tags }),
done.descriptions > 0 && t('admin.providers.removed.descriptions', { count: done.descriptions }),
done.images > 0 && t('admin.providers.removed.images', { count: done.images }),
done.artists > 0 && t('admin.providers.removed.artists', { count: done.artists }),
].filter((part): part is string => typeof part === 'string')
if (parts.length === 0) return t('admin.providers.removed.nothing')
const last = parts[parts.length - 1]
const list = parts.length === 1 ? last : `${parts.slice(0, -1).join(', ')} ${t('admin.providers.removed.and')} ${last}`
return t('admin.providers.removed.done', { list })
}
/** Checking the key, and taking back what the provider gave (Lidarr gave Sonda no data, so it has no such button). */
export default function ProviderTools({ provider, name }: { provider: Provider; name: string }) {
const { t } = useTranslation()
const test = useTestProvider()
const purge = usePurgeProvider()
const [asking, setAsking] = useState(false)
return (
<div className="flex flex-col gap-3">
<div className="flex flex-wrap gap-3">
<Button variant="outline" disabled={test.isPending} aria-label={t('admin.providers.testOne', { name })} onClick={() => test.mutate(provider.name)}>
{t('admin.providers.test')}
</Button>
{provider.name !== 'lidarr' && (
<Button variant="outline" disabled={purge.isPending} aria-label={t('admin.providers.purgeOne', { name })} onClick={() => setAsking(true)}>
{t('admin.providers.purge')}
</Button>
)}
</div>
{test.data && (
<p role="status" className="text-sm font-semibold">
{t(`admin.providers.testStatus.${test.data.status}`, { name })}
</p>
)}
{test.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, test.error, SCOPES)}
</p>
)}
{purge.data && (
<p role="status" className="text-sm font-semibold">
{purgeSummary(t, purge.data)}
</p>
)}
{purge.isError && (
<p role="alert" className="text-sm text-destructive">
{errorText(t, purge.error, SCOPES)}
</p>
)}
{asking && (
<Confirm
title={t('admin.providers.purgeTitle', { name })}
body={t('admin.providers.purgeBody')}
confirm={t('admin.providers.purgeConfirm')}
onClose={() => setAsking(false)}
onConfirm={() => {
purge.mutate(provider.name)
setAsking(false)
}}
/>
)}
</div>
)
}

View file

@ -0,0 +1,52 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import { beforeEach, expect, test, vi } from 'vitest'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { apiError, mockFetch } from '@/test/mockFetch'
import ProvidersPage from './ProvidersPage'
const provider = (name: string) => ({
name,
enabled: false,
needs_api_key: name === 'lastfm' || name === 'lidarr',
needs_url: name === 'lidarr',
has_api_key: false,
contact: '',
url: '',
sends: `What ${name} is sent.`,
notes: `Terms of ${name}.`,
updated_at: null,
})
const ORDER = ['lastfm', 'musicbrainz', 'wikipedia', 'commons', 'coverartarchive', 'lidarr']
function renderPage() {
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
return render(
<QueryClientProvider client={client}>
<ProvidersPage />
</QueryClientProvider>,
)
}
beforeEach(async () => {
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
await initI18n()
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
})
test('it says providers are off until one is turned on, and shows one card for each in the server order', async () => {
mockFetch({ 'GET /api/v1/providers': () => ({ providers: ORDER.map(provider) }) })
renderPage()
expect(await screen.findByText(/Providers are off until you turn one on/)).toBeInTheDocument()
const names = (await screen.findAllByRole('heading', { level: 3 })).map((h) => h.textContent)
expect(names).toEqual(['Last.fm', 'MusicBrainz', 'Wikipedia', 'Wikimedia Commons', 'Cover Art Archive', 'Lidarr'])
})
test('a failure to read them is said in words with a way to try again', async () => {
mockFetch({ 'GET /api/v1/providers': () => apiError(500, 'internal') })
renderPage()
const alert = await screen.findByRole('alert')
expect(within(alert).getByRole('button', { name: 'Try again' })).toBeInTheDocument()
})

View file

@ -0,0 +1,28 @@
import { useTranslation } from 'react-i18next'
import { useProviders } from '@/api/adminProviders'
import Section from '@/components/Section'
import { ErrorMessage, Loading } from '@/components/Status'
import ProviderCard from './ProviderCard'
/** Every external provider, one card each. They are all off until an admin turns one on. */
export default function ProvidersPage() {
const { t } = useTranslation()
const providers = useProviders()
return (
<Section title={t('admin.sectionProviders')}>
<p className="max-w-2xl text-sm text-muted-foreground">{t('admin.providers.intro')}</p>
{providers.isError ? (
<ErrorMessage error={providers.error} onRetry={() => void providers.refetch()} />
) : providers.isPending ? (
<Loading />
) : (
<div className="flex flex-col gap-4">
{providers.data.map((provider) => (
<ProviderCard key={provider.name} provider={provider} />
))}
</div>
)}
</Section>
)
}

View file

@ -8,44 +8,12 @@ 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 Confirm from './Confirm'
import { errorText } from './errorText'
import { passwordLengthOk } from './password'
const SCOPES = ['admin.users.errors', 'admin.errors']
/** A question with two answers, for what cannot be taken back or takes something away. */
function Confirm({
title,
body,
confirm,
onConfirm,
onClose,
}: {
title: string
body: string
confirm: string
onConfirm: () => void
onClose: () => void
}) {
const { t } = useTranslation()
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{body}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{t('admin.cancel')}
</Button>
<Button onClick={onConfirm}>{confirm}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
/**
* Asks for the new password. It lives only inside this dialog: closing it forgets it, and the mutation that
* holds it is reset as soon as it worked.

View file

@ -4,13 +4,14 @@ 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.
* thing for a code (a bad folder) and leave the rest to the shared texts; then the generic ones. `values`
* fill the placeholders of the text (the name of a provider, say).
*/
export function errorText(t: TFunction, error: unknown, scopes: string[] = ['admin.errors']): string {
export function errorText(t: TFunction, error: unknown, scopes: string[] = ['admin.errors'], values: Record<string, string> = {}): 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)
if (i18n.exists(key)) return t(key, values)
}
return t(errorMessageKey(code))
}

View file

@ -8,6 +8,7 @@ import DiscoverPage from '@/pages/DiscoverPage'
import HomePage from '@/pages/HomePage'
import AdminLayout from '@/pages/admin/AdminLayout'
import LibrariesPage from '@/pages/admin/LibrariesPage'
import ProvidersPage from '@/pages/admin/ProvidersPage'
import UsersPage from '@/pages/admin/UsersPage'
import NotFoundPage from '@/pages/NotFoundPage'
import SearchPage from '@/pages/SearchPage'
@ -34,6 +35,7 @@ export const routes: RouteObject[] = [
{ index: true, element: <Navigate to="/admin/libraries" replace /> },
{ path: 'libraries', element: <LibrariesPage /> },
{ path: 'users', element: <UsersPage /> },
{ path: 'providers', element: <ProvidersPage /> },
],
},
{ path: '*', element: <NotFoundPage /> },