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.
This commit is contained in:
tgiachi 2026-11-12 15:11:20 +01:00
commit 369bd2ec3f
5 changed files with 448 additions and 0 deletions

View file

@ -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": {

View file

@ -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": {

View file

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

View file

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

View file

@ -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 && <ProviderKey provider={provider} name={name} />}
<ProviderFields provider={provider} name={name} />
{provider.name === 'lidarr' && <LidarrSetup provider={provider} name={name} />}
<ProviderTools provider={provider} name={name} />
{asking && (