From c3edc564f4fc15412934f63c5af9d5a10a95a9b8 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:05:42 +0100 Subject: [PATCH 1/4] feat(web): hooks for the external providers List them, change one (only the fields given are sent), test a key, remove what a provider gave, and read what Lidarr offers only when asked. --- web/src/api/adminProviders.test.tsx | 92 +++++++++++++++++++++++++++++ web/src/api/adminProviders.ts | 68 +++++++++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 web/src/api/adminProviders.test.tsx create mode 100644 web/src/api/adminProviders.ts diff --git a/web/src/api/adminProviders.test.tsx b/web/src/api/adminProviders.test.tsx new file mode 100644 index 0000000..2fabc66 --- /dev/null +++ b/web/src/api/adminProviders.test.tsx @@ -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 }) => {children} + 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' }) +}) diff --git a/web/src/api/adminProviders.ts b/web/src/api/adminProviders.ts new file mode 100644 index 0000000..25fc59b --- /dev/null +++ b/web/src/api/adminProviders.ts @@ -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(`/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(`/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(`/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('/providers/lidarr/options'), + }) +} From 0ddcaff8e16e29aab2986c190fa331325f31ed1d Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:09:54 +0100 Subject: [PATCH 2/4] feat(web): the provider card with the switch, the write-only key, contact, address, test and removing data Turning a provider on asks first and repeats what it will be sent; one that needs a key or an address cannot be turned on without it and the card says why. The key is never shown or filled in, and is gone from the page once saved; removing it says it also turns the provider off. The confirm dialog is now shared with the users section. --- web/src/i18n/locales/en.json | 78 ++++++ web/src/i18n/locales/it.json | 78 ++++++ web/src/pages/admin/Confirm.tsx | 36 +++ web/src/pages/admin/ProviderCard.test.tsx | 314 ++++++++++++++++++++++ web/src/pages/admin/ProviderCard.tsx | 90 +++++++ web/src/pages/admin/ProviderFields.tsx | 97 +++++++ web/src/pages/admin/ProviderKey.tsx | 79 ++++++ web/src/pages/admin/ProviderTools.tsx | 78 ++++++ web/src/pages/admin/UserList.tsx | 34 +-- web/src/pages/admin/errorText.ts | 7 +- 10 files changed, 855 insertions(+), 36 deletions(-) create mode 100644 web/src/pages/admin/Confirm.tsx create mode 100644 web/src/pages/admin/ProviderCard.test.tsx create mode 100644 web/src/pages/admin/ProviderCard.tsx create mode 100644 web/src/pages/admin/ProviderFields.tsx create mode 100644 web/src/pages/admin/ProviderKey.tsx create mode 100644 web/src/pages/admin/ProviderTools.tsx diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index f73850e..991acd2 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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,80 @@ "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." + } + }, "users": { "title": "Users", "empty": "No users.", @@ -265,6 +340,9 @@ "wikipedia": "Wikipedia", "lastfm": "Last.fm", "musicbrainz": "MusicBrainz", + "commons": "Wikimedia Commons", + "coverartarchive": "Cover Art Archive", + "lidarr": "Lidarr", "files": "your files" }, "empty": { diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index c1ead25..dfd9488 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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,80 @@ "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." + } + }, "users": { "title": "Utenti", "empty": "Nessun utente.", @@ -265,6 +340,9 @@ "wikipedia": "Wikipedia", "lastfm": "Last.fm", "musicbrainz": "MusicBrainz", + "commons": "Wikimedia Commons", + "coverartarchive": "Cover Art Archive", + "lidarr": "Lidarr", "files": "i tuoi file" }, "empty": { diff --git a/web/src/pages/admin/Confirm.tsx b/web/src/pages/admin/Confirm.tsx new file mode 100644 index 0000000..8737c4c --- /dev/null +++ b/web/src/pages/admin/Confirm.tsx @@ -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 ( + !open && onClose()}> + + + {title} + {body} + + + + + + + + ) +} diff --git a/web/src/pages/admin/ProviderCard.test.tsx b/web/src/pages/admin/ProviderCard.test.tsx new file mode 100644 index 0000000..8a26cd8 --- /dev/null +++ b/web/src/pages/admin/ProviderCard.test.tsx @@ -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 +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 ? : null +} + +function renderCard(name: string) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + , + ) +} + +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() +}) diff --git a/web/src/pages/admin/ProviderCard.tsx b/web/src/pages/admin/ProviderCard.tsx new file mode 100644 index 0000000..d87dec9 --- /dev/null +++ b/web/src/pages/admin/ProviderCard.tsx @@ -0,0 +1,90 @@ +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 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 ( +
+
+ +

{name}

+ {t(on ? 'admin.providers.on' : 'admin.providers.off')} +
+ + {missing && !on &&

{t(missing)}

} + {update.isError && ( +

+ {errorText(t, update.error, ['admin.providers.errors', 'admin.errors'], { name })} +

+ )} + +
+

