feat(lidarr): a page of the artists I sent to Lidarr, and whether they arrived

Sonda kept no record of what an admin sent to Lidarr. Each send is now kept
(migration 0033, lidarr_requests), once for each artist, with the first date.
GET /lidarr/requests lists them newest first and says for each whether its
music is in the library: it is noticed when the list is read, by the artist
that was sent or by an artist of the same name that a scan made, and the day
it first was is kept.

The web app has a Requests page for admins, under Discover in the menu and on
Home on a phone, with the waiting and the arrived artists apart.
This commit is contained in:
tgiachi 2026-11-15 12:32:29 +01:00
commit af933ad9ea
13 changed files with 1050 additions and 27 deletions

View file

@ -0,0 +1,20 @@
import { useQuery } from '@tanstack/react-query'
import { api } from '@/api/client'
import type { components } from '@/api/schema'
export type LidarrRequestPage = components['schemas']['LidarrRequestPage']
export type LidarrRequest = LidarrRequestPage['items'][number]
export type RequestStatus = 'waiting' | 'arrived'
/**
* The artists the admin sent to Lidarr, newest first, with how many wait and how many arrived. They are few, so one
* request with the largest page the server gives is enough. Reading the list is also what notices that music arrived,
* so it is read again whenever the page is opened.
*/
export function useLidarrRequests(status?: RequestStatus) {
return useQuery({
queryKey: ['/lidarr/requests', status ?? 'all'],
queryFn: () => api.get<LidarrRequestPage>('/lidarr/requests', { status, limit: 200 }),
staleTime: 0,
})
}

View file

