From c3edc564f4fc15412934f63c5af9d5a10a95a9b8 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 15:05:42 +0100 Subject: [PATCH] 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'), + }) +}