From 369bd2ec3f71106a74af286a40044f608f39aa19 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:11:20 +0100 Subject: [PATCH] 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 && (