@ -1649,6 +1649,30 @@ export interface paths {
patch?: never;
trace?: never;
};
"/lidarr/requests": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* The artists you sent to Lidarr
* @description Admin only. The artists you sent to your Lidarr with `POST /artists/{id}/lidarr`, newest first, each saying
* whether its music has arrived: `waiting` while there is none in the library, `arrived` once there is (the
* day it was first noticed is `arrived_at`; it is noticed when this list is read, by the artist you sent or by
* an artist of the same name that a scan made). Sending an artist again keeps one request with the first date.
* Only what you sent is listed, never what is in Lidarr. `counts` are of all your requests, whatever `status`.
*/
get: operations["listLidarrRequests"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/artists/{id}/lidarr": {
parameters: {
query?: never;
@ -3339,6 +3363,38 @@ export interface components {
/** @description Whether the event counts as a listen under the current rule. */
counted: boolean;
};
LidarrRequestPage: {
items: {
/** Format: int64 */
id: number;
artist: {
/**
* Format: int64
* @description The artist on this server, null when it is gone.
*/
id: number | null;
name: string;
};
mbid: string | null;
/**
* Format: date-time
* @description The first time it was sent.
*/
requested_at: string;
/** @enum {string} */
status: "waiting" | "arrived";
/** Format: date-time */
arrived_at: string | null;
}[];
/** @description Size of the whole result (of the `status`), not of this page. */
total: number;
limit: number;
offset: number;
counts: {
waiting: number;
arrived: number;
};
};
ListeningSuggestion: {
name: string;
/** @description The artist on this server, null when there is none yet. */
@ -6947,6 +7003,35 @@ export interface operations {
};
};
};
listLidarrRequests: {
parameters: {
query?: {
/** @description Page size. 50 when absent or 0; values above 200 are lowered to 200. */
limit?: components["parameters"]["Limit"];
offset?: components["parameters"]["Offset"];
/** @description Only the requests that are `waiting` or `arrived`. */
status?: "waiting" | "arrived";
};
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description A page of requests. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["LidarrRequestPage"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
403: components["responses"]["AdminRequired"];
};
};
getArtistInLidarr: {
parameters: {
query?: never;

View file

@ -30,7 +30,7 @@ test('the tabs are Home, Search, Library and More, and only on a phone', () => {
expect(nav).toHaveClass('sm:hidden')
})
test.each(['/discover'])('Home is the current tab on %s, which it leads to', (path) => {
test.each(['/discover', '/requests'])('Home is the current tab on %s, which it leads to', (path) => {
const nav = renderTabs(path)
expect(within(nav).getByRole('link', { name: 'Home' })).toHaveAttribute('aria-current', 'page')
expect(within(nav).getByRole('link', { name: 'Library' })).not.toHaveAttribute('aria-current')

View file

@ -3,8 +3,8 @@ import { Link, useLocation } from 'react-router-dom'
import { useFriends } from '@/api/friends'
import { cn } from '@/lib/utils'
/** The pages the Home tab leads to (Home itself ends the list of them with a link to Discover). */
const HOME = ['/discover']
/** The pages the Home tab leads to (Home itself ends the list of them with links to Discover and, for an admin, Requests). */
const HOME = ['/discover', '/requests']
/** The pages the Library tab leads to: it is the current tab on all of them. */
const LIBRARY = ['/library', '/artists', '/albums', '/songs', '/playlists', '/smart-playlists', '/mixes', '/history', '/import']
const MORE = ['/more', '/settings', '/admin']

View file

@ -91,7 +91,7 @@ test('the links are in groups, in the order of what you do: find, the library, y
const nav = renderSidebar([{ id: 3, name: 'Anna' }])
await within(nav).findByRole('link', { name: 'Friends' })
expect(names(nav)).toEqual([
'Home', 'Search', 'Discover',
'Home', 'Search', 'Discover', 'Requests',
'Artists', 'Albums', 'Songs', 'Playlists', 'Smart playlists', 'Mixes',
'History', 'Import',
'Friends',
@ -126,3 +126,12 @@ test('a page inside a section lights the section: an artist, a new smart playlis
expect(within(nav).getAllByRole('link').filter((a) => a.getAttribute('aria-current') === 'page')).toHaveLength(1)
}
})
test('Requests, the artists sent to Lidarr, is a link of admins only', () => {
const admin = renderSidebar()
expect(within(admin).getByRole('link', { name: 'Requests' })).toHaveAttribute('href', '/requests')
document.body.innerHTML = ''
sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } })
const user = renderSidebar()
expect(within(user).queryByRole('link', { name: 'Requests' })).not.toBeInTheDocument()
})

View file

@ -29,6 +29,7 @@ const GROUPS: Group[] = [
{ to: '/', key: 'nav.home', end: true },
{ to: '/search', key: 'nav.search' },
{ to: '/discover', key: 'nav.discover' },
{ to: '/requests', key: 'nav.requests', adminOnly: true },
],
},
{

View file

@ -19,6 +19,7 @@
"friends": "Friends",
"admin": "Admin",
"settings": "Settings",
"requests": "Requests",
"listening": "Your listening",
"history": "History",
"import": "Import",
@ -842,6 +843,19 @@
"missing": "Artists you play on Spotify and have no music of here",
"missingMore": "and {{count}} more"
},
"requests": {
"intro": "The artists you sent to Lidarr from Sonda. Lidarr looks for the music and downloads it in its own time; an artist is waiting until its music is in your library.",
"filter": "Show",
"filterAll_one": "All ({{count}})",
"filterAll_other": "All ({{count}})",
"filterWaiting": "Waiting ({{count}})",
"filterArrived": "Arrived ({{count}})",
"sent": "Sent {{when}}",
"waiting": "Waiting for the music",
"arrived": "Music in your library since {{when}}",
"none": "You have not sent any artist to Lidarr yet. Do it from the page of an artist you do not have.",
"noneFiltered": "No artist here."
},
"history": {
"years": "Years",
"months": "Months of {{year}}",

View file

@ -19,6 +19,7 @@
"friends": "Amici",
"admin": "Admin",
"settings": "Impostazioni",
"requests": "Richieste",
"listening": "I tuoi ascolti",
"history": "Cronologia",
"import": "Importa",
@ -842,6 +843,19 @@
"missing": "Artisti che ascolti su Spotify e di cui qui non hai musica",
"missingMore": "e altri {{count}}"
},
"requests": {
"intro": "Gli artisti che hai inviato a Lidarr da Sonda. Lidarr cerca la musica e la scarica coi suoi tempi: un artista resta in attesa finché la sua musica non è nella tua libreria.",
"filter": "Mostra",
"filterAll_one": "Tutti ({{count}})",
"filterAll_other": "Tutti ({{count}})",
"filterWaiting": "In attesa ({{count}})",
"filterArrived": "Arrivati ({{count}})",
"sent": "Inviato il {{when}}",
"waiting": "In attesa della musica",
"arrived": "Musica in libreria dal {{when}}",
"none": "Non hai ancora inviato nessun artista a Lidarr. Fallo dalla pagina di un artista che non hai.",
"noneFiltered": "Nessun artista qui."
},
"history": {
"years": "Anni",
"months": "Mesi del {{year}}",

View file

@ -177,3 +177,15 @@ test('Home ends with a way to Discover, which has no tab on a phone and is hidde
expect(link).toHaveAttribute('href', '/discover')
expect(link.closest('div.sm\\:hidden')).not.toBeNull()
})
test('an admin also has a way to the Requests, a person who is not does not', async () => {
mockFetch(routes())
renderHome()
await screen.findByRole('link', { name: 'Discover' })
expect(screen.queryByRole('link', { name: 'Requests' })).not.toBeInTheDocument()
document.body.innerHTML = ''
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: true } })
mockFetch(routes())
renderHome()
expect(await screen.findByRole('link', { name: 'Requests' })).toHaveAttribute('href', '/requests')
})

View file

@ -5,6 +5,7 @@ import { Link } from 'react-router-dom'
import { useAlbumList, useArtistList, type Track } from '@/api/catalog'
import { api, ApiError } from '@/api/client'
import { useRecentListens } from '@/api/listens'
import { useSession } from '@/auth/session'
import { AlbumCard, ArtistCard, CARD_GRID } from '@/components/cards'
import LinkRows from '@/components/LinkRows'
import Section from '@/components/Section'
@ -25,6 +26,7 @@ function greetingKey(hour: number): string {
export default function HomePage() {
const { t } = useTranslation()
const { user } = useSession()
const queryClient = useQueryClient()
const playTracks = usePlayer((s) => s.playTracks)
const history = useRecentListens()
@ -138,7 +140,7 @@ export default function HomePage() {
{/* On a phone Discover has no tab of its own: this is the way to it. */}
<div className="sm:hidden">
<LinkRows links={[{ to: '/discover', label: t('nav.discover') }]} />
<LinkRows links={[{ to: '/discover', label: t('nav.discover') }, ...(user?.is_admin ? [{ to: '/requests', label: t('nav.requests') }] : [])]} />
</div>
</div>
)

View file

@ -0,0 +1,99 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, useLocation } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
import RequestsPage from './RequestsPage'
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 } })
})
const request = (id: number, name: string, status: 'waiting' | 'arrived', artistId: number | null = id) => ({
id,
artist: { id: artistId, name },
mbid: null,
requested_at: '2026-11-10T10:00:00Z',
status,
arrived_at: status === 'arrived' ? '2026-11-14T10:00:00Z' : null,
})
const all = [request(3, 'Sade', 'waiting'), request(2, 'Chet Baker', 'arrived'), request(1, 'Ghost', 'waiting', null)]
const page = (items: object[]) => ({ items, total: items.length, limit: 200, offset: 0, counts: { waiting: 2, arrived: 1 } })
function Where() {
const l = useLocation()
return <p data-testid="where">{l.pathname + l.search}</p>
}
function setup(routes: MockRoutes = {}, at = '/requests') {
const mocked = mockFetch({ 'GET /api/v1/lidarr/requests': () => page(all), ...routes })
render(
<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>
<MemoryRouter initialEntries={[at]}>
<RequestsPage />
<Where />
</MemoryRouter>
</QueryClientProvider>,
)
return mocked
}
test('it lists the artists sent to Lidarr and says which have arrived', async () => {
setup()
expect(screen.getByRole('heading', { level: 1, name: 'Requests' })).toBeInTheDocument()
expect(await screen.findByRole('link', { name: 'Sade' })).toHaveAttribute('href', '/artists/3')
const items = screen.getAllByRole('listitem')
expect(items).toHaveLength(3)
expect(within(items[0]).getByText('Waiting for the music')).toBeInTheDocument()
expect(within(items[0]).getByText('Sent Nov 10, 2026')).toBeInTheDocument()
expect(within(items[1]).getByText('Music in your library since Nov 14, 2026')).toBeInTheDocument()
// An artist the server no longer knows is a name, not a link.
expect(screen.getByText('Ghost')).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Ghost' })).not.toBeInTheDocument()
})
test('the buttons count the requests of each kind and filter the list through the address', async () => {
const { calls } = setup({
'GET /api/v1/lidarr/requests': ({ url }) => (url.searchParams.get('status') === 'arrived' ? page([all[1]]) : page(all)),
})
const group = await screen.findByRole('group', { name: 'Show' })
expect(await within(group).findByRole('button', { name: 'All (3)' })).toHaveAttribute('aria-pressed', 'true')
expect(within(group).getByRole('button', { name: 'Waiting (2)' })).toBeInTheDocument()
await userEvent.click(within(group).getByRole('button', { name: 'Arrived (1)' }))
expect(screen.getByTestId('where')).toHaveTextContent('/requests?status=arrived')
await screen.findByText('Music in your library since Nov 14, 2026')
expect(screen.queryByRole('link', { name: 'Sade' })).not.toBeInTheDocument()
expect(calls.some((c) => c.url.searchParams.get('status') === 'arrived')).toBe(true)
})
test('the address can name the filter, and a bad one is ignored', async () => {
setup({}, '/requests?status=bogus')
expect(await screen.findByRole('button', { name: /^All/ })).toHaveAttribute('aria-pressed', 'true')
})
test('with nothing sent it says how to send an artist', async () => {
setup({ 'GET /api/v1/lidarr/requests': () => ({ items: [], total: 0, limit: 200, offset: 0, counts: { waiting: 0, arrived: 0 } }) })
expect(await screen.findByText(/You have not sent any artist to Lidarr yet/)).toBeInTheDocument()
})
test('a list that cannot be read has a way to try again', async () => {
let fail = true
setup({ 'GET /api/v1/lidarr/requests': () => (fail ? apiError(500, 'internal', 'x') : page(all)) })
const retry = (await screen.findAllByRole('button', { name: 'Try again' }))[0]
fail = false
await userEvent.click(retry)
expect(await screen.findByRole('link', { name: 'Sade' })).toBeInTheDocument()
})
test('someone who is not an admin is told, and nothing is asked', () => {
sessionStore.setState({ status: 'authenticated', user: { id: 2, email: 'ann@example.org', is_admin: false } })
const { calls } = setup()
expect(screen.getByText('Only admins can see this page.')).toBeInTheDocument()
expect(calls).toHaveLength(0)
})

