From 67205ec2e145decd3d033a4d6da6c22aa6875379 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Thu, 12 Nov 2026 14:29:46 +0100 Subject: [PATCH] feat(web): the Request on Lidarr button, for admins, with a confirmation first Only an admin gets it. It reads what Lidarr has before showing itself (or, on a list card, not at all), asks before sending, sends one artist once, and explains every outcome in words, including a timeout that rereads the state. The API types are regenerated from the spec, which gained the Lidarr endpoints and providers since they were last built. --- web/src/api/schema.d.ts | 308 ++++++++++++++++++++++- web/src/components/LidarrButton.test.tsx | 184 ++++++++++++++ web/src/components/LidarrButton.tsx | 123 +++++++++ web/src/i18n/locales/en.json | 26 ++ web/src/i18n/locales/it.json | 26 ++ 5 files changed, 654 insertions(+), 13 deletions(-) create mode 100644 web/src/components/LidarrButton.test.tsx create mode 100644 web/src/components/LidarrButton.tsx diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index fceae48..28c2aab 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -634,6 +634,11 @@ export interface paths { * is still used, so the list can be empty. With every seed's data stored and fresh the status is `ok` * whether Last.fm is on or not. It is `error` when Last.fm failed for some seed (the * rest is still returned) and `ok` otherwise. Show `attribution` where you show the data. + * + * **How many at once.** One Discover at a time for each listener (a second one answers 429 + * `discover_busy`), and at most three at the same time on the server: a request that finds them + * busy waits for its turn (at most 30 seconds, then it answers 429 as well), and leaves without + * doing any work if the client gives up. A request that waits for its turn counts as running. */ get: operations["discover"]; put?: never; @@ -818,6 +823,46 @@ export interface paths { patch: operations["updateMySettings"]; trace?: never; }; + "/artists/{id}/lidarr": { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + /** + * Whether Lidarr has an artist + * @description Asks your own Lidarr, by the artist's MusicBrainz id and never by name, whether it has the artist and + * whether it monitors it. Like the descriptions, whatever stops the answer is a status and not an error: + * `disabled` when the `lidarr` provider is off (nobody is asked), `no_id` when the artist has no MusicBrainz id, + * `not_configured` when Lidarr has no address or key, `error` when it could not be asked now. Only the id and + * the API key go out, to the address an admin set. + */ + get: operations["getArtistInLidarr"]; + put?: never; + /** + * Send an artist to Lidarr + * @description Admin only. Adds the artist to your own Lidarr, which then looks for and downloads the music by itself: + * Sonda downloads nothing, and does this only when an admin asks, for one artist, never by itself. It works + * for any artist that has a MusicBrainz id, also one that Sonda only learned of from a list of similar + * artists, which is the point: asking for music you do not have. It never looks an id up by name. + * + * It uses what an admin set in `PUT /providers/lidarr`: the quality profile, the metadata profile, the root + * folder, which of the albums to monitor and whether Lidarr starts searching at once. It needs the provider + * switched on and those chosen. An artist that Lidarr already has is not an error (`already_added`, nothing + * changes), so the call can be repeated. If Lidarr does not answer in time, the artist may have been added + * all the same: read it with `GET /artists/{id}/lidarr`. Only the MusicBrainz id and the API key go out, + * to the address an admin set. + */ + post: operations["sendArtistToLidarr"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/artists/{id}/description": { parameters: { query?: never; @@ -1097,7 +1142,7 @@ export interface paths { }; /** * List the external providers - * @description Admin only. Every provider Sonda knows (Last.fm, MusicBrainz), with whether it is on and + * @description Admin only. Every provider Sonda knows (Last.fm, MusicBrainz, Wikipedia, Commons, the Cover Art Archive and Lidarr), with whether it is on and * what it would send. Providers are off by default: nothing leaves the server until an admin * enables one. The API key is never returned; `has_api_key` says whether one is stored. */ @@ -1110,19 +1155,42 @@ export interface paths { patch?: never; trace?: never; }; + "/providers/lidarr/options": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * What Lidarr offers to choose from + * @description Admin only. Reads Lidarr's quality profiles, metadata profiles and root folders, so an admin can pick + * the ones to send artists with (`PUT /providers/lidarr`, field `lidarr`). It works whether Lidarr is + * switched on or not, since it is needed to finish setting it up, and it sends nothing but the API key, + * to the address set for Lidarr, which is your own server. + */ + get: operations["getLidarrOptions"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/providers/{name}": { parameters: { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; get?: never; /** * Set up a provider - * @description Admin only. Send any of `enabled`, `api_key` and `contact`; fields you leave out are kept. + * @description Admin only. Send any of `enabled`, `api_key`, `contact`, `url` and `lidarr`; fields you leave out are kept. * * The key is write-only: it is never returned and never logged. Sending an empty `api_key` * clears it, and turns a provider that needs a key (Last.fm) off; a provider that needs none @@ -1142,7 +1210,7 @@ export interface paths { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -1171,7 +1239,7 @@ export interface paths { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -1434,14 +1502,19 @@ export interface components { }; Provider: { /** @enum {string} */ - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; /** @description Whether Sonda may contact this provider. */ enabled: boolean; needs_api_key: boolean; + /** @description Whether the provider is a server of your own that needs an address (only Lidarr). */ + needs_url: boolean; /** @description Whether a key is stored. The key itself is never returned. */ has_api_key: boolean; /** @description Contact in the User-Agent; empty means the project address. */ contact: string; + /** @description Where your own server is, without a closing slash. Empty for the providers that have none. */ + url: string; + lidarr?: components["schemas"]["LidarrOptions"]; /** @description Plain statement of what is sent to the provider, and what never is. */ sends: string; /** @description Terms of use and attribution that apply to the provider's data. */ @@ -1452,16 +1525,74 @@ export interface components { */ updated_at: string | null; }; + /** + * @description Only for `lidarr`: what is sent to Lidarr when an artist is added, chosen once by an admin from + * `GET /providers/lidarr/options`. Until they are saved, `monitor` is `all`, `search_missing` is + * true and the rest is empty or 0, which is not enough to add an artist. + */ + LidarrOptions: { + /** @description Lidarr's quality profile; 0 when none is chosen. */ + quality_profile_id: number; + /** @description Lidarr's metadata profile; 0 when none is chosen. */ + metadata_profile_id: number; + /** @description One of Lidarr's root folders; empty when none is chosen. */ + root_folder_path: string; + /** + * @description Which of the artist's albums Lidarr monitors when it is added. `none` also stops new albums from being monitored. + * @enum {string} + */ + monitor: "all" | "future" | "missing" | "existing" | "latest" | "first" | "none"; + /** @description Whether Lidarr starts looking for the albums as soon as the artist is added. */ + search_missing: boolean; + }; + LidarrOffers: { + quality_profiles: components["schemas"]["LidarrProfile"][]; + metadata_profiles: components["schemas"]["LidarrProfile"][]; + root_folders: { + path: string; + /** @description Whether Lidarr can use the folder now. */ + accessible: boolean; + }[]; + }; + ArtistInLidarr: { + /** + * @description `ok` when Lidarr was asked (and `in_lidarr` is its answer); the others say why it was not. + * @enum {string} + */ + provider_status: "ok" | "disabled" | "no_id" | "not_configured" | "error"; + in_lidarr: boolean; + /** @description Whether Lidarr monitors the artist; false when it does not have it. */ + monitored: boolean; + }; + LidarrProfile: { + id: number; + name: string; + }; ProviderUpdate: { enabled?: boolean; /** * Format: password - * @description A Last.fm key is 32 hexadecimal characters. Empty clears it. + * @description A Last.fm or Lidarr key is 32 hexadecimal characters. Empty clears it. */ api_key?: string; + /** + * @description Only for Lidarr: where your own server is, `http://` or `https://`, with a port and a path if it + * has them, and without user and password, query or fragment. A closing slash is dropped. Empty + * clears it, and turns Lidarr off. Lidarr cannot be enabled without an address and a key. + */ + url?: string; + /** @description Only for Lidarr. Replaces all its options at once: what is left out is the default (`monitor` all, `search_missing` true, the rest empty or 0). */ + lidarr?: { + quality_profile_id?: number; + metadata_profile_id?: number; + root_folder_path?: string; + /** @enum {string} */ + monitor?: "all" | "future" | "missing" | "existing" | "latest" | "first" | "none"; + search_missing?: boolean; + }; /** @description A URL or e-mail address, without parentheses. Empty restores the default. */ contact?: string; - } | unknown | unknown | unknown; + } | unknown | unknown | unknown | unknown | unknown; ArtistDescription: { /** @enum {string} */ provider: "wikipedia"; @@ -1532,11 +1663,11 @@ export interface components { ProviderTest: { ok: boolean; /** - * @description `no_api_key`: none is stored, so nobody was asked. `key_refused`: the provider does not accept + * @description `no_api_key`: none is stored, so nobody was asked. `no_address`: Lidarr has no address yet, so nobody was asked. `key_refused`: the provider does not accept * it. `rate_limited`: try again later. `unreachable`: the provider did not answer. `error`: anything else. * @enum {string} */ - status: "ok" | "no_api_key" | "key_refused" | "rate_limited" | "unreachable" | "error"; + status: "ok" | "no_api_key" | "no_address" | "key_refused" | "rate_limited" | "unreachable" | "error"; }; ArtistTags: { sources: { @@ -2942,6 +3073,17 @@ export interface operations { }; }; 401: components["responses"]["Unauthorized"]; + /** @description You already have a Discover running or waiting for its turn, or the server was too busy to give it one in 30 seconds (`discover_busy`). Ask again after `Retry-After` seconds. */ + 429: { + headers: { + /** @description Seconds to wait before asking again. */ + "Retry-After"?: number; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; }; }; listDismissed: { @@ -3192,6 +3334,106 @@ export interface operations { 401: components["responses"]["Unauthorized"]; }; }; + getArtistInLidarr: { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Whether Lidarr has the artist. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ArtistInLidarr"]; + }; + }; + 400: components["responses"]["InvalidInput"]; + 401: components["responses"]["Unauthorized"]; + /** @description No such artist (`artist_not_found`). */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; + sendArtistToLidarr: { + parameters: { + query?: never; + header?: never; + path: { + id: components["parameters"]["Id"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The artist is in Lidarr. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** + * @description `added` now, or `already_added` when Lidarr had it. + * @enum {string} + */ + status: "added" | "already_added"; + }; + }; + }; + 400: components["responses"]["InvalidInput"]; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["AdminRequired"]; + /** @description No such artist (`artist_not_found`). */ + 404: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description The provider is switched off (`lidarr_disabled`), or has no address or key, or the profiles and the folder were not chosen (`lidarr_not_configured`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description The artist has no MusicBrainz id (`no_musicbrainz_id`), Lidarr does not know the id (`lidarr_unknown_artist`), or it refused the artist (`lidarr_rejected`, with its reason). */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Lidarr refused the key (`lidarr_key_refused`), or could not be asked or did not answer in time (`lidarr_unavailable`; the artist may have been added). */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; getArtistDescription: { parameters: { query?: never; @@ -3836,12 +4078,52 @@ export interface operations { 403: components["responses"]["AdminRequired"]; }; }; + getLidarrOptions: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description What Lidarr offers. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["LidarrOffers"]; + }; + }; + 401: components["responses"]["Unauthorized"]; + 403: components["responses"]["AdminRequired"]; + /** @description Lidarr has no address or no API key yet (`lidarr_not_configured`). */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + /** @description Lidarr refused the key (`lidarr_key_refused`), or could not be asked or answered something unexpected (`lidarr_unavailable`). */ + 502: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["Error"]; + }; + }; + }; + }; updateProvider: { parameters: { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -3879,7 +4161,7 @@ export interface operations { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; @@ -3913,7 +4195,7 @@ export interface operations { query?: never; header?: never; path: { - name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive"; + name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr"; }; cookie?: never; }; diff --git a/web/src/components/LidarrButton.test.tsx b/web/src/components/LidarrButton.test.tsx new file mode 100644 index 0000000..38416dd --- /dev/null +++ b/web/src/components/LidarrButton.test.tsx @@ -0,0 +1,184 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, expect, test, vi } from 'vitest' +import { sessionStore } from '@/auth/session' +import { initI18n } from '@/i18n' +import { apiError, mockFetch, type MockRoutes, type RecordedCall } from '@/test/mockFetch' +import LidarrButton from './LidarrButton' + +const state = (provider_status: string, in_lidarr = false, monitored = false) => ({ provider_status, in_lidarr, monitored }) +const GET = 'GET /api/v1/artists/7/lidarr' +const POST = 'POST /api/v1/artists/7/lidarr' + +function renderButton(check = true) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + return render( + + + , + ) +} + +const posts = (calls: RecordedCall[]) => calls.filter((c) => c.key === POST) +const gets = (calls: RecordedCall[]) => calls.filter((c) => c.key === GET) +const request = () => screen.findByRole('button', { name: 'Request on Lidarr' }) + +async function confirm() { + await userEvent.click(await request()) + await userEvent.click(await screen.findByRole('button', { name: 'Send to Lidarr' })) +} + +function admin(routes: MockRoutes) { + return mockFetch({ [GET]: () => state('ok'), ...routes }) +} + +beforeEach(async () => { + vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US') + await initI18n() + sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } }) +}) + +test('a user who is not an admin sees nothing and nothing is asked', async () => { + sessionStore.setState({ user: { id: 2, username: 'ann', is_admin: false } }) + const { calls } = admin({}) + const view = renderButton() + await new Promise((r) => setTimeout(r, 50)) + expect(view.container).toBeEmptyDOMElement() + expect(calls).toHaveLength(0) +}) + +test('an admin whose artist is not in Lidarr gets the button', async () => { + admin({}) + renderButton() + expect(await request()).toBeInTheDocument() +}) + +test.each([ + [state('ok', true, true), 'In Lidarr, monitored'], + [state('ok', true, false), 'In Lidarr, not monitored'], +])('an artist Lidarr already has says so and has no button (%j)', async (answer, text) => { + admin({ [GET]: () => answer }) + renderButton() + expect(await screen.findByText(text)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() +}) + +test.each([ + ['disabled', 'Lidarr is off. An admin can turn it on in the server settings.'], + ['not_configured', 'Lidarr has no address or key yet.'], + ['no_id', 'This artist has no MusicBrainz id, so Lidarr cannot be asked.'], +])('when Lidarr cannot be asked (%s) it says why and offers no button', async (status, text) => { + admin({ [GET]: () => state(status) }) + renderButton() + expect(await screen.findByText(text)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() +}) + +test('when Lidarr fails just now it can be asked again', async () => { + let n = 0 + const { calls } = admin({ [GET]: () => (++n === 1 ? state('error') : state('ok')) }) + renderButton() + expect(await screen.findByText('Lidarr could not be asked right now.')).toBeInTheDocument() + await userEvent.click(screen.getByRole('button', { name: 'Check again' })) + expect(await request()).toBeInTheDocument() + expect(gets(calls)).toHaveLength(2) +}) + +test('a click only asks: nothing is sent until the answer is yes', async () => { + const { calls } = admin({ [POST]: () => ({ status: 'added' }) }) + renderButton() + await userEvent.click(await request()) + const dialog = await screen.findByRole('dialog') + expect(dialog).toHaveTextContent('Send Portishead to Lidarr?') + expect(dialog).toHaveTextContent('Lidarr will look for this artist and download its music. Sonda downloads nothing itself.') + expect(posts(calls)).toHaveLength(0) + + await userEvent.click(screen.getByRole('button', { name: 'Cancel' })) + await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument()) + expect(posts(calls)).toHaveLength(0) +}) + +test('yes sends the artist once and the page then shows it is in Lidarr', async () => { + let has = false + const { calls } = admin({ + [GET]: () => (has ? state('ok', true, true) : state('ok')), + [POST]: () => { + has = true + return { status: 'added' } + }, + }) + renderButton() + await confirm() + expect(await screen.findByText('Sent to Lidarr.')).toBeInTheDocument() + expect(await screen.findByText('In Lidarr, monitored')).toBeInTheDocument() + expect(posts(calls)).toHaveLength(1) +}) + +test('an artist Lidarr already had is not an error', async () => { + admin({ [POST]: () => ({ status: 'already_added' }) }) + renderButton() + await confirm() + expect(await screen.findByText('Lidarr already has this artist.')).toBeInTheDocument() + expect(screen.queryByRole('alert')).not.toBeInTheDocument() +}) + +test.each([ + [409, 'lidarr_disabled', 'x', 'Lidarr is off.'], + [409, 'lidarr_not_configured', 'x', 'Lidarr is not set up yet: choose its profiles and root folder in the server settings.'], + [422, 'no_musicbrainz_id', 'x', 'This artist has no MusicBrainz id.'], + [422, 'lidarr_unknown_artist', 'x', 'Lidarr does not know this artist.'], + [422, 'lidarr_rejected', 'Path is not writable', 'Lidarr refused the artist: Path is not writable'], + [502, 'lidarr_key_refused', 'x', 'Lidarr refused the API key.'], + [403, 'admin_required', 'x', 'Only an admin can send artists to Lidarr.'], + [500, 'internal', 'x', 'Something went wrong. Try again.'], +])('a %i %s is explained in words', async (status, code, message, text) => { + admin({ [POST]: () => apiError(status, code, message) }) + renderButton() + await confirm() + expect(await screen.findByRole('alert')).toHaveTextContent(text) + expect(await request()).toBeInTheDocument() +}) + +test('when Lidarr did not answer in time it says the artist may be there, and checks', async () => { + let has = false + const { calls } = admin({ + [GET]: () => (has ? state('ok', true, true) : state('ok')), + [POST]: () => { + has = true + return apiError(502, 'lidarr_unavailable') + }, + }) + renderButton() + await confirm() + expect(await screen.findByText('In Lidarr, monitored')).toBeInTheDocument() + expect(gets(calls).length).toBeGreaterThanOrEqual(2) + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() +}) + +test('without a check (a card in a list) nothing is asked of Lidarr until the artist is sent', async () => { + const { calls } = admin({ [POST]: () => ({ status: 'added' }) }) + renderButton(false) + expect(await request()).toBeInTheDocument() + await new Promise((r) => setTimeout(r, 50)) + expect(gets(calls)).toHaveLength(0) + + await confirm() + expect(await screen.findByText('Sent to Lidarr.')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() + expect(gets(calls)).toHaveLength(0) +}) + +test('a card says so when Lidarr already had the artist', async () => { + admin({ [POST]: () => ({ status: 'already_added' }) }) + renderButton(false) + await confirm() + expect(await screen.findByText('Lidarr already has this artist.')).toBeInTheDocument() +}) + +test('a stale admin whose server says no is told so and gets no button', async () => { + admin({ [GET]: () => apiError(403, 'admin_required') }) + renderButton() + expect(await screen.findByText('Only an admin can send artists to Lidarr.')).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() +}) diff --git a/web/src/components/LidarrButton.tsx b/web/src/components/LidarrButton.tsx new file mode 100644 index 0000000..4a7d843 --- /dev/null +++ b/web/src/components/LidarrButton.tsx @@ -0,0 +1,123 @@ +import { useState } from 'react' +import { useTranslation } from 'react-i18next' +import { ApiError } from '@/api/client' +import { useArtistInLidarr, useSendToLidarr } from '@/api/lidarr' +import { useSession } from '@/auth/session' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { errorMessageKey, i18n } from '@/i18n' + +interface Props { + artist: { id: number; name: string } + /** + * Ask Lidarr what it has before showing the button (the artist page does). Off for a card in a list: twenty + * cards would be twenty questions to Lidarr, so the button is there at once and Lidarr's own answer to + * the send says whether it already had the artist. + */ + check?: boolean +} + +/** Asks Lidarr, by the artist's MusicBrainz id. Only an admin gets it: everyone else sees nothing. */ +export default function LidarrButton({ artist, check = false }: Props) { + const { user } = useSession() + if (!user?.is_admin) return null + return +} + +/** A message for the status of Lidarr that stops the button from being useful. */ +const WHY_NOT: Record = { + disabled: 'lidarr.disabled', + not_configured: 'lidarr.notConfigured', + no_id: 'lidarr.noId', + error: 'lidarr.error', +} + +function LidarrControl({ artist, check }: Required) { + const { t } = useTranslation() + const state = useArtistInLidarr(artist.id, { enabled: check }) + const send = useSendToLidarr(artist.id) + const [asking, setAsking] = useState(false) + + const known = state.data + const inLidarr = known?.provider_status === 'ok' && known.in_lidarr + const sent = send.isSuccess + const askable = !check || (known?.provider_status === 'ok' && !known.in_lidarr) + + function errorText(error: unknown): string { + if (error instanceof ApiError) { + const key = `lidarr.errors.${error.code}` + if (i18n.exists(key)) return t(key, { reason: error.message }) + return t(errorMessageKey(error.code)) + } + return t(errorMessageKey('unknown')) + } + + if (check && state.isPending) return null + if (check && state.isError) { + return ( +
+

+ {errorText(state.error)} +

+
+ ) + } + if (check && known && known.provider_status !== 'ok') { + return ( +
+

{t(WHY_NOT[known.provider_status] ?? 'lidarr.error')}

+ {known.provider_status === 'error' && ( + + )} +
+ ) + } + + return ( +
+ {inLidarr && ( +

{t(known.monitored ? 'lidarr.inLidarrMonitored' : 'lidarr.inLidarrNotMonitored')}

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

+ {t(send.data.status === 'added' ? 'lidarr.sent' : 'lidarr.alreadyThere')} +

+ )} + {send.isError && !inLidarr && ( +

+ {errorText(send.error)} +

+ )} + + {askable && !inLidarr && !sent && ( + + )} + + + + + {t('lidarr.confirmTitle', { name: artist.name })} + {t('lidarr.confirmBody')} + + + + + + + +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index bc7c048..5030f6e 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -59,6 +59,32 @@ "currentPasswordWrong": "The current password is wrong.", "changePassword": "Change password" }, + "lidarr": { + "request": "Request on Lidarr", + "checkAgain": "Check again", + "inLidarrMonitored": "In Lidarr, monitored", + "inLidarrNotMonitored": "In Lidarr, not monitored", + "sent": "Sent to Lidarr.", + "alreadyThere": "Lidarr already has this artist.", + "disabled": "Lidarr is off. An admin can turn it on in the server settings.", + "notConfigured": "Lidarr has no address or key yet.", + "noId": "This artist has no MusicBrainz id, so Lidarr cannot be asked.", + "error": "Lidarr could not be asked right now.", + "confirmTitle": "Send {{name}} to Lidarr?", + "confirmBody": "Lidarr will look for this artist and download its music. Sonda downloads nothing itself. Only the MusicBrainz id and your Lidarr key go to the address you set.", + "cancel": "Cancel", + "send": "Send to Lidarr", + "errors": { + "lidarr_disabled": "Lidarr is off.", + "lidarr_not_configured": "Lidarr is not set up yet: choose its profiles and root folder in the server settings.", + "no_musicbrainz_id": "This artist has no MusicBrainz id.", + "lidarr_unknown_artist": "Lidarr does not know this artist.", + "lidarr_rejected": "Lidarr refused the artist: {{reason}}", + "lidarr_key_refused": "Lidarr refused the API key.", + "lidarr_unavailable": "Lidarr did not answer in time. The artist may have been added: checking now.", + "admin_required": "Only an admin can send artists to Lidarr." + } + }, "discover": { "title": "Discover", "tabs": { diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 7994d96..3f4904c 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -59,6 +59,32 @@ "currentPasswordWrong": "La password attuale è sbagliata.", "changePassword": "Cambia password" }, + "lidarr": { + "request": "Richiedi su Lidarr", + "checkAgain": "Controlla di nuovo", + "inLidarrMonitored": "In Lidarr, monitorato", + "inLidarrNotMonitored": "In Lidarr, non monitorato", + "sent": "Mandato a Lidarr.", + "alreadyThere": "Lidarr ha già questo artista.", + "disabled": "Lidarr è spento. Un admin può accenderlo nelle impostazioni del server.", + "notConfigured": "Lidarr non ha ancora indirizzo o chiave.", + "noId": "Questo artista non ha un id MusicBrainz, quindi non si può chiedere a Lidarr.", + "error": "Ora non si riesce a interrogare Lidarr.", + "confirmTitle": "Mandare {{name}} a Lidarr?", + "confirmBody": "Lidarr cercherà questo artista e ne scaricherà la musica. Sonda non scarica niente da sola. All'indirizzo che hai impostato vanno solo l'id MusicBrainz e la tua chiave di Lidarr.", + "cancel": "Annulla", + "send": "Manda a Lidarr", + "errors": { + "lidarr_disabled": "Lidarr è spento.", + "lidarr_not_configured": "Lidarr non è ancora configurato: scegli profili e cartella radice nelle impostazioni del server.", + "no_musicbrainz_id": "Questo artista non ha un id MusicBrainz.", + "lidarr_unknown_artist": "Lidarr non conosce questo artista.", + "lidarr_rejected": "Lidarr ha rifiutato l'artista: {{reason}}", + "lidarr_key_refused": "Lidarr ha rifiutato la chiave API.", + "lidarr_unavailable": "Lidarr non ha risposto in tempo. L'artista potrebbe essere stato aggiunto: controllo ora.", + "admin_required": "Solo un admin può mandare artisti a Lidarr." + } + }, "discover": { "title": "Discover", "tabs": {