{provider.sends}

+

{provider.notes}

+
+ + {provider.needs_api_key && } + + + + {asking && ( + setAsking(false)} + onConfirm={() => { + update.mutate({ name: provider.name, enabled: true }) + setAsking(false) + }} + /> + )} +
+ ) +} diff --git a/web/src/pages/admin/ProviderFields.tsx b/web/src/pages/admin/ProviderFields.tsx new file mode 100644 index 0000000..f9e93e6 --- /dev/null +++ b/web/src/pages/admin/ProviderFields.tsx @@ -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 ( +
+ +
+ setValue(e.target.value)} + /> + +
+

{setting.hint}

+ {update.isError && ( +

+ {errorText(t, update.error, [setting.errors, 'admin.errors'])} +

+ )} +
+ ) +} + +/** + * 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 ( + + ) + } + return ( + + ) +} diff --git a/web/src/pages/admin/ProviderKey.tsx b/web/src/pages/admin/ProviderKey.tsx new file mode 100644 index 0000000..1e0bfd3 --- /dev/null +++ b/web/src/pages/admin/ProviderKey.tsx @@ -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 ( +
+

{provider.has_api_key ? t('admin.providers.keyStored') : t('admin.providers.noKey')}

+
+
+ + setKey(e.target.value)} /> +
+ + {provider.has_api_key && ( + + )} +
+ {save.isError && ( +

+ {errorText(t, save.error, ['admin.providers.keyErrors', 'admin.providers.errors', 'admin.errors'], { name })} +

+ )} + {clear.isError && ( +

+ {errorText(t, clear.error, ['admin.providers.errors', 'admin.errors'])} +

+ )} + {removing && ( + setRemoving(false)} + onConfirm={() => { + clear.mutate({ name: provider.name, api_key: '' }) + setRemoving(false) + }} + /> + )} +
+ ) +} diff --git a/web/src/pages/admin/ProviderTools.tsx b/web/src/pages/admin/ProviderTools.tsx new file mode 100644 index 0000000..32a4c64 --- /dev/null +++ b/web/src/pages/admin/ProviderTools.tsx @@ -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['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 ( +
+
+ + {provider.name !== 'lidarr' && ( + + )} +
+ {test.data && ( +

+ {t(`admin.providers.testStatus.${test.data.status}`, { name })} +

+ )} + {test.isError && ( +

+ {errorText(t, test.error, SCOPES)} +

+ )} + {purge.data && ( +

+ {purgeSummary(t, purge.data)} +

+ )} + {purge.isError && ( +

+ {errorText(t, purge.error, SCOPES)} +

+ )} + {asking && ( + setAsking(false)} + onConfirm={() => { + purge.mutate(provider.name) + setAsking(false) + }} + /> + )} +
+ ) +} diff --git a/web/src/pages/admin/UserList.tsx b/web/src/pages/admin/UserList.tsx index a3479d5..80df971 100644 --- a/web/src/pages/admin/UserList.tsx +++ b/web/src/pages/admin/UserList.tsx @@ -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 ( - !open && onClose()}> - - - {title} - {body} - - - - - - - - ) -} - /** * 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. diff --git a/web/src/pages/admin/errorText.ts b/web/src/pages/admin/errorText.ts index c616c57..1e3914a 100644 --- a/web/src/pages/admin/errorText.ts +++ b/web/src/pages/admin/errorText.ts @@ -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 { 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)) } From 369bd2ec3f71106a74af286a40044f608f39aa19 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:11:20 +0100 Subject: [PATCH 3/4] feat(web): choose what is sent to Lidarr when an artist is added Nothing is asked of Lidarr until the admin loads its choices on purpose, which needs its address and a key. A folder Lidarr cannot use is shown and cannot be picked; saving sends all the options at once. --- web/src/i18n/locales/en.json | 45 +++++ web/src/i18n/locales/it.json | 45 +++++ web/src/pages/admin/LidarrSetup.test.tsx | 199 +++++++++++++++++++++++ web/src/pages/admin/LidarrSetup.tsx | 157 ++++++++++++++++++ web/src/pages/admin/ProviderCard.tsx | 2 + 5 files changed, 448 insertions(+) create mode 100644 web/src/pages/admin/LidarrSetup.test.tsx create mode 100644 web/src/pages/admin/LidarrSetup.tsx diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 991acd2..f395c88 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -146,6 +146,51 @@ }, "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": { diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index dfd9488..589427b 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -146,6 +146,51 @@ }, "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": { diff --git a/web/src/pages/admin/LidarrSetup.test.tsx b/web/src/pages/admin/LidarrSetup.test.tsx new file mode 100644 index 0000000..154e5e8 --- /dev/null +++ b/web/src/pages/admin/LidarrSetup.test.tsx @@ -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 +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 ? : null +} + +function renderCard() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + , + ) +} + +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 ? : null + } + render( + + + , + ) + const c = await screen.findByRole('region', { name: 'MusicBrainz' }) + expect(within(c).queryByRole('button', { name: 'Load choices from Lidarr' })).not.toBeInTheDocument() +}) diff --git a/web/src/pages/admin/LidarrSetup.tsx b/web/src/pages/admin/LidarrSetup.tsx new file mode 100644 index 0000000..51db4b0 --- /dev/null +++ b/web/src/pages/admin/LidarrSetup.tsx @@ -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

{t('admin.providers.lidarr.nothing')}

+ return ( +
+

+ {t('admin.providers.lidarr.chosen', { + quality: options.quality_profile_id, + metadata: options.metadata_profile_id, + folder: options.root_folder_path, + })} +

+

+ {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'), + })} +

+
+ ) +} + +/** 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(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 ( +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ + {update.isError && ( +

+ {errorText(t, update.error, ['admin.providers.lidarrSaveErrors', 'admin.errors'], { name })} +

+ )} + +
+ ) +} + +/** + * 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 ( +
+

{t('admin.providers.lidarr.title')}

+ +

{t('admin.providers.lidarr.needs')}

+
+ + {!ready &&

{t('admin.providers.lidarr.loadNeeds')}

} +
+ {offers.isError && ( +

+ {errorText(t, offers.error, ['admin.providers.lidarrErrors', 'admin.errors'])} +

+ )} + {offers.data && } +
+ ) +} diff --git a/web/src/pages/admin/ProviderCard.tsx b/web/src/pages/admin/ProviderCard.tsx index d87dec9..d0a277f 100644 --- a/web/src/pages/admin/ProviderCard.tsx +++ b/web/src/pages/admin/ProviderCard.tsx @@ -4,6 +4,7 @@ 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' @@ -71,6 +72,7 @@ export default function ProviderCard({ provider }: { provider: Provider }) { {provider.needs_api_key && } + {provider.name === 'lidarr' && } {asking && ( From fed1213030324e89ddc39211e057d02c38c1e8cd Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:12:23 +0100 Subject: [PATCH 4/4] feat(web): a Providers section in the admin area One card for each provider at /admin/providers, for admins only; anyone else gets the notice and the server is not asked. README says what the admin area covers. --- README.md | 6 +-- web/src/components/layout/Shell.test.tsx | 17 +++++++ web/src/pages/admin/AdminLayout.tsx | 1 + web/src/pages/admin/ProvidersPage.test.tsx | 52 ++++++++++++++++++++++ web/src/pages/admin/ProvidersPage.tsx | 28 ++++++++++++ web/src/router.tsx | 2 + 6 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 web/src/pages/admin/ProvidersPage.test.tsx create mode 100644 web/src/pages/admin/ProvidersPage.tsx diff --git a/README.md b/README.md index f13821d..b7292a6 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr ## What is not there yet -Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and 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 diff --git a/web/src/components/layout/Shell.test.tsx b/web/src/components/layout/Shell.test.tsx index 18cfb67..6fe51f3 100644 --- a/web/src/components/layout/Shell.test.tsx +++ b/web/src/components/layout/Shell.test.tsx @@ -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: [] }) }) diff --git a/web/src/pages/admin/AdminLayout.tsx b/web/src/pages/admin/AdminLayout.tsx index fed5036..f37873c 100644 --- a/web/src/pages/admin/AdminLayout.tsx +++ b/web/src/pages/admin/AdminLayout.tsx @@ -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' }, ] /** diff --git a/web/src/pages/admin/ProvidersPage.test.tsx b/web/src/pages/admin/ProvidersPage.test.tsx new file mode 100644 index 0000000..de2caa1 --- /dev/null +++ b/web/src/pages/admin/ProvidersPage.test.tsx @@ -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( + + + , + ) +} + +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() +}) diff --git a/web/src/pages/admin/ProvidersPage.tsx b/web/src/pages/admin/ProvidersPage.tsx new file mode 100644 index 0000000..7cfcfa4 --- /dev/null +++ b/web/src/pages/admin/ProvidersPage.tsx @@ -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 ( +
+

{t('admin.providers.intro')}

+ {providers.isError ? ( + void providers.refetch()} /> + ) : providers.isPending ? ( + + ) : ( +
+ {providers.data.map((provider) => ( + + ))} +
+ )} +
+ ) +} diff --git a/web/src/router.tsx b/web/src/router.tsx index 328d198..efec78a 100644 --- a/web/src/router.tsx +++ b/web/src/router.tsx @@ -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: }, { path: 'libraries', element: }, { path: 'users', element: }, + { path: 'providers', element: }, ], }, { path: '*', element: },