View file

@ -0,0 +1,96 @@
import { useTranslation } from 'react-i18next'
import { Link, useSearchParams } from 'react-router-dom'
import { useLidarrRequests, type LidarrRequest, type RequestStatus } from '@/api/lidarrRequests'
import { useSession } from '@/auth/session'
import PageTitle from '@/components/PageTitle'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
const FILTERS: (RequestStatus | undefined)[] = [undefined, 'waiting', 'arrived']
function Row({ request }: { request: LidarrRequest }) {
const { t, i18n } = useTranslation()
const day = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium' })
const arrived = request.status === 'arrived'
return (
<li className="flex flex-wrap items-baseline gap-x-4 gap-y-1 border-b border-border py-4">
<div className="flex min-w-40 flex-1 flex-col">
{request.artist.id !== null ? (
<Link to={`/artists/${request.artist.id}`} className="text-lg font-bold break-words hover:underline">
{request.artist.name}
</Link>
) : (
<span className="text-lg font-bold break-words">{request.artist.name}</span>
)}
<span className="text-sm text-muted-foreground">{t('requests.sent', { when: day.format(new Date(request.requested_at)) })}</span>
</div>
<span className={cn('flex items-center gap-2 text-sm font-semibold', arrived ? 'text-foreground' : 'text-muted-foreground')}>
<span aria-hidden="true" className={cn('size-2 rounded-full', arrived ? 'bg-primary' : 'border border-muted-foreground')} />
{arrived ? t('requests.arrived', { when: day.format(new Date(request.arrived_at ?? request.requested_at)) }) : t('requests.waiting')}
</span>
</li>
)
}
/**
* The artists the admin sent to Lidarr from Sonda, and whether their music is in the library yet. An artist is
* waiting until a scan finds music of it; Lidarr downloads in its own time.
*/
export default function RequestsPage() {
const { t } = useTranslation()
const { user } = useSession()
const [params, setParams] = useSearchParams()
const status = FILTERS.find((f) => f !== undefined && f === params.get('status'))
const requests = useLidarrRequests(status)
const all = useLidarrRequests()
if (!user?.is_admin) {
return (
<div className="flex flex-col gap-6">
<PageTitle>{t('nav.requests')}</PageTitle>
<p>{t('admin.adminOnly')}</p>
</div>
)
}
const counts = all.data?.counts
const label = (f: RequestStatus | undefined) =>
f === undefined
? t('requests.filterAll', { count: (counts?.waiting ?? 0) + (counts?.arrived ?? 0) })
: t(f === 'waiting' ? 'requests.filterWaiting' : 'requests.filterArrived', { count: counts?.[f] ?? 0 })
return (
<div className="flex flex-col gap-6">
<PageTitle>{t('nav.requests')}</PageTitle>
<p className="max-w-xl text-muted-foreground">{t('requests.intro')}</p>
<div role="group" aria-label={t('requests.filter')} className="flex flex-wrap gap-2">
{FILTERS.map((f) => (
<Button
key={f ?? 'all'}
variant={f === status ? 'default' : 'outline'}
aria-pressed={f === status}
onClick={() => setParams(f ? { status: f } : {})}
>
{label(f)}
</Button>
))}
</div>
{requests.isError ? (
<ErrorMessage error={requests.error} onRetry={() => void requests.refetch()} />
) : requests.isPending ? (
<Loading />
) : requests.data.items.length === 0 ? (
<EmptyMessage>{t(status ? 'requests.noneFiltered' : 'requests.none')}</EmptyMessage>
) : (
<ul className="max-w-2xl">
{requests.data.items.map((r) => (
<Row key={r.id} request={r} />
))}
</ul>
)}
</div>
)
}

View file

@ -34,6 +34,7 @@ export const routes: RouteObject[] = [
{ path: '/smart-playlists/suggested/:key', lazy: page(() => import('@/pages/SuggestedSmartPage')) },
{ path: '/smart-playlists/:id', lazy: page(() => import('@/pages/SmartPlaylistPage')) },
{ path: '/smart-playlists/:id/edit', lazy: page(() => import('@/pages/SmartEditorPage')) },
{ path: '/requests', lazy: page(() => import('@/pages/RequestsPage')) },
{ path: '/history', lazy: page(() => import('@/pages/HistoryPage')) },
{ path: '/import', lazy: page(() => import('@/pages/ImportPage')) },
{ path: '/settings', lazy: page(() => import('@/pages/SettingsPage')) },