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)) }