diff --git a/README.md b/README.md index a91b558..e3e5a13 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ It is a single executable, one database (SQLite by default, PostgreSQL if you pr ## What is not there yet -Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no admin screens or Lidarr button yet. +Radio queues, OpenSubsonic compatibility, transcoding, and the ListenBrainz integration. The web client exists (see [Web app](#web-app)) but `sondad` does not serve it yet, and it has no admin screens yet. ## Requirements @@ -328,9 +328,9 @@ npm install SONDA_URL=http://127.0.0.1:8080 npm run dev # open http://localhost:5173, /api is proxied to Sonda ``` -What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. +What it does today: sign in (and create the first account of a new server), browse artists, albums and songs, search, and play with a queue, shuffle, repeat, media keys and a full-screen player. Artist pages show the Wikipedia text, similar artists and tags when those providers are on, each with its credit, and the photo credit next to the photo. It reports one listen per play. Discover suggests artists from the ones you pick, or from your listening only after you allow it (a dialog says that their names go to Last.fm), explains each score, and keeps your wishlist and the artists you are not interested in. An admin who set up the `lidarr` provider gets a "Request on Lidarr" button on an artist's page and on the Discover cards: it asks first, then sends that one artist to their own Lidarr, which does the downloading (the web app downloads nothing; the page of an artist reads what Lidarr has, the cards ask nothing until you send). There are six themes (Sonda, Tokyo Night, Gruvbox dark, Gruvbox light, Dracula and Neon) and two languages (English and Italian), both chosen in Settings. -More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The Lidarr button, the admin screens and serving the app from the binary come later. +More commands, all run in `web/`: `npm test`, `npm run build`, and `npm run gen:api`, which rebuilds `src/api/schema.d.ts` from the OpenAPI spec (it fetches the generator with `npx`, so it needs the network once). The admin screens and serving the app from the binary come later. ## Development diff --git a/web/src/api/lidarr.test.tsx b/web/src/api/lidarr.test.tsx new file mode 100644 index 0000000..afde43b --- /dev/null +++ b/web/src/api/lidarr.test.tsx @@ -0,0 +1,83 @@ +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 { useArtistInLidarr, useSendToLidarr } from './lidarr' + +function setup() { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const wrapper = ({ children }: { children: ReactNode }) => {children} + return { client, wrapper } +} + +const ok = (in_lidarr: boolean, monitored = false) => ({ provider_status: 'ok', in_lidarr, monitored }) + +test('what Lidarr has is read from GET /artists/{id}/lidarr', async () => { + mockFetch({ 'GET /api/v1/artists/7/lidarr': () => ok(true, true) }) + const { result } = renderHook(() => useArtistInLidarr(7), { wrapper: setup().wrapper }) + await waitFor(() => expect(result.current.data).toEqual(ok(true, true))) +}) + +test('it asks nothing while it is not enabled', async () => { + const { calls } = mockFetch({ 'GET /api/v1/artists/7/lidarr': () => ok(false) }) + const { result } = renderHook(() => useArtistInLidarr(7, { enabled: false }), { wrapper: setup().wrapper }) + await new Promise((r) => setTimeout(r, 30)) + expect(calls).toHaveLength(0) + expect(result.current.fetchStatus).toBe('idle') +}) + +test('sending is a POST to the artist and nothing else', async () => { + const { calls } = mockFetch({ 'POST /api/v1/artists/7/lidarr': () => ({ status: 'added' }) }) + const { result } = renderHook(() => useSendToLidarr(7), { wrapper: setup().wrapper }) + await act(() => result.current.mutateAsync()) + expect(calls.map((c) => c.key)).toEqual(['POST /api/v1/artists/7/lidarr']) + await waitFor(() => expect(result.current.data).toEqual({ status: 'added' })) +}) + +test('after it was sent, what Lidarr has is read again', async () => { + let has = false + const { calls } = mockFetch({ + 'GET /api/v1/artists/7/lidarr': () => ok(has, has), + 'POST /api/v1/artists/7/lidarr': () => { + has = true + return { status: 'added' } + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ state: useArtistInLidarr(7), send: useSendToLidarr(7) }), { wrapper }) + await waitFor(() => expect(result.current.state.data?.in_lidarr).toBe(false)) + await act(() => result.current.send.mutateAsync()) + await waitFor(() => expect(result.current.state.data?.in_lidarr).toBe(true)) + expect(calls.filter((c) => c.key === 'GET /api/v1/artists/7/lidarr')).toHaveLength(2) +}) + +test('when Lidarr did not answer in time it is read again, because the artist may have been added', async () => { + let has = false + const { calls } = mockFetch({ + 'GET /api/v1/artists/7/lidarr': () => ok(has, has), + 'POST /api/v1/artists/7/lidarr': () => { + has = true + return apiError(502, 'lidarr_unavailable') + }, + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ state: useArtistInLidarr(7), send: useSendToLidarr(7) }), { wrapper }) + await waitFor(() => expect(result.current.state.data?.in_lidarr).toBe(false)) + await act(() => result.current.send.mutateAsync().catch(() => undefined)) + await waitFor(() => expect(result.current.state.data?.in_lidarr).toBe(true)) + expect(calls.filter((c) => c.key === 'GET /api/v1/artists/7/lidarr')).toHaveLength(2) +}) + +test('a refusal does not read Lidarr again: nothing changed', async () => { + const { calls } = mockFetch({ + 'GET /api/v1/artists/7/lidarr': () => ok(false), + 'POST /api/v1/artists/7/lidarr': () => apiError(422, 'lidarr_rejected', 'Artist exists'), + }) + const { wrapper } = setup() + const { result } = renderHook(() => ({ state: useArtistInLidarr(7), send: useSendToLidarr(7) }), { wrapper }) + await waitFor(() => expect(result.current.state.isSuccess).toBe(true)) + await act(() => result.current.send.mutateAsync().catch(() => undefined)) + await new Promise((r) => setTimeout(r, 30)) + expect(calls.filter((c) => c.key === 'GET /api/v1/artists/7/lidarr')).toHaveLength(1) +}) diff --git a/web/src/api/lidarr.ts b/web/src/api/lidarr.ts new file mode 100644 index 0000000..663681d --- /dev/null +++ b/web/src/api/lidarr.ts @@ -0,0 +1,40 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, ApiError } from './client' +import type { components } from './schema' + +export type ArtistInLidarr = components['schemas']['ArtistInLidarr'] +export interface SendResult { + status: 'added' | 'already_added' +} + +const lidarrKey = (artistId: number) => ['artist', artistId, 'lidarr'] + +/** + * Whether the user's own Lidarr has the artist. Whatever stops the answer (provider off, no MusicBrainz id, + * no address or key, Lidarr down) is a `provider_status`, not an error. Admins only: others get a 403. + */ +export function useArtistInLidarr(artistId: number, opts: { enabled?: boolean } = {}) { + return useQuery({ + queryKey: lidarrKey(artistId), + enabled: opts.enabled ?? true, + retry: false, + queryFn: () => api.get(`/artists/${artistId}/lidarr`), + }) +} + +/** + * Sends one artist to Lidarr, which then looks for and downloads the music by itself. It is only ever called + * for one artist, from a click the user confirmed. When it worked, or when Lidarr did not answer in time (the + * artist may have been added all the same), what Lidarr has is read again; a refusal changes nothing. + */ +export function useSendToLidarr(artistId: number) { + const client = useQueryClient() + const reread = () => client.invalidateQueries({ queryKey: lidarrKey(artistId) }) + return useMutation({ + mutationFn: () => api.post(`/artists/${artistId}/lidarr`), + onSuccess: reread, + onError: (error) => { + if (error instanceof ApiError && error.code === 'lidarr_unavailable') return reread() + }, + }) +} 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": { diff --git a/web/src/pages/ArtistPage.tsx b/web/src/pages/ArtistPage.tsx index 278a1d3..d1ef35d 100644 --- a/web/src/pages/ArtistPage.tsx +++ b/web/src/pages/ArtistPage.tsx @@ -5,6 +5,7 @@ import { useAlbumList, useArtist, useTrackList } from '@/api/catalog' import { ApiError } from '@/api/client' import ArtistPhoto from '@/components/ArtistPhoto' import { AlbumCard, CARD_GRID } from '@/components/cards' +import LidarrButton from '@/components/LidarrButton' import LoadMore from '@/components/LoadMore' import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' import TrackList from '@/components/TrackList' @@ -58,6 +59,7 @@ function ArtistView({ id }: { id: number }) { )} + diff --git a/web/src/pages/discover/SuggestionCard.test.tsx b/web/src/pages/discover/SuggestionCard.test.tsx index 45b67af..eed7494 100644 --- a/web/src/pages/discover/SuggestionCard.test.tsx +++ b/web/src/pages/discover/SuggestionCard.test.tsx @@ -61,6 +61,20 @@ test('an artist you have shows its photo', () => { expect(screen.getByRole('img', { name: 'Portishead' })).toBeInTheDocument() }) +test('an admin can request the artist on Lidarr from the card, and the card asks Lidarr nothing before that', async () => { + sessionStore.setState({ user: { id: 1, username: 'tom', is_admin: true } }) + const { calls } = mockFetch({}) + renderCard(make()) + expect(screen.getByRole('button', { name: 'Request on Lidarr' })).toBeInTheDocument() + await new Promise((r) => setTimeout(r, 30)) + expect(calls).toHaveLength(0) +}) + +test('someone who is not an admin has no Lidarr button on the card', () => { + renderCard(make()) + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() +}) + test('an artist with no reason to give says nothing about one', () => { renderCard(make({ because: [] })) expect(screen.queryByText(/Because of/)).not.toBeInTheDocument() diff --git a/web/src/pages/discover/SuggestionCard.tsx b/web/src/pages/discover/SuggestionCard.tsx index b550fba..db6936e 100644 --- a/web/src/pages/discover/SuggestionCard.tsx +++ b/web/src/pages/discover/SuggestionCard.tsx @@ -3,6 +3,7 @@ import { Link } from 'react-router-dom' import { ApiError } from '@/api/client' import { useArtistMarks, type Suggestion } from '@/api/discover' import ArtistPhoto from '@/components/ArtistPhoto' +import LidarrButton from '@/components/LidarrButton' import { Button } from '@/components/ui/button' import { errorMessageKey } from '@/i18n' @@ -57,6 +58,8 @@ export default function SuggestionCard({ suggestion }: { suggestion: Suggestion + +
{t('discover.why')}
    diff --git a/web/src/pages/pages.test.tsx b/web/src/pages/pages.test.tsx index 6f987d2..5db3fb4 100644 --- a/web/src/pages/pages.test.tsx +++ b/web/src/pages/pages.test.tsx @@ -371,6 +371,28 @@ test('an artist a provider named, with nothing to play, still has a page', async expect(await screen.findByText('Nothing of this artist is in your library.')).toBeInTheDocument() }) +test('an admin gets the Lidarr button on the page of an artist they have nothing of', async () => { + sessionStore.setState({ user: { id: 1, username: 'tom', is_admin: true } }) + mockFetch( + artistRoutes({ + 'GET /api/v1/artists/5': () => ({ ...artist, album_count: 0, track_count: 0 }), + 'GET /api/v1/albums': () => page([]), + 'GET /api/v1/tracks': () => page([]), + 'GET /api/v1/artists/5/lidarr': () => ({ provider_status: 'ok', in_lidarr: false, monitored: false }), + }), + ) + renderPage(, '/artists/5', '/artists/:id') + expect(await screen.findByRole('button', { name: 'Request on Lidarr' })).toBeInTheDocument() +}) + +test('anyone else gets no Lidarr button and the page never asks Lidarr', async () => { + const { calls } = mockFetch(artistRoutes()) + renderPage(, '/artists/5', '/artists/:id') + await screen.findByRole('heading', { level: 1, name: 'Radiohead' }) + expect(screen.queryByRole('button', { name: 'Request on Lidarr' })).not.toBeInTheDocument() + expect(calls.map((c) => c.key)).not.toContain('GET /api/v1/artists/5/lidarr') +}) + test('an artist the server does not know says so', async () => { mockFetch(artistRoutes({ 'GET /api/v1/artists/5': () => apiError(404, 'artist_not_found') })) renderPage(, '/artists/5', '/artists/:id')