feat: Minstrel stops acquiring music and drops Discover
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s
Minstrel is now a viewer of the library it is pointed at. Finding, downloading and filing music moves out of it. Removed from the server: - the request flow (requests, approval, auto-approve) and the wanted list, follows, release profiles and release blocks; - searching indexers, the download clients, the importer, the album lifecycle and missing-file re-acquisition; - the catalogue's discography, search and art (the MusicBrainz release and track-list cache stays, for the duplicate resolver); - Discover: its suggestions of artists not in the library, snoozes, the candidate-artist tag enrichment and its tuning scope; - writes to acquisition tables from moving the library folder and from merging duplicates, the want-list join on Suspect sources, the sealing of acquisition credentials, and the release-group lookup only re-acquisition used. Settling a wrong-slot duplicate no longer sets the release aside: the copies go and their slots show as missing until a good copy is in the library. Removed from the web: Admin > Acquisition and Requests, /requests, /discover, Follow on the artist page, the auto-approve toggle, and the Collection's wanted-list tabs. The Collection is now the library's health: an overview, Reports, Duplicates, Suspect sources and Missing files. The README and docs no longer describe getting music. The tables stay for now; a later migration drops them. The request notification kinds and the Android screens are still to go. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,22 +3,21 @@ import type { AdminQueue, AdminSummary } from '#lib/api/types.js';
|
||||
|
||||
// The queues that wait on an admin, in the order the Overview lists
|
||||
// them. The rails and the Overview read the same list, so a queue that
|
||||
// needs you is counted the same in every place. Requests live under Admin;
|
||||
// the library's health queues, Missing files among them, under Collection.
|
||||
// needs you is counted the same in every place. Every one of them is a
|
||||
// library health queue, worked under Collection.
|
||||
export type QueueKey = keyof AdminSummary;
|
||||
|
||||
export type QueueDef = {
|
||||
key: QueueKey;
|
||||
href: string;
|
||||
// How the Overview names a count of them: "2 requests to decide".
|
||||
// How the Overview names a count of them: "2 missing files".
|
||||
one: string;
|
||||
many: string;
|
||||
// How the Overview's healthy line names an empty one: "no requests".
|
||||
// How the Overview's healthy line names an empty one: "no missing files".
|
||||
none: string;
|
||||
};
|
||||
|
||||
export const QUEUES: QueueDef[] = [
|
||||
{ key: 'requests', href: '/admin/requests', one: 'request to decide', many: 'requests to decide', none: 'requests' },
|
||||
{ key: 'reports', href: '/collection/reports', one: 'broken track reported', many: 'broken tracks reported', none: 'reports' },
|
||||
{ key: 'duplicates', href: '/collection/duplicates', one: 'set of duplicates to review', many: 'sets of duplicates to review', none: 'duplicates' },
|
||||
{ key: 'suspect', href: '/collection/suspect-sources', one: 'track from a suspect source', many: 'tracks from suspect sources', none: 'suspect sources' },
|
||||
|
||||
@@ -17,8 +17,6 @@ function track(id: string): AdminSuspectTrack {
|
||||
markers: [],
|
||||
verdict: null,
|
||||
verdict_at: null,
|
||||
replacing: false,
|
||||
searched_at: null
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,6 @@ vi.mock('./client', () => ({
|
||||
}));
|
||||
|
||||
import {
|
||||
listAdminRequests,
|
||||
approveRequest,
|
||||
rejectRequest,
|
||||
listAdminQuarantine,
|
||||
resolveQuarantine,
|
||||
deleteQuarantineFile,
|
||||
@@ -23,111 +20,13 @@ import { qk } from './queries';
|
||||
import type {
|
||||
ActionResult,
|
||||
AdminQuarantineRow,
|
||||
QuarantineActionRow,
|
||||
MusicRequest
|
||||
QuarantineActionRow
|
||||
} from './types';
|
||||
|
||||
const baseRow: MusicRequest = {
|
||||
id: 'r1',
|
||||
user_id: 'u1',
|
||||
status: 'pending',
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'alb-mbid',
|
||||
track_mbid: null,
|
||||
artist_name: 'Aphex Twin',
|
||||
album_title: 'Drukqs',
|
||||
track_title: null,
|
||||
decided_at: null,
|
||||
decided_by: null,
|
||||
notes: null,
|
||||
completed_at: null,
|
||||
matched_track_id: null,
|
||||
matched_album_id: null,
|
||||
matched_artist_id: null,
|
||||
requested_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
imported_album_count: 0,
|
||||
imported_track_count: 0
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('listAdminRequests', () => {
|
||||
test('no args -> /api/admin/requests with no query string', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([baseRow]);
|
||||
await listAdminRequests();
|
||||
expect(api.get).toHaveBeenCalledWith('/api/admin/requests');
|
||||
});
|
||||
|
||||
test('status only -> ?status=', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([baseRow]);
|
||||
await listAdminRequests('approved');
|
||||
expect(api.get).toHaveBeenCalledWith('/api/admin/requests?status=approved');
|
||||
});
|
||||
|
||||
test('status + limit -> ?status=&limit=', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([baseRow]);
|
||||
await listAdminRequests('pending', 25);
|
||||
expect(api.get).toHaveBeenCalledWith(
|
||||
'/api/admin/requests?status=pending&limit=25'
|
||||
);
|
||||
});
|
||||
|
||||
test('limit only -> ?limit=', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([baseRow]);
|
||||
await listAdminRequests(undefined, 10);
|
||||
expect(api.get).toHaveBeenCalledWith('/api/admin/requests?limit=10');
|
||||
});
|
||||
});
|
||||
|
||||
describe('approveRequest', () => {
|
||||
test('POSTs to /api/admin/requests/:id/approve with empty body by default', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await approveRequest('r1');
|
||||
expect(api.post).toHaveBeenCalledWith('/api/admin/requests/r1/approve', {});
|
||||
});
|
||||
|
||||
test('sends the chosen release-type profile', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await approveRequest('r1', 'p1');
|
||||
expect(api.post).toHaveBeenCalledWith('/api/admin/requests/r1/approve', { profile_id: 'p1' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('rejectRequest', () => {
|
||||
test('POSTs to /api/admin/requests/:id/reject with empty body when no notes', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await rejectRequest('r1');
|
||||
expect(api.post).toHaveBeenCalledWith('/api/admin/requests/r1/reject', {});
|
||||
});
|
||||
|
||||
test('includes notes when provided', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await rejectRequest('r1', 'duplicate of r0');
|
||||
expect(api.post).toHaveBeenCalledWith('/api/admin/requests/r1/reject', {
|
||||
notes: 'duplicate of r0'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('qk admin keys', () => {
|
||||
test('adminRequests key uses "all" when status omitted', () => {
|
||||
// listAdminRequests sends no status param when called without one (returns
|
||||
// every status), so the cache key must distinguish that from any specific
|
||||
// status — otherwise an unfiltered call would falsely cache as `pending`.
|
||||
expect(qk.adminRequests()).toEqual(['adminRequests', { status: 'all' }]);
|
||||
});
|
||||
test('adminRequests key includes the status filter', () => {
|
||||
expect(qk.adminRequests('approved')).toEqual([
|
||||
'adminRequests',
|
||||
{ status: 'approved' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const baseQuarantineRow: AdminQuarantineRow = {
|
||||
track_id: 't1',
|
||||
track_title: 'Avril 14th',
|
||||
|
||||
+1
-162
@@ -16,8 +16,6 @@ import type {
|
||||
AdminStatus,
|
||||
AdminSummary,
|
||||
QuarantineActionRow,
|
||||
MusicRequest,
|
||||
RequestStatus,
|
||||
PlaybackErrorResolution
|
||||
} from './types';
|
||||
|
||||
@@ -38,7 +36,7 @@ export function createAdminSummaryQuery() {
|
||||
});
|
||||
}
|
||||
|
||||
// Admin status: who is listening, downloads, the library and disk,
|
||||
// Admin status: who is listening, the library and disk,
|
||||
// and the server, for the Overview below its verdict. Polled while open.
|
||||
|
||||
export async function getAdminStatus(): Promise<AdminStatus> {
|
||||
@@ -53,59 +51,6 @@ export function createAdminStatusQuery() {
|
||||
});
|
||||
}
|
||||
|
||||
// Admin request queue -----------------------------------------------------
|
||||
|
||||
export async function listAdminRequests(
|
||||
status?: RequestStatus,
|
||||
limit?: number
|
||||
): Promise<MusicRequest[]> {
|
||||
const params = new URLSearchParams();
|
||||
if (status) params.set('status', status);
|
||||
if (limit !== undefined) params.set('limit', String(limit));
|
||||
const qs = params.toString();
|
||||
return api.get<MusicRequest[]>(
|
||||
qs ? `/api/admin/requests?${qs}` : '/api/admin/requests'
|
||||
);
|
||||
}
|
||||
|
||||
// Approving puts the request on the wanted list. An artist
|
||||
// request is followed on profileId, or the default profile when omitted.
|
||||
export async function approveRequest(id: string, profileId?: string): Promise<MusicRequest> {
|
||||
return api.post<MusicRequest>(
|
||||
`/api/admin/requests/${id}/approve`,
|
||||
profileId ? { profile_id: profileId } : {}
|
||||
);
|
||||
}
|
||||
|
||||
export async function rejectRequest(
|
||||
id: string,
|
||||
notes?: string
|
||||
): Promise<MusicRequest> {
|
||||
const body = notes !== undefined ? { notes } : {};
|
||||
return api.post<MusicRequest>(`/api/admin/requests/${id}/reject`, body);
|
||||
}
|
||||
|
||||
// Query factories ---------------------------------------------------------
|
||||
|
||||
export function createAdminRequestsQuery(status?: RequestStatus) {
|
||||
return createQuery({
|
||||
queryKey: qk.adminRequests(status),
|
||||
queryFn: () => listAdminRequests(status),
|
||||
// Only the 'approved' tab needs polling — that's where in-flight
|
||||
// ingests live. Other tabs (pending/rejected/completed) are static
|
||||
// until an admin acts on them.
|
||||
refetchInterval: (query) => {
|
||||
if (status !== 'approved') return false;
|
||||
const rows = query.state.data as MusicRequest[] | undefined;
|
||||
return hasInFlightRequest(rows) ? 12_000 : false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hasInFlightRequest(rows: readonly MusicRequest[] | undefined): boolean {
|
||||
return rows?.some((r) => r.status === 'approved') ?? false;
|
||||
}
|
||||
|
||||
// Admin quarantine --------------------------------------------------------
|
||||
|
||||
export async function listAdminQuarantine(): Promise<AdminQuarantineRow[]> {
|
||||
@@ -594,7 +539,6 @@ export type AdminUser = {
|
||||
username: string;
|
||||
display_name: string | null;
|
||||
is_admin: boolean;
|
||||
auto_approve_requests: boolean;
|
||||
debug_mode_enabled: boolean;
|
||||
created_at: string;
|
||||
};
|
||||
@@ -652,10 +596,6 @@ export async function resetUserPassword(id: string, password: string): Promise<v
|
||||
await api.post(`/api/admin/users/${id}/reset-password`, { password });
|
||||
}
|
||||
|
||||
export async function updateUserAutoApprove(id: string, autoApprove: boolean): Promise<AdminUser> {
|
||||
return api.put<AdminUser>(`/api/admin/users/${id}/auto-approve`, { auto_approve: autoApprove });
|
||||
}
|
||||
|
||||
// Flip an account's diagnostics/debug-reporting opt-in. Admin-set;
|
||||
// the client obeys it (with a local per-device OFF switch).
|
||||
export async function updateUserDebugMode(id: string, enabled: boolean): Promise<AdminUser> {
|
||||
@@ -970,28 +910,6 @@ export async function setSuspectVerdict(trackId: string, verdict: SuspectVerdict
|
||||
await api.put(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}`, { verdict });
|
||||
}
|
||||
|
||||
// Missing-file re-acquisition ----------------------
|
||||
|
||||
export type ReacquisitionSettings = {
|
||||
enabled: boolean;
|
||||
grace_hours: number;
|
||||
max_per_pass: number;
|
||||
// Albums with missing files that can never be wanted automatically because
|
||||
// neither they nor their artist carries an MBID. Read-only; the server
|
||||
// computes it, and the card states it so the gap isn't a mystery.
|
||||
unnameable_albums: number;
|
||||
};
|
||||
|
||||
export async function getReacquisitionSettings(): Promise<ReacquisitionSettings> {
|
||||
return api.get<ReacquisitionSettings>('/api/admin/library/reacquisition');
|
||||
}
|
||||
|
||||
export async function updateReacquisitionSettings(
|
||||
s: ReacquisitionSettings
|
||||
): Promise<ReacquisitionSettings> {
|
||||
return api.put<ReacquisitionSettings>('/api/admin/library/reacquisition', s);
|
||||
}
|
||||
|
||||
// Notification emails: when the grouped emails go out.
|
||||
export type NotificationEmailSettings = {
|
||||
summary_hour: number;
|
||||
@@ -1008,85 +926,6 @@ export async function updateNotificationEmailSettings(
|
||||
return api.put<NotificationEmailSettings>('/api/admin/notification-email', s);
|
||||
}
|
||||
|
||||
// Indexers and download clients -------------------------------
|
||||
|
||||
export type AcquisitionProtocol = 'prowlarr' | 'torznab' | 'qbittorrent' | 'exchange';
|
||||
|
||||
/** One indexer or download client. Secrets never come back, only whether set. */
|
||||
export type AcquisitionService = {
|
||||
code: string;
|
||||
kind: 'search' | 'download';
|
||||
protocol: AcquisitionProtocol;
|
||||
label: string;
|
||||
enabled: boolean;
|
||||
base_url: string;
|
||||
has_api_key: boolean;
|
||||
has_password: boolean;
|
||||
username: string;
|
||||
category: string;
|
||||
timeout_ms: number;
|
||||
/** The three switches mean something on an exchange row only. */
|
||||
serves_search: boolean;
|
||||
serves_downloads: boolean;
|
||||
serves_enrichment: boolean;
|
||||
local_path: string;
|
||||
remote_path: string;
|
||||
searches_per_hour: number;
|
||||
/** Switched on and addressed. */
|
||||
usable: boolean;
|
||||
};
|
||||
|
||||
export type AcquisitionUpdate = Omit<
|
||||
AcquisitionService,
|
||||
'code' | 'kind' | 'protocol' | 'has_api_key' | 'has_password' | 'usable'
|
||||
>;
|
||||
|
||||
export type AcquisitionTestResult = { ok: boolean; detail: string };
|
||||
|
||||
const acquisitionBase = '/api/admin/acquisition/services';
|
||||
|
||||
export async function listAcquisitionServices(): Promise<AcquisitionService[]> {
|
||||
const res = await api.get<{ services: AcquisitionService[] }>(acquisitionBase);
|
||||
return res.services;
|
||||
}
|
||||
|
||||
export async function addAcquisitionService(
|
||||
protocol: AcquisitionProtocol
|
||||
): Promise<AcquisitionService> {
|
||||
return api.post<AcquisitionService>(acquisitionBase, { protocol });
|
||||
}
|
||||
|
||||
export async function updateAcquisitionService(
|
||||
code: string,
|
||||
u: AcquisitionUpdate
|
||||
): Promise<AcquisitionService> {
|
||||
return api.put<AcquisitionService>(`${acquisitionBase}/${encodeURIComponent(code)}`, u);
|
||||
}
|
||||
|
||||
export async function removeAcquisitionService(code: string): Promise<void> {
|
||||
await api.del(`${acquisitionBase}/${encodeURIComponent(code)}`);
|
||||
}
|
||||
|
||||
export async function testAcquisitionService(code: string): Promise<AcquisitionTestResult> {
|
||||
return api.post<AcquisitionTestResult>(`${acquisitionBase}/${encodeURIComponent(code)}/test`, {});
|
||||
}
|
||||
|
||||
/** Stores a key or password. Write-only: nothing comes back. */
|
||||
export async function setAcquisitionSecret(
|
||||
code: string,
|
||||
which: 'api-key' | 'password',
|
||||
value: string
|
||||
): Promise<void> {
|
||||
await api.put(`${acquisitionBase}/${encodeURIComponent(code)}/${which}`, { value });
|
||||
}
|
||||
|
||||
export async function clearAcquisitionSecret(
|
||||
code: string,
|
||||
which: 'api-key' | 'password'
|
||||
): Promise<void> {
|
||||
await api.del(`${acquisitionBase}/${encodeURIComponent(code)}/${which}`);
|
||||
}
|
||||
|
||||
// The server's own backup ---------------------------------------------------
|
||||
|
||||
export type BackupDestination = 'folder' | 's3';
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest';
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
api: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
del: vi.fn()
|
||||
}
|
||||
}));
|
||||
|
||||
import { searchCatalogue } from './catalogue';
|
||||
import { api } from './client';
|
||||
import { qk } from './queries';
|
||||
import type { CatalogueSearchResult } from './types';
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('searchCatalogue', () => {
|
||||
test('builds URL with q and kind query params', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]);
|
||||
await searchCatalogue('aphex twin', 'artist');
|
||||
expect(api.get).toHaveBeenCalledWith('/api/catalogue/search?q=aphex+twin&kind=artist');
|
||||
});
|
||||
|
||||
test('encodes special characters in q (quotes, ampersands, plus)', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]);
|
||||
await searchCatalogue('boards of canada & friends', 'album');
|
||||
const calledWith = (api.get as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
|
||||
// URLSearchParams encodes space as '+' and '&' as '%26'.
|
||||
expect(calledWith).toBe(
|
||||
'/api/catalogue/search?q=boards+of+canada+%26+friends&kind=album'
|
||||
);
|
||||
});
|
||||
|
||||
test('passes through results unchanged', async () => {
|
||||
const fixture: CatalogueSearchResult[] = [
|
||||
{
|
||||
mbid: 'mbid-1',
|
||||
name: 'Aphex Twin',
|
||||
secondary_text: 'Electronic',
|
||||
image_url: '/api/catalogue/art/artist/mbid-1?name=Aphex+Twin',
|
||||
artist_mbid: '',
|
||||
album_mbid: '',
|
||||
in_library: false,
|
||||
requested: false
|
||||
}
|
||||
];
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(fixture);
|
||||
const out = await searchCatalogue('aphex', 'artist');
|
||||
expect(out).toBe(fixture);
|
||||
});
|
||||
|
||||
test('propagates errors from api.get', async () => {
|
||||
const err = { code: 'musicbrainz_unreachable', message: 'down', status: 503 };
|
||||
(api.get as ReturnType<typeof vi.fn>).mockRejectedValueOnce(err);
|
||||
await expect(searchCatalogue('x', 'track')).rejects.toMatchObject({
|
||||
code: 'musicbrainz_unreachable',
|
||||
status: 503
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('qk.catalogueSearch', () => {
|
||||
test('keys include q + kind', () => {
|
||||
expect(qk.catalogueSearch('foo', 'artist')).toEqual([
|
||||
'catalogueSearch',
|
||||
{ q: 'foo', kind: 'artist' }
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
import { createQuery } from '@tanstack/svelte-query';
|
||||
import { api } from './client';
|
||||
import { qk } from './queries';
|
||||
import type { CatalogueSearchResult, RequestKind } from './types';
|
||||
|
||||
// searchCatalogue asks MusicBrainz through Minstrel's release catalogue.
|
||||
// URLSearchParams handles encoding (spaces, quotes,
|
||||
// ampersands) so callers can pass q raw.
|
||||
export async function searchCatalogue(
|
||||
q: string,
|
||||
kind: RequestKind
|
||||
): Promise<CatalogueSearchResult[]> {
|
||||
const params = new URLSearchParams({ q, kind });
|
||||
return api.get<CatalogueSearchResult[]>(`/api/catalogue/search?${params.toString()}`);
|
||||
}
|
||||
|
||||
// MusicBrainz allows a request a second, so a repeated search within a minute
|
||||
// is served from the client's cache rather than asked again.
|
||||
export function createCatalogueSearchQuery(q: string, kind: RequestKind) {
|
||||
return createQuery({
|
||||
queryKey: qk.catalogueSearch(q, kind),
|
||||
queryFn: () => searchCatalogue(q, kind),
|
||||
enabled: q.length > 0,
|
||||
staleTime: 60_000
|
||||
});
|
||||
}
|
||||
@@ -29,29 +29,6 @@ export const qk = {
|
||||
likedAlbums: () => ['likedAlbums'] as const,
|
||||
likedArtists: () => ['likedArtists'] as const,
|
||||
history: () => ['history'] as const,
|
||||
// Requests / admin.
|
||||
catalogueSearch: (q: string, kind: string) =>
|
||||
['catalogueSearch', { q, kind }] as const,
|
||||
myRequests: () => ['myRequests'] as const,
|
||||
adminRequests: (status?: string) =>
|
||||
['adminRequests', { status: status ?? 'all' }] as const,
|
||||
// Wanted list. Wants sit under ['adminWants'] so one prefix
|
||||
// invalidation refreshes every tab and its counts.
|
||||
adminWants: (state: string, q: string = '', artist: string = '') =>
|
||||
['adminWants', { state, q, artist }] as const,
|
||||
wantArtists: (q: string = '') => ['adminWants', 'artists', { q }] as const,
|
||||
wantTracks: (id: string) => ['wantTracks', id] as const,
|
||||
// The Collection's Unmatched section.
|
||||
unmatched: () => ['adminWants', 'unmatched'] as const,
|
||||
adminFollows: () => ['adminFollows'] as const,
|
||||
adminFollow: (artistMbid: string) => ['adminFollow', artistMbid] as const,
|
||||
releaseProfiles: () => ['releaseProfiles'] as const,
|
||||
// Search and grab.
|
||||
wantCandidates: (wantId: string) => ['wantCandidates', wantId] as const,
|
||||
searchSettings: () => ['searchSettings'] as const,
|
||||
// The Wanted view's Activity and Blocked tabs.
|
||||
downloads: () => ['adminWants', 'downloads'] as const,
|
||||
releaseBlocks: () => ['adminWants', 'releaseBlocks'] as const,
|
||||
myQuarantine: () => ['myQuarantine'] as const,
|
||||
adminQuarantine: () => ['adminQuarantine'] as const,
|
||||
adminQuarantineActions: (limit?: number) =>
|
||||
@@ -83,9 +60,6 @@ export const qk = {
|
||||
notifications: () => ['notifications', 'list'] as const,
|
||||
notificationsUnread: () => ['notifications', 'unread'] as const,
|
||||
notificationSettings: () => ['notificationSettings'] as const,
|
||||
suggestions: (limit?: number) =>
|
||||
['suggestions', { limit: limit ?? 12 }] as const,
|
||||
suggestionSnoozes: () => ['suggestionSnoozes'] as const,
|
||||
home: () => ['home'] as const,
|
||||
albumsAlpha: () => ['albumsAlpha'] as const,
|
||||
artistTracks: (artistId: string) => ['artistTracks', artistId] as const,
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
import { describe, expect, test, vi, beforeEach, afterEach } from 'vitest';
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
api: {
|
||||
get: vi.fn(),
|
||||
post: vi.fn(),
|
||||
put: vi.fn(),
|
||||
del: vi.fn()
|
||||
},
|
||||
apiFetch: vi.fn()
|
||||
}));
|
||||
|
||||
import {
|
||||
createRequest,
|
||||
listMyRequests,
|
||||
getRequest,
|
||||
cancelRequest,
|
||||
hasInFlightRequest
|
||||
} from './requests';
|
||||
import { api, apiFetch } from './client';
|
||||
import { qk } from './queries';
|
||||
import type { MusicRequest } from './types';
|
||||
|
||||
const mockRow: MusicRequest = {
|
||||
id: 'r1',
|
||||
user_id: 'u1',
|
||||
status: 'pending',
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'alb-mbid',
|
||||
track_mbid: null,
|
||||
artist_name: 'Aphex Twin',
|
||||
album_title: 'Selected Ambient Works',
|
||||
track_title: null,
|
||||
decided_at: null,
|
||||
decided_by: null,
|
||||
notes: null,
|
||||
completed_at: null,
|
||||
matched_track_id: null,
|
||||
matched_album_id: null,
|
||||
matched_artist_id: null,
|
||||
requested_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
imported_album_count: 0,
|
||||
imported_track_count: 0
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('createRequest', () => {
|
||||
test('POSTs /api/requests with full body for an album request', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(mockRow);
|
||||
const out = await createRequest({
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'alb-mbid',
|
||||
artist_name: 'Aphex Twin',
|
||||
album_title: 'Selected Ambient Works'
|
||||
});
|
||||
expect(api.post).toHaveBeenCalledWith('/api/requests', {
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
artist_name: 'Aphex Twin',
|
||||
album_mbid: 'alb-mbid',
|
||||
album_title: 'Selected Ambient Works'
|
||||
});
|
||||
expect(out).toBe(mockRow);
|
||||
});
|
||||
|
||||
test('omits empty / undefined optional MBID + title fields from wire body', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(mockRow);
|
||||
await createRequest({
|
||||
kind: 'artist',
|
||||
artist_mbid: 'art-mbid',
|
||||
artist_name: 'Aphex Twin',
|
||||
album_mbid: '',
|
||||
track_mbid: ''
|
||||
});
|
||||
const body = (api.post as ReturnType<typeof vi.fn>).mock.calls[0][1] as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
expect(body).toEqual({
|
||||
kind: 'artist',
|
||||
artist_mbid: 'art-mbid',
|
||||
artist_name: 'Aphex Twin'
|
||||
});
|
||||
expect(body).not.toHaveProperty('album_mbid');
|
||||
expect(body).not.toHaveProperty('track_mbid');
|
||||
expect(body).not.toHaveProperty('album_title');
|
||||
expect(body).not.toHaveProperty('track_title');
|
||||
});
|
||||
|
||||
test('includes track fields for a track-kind request', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(mockRow);
|
||||
await createRequest({
|
||||
kind: 'track',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'alb-mbid',
|
||||
track_mbid: 'trk-mbid',
|
||||
artist_name: 'Aphex Twin',
|
||||
album_title: 'Drukqs',
|
||||
track_title: 'Avril 14th'
|
||||
});
|
||||
expect(api.post).toHaveBeenCalledWith('/api/requests', {
|
||||
kind: 'track',
|
||||
artist_mbid: 'art-mbid',
|
||||
artist_name: 'Aphex Twin',
|
||||
album_mbid: 'alb-mbid',
|
||||
track_mbid: 'trk-mbid',
|
||||
album_title: 'Drukqs',
|
||||
track_title: 'Avril 14th'
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('listMyRequests', () => {
|
||||
test('GETs /api/requests', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([mockRow]);
|
||||
const out = await listMyRequests();
|
||||
expect(api.get).toHaveBeenCalledWith('/api/requests');
|
||||
expect(out).toEqual([mockRow]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRequest', () => {
|
||||
test('GETs /api/requests/:id', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(mockRow);
|
||||
const out = await getRequest('r1');
|
||||
expect(api.get).toHaveBeenCalledWith('/api/requests/r1');
|
||||
expect(out).toBe(mockRow);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cancelRequest', () => {
|
||||
test('DELETEs /api/requests/:id and returns the cancelled row', async () => {
|
||||
const cancelled = { ...mockRow, status: 'rejected' as const };
|
||||
(apiFetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce(cancelled);
|
||||
const out = await cancelRequest('r1');
|
||||
expect(apiFetch).toHaveBeenCalledWith('/api/requests/r1', { method: 'DELETE' });
|
||||
expect(out).toBe(cancelled);
|
||||
expect(out.status).toBe('rejected');
|
||||
});
|
||||
});
|
||||
|
||||
describe('qk.myRequests', () => {
|
||||
test('returns the expected key tuple', () => {
|
||||
expect(qk.myRequests()).toEqual(['myRequests']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasInFlightRequest', () => {
|
||||
test('false for undefined / empty', () => {
|
||||
expect(hasInFlightRequest(undefined)).toBe(false);
|
||||
expect(hasInFlightRequest([])).toBe(false);
|
||||
});
|
||||
|
||||
test('false when no row is approved', () => {
|
||||
expect(
|
||||
hasInFlightRequest([
|
||||
{ ...mockRow, status: 'pending' },
|
||||
{ ...mockRow, status: 'completed' },
|
||||
{ ...mockRow, status: 'rejected' }
|
||||
])
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('true when at least one row is approved (mid-ingest)', () => {
|
||||
expect(
|
||||
hasInFlightRequest([
|
||||
{ ...mockRow, status: 'pending' },
|
||||
{ ...mockRow, status: 'approved' },
|
||||
{ ...mockRow, status: 'completed' }
|
||||
])
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
import { createQuery } from '@tanstack/svelte-query';
|
||||
import { api, apiFetch } from './client';
|
||||
import { qk } from './queries';
|
||||
import type { MusicRequest, RequestKind } from './types';
|
||||
|
||||
/** Cadence for in-flight request polling: fast enough to feel live, slow
|
||||
enough not to hammer the server. */
|
||||
const POLL_INTERVAL_MS = 12_000;
|
||||
|
||||
/** True if any row is mid-ingest (status === 'approved'). The status flips
|
||||
to 'completed' / 'rejected' when the music arrives, so this predicate
|
||||
lets the page poll exactly while there's something interesting to watch. */
|
||||
export function hasInFlightRequest(rows: readonly MusicRequest[] | undefined): boolean {
|
||||
return rows?.some((r) => r.status === 'approved') ?? false;
|
||||
}
|
||||
|
||||
// CreateRequestParams is the shape callers pass; unused MBID fields are
|
||||
// optional, and we omit them from the wire body rather than sending empty
|
||||
// strings (the backend tolerates either, but this keeps test expectations
|
||||
// crisp and matches the server's wire shape).
|
||||
export type CreateRequestParams = {
|
||||
kind: RequestKind;
|
||||
artist_mbid: string;
|
||||
album_mbid?: string;
|
||||
track_mbid?: string;
|
||||
artist_name: string;
|
||||
album_title?: string;
|
||||
track_title?: string;
|
||||
};
|
||||
|
||||
type CreateRequestBody = {
|
||||
kind: RequestKind;
|
||||
artist_mbid: string;
|
||||
artist_name: string;
|
||||
album_mbid?: string;
|
||||
track_mbid?: string;
|
||||
album_title?: string;
|
||||
track_title?: string;
|
||||
};
|
||||
|
||||
function buildCreateBody(params: CreateRequestParams): CreateRequestBody {
|
||||
const body: CreateRequestBody = {
|
||||
kind: params.kind,
|
||||
artist_mbid: params.artist_mbid,
|
||||
artist_name: params.artist_name
|
||||
};
|
||||
if (params.album_mbid) body.album_mbid = params.album_mbid;
|
||||
if (params.track_mbid) body.track_mbid = params.track_mbid;
|
||||
if (params.album_title) body.album_title = params.album_title;
|
||||
if (params.track_title) body.track_title = params.track_title;
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function createRequest(params: CreateRequestParams): Promise<MusicRequest> {
|
||||
return api.post<MusicRequest>('/api/requests', buildCreateBody(params));
|
||||
}
|
||||
|
||||
export async function listMyRequests(): Promise<MusicRequest[]> {
|
||||
return api.get<MusicRequest[]>('/api/requests');
|
||||
}
|
||||
|
||||
export async function getRequest(id: string): Promise<MusicRequest> {
|
||||
return api.get<MusicRequest>(`/api/requests/${id}`);
|
||||
}
|
||||
|
||||
// Server returns the cancelled row body (not 204) so callers can patch the
|
||||
// cache without a refetch. api.del's return type is fixed to null, so we
|
||||
// drop down to apiFetch here to keep typing honest.
|
||||
export async function cancelRequest(id: string): Promise<MusicRequest> {
|
||||
return apiFetch(`/api/requests/${id}`, { method: 'DELETE' }) as Promise<MusicRequest>;
|
||||
}
|
||||
|
||||
export function createMyRequestsQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.myRequests(),
|
||||
queryFn: listMyRequests,
|
||||
staleTime: 60_000,
|
||||
// Auto-poll while at least one user request is mid-ingest. Stops
|
||||
// automatically when all rows are pending/completed/rejected.
|
||||
// refetchIntervalInBackground defaults to false → polling pauses
|
||||
// while the tab is hidden and resumes on focus.
|
||||
refetchInterval: (query) =>
|
||||
hasInFlightRequest(query.state.data as MusicRequest[] | undefined)
|
||||
? POLL_INTERVAL_MS
|
||||
: false
|
||||
});
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
vi.mock('./client', () => ({
|
||||
api: { get: vi.fn(), post: vi.fn(), del: vi.fn() }
|
||||
}));
|
||||
|
||||
import {
|
||||
listSuggestions,
|
||||
listSnoozes,
|
||||
snoozeSuggestion,
|
||||
unsnoozeSuggestion
|
||||
} from './suggestions';
|
||||
import { qk } from './queries';
|
||||
import { api } from './client';
|
||||
import type { ArtistSuggestion, SuggestionSnooze } from './types';
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('suggestions client', () => {
|
||||
test('listSuggestions hits the right URL with default limit', async () => {
|
||||
const fixture: ArtistSuggestion[] = [
|
||||
{
|
||||
mbid: 'm1',
|
||||
name: 'Outsider',
|
||||
score: 1.5,
|
||||
attribution: [
|
||||
{ artist_id: 'a1', name: 'Seed', contribution: 0.9, is_liked: true, play_count: 0 }
|
||||
]
|
||||
}
|
||||
];
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(fixture);
|
||||
const got = await listSuggestions();
|
||||
expect(api.get).toHaveBeenCalledWith('/api/discover/suggestions?limit=12');
|
||||
expect(got).toEqual(fixture);
|
||||
});
|
||||
|
||||
test('listSuggestions honors a custom limit', async () => {
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce([]);
|
||||
await listSuggestions(20);
|
||||
expect(api.get).toHaveBeenCalledWith('/api/discover/suggestions?limit=20');
|
||||
});
|
||||
|
||||
test('qk.suggestions key shape', () => {
|
||||
expect(qk.suggestions()).toEqual(['suggestions', { limit: 12 }]);
|
||||
expect(qk.suggestions(20)).toEqual(['suggestions', { limit: 20 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('suggestion snoozes (#2375)', () => {
|
||||
test('snoozeSuggestion sends the name — the server 400s without it', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
|
||||
await snoozeSuggestion('mb-1', 'Parked Artist');
|
||||
expect(api.post).toHaveBeenCalledWith('/api/discover/suggestions/mb-1/snooze', {
|
||||
name: 'Parked Artist'
|
||||
});
|
||||
});
|
||||
|
||||
test('snoozeSuggestion sends no days, leaving the default to the server', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
|
||||
await snoozeSuggestion('mb-1', 'Parked Artist');
|
||||
const body = (api.post as ReturnType<typeof vi.fn>).mock.calls[0][1] as Record<string, unknown>;
|
||||
expect(body).not.toHaveProperty('days');
|
||||
});
|
||||
|
||||
// MBIDs are UUIDs today, but the column is free-text and the value comes
|
||||
// from an external similarity feed, so it goes through encodeURIComponent.
|
||||
test('the mbid is URL-encoded into the path', async () => {
|
||||
(api.post as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
|
||||
await snoozeSuggestion('weird/id?x', 'Odd');
|
||||
expect(api.post).toHaveBeenCalledWith(
|
||||
'/api/discover/suggestions/weird%2Fid%3Fx/snooze',
|
||||
{ name: 'Odd' }
|
||||
);
|
||||
});
|
||||
|
||||
test('unsnoozeSuggestion DELETEs the same path', async () => {
|
||||
(api.del as ReturnType<typeof vi.fn>).mockResolvedValueOnce(null);
|
||||
await unsnoozeSuggestion('mb-1');
|
||||
expect(api.del).toHaveBeenCalledWith('/api/discover/suggestions/mb-1/snooze');
|
||||
});
|
||||
|
||||
test('listSnoozes hits the snoozes collection', async () => {
|
||||
const fixture: SuggestionSnooze[] = [
|
||||
{
|
||||
mbid: 'mb-1',
|
||||
name: 'Parked Artist',
|
||||
snoozed_until: '2026-11-01T00:00:00Z',
|
||||
created_at: '2026-08-03T00:00:00Z'
|
||||
}
|
||||
];
|
||||
(api.get as ReturnType<typeof vi.fn>).mockResolvedValueOnce(fixture);
|
||||
const got = await listSnoozes();
|
||||
expect(api.get).toHaveBeenCalledWith('/api/discover/snoozes');
|
||||
expect(got).toEqual(fixture);
|
||||
});
|
||||
|
||||
test('qk.suggestionSnoozes key shape', () => {
|
||||
expect(qk.suggestionSnoozes()).toEqual(['suggestionSnoozes']);
|
||||
});
|
||||
});
|
||||
@@ -1,49 +0,0 @@
|
||||
import { createQuery } from '@tanstack/svelte-query';
|
||||
import { api } from './client';
|
||||
import { qk } from './queries';
|
||||
import type { ArtistSuggestion, SuggestionSnooze } from './types';
|
||||
|
||||
export async function listSuggestions(limit = 12): Promise<ArtistSuggestion[]> {
|
||||
return api.get<ArtistSuggestion[]>(`/api/discover/suggestions?limit=${limit}`);
|
||||
}
|
||||
|
||||
export function createSuggestionsQuery(limit = 12) {
|
||||
return createQuery({
|
||||
queryKey: qk.suggestions(limit),
|
||||
queryFn: () => listSuggestions(limit),
|
||||
staleTime: 5 * 60_000 // 5 minutes
|
||||
});
|
||||
}
|
||||
|
||||
// Parks a suggestion for the server's default period (90 days). `name` is
|
||||
// REQUIRED by the server and is not optional bookkeeping: candidates are
|
||||
// out-of-library, so there is no artists row to resolve a display name from
|
||||
// and the snooze list would have nothing to render. Omitting it is a 400.
|
||||
//
|
||||
// No `days` is sent: the default is an admin setting on the server (Discover
|
||||
// tuning), and hardcoding a value here would pin it to the client instead of
|
||||
// the server that owns it.
|
||||
export async function snoozeSuggestion(mbid: string, name: string): Promise<void> {
|
||||
await api.post<null>(`/api/discover/suggestions/${encodeURIComponent(mbid)}/snooze`, { name });
|
||||
}
|
||||
|
||||
// Brings a parked suggestion back immediately. The server 404s an MBID that
|
||||
// was never snoozed; callers treat that as already-unsnoozed rather than as a
|
||||
// failure, since the end state the user asked for is the one they get.
|
||||
export async function unsnoozeSuggestion(mbid: string): Promise<void> {
|
||||
await api.del(`/api/discover/suggestions/${encodeURIComponent(mbid)}/snooze`);
|
||||
}
|
||||
|
||||
export async function listSnoozes(): Promise<SuggestionSnooze[]> {
|
||||
return api.get<SuggestionSnooze[]>('/api/discover/snoozes');
|
||||
}
|
||||
|
||||
export function createSnoozesQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.suggestionSnoozes(),
|
||||
queryFn: listSnoozes
|
||||
// No staleTime, unlike the suggestions query: this list is the only route
|
||||
// back to an un-snooze, so it must reflect a snooze made seconds ago
|
||||
// rather than a cached view of the world.
|
||||
});
|
||||
}
|
||||
@@ -26,15 +26,7 @@ export type TasteTuning = {
|
||||
mood_scale: number;
|
||||
};
|
||||
|
||||
// Discover request-surface knobs. Its own scope rather than part of
|
||||
// taste: snooze_days belongs here, and a snooze must never be read as taste
|
||||
// signal.
|
||||
export type DiscoverTuning = {
|
||||
tag_overlap_weight: number;
|
||||
snooze_days: number;
|
||||
};
|
||||
|
||||
export type TuningScope = 'radio' | 'daily_mix' | 'songs_like' | 'taste' | 'discover';
|
||||
export type TuningScope = 'radio' | 'daily_mix' | 'songs_like' | 'taste';
|
||||
|
||||
/** The weight-profile scopes, as distinct from the singleton-settings scopes. */
|
||||
export type WeightProfileScope = 'radio' | 'daily_mix' | 'songs_like';
|
||||
@@ -42,11 +34,9 @@ export type WeightProfileScope = 'radio' | 'daily_mix' | 'songs_like';
|
||||
export type TuningSnapshot = {
|
||||
profiles: Record<WeightProfileScope, WeightProfile>;
|
||||
taste: TasteTuning;
|
||||
discover: DiscoverTuning;
|
||||
shipped: {
|
||||
profiles: Record<WeightProfileScope, WeightProfile>;
|
||||
taste: TasteTuning;
|
||||
discover: DiscoverTuning;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
+1
-465
@@ -133,66 +133,6 @@ export type EventRequest =
|
||||
export type PlayStartedResponse = { play_event_id: string; session_id: string };
|
||||
export type EventOkResponse = { ok: true };
|
||||
|
||||
// Request shared enums + shapes.
|
||||
// Status + Kind are used across catalogue.ts, requests.ts, and admin.ts so
|
||||
// they live here. Per-module helpers (CreateRequestParams, etc.) stay in their
|
||||
// respective modules.
|
||||
export type RequestStatus =
|
||||
| 'pending'
|
||||
| 'approved'
|
||||
| 'rejected'
|
||||
| 'completed'
|
||||
| 'failed';
|
||||
|
||||
export type RequestKind = 'artist' | 'album' | 'track';
|
||||
|
||||
// One row of the request search (GET /api/catalogue/search).
|
||||
// An album is a MusicBrainz release group; image_url is Minstrel's own art
|
||||
// endpoint, which answers 404 when no source has an image.
|
||||
export type CatalogueSearchResult = {
|
||||
mbid: string;
|
||||
name: string;
|
||||
secondary_text: string;
|
||||
image_url: string;
|
||||
artist_mbid: string;
|
||||
album_mbid: string;
|
||||
in_library: boolean;
|
||||
requested: boolean;
|
||||
};
|
||||
|
||||
// pgtype.UUID and pgtype.Timestamptz JSON-marshal as a native string when
|
||||
// Valid, and as `null` (or omitted, with omitempty) otherwise. We unify both
|
||||
// "absent" cases as `string | null` so callers branch on a single check.
|
||||
export type MusicRequest = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
// The requester's username. Only the admin list sends it.
|
||||
username?: string;
|
||||
status: RequestStatus;
|
||||
kind: RequestKind;
|
||||
artist_mbid: string;
|
||||
// The album's MusicBrainz release group.
|
||||
album_mbid?: string | null;
|
||||
track_mbid?: string | null;
|
||||
artist_name: string;
|
||||
album_title?: string | null;
|
||||
track_title?: string | null;
|
||||
decided_at?: string | null;
|
||||
decided_by?: string | null;
|
||||
notes?: string | null;
|
||||
completed_at?: string | null;
|
||||
matched_track_id?: string | null;
|
||||
matched_album_id?: string | null;
|
||||
matched_artist_id?: string | null;
|
||||
requested_at: string;
|
||||
updated_at: string;
|
||||
// Live ingest counters. Server fills these from the matched entity's
|
||||
// children. Useful for in-flight requests so an admin can see
|
||||
// "5 albums · 47 tracks" while the rest is still being fetched.
|
||||
imported_album_count: number;
|
||||
imported_track_count: number;
|
||||
};
|
||||
|
||||
// Quarantine ------------------------------------------------------------
|
||||
|
||||
export type QuarantineReason =
|
||||
@@ -295,36 +235,6 @@ export type ActionResult = {
|
||||
affected_users: number;
|
||||
};
|
||||
|
||||
export type SeedContribution = {
|
||||
artist_id: string;
|
||||
name: string;
|
||||
contribution: number;
|
||||
is_liked: boolean;
|
||||
play_count: number;
|
||||
};
|
||||
|
||||
export type ArtistSuggestion = {
|
||||
mbid: string;
|
||||
name: string;
|
||||
score: number;
|
||||
attribution: SeedContribution[]; // up to 3 entries, ordered by contribution DESC
|
||||
image_url?: string; // absent → card placeholder
|
||||
// Tags this candidate shares with your taste profile, strongest first (max
|
||||
// 3). Absent for most candidates — tag coverage for artists you don't own
|
||||
// is partial by nature — so the card falls back to seed attribution.
|
||||
matched_tags?: string[];
|
||||
};
|
||||
|
||||
// One parked suggestion — "not right now", not a dislike. The server only
|
||||
// ever returns rows whose snoozed_until is still in the future, so the client
|
||||
// never has to compare against the clock to decide what to show.
|
||||
export type SuggestionSnooze = {
|
||||
mbid: string;
|
||||
name: string;
|
||||
snoozed_until: string; // RFC3339
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
// Mirrors internal/api/types.go HomePayload. All slices are non-null
|
||||
// per the server contract — empty sections render as [].
|
||||
export type HomePayload = {
|
||||
@@ -357,17 +267,6 @@ export type AdminMissingTrack = {
|
||||
last_played_at: string | null;
|
||||
};
|
||||
|
||||
// What the wanted list says about this group's album:
|
||||
// when it was wanted back, and when the library held it again. null while the
|
||||
// album is inside the grace window, or when MusicBrainz can't name it.
|
||||
export type AdminReacquisitionState = {
|
||||
wanted_at: string | null;
|
||||
held_at: string | null;
|
||||
// The want itself, as the wanted list sends it, so the Missing page
|
||||
// shows its search and download and acts on it.
|
||||
want: Want | null;
|
||||
};
|
||||
|
||||
// A directory's worth of missing tracks. The server groups because the unit an
|
||||
// operator reasons about is a folder: three reorganised albums are three
|
||||
// decisions, not forty.
|
||||
@@ -375,7 +274,6 @@ export type AdminMissingGroup = {
|
||||
directory: string;
|
||||
missing_since: string;
|
||||
tracks: AdminMissingTrack[];
|
||||
reacquisition: AdminReacquisitionState | null;
|
||||
};
|
||||
|
||||
export type AdminMissingResponse = {
|
||||
@@ -405,10 +303,6 @@ export type AdminSuspectTrack = {
|
||||
// back. null: the resolver hasn't looked yet.
|
||||
verdict: SuspectVerdict | null;
|
||||
verdict_at: string | null;
|
||||
// The album is on the wanted list for a clean copy, and when one was last
|
||||
// searched for.
|
||||
replacing: boolean;
|
||||
searched_at: string | null;
|
||||
};
|
||||
|
||||
export type SuspectVerdict = 'suspect' | 'fine';
|
||||
@@ -486,12 +380,10 @@ export type MergeDuplicateResult = {
|
||||
};
|
||||
|
||||
// What settling one recording in several slots did. kept_track_id is
|
||||
// null when every copy went; blocked names the releases set aside, empty when
|
||||
// the album came from before Minstrel downloaded anything.
|
||||
// null when every copy went.
|
||||
export type RefetchDuplicateResult = {
|
||||
kept_track_id: string | null;
|
||||
removed_paths: string[];
|
||||
blocked: string[];
|
||||
};
|
||||
|
||||
export type AdminDuplicatesResponse = {
|
||||
@@ -540,357 +432,10 @@ export type ResolvedDuplicatesResponse = {
|
||||
items: ResolvedDuplicateActivity[];
|
||||
};
|
||||
|
||||
// Wanted list ------------------------------------------------
|
||||
|
||||
// library: in the library when the list began.
|
||||
export type WantReason = 'request' | 'follow' | 'missing' | 'library';
|
||||
// all: one artist's page, every album of theirs on the list.
|
||||
// upgrade: held albums wanted for a better copy.
|
||||
export type WantState = 'wanted' | 'missing' | 'upgrade' | 'held' | 'all';
|
||||
// Why a held album is wanted again: its copy is below the quality settled
|
||||
// for, or one of its tracks is a video rip.
|
||||
export type WantUpgrade = 'quality' | 'rip';
|
||||
|
||||
// One release group on the wanted list. held_at is set once the library
|
||||
// holds it; artist_id and album_id link into the library when it has them.
|
||||
export type Want = {
|
||||
id: string;
|
||||
release_group_mbid: string;
|
||||
title: string;
|
||||
artist_mbid: string;
|
||||
artist_name: string;
|
||||
artist_id?: string;
|
||||
primary_type: string;
|
||||
secondary_types: string[];
|
||||
year: string;
|
||||
reason: WantReason;
|
||||
requested_by?: string;
|
||||
album_id?: string;
|
||||
wanted_at: string;
|
||||
held_at: string | null;
|
||||
image_url: string;
|
||||
// A held album wanted for a better copy, and what the copy it has is
|
||||
// ("MP3, about 192 kbps").
|
||||
upgrade?: WantUpgrade;
|
||||
held_quality?: string;
|
||||
// The search schedule's last look, and the download running.
|
||||
search?: WantSearch | null;
|
||||
grab?: WantGrab | null;
|
||||
};
|
||||
|
||||
export type SearchOutcome = 'grabbed' | 'waiting' | 'nothing' | 'error';
|
||||
|
||||
export type WantSearch = {
|
||||
searched_at: string;
|
||||
outcome: SearchOutcome;
|
||||
considered: number;
|
||||
best_release: string;
|
||||
best_verdict: string;
|
||||
error: string;
|
||||
};
|
||||
|
||||
// What an import made of a finished download.
|
||||
export type ImportState =
|
||||
| ''
|
||||
| 'downloading'
|
||||
| 'waiting'
|
||||
| 'importing'
|
||||
| 'imported'
|
||||
| 'refused'
|
||||
| 'review'
|
||||
| 'held'
|
||||
| 'failed';
|
||||
|
||||
// A want's latest download, running or ended.
|
||||
export type WantGrab = {
|
||||
id: string;
|
||||
name: string;
|
||||
grabbed_at: string;
|
||||
origin: 'schedule' | 'operator';
|
||||
quality: string;
|
||||
live: boolean;
|
||||
end_reason: string;
|
||||
progress: number;
|
||||
import_state: ImportState;
|
||||
import_reason: string;
|
||||
// Why an ended download ended.
|
||||
end_detail: string;
|
||||
imported_at: string | null;
|
||||
imported_files: number;
|
||||
};
|
||||
|
||||
// Search and grab ----------------------------------------------
|
||||
|
||||
export type CandidateVerdict = 'grab' | 'review' | 'refused' | 'rejected' | 'blocked';
|
||||
|
||||
// One release a want's last search found, with what was decided about it.
|
||||
export type Candidate = {
|
||||
key: string;
|
||||
name: string;
|
||||
info_hash: string;
|
||||
indexer: string;
|
||||
size_bytes: number;
|
||||
seeders: number;
|
||||
files_count: number;
|
||||
format: string;
|
||||
quality: string;
|
||||
year: number;
|
||||
verdict: CandidateVerdict;
|
||||
reason: string;
|
||||
reasons: { kind: 'hard' | 'soft'; code: string; text: string }[];
|
||||
folded_from: string[];
|
||||
searched_at: string;
|
||||
downloading: boolean;
|
||||
};
|
||||
|
||||
export type Narrowing = { source: string; label: string; reason: string };
|
||||
|
||||
export type SearchResult = {
|
||||
outcome: SearchOutcome;
|
||||
considered: number;
|
||||
best_release: string;
|
||||
best_verdict: string;
|
||||
grabbed?: string;
|
||||
narrowed: Narrowing[];
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type GrabResult = {
|
||||
added: boolean;
|
||||
refused: boolean;
|
||||
gone: boolean;
|
||||
unconfigured: boolean;
|
||||
missing?: string;
|
||||
kept: boolean;
|
||||
replaced: boolean;
|
||||
verdict?: CandidateVerdict;
|
||||
reason?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type QualityTier = { tier: string; label: string; what: string };
|
||||
|
||||
// The last scheduled pass; empty before the first.
|
||||
export type SearchPass = {
|
||||
looked?: number;
|
||||
grabbed?: number;
|
||||
waiting?: number;
|
||||
nothing?: number;
|
||||
failed?: number;
|
||||
paced?: boolean;
|
||||
off?: boolean;
|
||||
unconfigured?: boolean;
|
||||
auto_grab?: boolean;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type SearchSettings = {
|
||||
auto_grab: boolean;
|
||||
search_interval_hours: number;
|
||||
allowed_qualities: string[];
|
||||
tiers: QualityTier[];
|
||||
last_pass_at: string | null;
|
||||
last_pass: SearchPass;
|
||||
// The library folder new music is filed into ("" = the first of
|
||||
// scan_paths), and the library's folders.
|
||||
import_root: string;
|
||||
scan_paths: string[];
|
||||
// The download lifecycle: an imported download seeds to this
|
||||
// ratio or for this many days (0: removed once imported; no time limit),
|
||||
// and one nobody shares is given up after this many hours (0: never).
|
||||
seed_ratio: number;
|
||||
seed_days: number;
|
||||
stall_hours: number;
|
||||
// The tier a held album is upgraded to; "" is no quality upgrades.
|
||||
upgrade_until: string;
|
||||
};
|
||||
|
||||
export type WantCounts = {
|
||||
// Artists in the Collection's catalogue.
|
||||
artists: number;
|
||||
wanted: number;
|
||||
missing: number;
|
||||
held: number;
|
||||
// Held albums wanted for a better copy.
|
||||
upgrades: number;
|
||||
following: number;
|
||||
// Downloads running, those of them waiting on a person, releases set aside.
|
||||
activity: number;
|
||||
attention: number;
|
||||
blocked: number;
|
||||
// Library albums no MusicBrainz album matched, waiting to be matched by
|
||||
// hand or left off.
|
||||
unmatched: number;
|
||||
};
|
||||
|
||||
// What an import's check counted.
|
||||
export type ImportEvidence = {
|
||||
files: number;
|
||||
tracks: number;
|
||||
identified: number;
|
||||
recordings: number;
|
||||
lengths: number;
|
||||
titles: number;
|
||||
group_tag?: string;
|
||||
album_tag?: string;
|
||||
fingerprinted: boolean;
|
||||
};
|
||||
|
||||
// One download on the Activity tab.
|
||||
export type Download = {
|
||||
id: string;
|
||||
want_id: string | null;
|
||||
want_title: string;
|
||||
want_artist: string;
|
||||
name: string;
|
||||
indexer: string;
|
||||
client: string;
|
||||
quality: string;
|
||||
origin: 'schedule' | 'operator';
|
||||
grabbed_at: string;
|
||||
ended_at: string | null;
|
||||
end_reason: string;
|
||||
progress: number;
|
||||
import_state: ImportState;
|
||||
import_reason: string;
|
||||
imported_at: string | null;
|
||||
imported_files: number;
|
||||
destination: string;
|
||||
edition?: string;
|
||||
evidence?: ImportEvidence;
|
||||
files: string[];
|
||||
skipped: number;
|
||||
rehomed_from?: string;
|
||||
// Why an ended download ended; for an imported one, its seeding.
|
||||
end_detail: string;
|
||||
seeding: boolean;
|
||||
ratio: number;
|
||||
seed_released_at: string | null;
|
||||
// What is wrong with it now, if anything.
|
||||
condition: DownloadCondition | null;
|
||||
};
|
||||
|
||||
// An open condition on a download, from the lifecycle's ledger.
|
||||
export type DownloadCondition = {
|
||||
trigger: 'no_peers' | 'no_metadata' | 'client_error' | 'client_unreachable' | 'gone' | 'not_removed';
|
||||
detail: string;
|
||||
retries: number;
|
||||
since: string;
|
||||
};
|
||||
|
||||
// A download client not answering now.
|
||||
export type ClientDown = { client: string; detail: string; since: string };
|
||||
|
||||
export type DownloadsPage = {
|
||||
items: Download[];
|
||||
limit: number;
|
||||
offset: number;
|
||||
clients_down: ClientDown[];
|
||||
};
|
||||
|
||||
// A release set aside: by a person, by its files, or by an import's check.
|
||||
export type ReleaseBlock = {
|
||||
info_hash: string;
|
||||
name: string;
|
||||
reason: 'operator' | 'files' | 'import' | 'stalled' | 'gone';
|
||||
detail: string;
|
||||
blocked_at: string;
|
||||
// When a release given up on may be taken again; null is for good.
|
||||
expires_at: string | null;
|
||||
want_title: string;
|
||||
want_artist: string;
|
||||
};
|
||||
|
||||
export type ReleaseBlocksPage = { items: ReleaseBlock[]; limit: number; offset: number };
|
||||
|
||||
// The one-time listing of the library's albums as held: when it
|
||||
// finished (null while it runs), and how many albums nothing names to
|
||||
// MusicBrainz, so they could not be listed.
|
||||
// One album in the Collection's Unmatched section: why no
|
||||
// MusicBrainz album matched it, or that a person left it off.
|
||||
export type UnmatchedAlbum = {
|
||||
album_id: string;
|
||||
title: string;
|
||||
artist: string;
|
||||
detail: string;
|
||||
tracks: number;
|
||||
left_off: boolean;
|
||||
decided_at: string;
|
||||
};
|
||||
|
||||
// What matching an album by hand did: the MusicBrainz album it is now, and
|
||||
// how many of its tracks agree with that album's closest edition.
|
||||
export type ManualMatch = { release_group_mbid: string; title: string; artist: string; agree: number; tracks: number };
|
||||
|
||||
export type LibraryListing = { listed_at: string | null; unlisted: number };
|
||||
|
||||
// artist heads the list when it is narrowed to one artist's page.
|
||||
export type WantsPage = Page<Want> & { counts: WantCounts; library: LibraryListing; artist?: WantArtist };
|
||||
|
||||
// One artist in the Collection's catalogue: how many of their albums
|
||||
// on the list are held, of how many.
|
||||
export type WantArtist = {
|
||||
artist_mbid: string;
|
||||
artist_name: string;
|
||||
sort_name: string;
|
||||
artist_id?: string;
|
||||
image_url: string;
|
||||
albums: number;
|
||||
held: number;
|
||||
wanted: number;
|
||||
missing: number;
|
||||
downloading: number;
|
||||
following: boolean;
|
||||
};
|
||||
|
||||
export type WantArtistsPage = Page<WantArtist> & { counts: WantCounts; library: LibraryListing };
|
||||
|
||||
// An album's tracks in the Wanted view: the library's own for an
|
||||
// album it holds (a lost file marked missing), else MusicBrainz's standard
|
||||
// edition, named by edition; none when MusicBrainz lists no edition.
|
||||
export type WantTrack = { disc: number; number: number; title: string; length_ms: number; missing: boolean };
|
||||
|
||||
export type WantTracks = { source: 'library' | 'musicbrainz' | 'none'; edition?: string; tracks: WantTrack[] };
|
||||
|
||||
export type Follow = {
|
||||
artist_mbid: string;
|
||||
artist_name: string;
|
||||
artist_id?: string;
|
||||
profile_id: string;
|
||||
profile_name: string;
|
||||
followed_at: string;
|
||||
checked_at: string | null;
|
||||
open_wants: number;
|
||||
image_url: string;
|
||||
};
|
||||
|
||||
export type FollowState = { following: boolean; profile_id?: string; profile_name?: string };
|
||||
|
||||
// A release-type profile: which kinds of release a follow wants. A group
|
||||
// passes when its primary type is listed and every secondary type is too;
|
||||
// no secondary types means studio releases only.
|
||||
export type ReleaseProfile = {
|
||||
id: string;
|
||||
name: string;
|
||||
primary_types: string[];
|
||||
secondary_types: string[];
|
||||
is_default: boolean;
|
||||
follow_count: number;
|
||||
};
|
||||
|
||||
export type ReleaseProfileInput = Omit<ReleaseProfile, 'id' | 'follow_count'>;
|
||||
|
||||
export type ReleaseProfilesResponse = {
|
||||
profiles: ReleaseProfile[];
|
||||
primary_types: string[];
|
||||
secondary_types: string[];
|
||||
};
|
||||
|
||||
// What GET /api/admin/summary returns: each queue that waits on an
|
||||
// admin, with how many and since when the oldest has waited (null when empty).
|
||||
export type AdminQueue = { count: number; since: string | null };
|
||||
export type AdminSummary = {
|
||||
requests: AdminQueue;
|
||||
// Broken tracks: flagged by a listener or failed to play, counted by track.
|
||||
reports: AdminQueue;
|
||||
duplicates: AdminQueue;
|
||||
@@ -921,15 +466,6 @@ export type AdminStatus = {
|
||||
listeners_day: number;
|
||||
last_play_at: string | null;
|
||||
};
|
||||
downloads: {
|
||||
running: number;
|
||||
needs_you: number;
|
||||
needs_you_since: string | null;
|
||||
imported_day: number;
|
||||
given_up_day: number;
|
||||
live: Download[];
|
||||
clients_down: { client: string; detail: string; since: string }[];
|
||||
};
|
||||
library: { tracks: number; albums: number; artists: number; bytes: number; disks: AdminDisk[] };
|
||||
server: {
|
||||
version: string;
|
||||
|
||||
@@ -1,308 +0,0 @@
|
||||
import { createInfiniteQuery, createQuery, keepPreviousData } from '@tanstack/svelte-query';
|
||||
import { api } from './client';
|
||||
import { qk } from './queries';
|
||||
import type {
|
||||
Candidate,
|
||||
DownloadsPage,
|
||||
Follow,
|
||||
ReleaseBlocksPage,
|
||||
FollowState,
|
||||
ReleaseProfile,
|
||||
ReleaseProfileInput,
|
||||
ReleaseProfilesResponse,
|
||||
GrabResult,
|
||||
ManualMatch,
|
||||
SearchResult,
|
||||
SearchSettings,
|
||||
UnmatchedAlbum,
|
||||
WantArtistsPage,
|
||||
WantState,
|
||||
WantTracks,
|
||||
WantsPage
|
||||
} from './types';
|
||||
|
||||
// The wanted list: release groups Minstrel is to get, the
|
||||
// artists it follows for new releases, and the release-type profiles that
|
||||
// say which kinds of release a follow wants.
|
||||
|
||||
// q narrows the list to an artist or album whose name holds it; artist to
|
||||
// one artist's page, which the response then heads.
|
||||
export async function listWants(
|
||||
state: WantState,
|
||||
offset: number = 0,
|
||||
q: string = '',
|
||||
artist: string = ''
|
||||
): Promise<WantsPage> {
|
||||
const params = new URLSearchParams({ state, offset: String(offset) });
|
||||
if (q) params.set('q', q);
|
||||
if (artist) params.set('artist', artist);
|
||||
return api.get<WantsPage>(`/api/admin/wanted?${params}`);
|
||||
}
|
||||
|
||||
export function wantsNextOffset(last: WantsPage): number | undefined {
|
||||
const loaded = last.offset + last.items.length;
|
||||
return last.items.length === 0 || loaded >= last.total ? undefined : loaded;
|
||||
}
|
||||
|
||||
// Loads as the page scrolls, one tab at a time.
|
||||
export function createWantsQuery(state: WantState, q: string = '', artist: string = '') {
|
||||
return createInfiniteQuery({
|
||||
queryKey: qk.adminWants(state, q, artist),
|
||||
queryFn: ({ pageParam }) => listWants(state, pageParam as number, q, artist),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: wantsNextOffset,
|
||||
// A new filter keeps the list it narrows on screen until its answer comes.
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// The Collection's catalogue: every artist on the list, A–Z, with
|
||||
// how many of their albums are held. Its first page carries every section's
|
||||
// count.
|
||||
export async function listWantArtists(offset: number = 0, q: string = ''): Promise<WantArtistsPage> {
|
||||
const params = new URLSearchParams({ offset: String(offset) });
|
||||
if (q) params.set('q', q);
|
||||
return api.get<WantArtistsPage>(`/api/admin/wanted/artists?${params}`);
|
||||
}
|
||||
|
||||
export function createWantArtistsQuery(q: string = '') {
|
||||
return createInfiniteQuery({
|
||||
queryKey: qk.wantArtists(q),
|
||||
queryFn: ({ pageParam }) => listWantArtists(pageParam as number, q),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (last: WantArtistsPage) => {
|
||||
const loaded = last.offset + last.items.length;
|
||||
return last.items.length === 0 || loaded >= last.total ? undefined : loaded;
|
||||
},
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// An album's tracks: the library's own for an album it holds,
|
||||
// otherwise MusicBrainz's standard edition.
|
||||
export async function getWantTracks(id: string): Promise<WantTracks> {
|
||||
return api.get<WantTracks>(`/api/admin/wanted/${id}/tracks`);
|
||||
}
|
||||
|
||||
export function createWantTracksQuery(id: string) {
|
||||
return createQuery({
|
||||
queryKey: qk.wantTracks(id),
|
||||
queryFn: () => getWantTracks(id),
|
||||
staleTime: 5 * 60_000
|
||||
});
|
||||
}
|
||||
|
||||
// The Collection's Unmatched section: library albums no MusicBrainz
|
||||
// album matched, and after them the ones a person left off.
|
||||
export async function listUnmatched(): Promise<UnmatchedAlbum[]> {
|
||||
const out = await api.get<{ items: UnmatchedAlbum[] }>('/api/admin/wanted/unmatched');
|
||||
return out.items;
|
||||
}
|
||||
|
||||
export function createUnmatchedQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.unmatched(),
|
||||
queryFn: listUnmatched,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// Puts an unmatched album on the list as held, as the MusicBrainz album ref
|
||||
// names: a release group's or a release's link, or a bare id.
|
||||
export async function matchUnmatched(albumId: string, ref: string): Promise<ManualMatch> {
|
||||
return api.post<ManualMatch>(`/api/admin/wanted/unmatched/${albumId}/match`, { ref });
|
||||
}
|
||||
|
||||
// Leaves an album off for good (a local band's, which MusicBrainz will
|
||||
// never have), or puts one left off back.
|
||||
export async function leaveUnmatchedOff(albumId: string): Promise<void> {
|
||||
await api.post<void>(`/api/admin/wanted/unmatched/${albumId}/leave-off`, {});
|
||||
}
|
||||
|
||||
export async function putUnmatchedBack(albumId: string): Promise<void> {
|
||||
await api.post<void>(`/api/admin/wanted/unmatched/${albumId}/put-back`, {});
|
||||
}
|
||||
|
||||
export async function removeWant(id: string): Promise<void> {
|
||||
await api.del(`/api/admin/wanted/${id}`);
|
||||
}
|
||||
|
||||
export async function listFollows(): Promise<Follow[]> {
|
||||
return api.get<Follow[]>('/api/admin/follows');
|
||||
}
|
||||
|
||||
export function createFollowsQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.adminFollows(),
|
||||
queryFn: listFollows,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
export async function getFollow(artistMbid: string): Promise<FollowState> {
|
||||
return api.get<FollowState>(`/api/admin/follows/${artistMbid}`);
|
||||
}
|
||||
|
||||
export function createFollowQuery(artistMbid: string) {
|
||||
return createQuery({
|
||||
queryKey: qk.adminFollow(artistMbid),
|
||||
queryFn: () => getFollow(artistMbid),
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// Follows an artist, or moves a follow to another profile. wantExisting also
|
||||
// wants what the artist has already released that the profile passes and the
|
||||
// library doesn't hold. An omitted profile is the default.
|
||||
export async function putFollow(
|
||||
artistMbid: string,
|
||||
body: { artist_name: string; profile_id?: string; want_existing?: boolean }
|
||||
): Promise<FollowState> {
|
||||
return api.put<FollowState>(`/api/admin/follows/${artistMbid}`, body);
|
||||
}
|
||||
|
||||
export async function deleteFollow(artistMbid: string): Promise<void> {
|
||||
await api.del(`/api/admin/follows/${artistMbid}`);
|
||||
}
|
||||
|
||||
export async function listReleaseProfiles(): Promise<ReleaseProfilesResponse> {
|
||||
return api.get<ReleaseProfilesResponse>('/api/admin/release-profiles');
|
||||
}
|
||||
|
||||
export function createReleaseProfilesQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.releaseProfiles(),
|
||||
queryFn: listReleaseProfiles,
|
||||
staleTime: 60_000
|
||||
});
|
||||
}
|
||||
|
||||
export async function createReleaseProfile(body: ReleaseProfileInput): Promise<ReleaseProfile> {
|
||||
return api.post<ReleaseProfile>('/api/admin/release-profiles', body);
|
||||
}
|
||||
|
||||
export async function updateReleaseProfile(id: string, body: ReleaseProfileInput): Promise<ReleaseProfile> {
|
||||
return api.put<ReleaseProfile>(`/api/admin/release-profiles/${id}`, body);
|
||||
}
|
||||
|
||||
export async function deleteReleaseProfile(id: string): Promise<void> {
|
||||
await api.del(`/api/admin/release-profiles/${id}`);
|
||||
}
|
||||
|
||||
// Search and grab: each want's last search, a person's Search,
|
||||
// Grab and "never this one", and the schedule's settings.
|
||||
|
||||
export async function listCandidates(wantId: string): Promise<Candidate[]> {
|
||||
const res = await api.get<{ items: Candidate[] }>(`/api/admin/wanted/${wantId}/candidates`);
|
||||
return res.items;
|
||||
}
|
||||
|
||||
export function createCandidatesQuery(wantId: string) {
|
||||
return createQuery({
|
||||
queryKey: qk.wantCandidates(wantId),
|
||||
queryFn: () => listCandidates(wantId),
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
// Searches now, as the schedule would: takes the best release when
|
||||
// auto-grab is on. Can take most of a minute.
|
||||
export async function searchWant(wantId: string): Promise<SearchResult> {
|
||||
return api.post<SearchResult>(`/api/admin/wanted/${wantId}/search`, {});
|
||||
}
|
||||
|
||||
// Takes the release named by key; force takes what the verdict would not.
|
||||
export async function grabCandidate(wantId: string, key: string, force: boolean): Promise<GrabResult> {
|
||||
return api.post<GrabResult>(`/api/admin/wanted/${wantId}/grab`, { key, force });
|
||||
}
|
||||
|
||||
// Never takes this release again, for any want.
|
||||
export async function blockCandidate(wantId: string, key: string): Promise<void> {
|
||||
await api.post(`/api/admin/wanted/${wantId}/block`, { key });
|
||||
}
|
||||
|
||||
export async function unblockRelease(infoHash: string): Promise<void> {
|
||||
await api.del(`/api/admin/release-blocks/${infoHash}`);
|
||||
}
|
||||
|
||||
export async function getSearchSettings(): Promise<SearchSettings> {
|
||||
return api.get<SearchSettings>('/api/admin/acquisition/settings');
|
||||
}
|
||||
|
||||
export function createSearchSettingsQuery() {
|
||||
return createQuery({
|
||||
queryKey: qk.searchSettings(),
|
||||
queryFn: getSearchSettings,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
|
||||
export async function putSearchSettings(body: {
|
||||
auto_grab: boolean;
|
||||
search_interval_hours: number;
|
||||
allowed_qualities: string[];
|
||||
import_root: string;
|
||||
seed_ratio: number;
|
||||
seed_days: number;
|
||||
stall_hours: number;
|
||||
upgrade_until: string;
|
||||
}): Promise<SearchSettings> {
|
||||
return api.put<SearchSettings>('/api/admin/acquisition/settings', body);
|
||||
}
|
||||
|
||||
// Downloads and their imports ----------------------------------
|
||||
|
||||
// A page holding fewer than it asked for is the last.
|
||||
function nextOffset(last: { items: unknown[]; limit: number; offset: number }): number | undefined {
|
||||
return last.items.length < last.limit ? undefined : last.offset + last.items.length;
|
||||
}
|
||||
|
||||
export async function listDownloads(offset: number = 0): Promise<DownloadsPage> {
|
||||
return api.get<DownloadsPage>(`/api/admin/downloads?offset=${offset}`);
|
||||
}
|
||||
|
||||
// Running downloads first; refreshed every few seconds while one runs.
|
||||
export function createDownloadsQuery() {
|
||||
return createInfiniteQuery({
|
||||
queryKey: qk.downloads(),
|
||||
queryFn: ({ pageParam }) => listDownloads(pageParam as number),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: nextOffset,
|
||||
refetchInterval: (q) =>
|
||||
q.state.data?.pages[0]?.items.some((d) => !d.ended_at) ? 5_000 : false
|
||||
});
|
||||
}
|
||||
|
||||
export async function importAnyway(id: string): Promise<void> {
|
||||
await api.post(`/api/admin/downloads/${id}/import`, {});
|
||||
}
|
||||
|
||||
export async function retryImport(id: string): Promise<void> {
|
||||
await api.post(`/api/admin/downloads/${id}/retry`, {});
|
||||
}
|
||||
|
||||
export async function refuseDownload(id: string): Promise<void> {
|
||||
await api.post(`/api/admin/downloads/${id}/refuse`, {});
|
||||
}
|
||||
|
||||
// A running download given up: the release is set aside for good, the
|
||||
// download removed and the album searched for again.
|
||||
export async function abandonDownload(id: string): Promise<void> {
|
||||
await api.post(`/api/admin/downloads/${id}/abandon`, {});
|
||||
}
|
||||
|
||||
export async function listReleaseBlocks(offset: number = 0): Promise<ReleaseBlocksPage> {
|
||||
return api.get<ReleaseBlocksPage>(`/api/admin/release-blocks?offset=${offset}`);
|
||||
}
|
||||
|
||||
export function createReleaseBlocksQuery() {
|
||||
return createInfiniteQuery({
|
||||
queryKey: qk.releaseBlocks(),
|
||||
queryFn: ({ pageParam }) => listReleaseBlocks(pageParam as number),
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: nextOffset,
|
||||
staleTime: 30_000
|
||||
});
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
addAcquisitionService,
|
||||
listAcquisitionServices,
|
||||
type AcquisitionProtocol,
|
||||
type AcquisitionService
|
||||
} from '#lib/api/admin.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import AcquisitionServiceRow from './AcquisitionServiceRow.svelte';
|
||||
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
|
||||
|
||||
// Where Minstrel looks for music and what downloads it: two lists of
|
||||
// connections an admin adds and configures. Nothing is seeded or copied. A
|
||||
// FabledExchange is one entry under download clients, with a switch for each
|
||||
// of its jobs.
|
||||
|
||||
let services = $state<AcquisitionService[] | null>(null);
|
||||
let loadError = $state(false);
|
||||
let adding = $state<'search' | 'download' | null>(null);
|
||||
|
||||
const indexers = $derived((services ?? []).filter((s) => s.kind === 'search'));
|
||||
const clients = $derived((services ?? []).filter((s) => s.kind === 'download'));
|
||||
const searchingExchanges = $derived(
|
||||
clients.filter((s) => s.protocol === 'exchange' && s.serves_search)
|
||||
);
|
||||
const canSearch = $derived(
|
||||
(services ?? []).some(
|
||||
(s) => s.usable && (s.protocol === 'exchange' ? s.serves_search : s.kind === 'search')
|
||||
)
|
||||
);
|
||||
const canFetch = $derived(
|
||||
(services ?? []).some(
|
||||
(s) => s.usable && (s.protocol === 'exchange' ? s.serves_downloads : s.kind === 'download')
|
||||
)
|
||||
);
|
||||
|
||||
const choices: Record<
|
||||
'search' | 'download',
|
||||
{ protocol: AcquisitionProtocol; name: string; note: string }[]
|
||||
> = {
|
||||
search: [
|
||||
{
|
||||
protocol: 'prowlarr',
|
||||
name: 'Prowlarr',
|
||||
note: 'Suggested. Every indexer you have set up in Prowlarr, asked in one search.'
|
||||
},
|
||||
{
|
||||
protocol: 'torznab',
|
||||
name: 'Torznab feed',
|
||||
note: 'Jackett, or a single indexer you point at directly.'
|
||||
}
|
||||
],
|
||||
download: [
|
||||
{
|
||||
protocol: 'qbittorrent',
|
||||
name: 'qBittorrent',
|
||||
note: 'Or anything else that speaks its WebUI.'
|
||||
},
|
||||
{
|
||||
protocol: 'exchange',
|
||||
name: 'FabledExchange',
|
||||
note: 'If you run it: one entry that downloads, searches its DHT index and checks releases. Each job can be switched off.'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
services = await listAcquisitionServices();
|
||||
loadError = false;
|
||||
} catch {
|
||||
loadError = true;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
|
||||
async function add(protocol: AcquisitionProtocol) {
|
||||
try {
|
||||
const created = await addAcquisitionService(protocol);
|
||||
adding = null;
|
||||
pushToast(`${created.label} added. Give it an address, test it, then switch it on.`);
|
||||
await load();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
const addButtonClass =
|
||||
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary';
|
||||
</script>
|
||||
|
||||
{#snippet addMenu(kind: 'search' | 'download', label: string)}
|
||||
<div class="px-4 py-3">
|
||||
{#if adding === kind}
|
||||
<div class="space-y-2" data-testid="add-{kind}">
|
||||
{#each choices[kind] as choice (choice.protocol)}
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full rounded-md border border-border px-4 py-2 text-left hover:bg-surface-hover"
|
||||
onclick={() => add(choice.protocol)}
|
||||
>
|
||||
<span class="block text-sm text-text-primary">{choice.name}</span>
|
||||
<span class="block text-xs text-text-secondary">{choice.note}</span>
|
||||
</button>
|
||||
{/each}
|
||||
<button type="button" class="text-sm text-text-secondary underline hover:no-underline" onclick={() => (adding = null)}
|
||||
>Cancel</button
|
||||
>
|
||||
</div>
|
||||
{:else}
|
||||
<button type="button" class={addButtonClass} onclick={() => (adding = kind)}>{label}</button>
|
||||
{/if}
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<div class="space-y-6" data-testid="acquisition-card">
|
||||
{#if loadError}
|
||||
<p class="text-sm text-error-fg">
|
||||
Couldn't load indexers and download clients.
|
||||
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
|
||||
</p>
|
||||
{:else if services === null}
|
||||
<p class="text-sm text-text-secondary">Loading indexers and download clients…</p>
|
||||
{:else}
|
||||
<!-- The verdict first: can music be found and downloaded at all. -->
|
||||
<p class="text-sm" data-testid="acquisition-health">
|
||||
{#if !canFetch}
|
||||
<span class="text-error-fg">No download client is switched on, so nothing can be downloaded.</span>
|
||||
{:else if !canSearch}
|
||||
<span class="text-error-fg">No indexer is switched on, so nothing new can be found.</span>
|
||||
{:else}
|
||||
<span class="text-text-secondary">Music can be searched for and downloaded.</span>
|
||||
{/if}
|
||||
</p>
|
||||
|
||||
<div data-testid="indexers">
|
||||
<SettingsGroup title="Indexers" id="indexers" hint="Where music is looked for. Every one switched on is searched.">
|
||||
{#each indexers as service (service.code)}
|
||||
<AcquisitionServiceRow {service} onChanged={load} />
|
||||
{:else}
|
||||
<p class="px-4 py-3 text-sm text-text-secondary">No indexer yet. Prowlarr is the usual choice.</p>
|
||||
{/each}
|
||||
{#if searchingExchanges.length > 0}
|
||||
<p class="px-4 py-3 text-xs text-text-secondary">
|
||||
Also searched: {searchingExchanges.map((s) => s.label).join(', ')}, under download clients.
|
||||
</p>
|
||||
{/if}
|
||||
{@render addMenu('search', 'Add indexer')}
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
|
||||
<div data-testid="download-clients">
|
||||
<SettingsGroup title="Download clients" id="download-clients" hint="What a grab is handed to.">
|
||||
{#each clients as service (service.code)}
|
||||
<AcquisitionServiceRow {service} onChanged={load} />
|
||||
{:else}
|
||||
<p class="px-4 py-3 text-sm text-text-secondary">No download client yet.</p>
|
||||
{/each}
|
||||
{@render addMenu('download', 'Add download client')}
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,168 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, within } from '@testing-library/svelte';
|
||||
import type { AcquisitionService } from '#lib/api/admin.js';
|
||||
|
||||
vi.mock('#lib/api/admin.js', () => ({
|
||||
listAcquisitionServices: vi.fn(),
|
||||
addAcquisitionService: vi.fn(),
|
||||
updateAcquisitionService: vi.fn(),
|
||||
removeAcquisitionService: vi.fn(),
|
||||
testAcquisitionService: vi.fn(),
|
||||
setAcquisitionSecret: vi.fn(),
|
||||
clearAcquisitionSecret: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import AcquisitionCard from './AcquisitionCard.svelte';
|
||||
import {
|
||||
addAcquisitionService,
|
||||
listAcquisitionServices,
|
||||
setAcquisitionSecret,
|
||||
testAcquisitionService,
|
||||
updateAcquisitionService
|
||||
} from '#lib/api/admin.js';
|
||||
|
||||
function service(over: Partial<AcquisitionService> = {}): AcquisitionService {
|
||||
return {
|
||||
code: 'prowlarr',
|
||||
kind: 'search',
|
||||
protocol: 'prowlarr',
|
||||
label: 'Prowlarr',
|
||||
enabled: false,
|
||||
base_url: '',
|
||||
has_api_key: false,
|
||||
has_password: false,
|
||||
username: '',
|
||||
category: '',
|
||||
timeout_ms: 60000,
|
||||
serves_search: true,
|
||||
serves_downloads: true,
|
||||
serves_enrichment: true,
|
||||
local_path: '/downloads',
|
||||
remote_path: '',
|
||||
searches_per_hour: 120,
|
||||
usable: false,
|
||||
...over
|
||||
};
|
||||
}
|
||||
|
||||
const exchange = (over: Partial<AcquisitionService> = {}) =>
|
||||
service({
|
||||
code: 'exchange',
|
||||
kind: 'download',
|
||||
protocol: 'exchange',
|
||||
label: 'FabledExchange',
|
||||
category: 'minstrel',
|
||||
searches_per_hour: 0,
|
||||
...over
|
||||
});
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
async function renderCard(services: AcquisitionService[]) {
|
||||
vi.mocked(listAcquisitionServices).mockResolvedValue(services);
|
||||
render(AcquisitionCard);
|
||||
await screen.findByTestId('acquisition-health');
|
||||
}
|
||||
|
||||
describe('AcquisitionCard', () => {
|
||||
test('starts empty: nothing is seeded', async () => {
|
||||
await renderCard([]);
|
||||
expect(screen.getByText(/no indexer yet/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/no download client yet/i)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('acquisition-health')).toHaveTextContent(/nothing can be downloaded/i);
|
||||
});
|
||||
|
||||
test('adding offers the types each list takes', async () => {
|
||||
await renderCard([]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Add indexer' }));
|
||||
const indexerChoices = within(screen.getByTestId('add-search'));
|
||||
expect(indexerChoices.getByRole('button', { name: /prowlarr/i })).toBeInTheDocument();
|
||||
expect(indexerChoices.getByRole('button', { name: /torznab feed/i })).toBeInTheDocument();
|
||||
expect(indexerChoices.queryByRole('button', { name: /qbittorrent/i })).toBeNull();
|
||||
|
||||
vi.mocked(addAcquisitionService).mockResolvedValue(service());
|
||||
await fireEvent.click(indexerChoices.getByRole('button', { name: /prowlarr/i }));
|
||||
expect(addAcquisitionService).toHaveBeenCalledWith('prowlarr');
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Add download client' }));
|
||||
const clientChoices = within(screen.getByTestId('add-download'));
|
||||
expect(clientChoices.getByRole('button', { name: /qbittorrent/i })).toBeInTheDocument();
|
||||
expect(clientChoices.getByRole('button', { name: /fabledexchange/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('an exchange sits under download clients with a switch per job; others have none', async () => {
|
||||
await renderCard([
|
||||
service({ code: 'qbittorrent', kind: 'download', protocol: 'qbittorrent', label: 'qBittorrent' }),
|
||||
exchange()
|
||||
]);
|
||||
const clients = within(screen.getByTestId('download-clients'));
|
||||
expect(clients.getAllByTestId('acquisition-service')).toHaveLength(2);
|
||||
// Only the exchange carries the job switches.
|
||||
expect(clients.getAllByTestId('exchange-jobs')).toHaveLength(1);
|
||||
expect(clients.getByRole('checkbox', { name: /downloads what is grabbed/i })).toBeChecked();
|
||||
expect(clients.getByRole('checkbox', { name: /searches its dht index/i })).toBeChecked();
|
||||
expect(clients.getByRole('checkbox', { name: /checks a release/i })).toBeChecked();
|
||||
// qBittorrent asks for a username and a password; the exchange for an optional key.
|
||||
expect(clients.getByText('Username')).toBeInTheDocument();
|
||||
expect(clients.getByText(/save password/i)).toBeInTheDocument();
|
||||
expect(clients.getByText(/save key/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('an exchange searching is named under indexers too', async () => {
|
||||
await renderCard([exchange({ usable: true, enabled: true, base_url: 'http://ex' })]);
|
||||
expect(within(screen.getByTestId('indexers')).getByText(/also searched: fabledexchange/i)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('acquisition-health')).toHaveTextContent(/searched for and downloaded/i);
|
||||
});
|
||||
|
||||
test('switching a job off and saving sends the switches', async () => {
|
||||
const ex = exchange({ base_url: 'http://ex' });
|
||||
await renderCard([ex]);
|
||||
await fireEvent.click(screen.getByRole('checkbox', { name: /checks a release/i }));
|
||||
vi.mocked(updateAcquisitionService).mockResolvedValue({ ...ex, serves_enrichment: false });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
|
||||
await waitFor(() => expect(updateAcquisitionService).toHaveBeenCalled());
|
||||
const [code, sent] = vi.mocked(updateAcquisitionService).mock.calls[0];
|
||||
expect(code).toBe('exchange');
|
||||
expect(sent).toMatchObject({ serves_enrichment: false, serves_search: true, serves_downloads: true });
|
||||
});
|
||||
|
||||
test('a refused setting is shown beside the form in the server’s words', async () => {
|
||||
await renderCard([service({ base_url: 'http://p' })]);
|
||||
await fireEvent.input(screen.getByRole('textbox', { name: /^name$/i }), {
|
||||
target: { value: 'Mine' }
|
||||
});
|
||||
vi.mocked(updateAcquisitionService).mockRejectedValue({
|
||||
code: 'invalid_setting',
|
||||
message: 'Address: start with http:// or https://.',
|
||||
status: 400
|
||||
});
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
|
||||
expect(await screen.findByTestId('acquisition-problem')).toHaveTextContent(
|
||||
'Address: start with http:// or https://.'
|
||||
);
|
||||
});
|
||||
|
||||
test('Test shows what the server found, and needs an address', async () => {
|
||||
await renderCard([service({ code: 'a' }), service({ code: 'b', label: 'Second', base_url: 'http://p' })]);
|
||||
const [noAddress, addressed] = screen.getAllByRole('button', { name: 'Test' });
|
||||
expect(noAddress).toBeDisabled();
|
||||
vi.mocked(testAcquisitionService).mockResolvedValue({
|
||||
ok: false,
|
||||
detail: 'the API key was refused: HTTP 401. Check it on the service’s own settings page.'
|
||||
});
|
||||
await fireEvent.click(addressed);
|
||||
expect(testAcquisitionService).toHaveBeenCalledWith('b');
|
||||
expect(await screen.findByTestId('acquisition-test-result')).toHaveTextContent(/key was refused/i);
|
||||
});
|
||||
|
||||
test('a key is sent write-only and never shown back', async () => {
|
||||
await renderCard([service({ base_url: 'http://p', has_api_key: true })]);
|
||||
expect(screen.getByLabelText(/replace the api key/i)).toHaveValue('');
|
||||
await fireEvent.input(screen.getByLabelText(/replace the api key/i), { target: { value: 'k2' } });
|
||||
vi.mocked(setAcquisitionSecret).mockResolvedValue(undefined);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /save key/i }));
|
||||
await waitFor(() => expect(setAcquisitionSecret).toHaveBeenCalledWith('prowlarr', 'api-key', 'k2'));
|
||||
});
|
||||
});
|
||||
@@ -1,394 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import {
|
||||
clearAcquisitionSecret,
|
||||
removeAcquisitionService,
|
||||
setAcquisitionSecret,
|
||||
testAcquisitionService,
|
||||
updateAcquisitionService,
|
||||
type AcquisitionService,
|
||||
type AcquisitionTestResult,
|
||||
type AcquisitionUpdate
|
||||
} from '#lib/api/admin.js';
|
||||
import { errCode, errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
|
||||
// One indexer or download client. The form is a copy of the
|
||||
// saved row, so Save is only offered when something changed. Secrets are
|
||||
// write-only: the server says whether one is set and never what it is.
|
||||
|
||||
let {
|
||||
service,
|
||||
onChanged
|
||||
}: { service: AcquisitionService; onChanged: () => void | Promise<void> } = $props();
|
||||
|
||||
function formOf(s: AcquisitionService): AcquisitionUpdate {
|
||||
return {
|
||||
label: s.label,
|
||||
enabled: s.enabled,
|
||||
base_url: s.base_url,
|
||||
username: s.username,
|
||||
category: s.category,
|
||||
timeout_ms: s.timeout_ms,
|
||||
serves_search: s.serves_search,
|
||||
serves_downloads: s.serves_downloads,
|
||||
serves_enrichment: s.serves_enrichment,
|
||||
local_path: s.local_path,
|
||||
remote_path: s.remote_path,
|
||||
searches_per_hour: s.searches_per_hour
|
||||
};
|
||||
}
|
||||
|
||||
// The row is keyed by code in the list, so the first value is the one to
|
||||
// start from; after a save the form takes the saved row.
|
||||
let form = $state<AcquisitionUpdate>(untrack(() => formOf(service)));
|
||||
let secret = $state('');
|
||||
let saving = $state(false);
|
||||
let testing = $state(false);
|
||||
let confirmRemove = $state(false);
|
||||
let problem = $state('');
|
||||
let result = $state<AcquisitionTestResult | null>(null);
|
||||
|
||||
const isExchange = $derived(service.protocol === 'exchange');
|
||||
const isQbit = $derived(service.protocol === 'qbittorrent');
|
||||
const searches = $derived(isExchange ? form.serves_search : service.kind === 'search');
|
||||
const fetches = $derived(isExchange ? form.serves_downloads : service.kind === 'download');
|
||||
const dirty = $derived(JSON.stringify(form) !== JSON.stringify(formOf(service)));
|
||||
const secretWhich = $derived<'api-key' | 'password'>(isQbit ? 'password' : 'api-key');
|
||||
const secretSet = $derived(isQbit ? service.has_password : service.has_api_key);
|
||||
|
||||
const placeholder: Record<string, string> = {
|
||||
prowlarr: 'http://prowlarr:9696',
|
||||
torznab: 'http://jackett:9117/api/v2.0/indexers/name/results/torznab/api',
|
||||
qbittorrent: 'http://qbittorrent:8080',
|
||||
exchange: 'http://fabledexchange:8080'
|
||||
};
|
||||
|
||||
const blurb: Record<string, string> = {
|
||||
prowlarr:
|
||||
"Asked through Prowlarr's own API, which searches every indexer you have set up in Prowlarr at once.",
|
||||
torznab:
|
||||
'A single Torznab feed: Jackett, or one indexer you point at directly. Anything that serves the open standard works.',
|
||||
qbittorrent:
|
||||
'Your qBittorrent, or anything else that speaks its WebUI. Downloads are added with the save path already set, so a finished one lands where Minstrel looks.',
|
||||
exchange:
|
||||
'One FabledExchange, doing each job switched on below: it downloads what is grabbed, searches its DHT index alongside your indexers, and describes a release (its files, whether anyone is sharing it) before one is chosen.'
|
||||
};
|
||||
|
||||
const jobs = $derived(
|
||||
isExchange
|
||||
? [
|
||||
form.serves_downloads && 'Downloads',
|
||||
form.serves_search && 'Searches',
|
||||
form.serves_enrichment && 'Release details'
|
||||
].filter((j): j is string => !!j)
|
||||
: [service.kind === 'search' ? 'Searches' : 'Downloads']
|
||||
);
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
problem = '';
|
||||
try {
|
||||
const saved = await updateAcquisitionService(service.code, {
|
||||
...form,
|
||||
timeout_ms: Number(form.timeout_ms),
|
||||
searches_per_hour: Number(form.searches_per_hour)
|
||||
});
|
||||
form = formOf(saved);
|
||||
pushToast(`${saved.label} saved.`);
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
// The server names the field and what it wants; show it beside the form.
|
||||
if (errCode(e) === 'invalid_setting') problem = (e as { message?: string }).message ?? '';
|
||||
else pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function test() {
|
||||
testing = true;
|
||||
try {
|
||||
result = await testAcquisitionService(service.code);
|
||||
} catch (e) {
|
||||
result = { ok: false, detail: errMessage(e, 'The test itself could not be run.') };
|
||||
} finally {
|
||||
testing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSecret() {
|
||||
try {
|
||||
await setAcquisitionSecret(service.code, secretWhich, secret);
|
||||
secret = '';
|
||||
pushToast(isQbit ? 'Password saved.' : 'Key saved.');
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function clearSecret() {
|
||||
try {
|
||||
await clearAcquisitionSecret(service.code, secretWhich);
|
||||
pushToast(isQbit ? 'Password removed.' : 'Key removed.');
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
try {
|
||||
await removeAcquisitionService(service.code);
|
||||
pushToast(`${service.label} removed.`);
|
||||
await onChanged();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
const fieldClass = 'block text-sm';
|
||||
const inputClass =
|
||||
'mt-1 w-full rounded-md border border-border bg-background px-3 py-1.5 text-sm text-text-primary ' +
|
||||
'placeholder:text-text-muted focus:outline-hidden focus:ring-2 focus:ring-accent';
|
||||
const secretInputClass = inputClass.replace('mt-1 ', '');
|
||||
const noteClass = 'mt-1 block text-xs text-text-secondary';
|
||||
const buttonClass =
|
||||
'rounded-md px-3 py-1.5 text-sm focus-visible:outline-solid focus-visible:outline-2 ' +
|
||||
'focus-visible:outline-accent disabled:cursor-not-allowed disabled:opacity-50';
|
||||
</script>
|
||||
|
||||
<article class="space-y-3 px-4 py-3" data-testid="acquisition-service">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<label class="flex items-center gap-2">
|
||||
<input type="checkbox" bind:checked={form.enabled} aria-label="Use {form.label}" />
|
||||
<span class="text-sm font-medium text-text-primary">{form.label}</span>
|
||||
</label>
|
||||
<div class="flex flex-wrap items-center gap-2 text-xs">
|
||||
{#each jobs as job (job)}
|
||||
<span class="rounded-md border border-border px-2 py-0.5 text-text-secondary">{job}</span>
|
||||
{/each}
|
||||
{#if service.usable}
|
||||
<span class="rounded-md bg-accent-tint px-2 py-0.5 font-medium text-action-primary">On</span>
|
||||
{:else if service.enabled}
|
||||
<span class="rounded-md px-2 py-0.5 text-action-destructive">On, but no address</span>
|
||||
{:else}
|
||||
<span class="rounded-md border border-border px-2 py-0.5 text-text-muted">Off</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-xs text-text-secondary">{blurb[service.protocol]}</p>
|
||||
|
||||
<details open={!service.usable} class="group">
|
||||
<summary class="cursor-pointer text-sm text-text-secondary">Connection</summary>
|
||||
<div class="mt-3 grid gap-4 sm:grid-cols-2">
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Name</span>
|
||||
<input type="text" bind:value={form.label} class={inputClass} />
|
||||
</label>
|
||||
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Address</span>
|
||||
<input
|
||||
type="url"
|
||||
bind:value={form.base_url}
|
||||
placeholder={placeholder[service.protocol]}
|
||||
class={inputClass}
|
||||
/>
|
||||
<span class={noteClass}>
|
||||
{#if service.protocol === 'torznab'}
|
||||
The feed's whole address, up to and including /api, as Jackett or the indexer shows it.
|
||||
{:else}
|
||||
Exactly as you open it in your browser.
|
||||
{/if}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
{#if isExchange}
|
||||
<fieldset class="space-y-2 sm:col-span-2" data-testid="exchange-jobs">
|
||||
<legend class="text-sm text-text-primary">What it does here</legend>
|
||||
<label class="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input type="checkbox" bind:checked={form.serves_downloads} />
|
||||
Downloads what is grabbed
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input type="checkbox" bind:checked={form.serves_search} />
|
||||
Searches its DHT index alongside your indexers
|
||||
</label>
|
||||
<label class="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input type="checkbox" bind:checked={form.serves_enrichment} />
|
||||
Checks a release's files and sharers before one is chosen
|
||||
</label>
|
||||
</fieldset>
|
||||
{/if}
|
||||
|
||||
{#if isQbit}
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Username</span>
|
||||
<input type="text" autocomplete="off" bind:value={form.username} class={inputClass} />
|
||||
<span class={noteClass}>Empty if your WebUI does not ask for one.</span>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
{#if fetches}
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Category</span>
|
||||
<input type="text" bind:value={form.category} class={inputClass} />
|
||||
<span class={noteClass}>
|
||||
Everything Minstrel adds is filed under this, so you can tell its downloads from yours.
|
||||
</span>
|
||||
</label>
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Downloads folder, as {form.label} sees it</span>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={form.remote_path}
|
||||
placeholder={form.local_path || '/downloads'}
|
||||
class={inputClass}
|
||||
/>
|
||||
<span class={noteClass}>
|
||||
The folder it saves downloads into, by its own path. Leave empty if it is the same path
|
||||
Minstrel uses below.
|
||||
</span>
|
||||
</label>
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">The same folder, as Minstrel sees it</span>
|
||||
<input type="text" bind:value={form.local_path} class={inputClass} />
|
||||
<span class={noteClass}>
|
||||
Where that folder is mounted in Minstrel's container. Finished downloads are moved from
|
||||
here into the library. Test checks Minstrel can see it and write to it.
|
||||
</span>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
{#if searches}
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Searches per hour</span>
|
||||
<input
|
||||
type="number"
|
||||
min="0"
|
||||
max="3600"
|
||||
bind:value={form.searches_per_hour}
|
||||
class={inputClass}
|
||||
/>
|
||||
<span class={noteClass}>
|
||||
How often the search schedule may ask this one. Searches are spaced evenly, and one
|
||||
that answers "too many requests" is left alone as long as it asks. 0 means no limit.
|
||||
</span>
|
||||
</label>
|
||||
{/if}
|
||||
|
||||
<label class={fieldClass}>
|
||||
<span class="text-text-primary">Give up after (ms)</span>
|
||||
<input
|
||||
type="number"
|
||||
min="1000"
|
||||
max="300000"
|
||||
step="1000"
|
||||
bind:value={form.timeout_ms}
|
||||
class={inputClass}
|
||||
/>
|
||||
{#if searches}
|
||||
<span class={noteClass}>A search waits on every indexer behind it, so allow plenty.</span>
|
||||
{/if}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 border-t border-border pt-3 {fieldClass}">
|
||||
<label for="secret-{service.code}" class="text-text-primary">
|
||||
{#if isQbit}{secretSet ? 'Replace the password' : 'Password'}{:else}{secretSet
|
||||
? 'Replace the API key'
|
||||
: 'API key'}{/if}
|
||||
</label>
|
||||
<div class="mt-1 flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
id="secret-{service.code}"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
placeholder="Paste it here"
|
||||
bind:value={secret}
|
||||
class="{secretInputClass} max-w-xs font-mono"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} border border-border text-text-primary hover:bg-surface-hover"
|
||||
disabled={secret === ''}
|
||||
onclick={saveSecret}>{isQbit ? 'Save password' : 'Save key'}</button
|
||||
>
|
||||
{#if secretSet}
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-text-secondary underline hover:no-underline"
|
||||
onclick={clearSecret}>Remove</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
<span class={noteClass}>
|
||||
{#if service.protocol === 'prowlarr'}
|
||||
Prowlarr shows it under Settings → General.
|
||||
{:else if isExchange}
|
||||
Optional: only if your FabledExchange asks for one. Give Minstrel a key of its own there,
|
||||
so it can be revoked on its own.
|
||||
{:else if service.protocol === 'torznab'}
|
||||
Optional: only if the feed asks for one.
|
||||
{:else}
|
||||
Empty if your WebUI does not ask for one.
|
||||
{/if}
|
||||
{secretSet ? 'One is saved.' : ''} Never shown again once saved.
|
||||
</span>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
{#if problem}
|
||||
<p class="text-sm text-action-destructive" data-testid="acquisition-problem">{problem}</p>
|
||||
{/if}
|
||||
{#if result}
|
||||
<p
|
||||
class="text-sm {result.ok ? 'text-text-secondary' : 'text-action-destructive'}"
|
||||
role="status"
|
||||
data-testid="acquisition-test-result"
|
||||
>
|
||||
{result.detail}
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
{#if confirmRemove}
|
||||
<span class="text-sm text-text-secondary">
|
||||
Remove <strong>{service.label}</strong>? Minstrel forgets its address and credentials.
|
||||
Nothing on the service itself changes.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} bg-action-destructive text-action-fg hover:opacity-90"
|
||||
onclick={remove}>Yes, remove it</button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} text-text-secondary hover:bg-surface-hover"
|
||||
onclick={() => (confirmRemove = false)}>Keep it</button
|
||||
>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} text-text-secondary hover:bg-surface-hover"
|
||||
onclick={() => (confirmRemove = true)}>Remove</button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} border border-border text-text-primary hover:bg-surface-hover"
|
||||
disabled={testing || !service.base_url}
|
||||
title={service.base_url ? '' : 'Save an address first'}
|
||||
onclick={test}>{testing ? 'Testing…' : 'Test'}</button
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="{buttonClass} bg-action-secondary text-action-fg hover:opacity-90"
|
||||
disabled={!dirty || saving}
|
||||
onclick={save}>{saving ? 'Saving…' : 'Save'}</button
|
||||
>
|
||||
{/if}
|
||||
</div>
|
||||
</article>
|
||||
@@ -0,0 +1,21 @@
|
||||
<script lang="ts">
|
||||
import SectionRail from '#lib/components/SectionRail.svelte';
|
||||
import { countOf } from '#lib/admin/queues.js';
|
||||
import type { AdminSummary } from '#lib/api/types.js';
|
||||
|
||||
// The Collection's sections, down the left: the overview first, then the
|
||||
// library's health queues. Their counts come from the admin summary and are
|
||||
// accented, as they wait on a person. Missing files counts tracks.
|
||||
|
||||
let { summary }: { summary?: AdminSummary } = $props();
|
||||
|
||||
const items = $derived([
|
||||
{ href: '/collection', label: 'Overview', exact: true },
|
||||
{ href: '/collection/reports', label: 'Reports', attention: countOf(summary, 'reports') },
|
||||
{ href: '/collection/duplicates', label: 'Duplicates', attention: countOf(summary, 'duplicates') },
|
||||
{ href: '/collection/suspect-sources', label: 'Suspect sources', attention: countOf(summary, 'suspect') },
|
||||
{ href: '/collection/missing', label: 'Missing files', attention: countOf(summary, 'missing') }
|
||||
]);
|
||||
</script>
|
||||
|
||||
<SectionRail label="Collection sections" {items} />
|
||||
@@ -1,202 +0,0 @@
|
||||
<script lang="ts" module>
|
||||
export type DiscoverCardKind = 'artist' | 'album' | 'track';
|
||||
// 'snoozed' is a transient state the card flips to in place after the user
|
||||
// parks it, so the disappearance is legible and undoable rather than a card
|
||||
// silently vanishing from under the cursor. The row is gone on
|
||||
// the next refetch; the persistent way back is the snoozed list.
|
||||
export type DiscoverCardState = 'requestable' | 'kept' | 'requested' | 'snoozed';
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import { Plus, Disc3, Album, Music2, Clock } from 'lucide-svelte';
|
||||
|
||||
let {
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
imageUrl,
|
||||
// Renamed inside the component: a binding called `state` would make
|
||||
// `$state` read as a store subscription instead of the rune.
|
||||
state: cardState,
|
||||
attribution,
|
||||
onRequest,
|
||||
onSnooze,
|
||||
onUnsnooze,
|
||||
}: {
|
||||
kind: DiscoverCardKind;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
imageUrl?: string;
|
||||
state: DiscoverCardState;
|
||||
attribution?: string;
|
||||
onRequest?: () => void;
|
||||
// Omit both to get a card with no snooze affordance — the catalogue search
|
||||
// results reuse this component and have nothing to park.
|
||||
onSnooze?: () => void;
|
||||
onUnsnooze?: () => void;
|
||||
} = $props();
|
||||
|
||||
// Art comes from Minstrel's catalogue endpoint, which answers 404 when no
|
||||
// source has an image: show the icon then, not a broken image.
|
||||
// Reset when the card is reused for another result.
|
||||
let imageFailed = $state(false);
|
||||
$effect(() => {
|
||||
void imageUrl;
|
||||
imageFailed = false;
|
||||
});
|
||||
|
||||
const FallbackIcon = $derived(
|
||||
kind === 'artist' ? Disc3 : kind === 'album' ? Album : Music2
|
||||
);
|
||||
|
||||
function handleRequest() {
|
||||
if (cardState === 'requestable') onRequest?.();
|
||||
}
|
||||
</script>
|
||||
|
||||
<article
|
||||
class="card rounded-lg border border-border bg-surface p-3"
|
||||
data-state={cardState}
|
||||
>
|
||||
<div
|
||||
class="art flex aspect-square w-full items-center justify-center overflow-hidden rounded-md bg-surface-hover"
|
||||
>
|
||||
{#if imageUrl && !imageFailed}
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
class="h-full w-full object-cover"
|
||||
onerror={() => (imageFailed = true)}
|
||||
/>
|
||||
{:else}
|
||||
<FallbackIcon size={32} strokeWidth={1} class="text-text-muted" />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="text mt-3">
|
||||
<div class="title text-base font-medium text-text-primary">{title}</div>
|
||||
{#if subtitle}
|
||||
<div class="subtitle text-sm text-text-secondary">{subtitle}</div>
|
||||
{/if}
|
||||
{#if attribution}
|
||||
<div class="attribution text-xs italic text-text-secondary" data-testid="attribution">
|
||||
{attribution}
|
||||
</div>
|
||||
{/if}
|
||||
<div class="badge-row" data-testid="badge-row">
|
||||
{#if cardState === 'kept'}
|
||||
<span class="kept-pill" role="status">Kept</span>
|
||||
{:else if cardState === 'snoozed'}
|
||||
<span class="snoozed-pill" role="status">Not right now</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions pt-3" data-testid="actions">
|
||||
{#if cardState === 'snoozed'}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Bring ${title} back`}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-primary hover:bg-surface-hover focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
onclick={() => onUnsnooze?.()}
|
||||
>
|
||||
Undo
|
||||
</button>
|
||||
{:else if cardState === 'requestable'}
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Request ${title}`}
|
||||
class="flex items-center gap-1 rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg"
|
||||
onclick={handleRequest}
|
||||
>
|
||||
<Plus size={16} strokeWidth={1} /> Request
|
||||
</button>
|
||||
{#if onSnooze}
|
||||
<!--
|
||||
Icon-only to keep Request unambiguously the primary action, with
|
||||
the intent carried by the accessible name. "Not right now" is the
|
||||
whole point of the wording: this parks a suggestion, it does not
|
||||
record an opinion about the artist.
|
||||
-->
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Not right now — hide ${title} for a while`}
|
||||
title="Not right now"
|
||||
class="rounded-md border border-border p-1.5 text-text-secondary hover:bg-surface-hover hover:text-text-primary focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
onclick={() => onSnooze?.()}
|
||||
>
|
||||
<Clock size={16} strokeWidth={1} />
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if cardState === 'kept'}
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-label={`${title} is already in library`}
|
||||
onclick={handleRequest}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-muted"
|
||||
>
|
||||
In library
|
||||
</button>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
aria-label={`${title} already requested`}
|
||||
onclick={handleRequest}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-muted"
|
||||
>
|
||||
Requested
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<style>
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.badge-row {
|
||||
min-height: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.actions {
|
||||
margin-top: auto;
|
||||
}
|
||||
.kept-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
background: color-mix(in srgb, var(--fs-accent) 15%, transparent);
|
||||
color: var(--fs-accent-fg);
|
||||
}
|
||||
/* Muted rather than accented: a parked card should recede, not compete
|
||||
with the live suggestions around it. Same geometry as .kept-pill so the
|
||||
two read as one component in different states. */
|
||||
.snoozed-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
background: var(--fs-slate);
|
||||
color: var(--fs-vellum);
|
||||
}
|
||||
.card[data-state='snoozed'] {
|
||||
opacity: 0.6;
|
||||
}
|
||||
</style>
|
||||
@@ -1,188 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/svelte';
|
||||
import DiscoverResultCard from './DiscoverResultCard.svelte';
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('DiscoverResultCard', () => {
|
||||
test('requestable state renders Request button and calls onRequest on click', async () => {
|
||||
const onRequest = vi.fn();
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'artist',
|
||||
title: 'Boards of Canada',
|
||||
state: 'requestable',
|
||||
onRequest,
|
||||
},
|
||||
});
|
||||
// aria-label includes the title, so the accessible name is
|
||||
// "Request Boards of Canada".
|
||||
const btn = screen.getByRole('button', {
|
||||
name: /request boards of canada/i,
|
||||
});
|
||||
expect(btn).not.toBeDisabled();
|
||||
await fireEvent.click(btn);
|
||||
expect(onRequest).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test('kept state renders disabled "In library" button + Kept pill with role=status', () => {
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'album',
|
||||
title: 'Music Has The Right To Children',
|
||||
state: 'kept',
|
||||
},
|
||||
});
|
||||
expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled();
|
||||
// Kept pill is exposed as a status region so SR users hear it when it
|
||||
// appears.
|
||||
const status = screen.getByRole('status');
|
||||
expect(status).toBeInTheDocument();
|
||||
expect(status.textContent).toMatch(/kept/i);
|
||||
});
|
||||
|
||||
test('requested state renders disabled "Requested" button', () => {
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'track',
|
||||
title: 'Roygbiv',
|
||||
state: 'requested',
|
||||
},
|
||||
});
|
||||
expect(screen.getByRole('button', { name: /requested/i })).toBeDisabled();
|
||||
});
|
||||
|
||||
test('does not call onRequest when state is not requestable', async () => {
|
||||
const onRequest = vi.fn();
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'album',
|
||||
title: 'Geogaddi',
|
||||
state: 'kept',
|
||||
onRequest,
|
||||
},
|
||||
});
|
||||
// Button is disabled — the test still verifies onRequest isn't called even
|
||||
// if a click slips through (jsdom does not enforce :disabled at fireEvent
|
||||
// level).
|
||||
const btn = screen.getByRole('button');
|
||||
await fireEvent.click(btn);
|
||||
expect(onRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// The layout discipline (reserved badge slot + bottom-anchored actions) is
|
||||
// not asserted here: vitest's @testing-library/svelte renderer does not
|
||||
// inject the component's scoped <style> block into jsdom
|
||||
// (styleSheets.length === 0), so getComputedStyle sees nothing, and
|
||||
// asserting "CSS exists in CSS" has weak value anyway. It is checked
|
||||
// visually at the consumer page.
|
||||
|
||||
test('renders <img> when imageUrl is set', () => {
|
||||
const { container } = render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'artist',
|
||||
title: 'X',
|
||||
state: 'requestable',
|
||||
imageUrl: 'https://example.com/x.jpg',
|
||||
},
|
||||
});
|
||||
const img = container.querySelector('img') as HTMLImageElement;
|
||||
expect(img).toBeInTheDocument();
|
||||
expect(img.src).toBe('https://example.com/x.jpg');
|
||||
});
|
||||
|
||||
test('renders fallback Lucide glyph (no <img>) when imageUrl is absent', () => {
|
||||
const { container } = render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'album',
|
||||
title: 'X',
|
||||
state: 'requestable',
|
||||
},
|
||||
});
|
||||
expect(container.querySelector('img')).not.toBeInTheDocument();
|
||||
// Lucide renders an inline <svg>; verify its presence as a proxy for
|
||||
// "fallback rendered"
|
||||
expect(container.querySelector('svg')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('renders attribution line when prop is set', () => {
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'artist',
|
||||
title: 'Outsider',
|
||||
state: 'requestable',
|
||||
attribution: 'Because you liked Boards of Canada and played Aphex Twin.'
|
||||
}
|
||||
});
|
||||
expect(screen.getByTestId('attribution')).toHaveTextContent(
|
||||
'Because you liked Boards of Canada and played Aphex Twin.'
|
||||
);
|
||||
});
|
||||
|
||||
test('omits attribution line when prop is absent', () => {
|
||||
render(DiscoverResultCard, {
|
||||
props: { kind: 'artist', title: 'Outsider', state: 'requestable' }
|
||||
});
|
||||
expect(screen.queryByTestId('attribution')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// --- snooze affordance ---
|
||||
|
||||
test('snooze button appears only when onSnooze is supplied', () => {
|
||||
// The catalogue search results reuse this card and have nothing to park, so
|
||||
// the affordance must not appear unconditionally.
|
||||
render(DiscoverResultCard, {
|
||||
props: { kind: 'artist', title: 'Outsider', state: 'requestable' }
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: /not right now/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('snooze button calls onSnooze and reads as "not right now", never as a dislike', async () => {
|
||||
const onSnooze = vi.fn();
|
||||
render(DiscoverResultCard, {
|
||||
props: { kind: 'artist', title: 'Outsider', state: 'requestable', onSnooze }
|
||||
});
|
||||
const btn = screen.getByRole('button', { name: /not right now — hide outsider for a while/i });
|
||||
// A snooze is not a dislike: the accessible name must carry no verdict on
|
||||
// the music.
|
||||
expect(btn.getAttribute('aria-label')).not.toMatch(/dislike|not for me|never|hate/i);
|
||||
await fireEvent.click(btn);
|
||||
expect(onSnooze).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test('snoozed state swaps Request for Undo and shows a status pill', async () => {
|
||||
const onUnsnooze = vi.fn();
|
||||
const onRequest = vi.fn();
|
||||
render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'artist',
|
||||
title: 'Outsider',
|
||||
state: 'snoozed',
|
||||
onRequest,
|
||||
onUnsnooze
|
||||
}
|
||||
});
|
||||
expect(screen.queryByRole('button', { name: /request outsider/i })).not.toBeInTheDocument();
|
||||
const status = screen.getByRole('status');
|
||||
expect(status.textContent).toMatch(/not right now/i);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /bring outsider back/i }));
|
||||
expect(onUnsnooze).toHaveBeenCalledOnce();
|
||||
expect(onRequest).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('an image that fails to load falls back to the icon', async () => {
|
||||
const { container } = render(DiscoverResultCard, {
|
||||
props: {
|
||||
kind: 'artist',
|
||||
title: 'Boards of Canada',
|
||||
state: 'requestable',
|
||||
imageUrl: '/api/catalogue/art/artist/x',
|
||||
},
|
||||
});
|
||||
const img = container.querySelector('img');
|
||||
expect(img).not.toBeNull();
|
||||
await fireEvent.error(img!);
|
||||
expect(container.querySelector('img')).toBeNull();
|
||||
expect(container.querySelector('.art svg')).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
|
||||
type Item = { href: string; label: string };
|
||||
|
||||
// Discover and Requests are paired: discover an artist → request it. The
|
||||
// tab strip lifts both surfaces onto the same horizontal axis so the
|
||||
// operator can move between them without round-tripping through the
|
||||
// main nav.
|
||||
const items: Item[] = [
|
||||
{ href: '/discover', label: 'Discover' },
|
||||
{ href: '/requests', label: 'Requests' }
|
||||
];
|
||||
|
||||
function isActive(href: string): boolean {
|
||||
return page.url.pathname.startsWith(href);
|
||||
}
|
||||
</script>
|
||||
|
||||
<nav aria-label="Discover sections" class="border-b border-border">
|
||||
<ul class="flex gap-2">
|
||||
{#each items as item (item.href)}
|
||||
<li>
|
||||
<a
|
||||
href={item.href}
|
||||
aria-current={isActive(item.href) ? 'page' : undefined}
|
||||
class="block border-b-2 px-3 py-2 text-sm transition-colors {isActive(item.href)
|
||||
? 'border-accent text-text-primary'
|
||||
: 'border-transparent text-text-secondary hover:text-text-primary'}"
|
||||
>
|
||||
{item.label}
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</nav>
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { pageUrlModule } from '#test-utils/mocks/appState.js';
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
pageUrl: new URL('http://localhost/discover')
|
||||
}));
|
||||
|
||||
vi.mock('$app/state', () => pageUrlModule(state));
|
||||
|
||||
import DiscoverTabs from './DiscoverTabs.svelte';
|
||||
|
||||
describe('DiscoverTabs', () => {
|
||||
test('Discover tab is current on /discover', () => {
|
||||
state.pageUrl = new URL('http://localhost/discover');
|
||||
render(DiscoverTabs);
|
||||
expect(screen.getByRole('link', { name: /discover/i })).toHaveAttribute('aria-current', 'page');
|
||||
expect(screen.getByRole('link', { name: /requests/i })).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
test('Requests tab is current on /requests', () => {
|
||||
state.pageUrl = new URL('http://localhost/requests');
|
||||
render(DiscoverTabs);
|
||||
expect(screen.getByRole('link', { name: /requests/i })).toHaveAttribute('aria-current', 'page');
|
||||
expect(screen.getByRole('link', { name: /discover/i })).not.toHaveAttribute('aria-current');
|
||||
});
|
||||
|
||||
test('renders both tabs in order', () => {
|
||||
state.pageUrl = new URL('http://localhost/discover');
|
||||
render(DiscoverTabs);
|
||||
const labels = screen.getAllByRole('link').map((l) => l.textContent?.trim());
|
||||
expect(labels).toEqual(['Discover', 'Requests']);
|
||||
});
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { BellPlus, BellRing } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createFollowQuery,
|
||||
createReleaseProfilesQuery,
|
||||
putFollow,
|
||||
deleteFollow
|
||||
} from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import Modal from './Modal.svelte';
|
||||
|
||||
// Follow an artist for the wanted list: their new releases are
|
||||
// wanted, filtered by a release-type profile. Admin-only; the artist page
|
||||
// shows it when the artist carries a MusicBrainz id.
|
||||
|
||||
let { artistMbid, artistName }: { artistMbid: string; artistName: string } = $props();
|
||||
|
||||
const client = useQueryClient();
|
||||
const followStore = $derived(createFollowQuery(artistMbid));
|
||||
const follow = $derived($followStore);
|
||||
const profilesStore = createReleaseProfilesQuery();
|
||||
const profiles = $derived($profilesStore.data?.profiles ?? []);
|
||||
|
||||
const following = $derived(follow.data?.following === true);
|
||||
|
||||
let open = $state(false);
|
||||
let profileChoice = $state('');
|
||||
let wantExisting = $state(false);
|
||||
let saving = $state(false);
|
||||
|
||||
function openModal() {
|
||||
profileChoice = follow.data?.profile_id ?? profiles.find((p) => p.is_default)?.id ?? '';
|
||||
wantExisting = false;
|
||||
open = true;
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: qk.adminFollow(artistMbid) }),
|
||||
client.invalidateQueries({ queryKey: ['adminFollows'] }),
|
||||
client.invalidateQueries({ queryKey: ['adminWants'] })
|
||||
]);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
await putFollow(artistMbid, {
|
||||
artist_name: artistName,
|
||||
profile_id: profileChoice || undefined,
|
||||
want_existing: wantExisting
|
||||
});
|
||||
open = false;
|
||||
pushToast(
|
||||
wantExisting
|
||||
? `Following ${artistName}. What they've released that isn't here is wanted on the next check.`
|
||||
: `Following ${artistName}. New releases will be wanted.`
|
||||
);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function unfollow() {
|
||||
saving = true;
|
||||
try {
|
||||
await deleteFollow(artistMbid);
|
||||
open = false;
|
||||
pushToast(`No longer following ${artistName}. What was already wanted stays wanted.`);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onclick={openModal}
|
||||
disabled={follow.isPending}
|
||||
class="inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
{#if following}
|
||||
<BellRing size={14} strokeWidth={1.5} />
|
||||
Following · {follow.data?.profile_name}
|
||||
{:else}
|
||||
<BellPlus size={14} strokeWidth={1.5} />
|
||||
Follow
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<Modal title={following ? `Following ${artistName}` : `Follow ${artistName}`} {open} onClose={() => (open = false)}>
|
||||
<p class="-mt-2 text-sm text-text-secondary">
|
||||
New releases from {artistName} go on the wanted list. The profile says which kinds of
|
||||
release are wanted.
|
||||
</p>
|
||||
|
||||
<label class="mt-4 block">
|
||||
<span class="block text-sm text-text-secondary">Release-type profile</span>
|
||||
<select
|
||||
bind:value={profileChoice}
|
||||
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
>
|
||||
{#each profiles as p (p.id)}
|
||||
<option value={p.id}>{p.name}{p.is_default ? ' (default)' : ''}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="mt-3 flex items-start gap-3">
|
||||
<input type="checkbox" bind:checked={wantExisting} class="mt-1" />
|
||||
<span>
|
||||
<span class="text-sm text-text-primary">Also want what they've released that isn't here</span>
|
||||
<span class="block text-xs text-text-secondary">
|
||||
Off wants only releases from now on.
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
{#if following}
|
||||
<button
|
||||
type="button"
|
||||
onclick={unfollow}
|
||||
disabled={saving}
|
||||
class="mr-auto rounded-md px-3 py-1.5 text-sm text-text-muted hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Unfollow
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (open = false)}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={save}
|
||||
disabled={saving || !profileChoice}
|
||||
class="rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg disabled:opacity-50"
|
||||
>
|
||||
{following ? 'Save' : 'Follow'}
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -1,67 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import type { FollowState, ReleaseProfilesResponse } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createFollowQuery: vi.fn(),
|
||||
createReleaseProfilesQuery: vi.fn(),
|
||||
putFollow: vi.fn().mockResolvedValue({ following: true }),
|
||||
deleteFollow: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import FollowControl from './FollowControl.svelte';
|
||||
import {
|
||||
createFollowQuery,
|
||||
createReleaseProfilesQuery,
|
||||
deleteFollow,
|
||||
putFollow
|
||||
} from '#lib/api/wanted.js';
|
||||
|
||||
const profiles: ReleaseProfilesResponse = {
|
||||
profiles: [
|
||||
{ id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 0 },
|
||||
{ id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 }
|
||||
],
|
||||
primary_types: ['Album'],
|
||||
secondary_types: ['Live']
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(state: FollowState) {
|
||||
vi.mocked(createFollowQuery).mockReturnValue(
|
||||
mockQuery({ data: state }) as unknown as ReturnType<typeof createFollowQuery>
|
||||
);
|
||||
vi.mocked(createReleaseProfilesQuery).mockReturnValue(
|
||||
mockQuery({ data: profiles }) as unknown as ReturnType<typeof createReleaseProfilesQuery>
|
||||
);
|
||||
return render(FollowControl, { artistMbid: 'mb-blur', artistName: 'Blur' });
|
||||
}
|
||||
|
||||
describe('FollowControl', () => {
|
||||
test('follows on the default profile, wanting what is already released when asked', async () => {
|
||||
setup({ following: false });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^follow$/i }));
|
||||
expect((screen.getByLabelText(/release-type profile/i) as HTMLSelectElement).value).toBe('p-std');
|
||||
await fireEvent.click(screen.getByLabelText(/also want what they've released/i));
|
||||
const buttons = screen.getAllByRole('button', { name: /^follow$/i });
|
||||
await fireEvent.click(buttons[buttons.length - 1]);
|
||||
await waitFor(() =>
|
||||
expect(putFollow).toHaveBeenCalledWith('mb-blur', {
|
||||
artist_name: 'Blur',
|
||||
profile_id: 'p-std',
|
||||
want_existing: true
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('a followed artist shows its profile and can be unfollowed', async () => {
|
||||
setup({ following: true, profile_id: 'p-live', profile_name: 'With live' });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /following · with live/i }));
|
||||
expect((screen.getByLabelText(/release-type profile/i) as HTMLSelectElement).value).toBe('p-live');
|
||||
await fireEvent.click(screen.getByRole('button', { name: /unfollow/i }));
|
||||
await waitFor(() => expect(deleteFollow).toHaveBeenCalledWith('mb-blur'));
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
|
||||
// A small accent-tinted chip naming what something is: a request's kind,
|
||||
// a hidden track's reason. Beside StatusPill, which says where it stands.
|
||||
// A small accent-tinted chip naming what something is, such as a hidden
|
||||
// track's reason.
|
||||
let { children }: { children: Snippet } = $props();
|
||||
</script>
|
||||
|
||||
|
||||
@@ -130,12 +130,12 @@ describe('NotificationBell', () => {
|
||||
});
|
||||
|
||||
test('clicking a read item only opens it', async () => {
|
||||
setInbox([item({ read_at: new Date().toISOString(), link: '/requests' })]);
|
||||
setInbox([item({ read_at: new Date().toISOString(), link: '/collection/missing' })]);
|
||||
render(NotificationBell);
|
||||
await openPanel();
|
||||
await fireEvent.click(screen.getByTestId('notification-item'));
|
||||
|
||||
await waitFor(() => expect(goto).toHaveBeenCalledWith('/requests'));
|
||||
await waitFor(() => expect(goto).toHaveBeenCalledWith('/collection/missing'));
|
||||
expect(markNotificationRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { onMount } from 'svelte';
|
||||
import {
|
||||
getReacquisitionSettings,
|
||||
updateReacquisitionSettings,
|
||||
type ReacquisitionSettings
|
||||
} from '#lib/api/admin.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
|
||||
import SettingRow from '#lib/components/settings/SettingRow.svelte';
|
||||
|
||||
// Policy for putting an album whose files went missing back on the wanted
|
||||
// list. On Admin › Acquisition with the rest
|
||||
// of how music is got; Missing files says what it is set to and
|
||||
// links here. Searching for a want, and retrying, is the search
|
||||
// schedule's job, so there is no retry policy here.
|
||||
|
||||
const button =
|
||||
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
|
||||
const field = 'w-24 rounded-md border border-border bg-background px-2 py-1.5 text-sm';
|
||||
|
||||
let saved = $state<ReacquisitionSettings | null>(null);
|
||||
let form = $state<ReacquisitionSettings | null>(null);
|
||||
let saving = $state(false);
|
||||
let loadError = $state(false);
|
||||
|
||||
const dirty = $derived(
|
||||
!!saved && !!form && JSON.stringify(stripDerived(saved)) !== JSON.stringify(stripDerived(form))
|
||||
);
|
||||
|
||||
// unnameable_albums is server-computed and read-only; comparing it would
|
||||
// make the form look dirty whenever the library changed underneath. Listed
|
||||
// explicitly rather than destructured-and-spread so no lint rule has to be
|
||||
// argued with about an intentionally unused binding.
|
||||
function stripDerived(s: ReacquisitionSettings) {
|
||||
return {
|
||||
enabled: s.enabled,
|
||||
grace_hours: s.grace_hours,
|
||||
max_per_pass: s.max_per_pass
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
saved = await getReacquisitionSettings();
|
||||
form = { ...saved };
|
||||
loadError = false;
|
||||
} catch {
|
||||
loadError = true;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
|
||||
async function save() {
|
||||
if (!form) return;
|
||||
saving = true;
|
||||
try {
|
||||
saved = await updateReacquisitionSettings(form);
|
||||
form = { ...saved };
|
||||
pushToast('Re-acquisition settings saved.');
|
||||
} catch (e) {
|
||||
// The server validates the same ranges the database CHECKs enforce and
|
||||
// names the offending field, so surface its message rather than a
|
||||
// generic failure. errMessage, not `e.message`: the API client throws a
|
||||
// plain {code, message} object, never an Error, so an instanceof check
|
||||
// here would silently discard every reason the server gives.
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<SettingsGroup title="Missing files" id="reacquisition" hint="Put an album back on the wanted list when its files go missing.">
|
||||
{#if loadError}
|
||||
<p class="px-4 py-3 text-sm text-error-fg">
|
||||
Couldn't load re-acquisition settings.
|
||||
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
|
||||
</p>
|
||||
{:else if form === null}
|
||||
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
|
||||
{:else}
|
||||
<SettingRow label="Want missing albums back" for="reacq-enabled" hint="Per album, not per track: a lost folder is one want.">
|
||||
<input id="reacq-enabled" type="checkbox" role="switch" aria-checked={form.enabled} bind:checked={form.enabled} class="h-4 w-4 cursor-pointer accent-accent" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Wait before wanting it back" for="reacq-grace" hint="Rides out a drive that didn't mount in time.">
|
||||
<input id="reacq-grace" type="number" min="1" max="720" bind:value={form.grace_hours} class={field} />
|
||||
<span class="text-sm text-text-secondary">hours</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="Albums per sweep" for="reacq-max" hint="Each hour, so a large loss trickles in.">
|
||||
<input id="reacq-max" type="number" min="1" max="200" bind:value={form.max_per_pass} class={field} />
|
||||
</SettingRow>
|
||||
{#if saved && saved.unnameable_albums > 0}
|
||||
<!-- Said outright: otherwise rows that never get wanted read as a broken feature. -->
|
||||
<p class="px-4 py-3 text-sm text-text-primary">
|
||||
{plural(saved.unnameable_albums, 'album has', 'albums have')} missing files but no MusicBrainz ID,
|
||||
so {saved.unnameable_albums === 1 ? 'it' : 'they'} can't be wanted. Tag and re-scan to fix.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="flex justify-end px-4 py-3">
|
||||
<button type="button" class={button} disabled={!dirty || saving} onclick={save}>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</SettingsGroup>
|
||||
@@ -1,118 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import type { ReacquisitionSettings } from '#lib/api/admin.js';
|
||||
import { ERROR_COPY } from '#lib/api/error-copy.js';
|
||||
|
||||
vi.mock('#lib/api/admin.js', () => ({
|
||||
getReacquisitionSettings: vi.fn(),
|
||||
updateReacquisitionSettings: vi.fn()
|
||||
}));
|
||||
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import ReacquisitionSettingsCard from './ReacquisitionSettingsCard.svelte';
|
||||
import { getReacquisitionSettings, updateReacquisitionSettings } from '#lib/api/admin.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
|
||||
const base: ReacquisitionSettings = {
|
||||
enabled: true,
|
||||
grace_hours: 24,
|
||||
max_per_pass: 20,
|
||||
unnameable_albums: 0
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
async function renderCard(over: Partial<ReacquisitionSettings> = {}) {
|
||||
vi.mocked(getReacquisitionSettings).mockResolvedValue({ ...base, ...over });
|
||||
const r = render(ReacquisitionSettingsCard);
|
||||
await waitFor(() => expect(getReacquisitionSettings).toHaveBeenCalled());
|
||||
return r;
|
||||
}
|
||||
|
||||
describe('ReacquisitionSettingsCard', () => {
|
||||
// Searching and retrying belong to the wanted list's search schedule, so
|
||||
// the card holds no retry policy of its own.
|
||||
test('has no retry or approval settings', async () => {
|
||||
await renderCard();
|
||||
await screen.findByRole('spinbutton', { name: /wait before wanting it back/i });
|
||||
expect(screen.queryByText(/attempts/i)).toBeNull();
|
||||
expect(screen.queryByText(/retry/i)).toBeNull();
|
||||
expect(screen.queryByText(/without approval/i)).toBeNull();
|
||||
});
|
||||
|
||||
// Saving an unchanged form would be a pointless round-trip, and a live Save
|
||||
// button invites an admin to wonder whether anything happened.
|
||||
test('save is disabled until something changes', async () => {
|
||||
await renderCard();
|
||||
const save = await screen.findByRole('button', { name: /save/i });
|
||||
expect(save).toHaveProperty('disabled', true);
|
||||
|
||||
const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i });
|
||||
await fireEvent.input(grace, { target: { value: '48' } });
|
||||
await waitFor(() => expect(save).toHaveProperty('disabled', false));
|
||||
});
|
||||
|
||||
test('saving sends the edited values', async () => {
|
||||
vi.mocked(updateReacquisitionSettings).mockResolvedValue({ ...base, grace_hours: 48 });
|
||||
await renderCard();
|
||||
|
||||
const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i });
|
||||
await fireEvent.input(grace, { target: { value: '48' } });
|
||||
await fireEvent.click(await screen.findByRole('button', { name: /save/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(updateReacquisitionSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ grace_hours: 48 })
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
// The server names the offending field ("grace_hours must be 1-720"); a
|
||||
// generic "couldn't save" would throw that away.
|
||||
//
|
||||
// Rejects with what api.put actually throws — a plain {code, message, status}
|
||||
// object, not an Error. Rejecting with an Error, which no code path
|
||||
// produces, would let this pass while the card discarded every server
|
||||
// message.
|
||||
test('a rejected save surfaces the server message', async () => {
|
||||
const message = 'grace_hours must be 1-720';
|
||||
vi.mocked(updateReacquisitionSettings).mockRejectedValue({
|
||||
code: 'invalid_setting',
|
||||
message,
|
||||
status: 400
|
||||
});
|
||||
await renderCard();
|
||||
|
||||
const grace = screen.getByRole('spinbutton', { name: /wait before wanting it back/i });
|
||||
await fireEvent.input(grace, { target: { value: '900' } });
|
||||
await fireEvent.click(await screen.findByRole('button', { name: /save/i }));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(pushToast).toHaveBeenCalledWith(`${ERROR_COPY.invalid_setting} ${message}`, 'error')
|
||||
);
|
||||
});
|
||||
|
||||
// Without this an admin watches those albums never get wanted and
|
||||
// reasonably concludes the feature is broken.
|
||||
test('unnameable albums are called out with the reason', async () => {
|
||||
await renderCard({ unnameable_albums: 3 });
|
||||
await waitFor(() => expect(screen.getByText(/no\s+MusicBrainz ID/i)).toBeTruthy());
|
||||
expect(screen.getByText(/3\s+albums have/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
test('no warning when every missing album is identifiable', async () => {
|
||||
await renderCard({ unnameable_albums: 0 });
|
||||
await screen.findByRole('spinbutton', { name: /wait before wanting it back/i });
|
||||
expect(screen.queryByText(/MusicBrainz ID/i)).toBeNull();
|
||||
});
|
||||
|
||||
test('a failed load offers a retry rather than an empty card', async () => {
|
||||
vi.mocked(getReacquisitionSettings).mockRejectedValue(new Error('nope'));
|
||||
render(ReacquisitionSettingsCard);
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/couldn't load re-acquisition settings/i)).toBeTruthy()
|
||||
);
|
||||
expect(screen.getByRole('button', { name: /try again/i })).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,233 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createReleaseProfilesQuery,
|
||||
createReleaseProfile,
|
||||
updateReleaseProfile,
|
||||
deleteReleaseProfile
|
||||
} from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import type { ReleaseProfile, ReleaseProfileInput } from '#lib/api/types.js';
|
||||
|
||||
// Release-type profiles: which kinds of release a followed
|
||||
// artist's new releases must be to be wanted. A release passes when its
|
||||
// primary type is ticked and so is every one of its secondary types, so a
|
||||
// profile with no secondary types wants studio releases only and leaves out
|
||||
// live recordings, compilations and remixes.
|
||||
|
||||
const client = useQueryClient();
|
||||
const store = createReleaseProfilesQuery();
|
||||
const query = $derived($store);
|
||||
const profiles = $derived(query.data?.profiles ?? []);
|
||||
const primaryTypes = $derived(query.data?.primary_types ?? []);
|
||||
const secondaryTypes = $derived(query.data?.secondary_types ?? []);
|
||||
|
||||
// The profile being edited: its id, 'new', or null when none is.
|
||||
let editing = $state<string | null>(null);
|
||||
let form = $state<ReleaseProfileInput>({ name: '', primary_types: [], secondary_types: [], is_default: false });
|
||||
let saving = $state(false);
|
||||
|
||||
function startEdit(p: ReleaseProfile) {
|
||||
editing = p.id;
|
||||
form = {
|
||||
name: p.name,
|
||||
primary_types: [...p.primary_types],
|
||||
secondary_types: [...p.secondary_types],
|
||||
is_default: p.is_default
|
||||
};
|
||||
}
|
||||
|
||||
function startNew() {
|
||||
editing = 'new';
|
||||
form = { name: '', primary_types: ['Album', 'EP'], secondary_types: [], is_default: false };
|
||||
}
|
||||
|
||||
function toggle(list: string[], value: string): string[] {
|
||||
return list.includes(value) ? list.filter((v) => v !== value) : [...list, value];
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await client.invalidateQueries({ queryKey: qk.releaseProfiles() });
|
||||
await client.invalidateQueries({ queryKey: ['adminFollows'] });
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving = true;
|
||||
try {
|
||||
if (editing === 'new') {
|
||||
await createReleaseProfile(form);
|
||||
pushToast(`${form.name} added.`);
|
||||
} else if (editing) {
|
||||
await updateReleaseProfile(editing, form);
|
||||
pushToast(`${form.name} saved. Followed artists judge new releases by it from their next check.`);
|
||||
}
|
||||
editing = null;
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(p: ReleaseProfile) {
|
||||
try {
|
||||
await deleteReleaseProfile(p.id);
|
||||
pushToast(`${p.name} deleted.`);
|
||||
if (editing === p.id) editing = null;
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function describe(p: ReleaseProfile): string {
|
||||
const extra = p.secondary_types.length ? `, including ${p.secondary_types.join(', ')}` : ', studio only';
|
||||
return p.primary_types.join(', ') + extra;
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet editor()}
|
||||
<div class="space-y-4 rounded-lg border border-border p-4" data-testid="profile-editor">
|
||||
<label class="block">
|
||||
<span class="text-sm text-text-primary">Name</span>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={form.name}
|
||||
class="mt-1 w-full max-w-xs rounded border border-border bg-background px-2 py-1 text-sm text-text-primary
|
||||
focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-accent"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<fieldset>
|
||||
<legend class="text-sm text-text-primary">Kinds of release</legend>
|
||||
<div class="mt-1 flex flex-wrap gap-x-4 gap-y-1">
|
||||
{#each primaryTypes as t (t)}
|
||||
<label class="flex items-center gap-1.5 text-sm text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.primary_types.includes(t)}
|
||||
onchange={() => (form.primary_types = toggle(form.primary_types, t))}
|
||||
/>
|
||||
{t}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<fieldset>
|
||||
<legend class="text-sm text-text-primary">Also allow</legend>
|
||||
<span class="block text-xs text-text-secondary">
|
||||
Leave these unticked for studio releases only. A live album is wanted only when Live is
|
||||
ticked here.
|
||||
</span>
|
||||
<div class="mt-1 flex flex-wrap gap-x-4 gap-y-1">
|
||||
{#each secondaryTypes as t (t)}
|
||||
<label class="flex items-center gap-1.5 text-sm text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={form.secondary_types.includes(t)}
|
||||
onchange={() => (form.secondary_types = toggle(form.secondary_types, t))}
|
||||
/>
|
||||
{t}
|
||||
</label>
|
||||
{/each}
|
||||
</div>
|
||||
</fieldset>
|
||||
|
||||
<label class="flex items-center gap-2 text-sm text-text-secondary">
|
||||
<input type="checkbox" bind:checked={form.is_default} />
|
||||
Default for new follows
|
||||
</label>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (editing = null)}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={save}
|
||||
disabled={saving || !form.name.trim() || form.primary_types.length === 0}
|
||||
class="rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{saving ? 'Saving…' : 'Save profile'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<section class="space-y-4 rounded-xl border border-border bg-surface p-5" data-testid="release-profiles-card">
|
||||
<div>
|
||||
<h3 class="font-display text-lg font-medium text-text-primary">Release-type profiles</h3>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
Each followed artist is on one profile, which says which of their new releases are
|
||||
wanted. Requests for a specific album aren't filtered.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{#if query.isPending}
|
||||
<p class="text-sm text-text-secondary">Loading…</p>
|
||||
{:else if query.isError}
|
||||
<p class="text-sm text-action-destructive">Couldn't load the profiles.</p>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border">
|
||||
{#each profiles as p (p.id)}
|
||||
<li class="space-y-3 p-3" data-testid="profile-row">
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-text-primary">
|
||||
{p.name}
|
||||
{#if p.is_default}
|
||||
<span class="rounded-full bg-accent-tint px-2 py-0.5 text-xs text-accent-fg">Default</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-xs text-text-secondary">
|
||||
{describe(p)} · {plural(p.follow_count, 'artist', 'artists')}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => startEdit(p)}
|
||||
aria-label="Edit {p.name}"
|
||||
class="rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Edit
|
||||
</button>
|
||||
{#if !p.is_default}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => remove(p)}
|
||||
aria-label="Delete {p.name}"
|
||||
class="rounded-md px-2.5 py-1 text-xs text-text-muted hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
{#if editing === p.id}
|
||||
{@render editor()}
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if editing === 'new'}
|
||||
{@render editor()}
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
onclick={startNew}
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-primary hover:bg-surface-hover"
|
||||
>
|
||||
New profile
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
@@ -1,91 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor, within } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import type { ReleaseProfilesResponse } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createReleaseProfilesQuery: vi.fn(),
|
||||
createReleaseProfile: vi.fn().mockResolvedValue({}),
|
||||
updateReleaseProfile: vi.fn().mockResolvedValue({}),
|
||||
deleteReleaseProfile: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import ReleaseProfilesCard from './ReleaseProfilesCard.svelte';
|
||||
import {
|
||||
createReleaseProfile,
|
||||
createReleaseProfilesQuery,
|
||||
deleteReleaseProfile,
|
||||
updateReleaseProfile
|
||||
} from '#lib/api/wanted.js';
|
||||
|
||||
const data: ReleaseProfilesResponse = {
|
||||
profiles: [
|
||||
{ id: 'p-std', name: 'Standard', primary_types: ['Album', 'EP', 'Single'], secondary_types: [], is_default: true, follow_count: 3 },
|
||||
{ id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 }
|
||||
],
|
||||
primary_types: ['Album', 'EP', 'Single', 'Broadcast', 'Other'],
|
||||
secondary_types: ['Compilation', 'Live', 'Remix']
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup() {
|
||||
vi.mocked(createReleaseProfilesQuery).mockReturnValue(
|
||||
mockQuery({ data }) as unknown as ReturnType<typeof createReleaseProfilesQuery>
|
||||
);
|
||||
return render(ReleaseProfilesCard);
|
||||
}
|
||||
|
||||
describe('ReleaseProfilesCard', () => {
|
||||
test('says what each profile wants', () => {
|
||||
setup();
|
||||
const rows = screen.getAllByTestId('profile-row');
|
||||
expect(rows[0].textContent).toMatch(/studio only/i);
|
||||
expect(rows[0].textContent).toMatch(/3 artists/i);
|
||||
expect(rows[1].textContent).toMatch(/including live/i);
|
||||
});
|
||||
|
||||
// The default can't be deleted; the server refuses it, so the card doesn't offer it.
|
||||
test('the default profile has no delete button', () => {
|
||||
setup();
|
||||
expect(screen.queryByRole('button', { name: /delete standard/i })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: /delete with live/i })).toBeTruthy();
|
||||
});
|
||||
|
||||
test('editing ticks a secondary type and saves it', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /edit standard/i }));
|
||||
const editor = screen.getByTestId('profile-editor');
|
||||
await fireEvent.click(within(editor).getByLabelText('Live'));
|
||||
await fireEvent.click(within(editor).getByRole('button', { name: /save profile/i }));
|
||||
await waitFor(() =>
|
||||
expect(updateReleaseProfile).toHaveBeenCalledWith('p-std', {
|
||||
name: 'Standard',
|
||||
primary_types: ['Album', 'EP', 'Single'],
|
||||
secondary_types: ['Live'],
|
||||
is_default: true
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('a new profile is created', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /new profile/i }));
|
||||
const editor = screen.getByTestId('profile-editor');
|
||||
await fireEvent.input(within(editor).getByLabelText(/name/i), { target: { value: 'Everything live' } });
|
||||
await fireEvent.click(within(editor).getByLabelText('Live'));
|
||||
await fireEvent.click(within(editor).getByRole('button', { name: /save profile/i }));
|
||||
await waitFor(() =>
|
||||
expect(createReleaseProfile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'Everything live', secondary_types: ['Live'] })
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test('delete removes a profile', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /delete with live/i }));
|
||||
await waitFor(() => expect(deleteReleaseProfile).toHaveBeenCalledWith('p-live'));
|
||||
});
|
||||
});
|
||||
@@ -1,74 +0,0 @@
|
||||
<script lang="ts" module>
|
||||
import type { MusicRequest } from '#lib/api/types.js';
|
||||
|
||||
// A request's name for aria-labels: '—' means nothing to a screen reader,
|
||||
// so a missing title falls back to a phrase that still says what it is.
|
||||
export function requestName(r: MusicRequest): string {
|
||||
if (r.kind === 'artist') return r.artist_name;
|
||||
if (r.kind === 'album') return r.album_title ?? `this album by ${r.artist_name}`;
|
||||
return r.track_title ?? `this track by ${r.artist_name}`;
|
||||
}
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
import type { Snippet } from 'svelte';
|
||||
import { Disc3, Album, Music2 } from 'lucide-svelte';
|
||||
import StatusPill from '#lib/components/StatusPill.svelte';
|
||||
import KindPill from '#lib/components/KindPill.svelte';
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
|
||||
// One request in a list, as the requester's page and the admin queue both
|
||||
// show it: what was asked for, where it stands, and how much of it has
|
||||
// arrived. Each page supplies who or when (meta), its own extra lines
|
||||
// (details) and its own controls (actions).
|
||||
let {
|
||||
request: r,
|
||||
meta,
|
||||
testid,
|
||||
details,
|
||||
actions
|
||||
}: {
|
||||
request: MusicRequest;
|
||||
meta: string;
|
||||
testid: string;
|
||||
details?: Snippet;
|
||||
actions?: Snippet;
|
||||
} = $props();
|
||||
|
||||
const Icon = $derived(r.kind === 'artist' ? Disc3 : r.kind === 'album' ? Album : Music2);
|
||||
const title = $derived(
|
||||
r.kind === 'artist' ? r.artist_name : r.kind === 'album' ? (r.album_title ?? '—') : (r.track_title ?? '—')
|
||||
);
|
||||
</script>
|
||||
|
||||
<li class="flex items-start gap-4 p-3" data-testid={testid} data-status={r.status}>
|
||||
<div class="flex h-14 w-14 shrink-0 items-center justify-center rounded-md bg-surface-hover" aria-hidden="true">
|
||||
<Icon size={24} strokeWidth={1} class="text-text-muted" />
|
||||
</div>
|
||||
|
||||
<div class="min-w-0 flex-1 space-y-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<KindPill>{r.kind[0].toUpperCase() + r.kind.slice(1)}</KindPill>
|
||||
<StatusPill status={r.status} />
|
||||
</div>
|
||||
<div class="truncate text-base font-medium text-text-primary">{title}</div>
|
||||
<div class="truncate text-sm text-text-secondary">{meta}</div>
|
||||
{#if r.imported_album_count > 0 || r.imported_track_count > 0}
|
||||
<div class="text-sm text-accent-fg" data-testid="ingest-progress">
|
||||
{#if r.kind === 'artist'}
|
||||
{plural(r.imported_album_count, 'album', 'albums')}
|
||||
· {plural(r.imported_track_count, 'track', 'tracks')} ingested
|
||||
{:else if r.kind === 'album'}
|
||||
{plural(r.imported_track_count, 'track', 'tracks')} ingested
|
||||
{:else}
|
||||
Track ingested
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{@render details?.()}
|
||||
</div>
|
||||
|
||||
{#if actions}
|
||||
<div class="flex shrink-0 items-center gap-2">{@render actions()}</div>
|
||||
{/if}
|
||||
</li>
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import type { MusicRequest } from '#lib/api/types.js';
|
||||
import RequestRow, { requestName } from './RequestRow.svelte';
|
||||
|
||||
function req(over: Partial<MusicRequest> = {}): MusicRequest {
|
||||
return {
|
||||
id: 'r1',
|
||||
user_id: 'u1',
|
||||
status: 'approved',
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
artist_name: 'Boards of Canada',
|
||||
album_title: 'Geogaddi',
|
||||
track_title: null,
|
||||
requested_at: '2026-04-28T12:00:00Z',
|
||||
updated_at: '2026-04-28T12:00:00Z',
|
||||
imported_album_count: 0,
|
||||
imported_track_count: 0,
|
||||
...over
|
||||
};
|
||||
}
|
||||
|
||||
const text = (el: HTMLElement) => (el.textContent ?? '').replace(/\s+/g, ' ').trim();
|
||||
|
||||
// The row both Requests pages draw: the admin queue and the
|
||||
// requester's own list read the same request the same way.
|
||||
describe('RequestRow', () => {
|
||||
test('says what was asked for, where it stands, and who or when', () => {
|
||||
render(RequestRow, { request: req(), meta: 'by Boards of Canada · 4/28/2026', testid: 'request-row' });
|
||||
const row = screen.getByTestId('request-row');
|
||||
expect(row.dataset.status).toBe('approved');
|
||||
expect(text(row)).toMatch(/^Album Approved · downloading Geogaddi by Boards of Canada · 4\/28\/2026$/);
|
||||
});
|
||||
|
||||
test('says how much has arrived, in the words for each kind', () => {
|
||||
const { unmount } = render(RequestRow, {
|
||||
request: req({ kind: 'artist', imported_album_count: 3, imported_track_count: 41 }),
|
||||
meta: '',
|
||||
testid: 'r'
|
||||
});
|
||||
expect(text(screen.getByTestId('ingest-progress'))).toBe('3 albums · 41 tracks ingested');
|
||||
unmount();
|
||||
|
||||
render(RequestRow, { request: req({ kind: 'track', track_title: 'Roygbiv', imported_track_count: 1 }), meta: '', testid: 'r' });
|
||||
expect(text(screen.getByTestId('ingest-progress'))).toBe('Track ingested');
|
||||
});
|
||||
|
||||
test('nothing arrived yet says nothing about it', () => {
|
||||
render(RequestRow, { request: req(), meta: '', testid: 'r' });
|
||||
expect(screen.queryByTestId('ingest-progress')).toBeNull();
|
||||
});
|
||||
|
||||
test('a request with no title still has a name a screen reader can say', () => {
|
||||
render(RequestRow, { request: req({ album_title: null }), meta: '', testid: 'r' });
|
||||
expect(text(screen.getByTestId('r'))).toMatch(/—/);
|
||||
expect(requestName(req({ album_title: null }))).toBe('this album by Boards of Canada');
|
||||
expect(requestName(req({ kind: 'artist' }))).toBe('Boards of Canada');
|
||||
});
|
||||
});
|
||||
@@ -1,240 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { createSearchSettingsQuery, putSearchSettings } from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import type { SearchSettings } from '#lib/api/types.js';
|
||||
import SettingsGroup from '#lib/components/settings/SettingsGroup.svelte';
|
||||
import SettingRow from '#lib/components/settings/SettingRow.svelte';
|
||||
|
||||
// Searching and grabbing: how often each want is searched
|
||||
// for, whether the best release is taken without asking, and which
|
||||
// qualities are taken at all. The schedule wakes every ten minutes and
|
||||
// keeps to each indexer's searches-per-hour. A finished download is
|
||||
// checked and filed into one of the library's folders; it then
|
||||
// seeds until the ratio or the days below, and a download nobody shares
|
||||
// is given up after the hours below. A held album below "Upgrade
|
||||
// until" is searched for weekly and replaced by a better copy.
|
||||
|
||||
const client = useQueryClient();
|
||||
const button =
|
||||
'rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
|
||||
const field = 'w-20 rounded-md border border-border bg-background px-2 py-1.5 text-sm';
|
||||
const store = createSearchSettingsQuery();
|
||||
const query = $derived($store);
|
||||
|
||||
type Form = {
|
||||
auto_grab: boolean;
|
||||
search_interval_hours: number;
|
||||
allowed: string[];
|
||||
import_root: string;
|
||||
seed_ratio: number;
|
||||
seed_days: number;
|
||||
stall_hours: number;
|
||||
upgrade_until: string;
|
||||
};
|
||||
|
||||
// The form is the server's settings until edited; saved holds what a save
|
||||
// returned until the query catches up.
|
||||
let saved = $state<SearchSettings | null>(null);
|
||||
let edited = $state<Form | null>(null);
|
||||
let saving = $state(false);
|
||||
const base = $derived(saved ?? query.data ?? null);
|
||||
const form = $derived<Form | null>(edited ?? (base ? fromSettings(base) : null));
|
||||
|
||||
function fromSettings(s: SearchSettings): Form {
|
||||
return {
|
||||
auto_grab: s.auto_grab,
|
||||
search_interval_hours: s.search_interval_hours,
|
||||
allowed: [...s.allowed_qualities],
|
||||
import_root: s.import_root,
|
||||
seed_ratio: s.seed_ratio,
|
||||
seed_days: s.seed_days,
|
||||
stall_hours: s.stall_hours,
|
||||
upgrade_until: s.upgrade_until
|
||||
};
|
||||
}
|
||||
|
||||
const dirty = $derived(!!edited && !!base && JSON.stringify(edited) !== JSON.stringify(fromSettings(base)));
|
||||
|
||||
function edit(change: Partial<Form>) {
|
||||
if (form) edited = { ...form, ...change };
|
||||
}
|
||||
|
||||
function toggle(tier: string) {
|
||||
if (!form) return;
|
||||
edit({ allowed: form.allowed.includes(tier) ? form.allowed.filter((t) => t !== tier) : [...form.allowed, tier] });
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!form) return;
|
||||
saving = true;
|
||||
try {
|
||||
saved = await putSearchSettings({
|
||||
auto_grab: form.auto_grab,
|
||||
search_interval_hours: Number(form.search_interval_hours),
|
||||
allowed_qualities: form.allowed,
|
||||
import_root: form.import_root,
|
||||
seed_ratio: Number(form.seed_ratio),
|
||||
seed_days: Number(form.seed_days),
|
||||
stall_hours: Number(form.stall_hours),
|
||||
upgrade_until: form.upgrade_until
|
||||
});
|
||||
edited = null;
|
||||
await client.invalidateQueries({ queryKey: qk.searchSettings() });
|
||||
pushToast('Search settings saved. The next pass uses them.');
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function lastPass(s: SearchSettings): string {
|
||||
const p = s.last_pass;
|
||||
if (!s.last_pass_at) return 'The schedule hasn’t run yet.';
|
||||
const when = `Last pass ${relativeTime(s.last_pass_at)}`;
|
||||
if (p.off) return `${when}: the schedule is off.`;
|
||||
if (p.unconfigured) return `${when}: no indexer is set up, so nothing was searched.`;
|
||||
if (p.error) return `${when} failed: ${p.error}`;
|
||||
if (!p.looked) return `${when}: nothing was due.`;
|
||||
let said = `${when}: searched ${p.looked}, took ${p.grabbed ?? 0}, ${p.waiting ?? 0} waiting for you, ${p.nothing ?? 0} with nothing found`;
|
||||
if (p.failed) said += `, ${p.failed} failed`;
|
||||
said += '.';
|
||||
if (p.paced) said += ' It stopped to keep to your indexers’ searches per hour; the rest wait for the next pass.';
|
||||
return said;
|
||||
}
|
||||
</script>
|
||||
|
||||
<SettingsGroup title="Searching" id="searching" hint="Each wanted album is searched for, judged, and the best release downloaded.">
|
||||
{#if query.isPending}
|
||||
<p class="px-4 py-3 text-sm text-text-secondary">Loading…</p>
|
||||
{:else if query.isError || !form || !query.data}
|
||||
<p class="px-4 py-3 text-sm text-error-fg">
|
||||
Couldn't load the search settings.
|
||||
<button type="button" class="underline hover:no-underline" onclick={() => query.refetch()}>Try again</button>
|
||||
</p>
|
||||
{:else}
|
||||
{@const data = query.data}
|
||||
<SettingRow label="Last pass">
|
||||
{#snippet hint()}<span data-testid="last-pass">{lastPass(data)}</span>{/snippet}
|
||||
<a href="/collection/wanted" class="text-sm text-accent-fg hover:underline">Wanted</a>
|
||||
</SettingRow>
|
||||
<SettingRow label="Take the best release without asking" for="search-auto" hint="Off, you choose from the Wanted page.">
|
||||
<input
|
||||
id="search-auto"
|
||||
type="checkbox"
|
||||
role="switch"
|
||||
aria-checked={form.auto_grab}
|
||||
checked={form.auto_grab}
|
||||
onchange={(e) => edit({ auto_grab: e.currentTarget.checked })}
|
||||
class="h-4 w-4 cursor-pointer accent-accent"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="Search again after" for="search-interval" hint="For an album still wanted. 0 turns the schedule off.">
|
||||
<input
|
||||
id="search-interval"
|
||||
type="number"
|
||||
min="0"
|
||||
max="720"
|
||||
value={form.search_interval_hours}
|
||||
oninput={(e) => edit({ search_interval_hours: Number(e.currentTarget.value) })}
|
||||
class={field}
|
||||
/>
|
||||
<span class="text-sm text-text-secondary">hours</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="Qualities to take" hint="The best of these is taken first." />
|
||||
{#each data.tiers as t (t.tier)}
|
||||
<div class="pl-4">
|
||||
<SettingRow label={t.label} for="tier-{t.tier}" hint={t.what}>
|
||||
<input
|
||||
id="tier-{t.tier}"
|
||||
type="checkbox"
|
||||
checked={form.allowed.includes(t.tier)}
|
||||
onchange={() => toggle(t.tier)}
|
||||
class="h-4 w-4 cursor-pointer accent-accent"
|
||||
/>
|
||||
</SettingRow>
|
||||
</div>
|
||||
{/each}
|
||||
<SettingRow
|
||||
label="Upgrade until"
|
||||
for="upgrade-until"
|
||||
hint="An album you have below this is searched for weekly and replaced by a better copy. A video rip is always replaced."
|
||||
>
|
||||
<select
|
||||
id="upgrade-until"
|
||||
value={form.upgrade_until}
|
||||
onchange={(e) => edit({ upgrade_until: e.currentTarget.value })}
|
||||
class="rounded-md border border-border bg-background px-2 py-1.5 text-sm"
|
||||
>
|
||||
<option value="">Don't upgrade</option>
|
||||
{#each data.tiers.filter((t) => t.tier !== 'unknown') as t (t.tier)}
|
||||
<option value={t.tier}>{t.label}</option>
|
||||
{/each}
|
||||
</select>
|
||||
<a href="/collection/upgrades" class="text-sm text-accent-fg hover:underline">Upgrades</a>
|
||||
</SettingRow>
|
||||
{#if data.scan_paths.length > 1}
|
||||
<SettingRow label="File new music into" for="search-root" hint="As Artist/Album (Year), tagged with its MusicBrainz ids.">
|
||||
<select
|
||||
id="search-root"
|
||||
value={form.import_root || data.scan_paths[0]}
|
||||
onchange={(e) => edit({ import_root: e.currentTarget.value })}
|
||||
class="rounded-md border border-border bg-background px-2 py-1.5 font-mono text-sm"
|
||||
>
|
||||
{#each data.scan_paths as p (p)}
|
||||
<option value={p}>{p}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</SettingRow>
|
||||
{:else if data.scan_paths.length === 1}
|
||||
<SettingRow label="New music goes into" hint="As Artist/Album (Year), tagged with its MusicBrainz ids.">
|
||||
<span class="font-mono text-sm text-text-secondary">{data.scan_paths[0]}</span>
|
||||
</SettingRow>
|
||||
{/if}
|
||||
<SettingRow label="Seed ratio" for="seed-ratio" hint="Share a finished download to this ratio. 0 stops once it's filed.">
|
||||
<input
|
||||
id="seed-ratio"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
step="0.1"
|
||||
value={form.seed_ratio}
|
||||
oninput={(e) => edit({ seed_ratio: Number(e.currentTarget.value) })}
|
||||
class={field}
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="Seed days" for="seed-days" hint="Or for this long, whichever comes first. 0 is no limit.">
|
||||
<input
|
||||
id="seed-days"
|
||||
type="number"
|
||||
min="0"
|
||||
max="365"
|
||||
value={form.seed_days}
|
||||
oninput={(e) => edit({ seed_days: Number(e.currentTarget.value) })}
|
||||
class={field}
|
||||
/>
|
||||
<span class="text-sm text-text-secondary">days</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="Give up on a stalled download after" for="stall-hours" hint="When nobody shares it. 0 never gives up.">
|
||||
<input
|
||||
id="stall-hours"
|
||||
type="number"
|
||||
min="0"
|
||||
max="720"
|
||||
value={form.stall_hours}
|
||||
oninput={(e) => edit({ stall_hours: Number(e.currentTarget.value) })}
|
||||
class={field}
|
||||
/>
|
||||
<span class="text-sm text-text-secondary">hours</span>
|
||||
</SettingRow>
|
||||
<div class="flex justify-end px-4 py-3">
|
||||
<button type="button" class={button} onclick={save} disabled={!dirty || saving || form.allowed.length === 0}>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</SettingsGroup>
|
||||
@@ -1,127 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import type { SearchSettings } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createSearchSettingsQuery: vi.fn(),
|
||||
putSearchSettings: vi.fn()
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import SearchSettingsCard from './SearchSettingsCard.svelte';
|
||||
import { createSearchSettingsQuery, putSearchSettings } from '#lib/api/wanted.js';
|
||||
|
||||
const settings: SearchSettings = {
|
||||
auto_grab: true,
|
||||
search_interval_hours: 24,
|
||||
allowed_qualities: ['lossless', 'lossy_high'],
|
||||
tiers: [
|
||||
{ tier: 'lossless', label: 'Lossless', what: 'FLAC, ALAC' },
|
||||
{ tier: 'lossy_high', label: 'High quality lossy', what: 'MP3 320 or V0' },
|
||||
{ tier: 'unknown', label: 'Unknown', what: 'Nothing says what format it is' }
|
||||
],
|
||||
last_pass_at: new Date(Date.now() - 5 * 60_000).toISOString(),
|
||||
last_pass: { looked: 12, grabbed: 3, waiting: 2, nothing: 7, failed: 0, paced: true },
|
||||
import_root: '',
|
||||
scan_paths: ['/music', '/music2'],
|
||||
seed_ratio: 2,
|
||||
seed_days: 14,
|
||||
stall_hours: 6,
|
||||
upgrade_until: 'lossy_high'
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(s: SearchSettings = settings) {
|
||||
vi.mocked(createSearchSettingsQuery).mockReturnValue(
|
||||
mockQuery({ data: s }) as unknown as ReturnType<typeof createSearchSettingsQuery>
|
||||
);
|
||||
vi.mocked(putSearchSettings).mockImplementation(async (body) => ({ ...s, ...body }));
|
||||
return render(SearchSettingsCard);
|
||||
}
|
||||
|
||||
describe('SearchSettingsCard', () => {
|
||||
test('shows the settings and what the last pass did', () => {
|
||||
setup();
|
||||
expect((screen.getByLabelText(/take the best release without asking/i) as HTMLInputElement).checked).toBe(true);
|
||||
expect((screen.getByLabelText(/search again after/i) as HTMLInputElement).value).toBe('24');
|
||||
expect((screen.getByLabelText(/^unknown/i) as HTMLInputElement).checked).toBe(false);
|
||||
const last = screen.getByTestId('last-pass').textContent ?? '';
|
||||
expect(last).toMatch(/searched 12, took 3, 2 waiting for you, 7 with nothing found\./);
|
||||
expect(last).toMatch(/searches per hour/);
|
||||
});
|
||||
|
||||
test('saves what changed', async () => {
|
||||
setup();
|
||||
const save = screen.getByRole('button', { name: /^save$/i }) as HTMLButtonElement;
|
||||
expect(save.disabled).toBe(true);
|
||||
await fireEvent.click(screen.getByLabelText(/take the best release without asking/i));
|
||||
await fireEvent.click(screen.getByLabelText(/^unknown/i));
|
||||
await fireEvent.click(save);
|
||||
await waitFor(() =>
|
||||
expect(putSearchSettings).toHaveBeenCalledWith({
|
||||
auto_grab: false,
|
||||
search_interval_hours: 24,
|
||||
allowed_qualities: ['lossless', 'lossy_high', 'unknown'],
|
||||
import_root: '',
|
||||
seed_ratio: 2,
|
||||
seed_days: 14,
|
||||
stall_hours: 6,
|
||||
upgrade_until: 'lossy_high'
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('new music is filed into the chosen library folder, the first by default', async () => {
|
||||
setup();
|
||||
const folder = screen.getByLabelText(/file new music into/i) as HTMLSelectElement;
|
||||
expect(folder.value).toBe('/music');
|
||||
await fireEvent.change(folder, { target: { value: '/music2' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
|
||||
await waitFor(() =>
|
||||
expect(putSearchSettings).toHaveBeenCalledWith(expect.objectContaining({ import_root: '/music2' }))
|
||||
);
|
||||
});
|
||||
|
||||
test('with one library folder there is nothing to choose', () => {
|
||||
setup({ ...settings, scan_paths: ['/music'] });
|
||||
expect(screen.queryByLabelText(/file new music into/i)).toBeNull();
|
||||
expect(screen.getByText('/music')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('seeding and giving up on a stalled download are set here', async () => {
|
||||
setup();
|
||||
expect((screen.getByLabelText(/seed ratio/i) as HTMLInputElement).value).toBe('2');
|
||||
await fireEvent.input(screen.getByLabelText(/seed ratio/i), { target: { value: '1.5' } });
|
||||
await fireEvent.input(screen.getByLabelText(/seed days/i), { target: { value: '7' } });
|
||||
await fireEvent.input(screen.getByLabelText(/give up on a stalled download/i), { target: { value: '0' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
|
||||
await waitFor(() =>
|
||||
expect(putSearchSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ seed_ratio: 1.5, seed_days: 7, stall_hours: 0 })
|
||||
)
|
||||
);
|
||||
});
|
||||
|
||||
test('upgrades go up to the chosen quality, or are switched off', async () => {
|
||||
setup();
|
||||
const until = screen.getByLabelText(/upgrade until/i) as HTMLSelectElement;
|
||||
expect(until.value).toBe('lossy_high');
|
||||
expect([...until.options].map((o) => o.textContent)).toEqual([
|
||||
"Don't upgrade",
|
||||
'Lossless',
|
||||
'High quality lossy'
|
||||
]);
|
||||
await fireEvent.change(until, { target: { value: '' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
|
||||
await waitFor(() =>
|
||||
expect(putSearchSettings).toHaveBeenCalledWith(expect.objectContaining({ upgrade_until: '' }))
|
||||
);
|
||||
});
|
||||
|
||||
test('before the first pass it says so', () => {
|
||||
setup({ ...settings, last_pass_at: null, last_pass: {} });
|
||||
expect(screen.getByTestId('last-pass').textContent).toMatch(/hasn’t run yet/);
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { goto } from '$app/navigation';
|
||||
import { ChevronDown, Compass, Disc3, House, LibraryBig } from 'lucide-svelte';
|
||||
import { ChevronDown, Disc3, House, LibraryBig } from 'lucide-svelte';
|
||||
import { user, logout } from '#lib/auth/store.svelte.js';
|
||||
import { player } from '#lib/player/store.svelte.js';
|
||||
import { appName } from '#lib/branding.js';
|
||||
@@ -43,18 +43,16 @@
|
||||
}
|
||||
|
||||
// Primary nav. Sits centered in the top bar. Mirrors the Android top-app-bar
|
||||
// treatment: three first-class destinations, plus Library acting as a parent
|
||||
// treatment: two first-class destinations, with Library acting as a parent
|
||||
// for Artists / Albums / Liked / History / Playlists (tabs at
|
||||
// /library/+layout.svelte). Search + user menu live on the right side of the
|
||||
// header. Library targets the Artists tab directly so SPA navigation doesn't
|
||||
// bounce through the /library 308-redirect. isActive('/library') still
|
||||
// matches all sub-routes by prefix so the active state covers every tab.
|
||||
// Collection is an admin's: the catalogue of what the library holds and
|
||||
// wants, and what Minstrel is fetching for it.
|
||||
// Collection is an admin's: the library's health queues.
|
||||
const navItems = $derived([
|
||||
{ href: '/', label: 'Home', icon: House, matchPrefix: '/' },
|
||||
{ href: '/library/artists', label: 'Library', icon: LibraryBig, matchPrefix: '/library' },
|
||||
{ href: '/discover', label: 'Discover', icon: Compass, matchPrefix: '/discover' },
|
||||
...(user.value?.is_admin
|
||||
? [{ href: '/collection', label: 'Collection', icon: Disc3, matchPrefix: '/collection' }]
|
||||
: [])
|
||||
|
||||
@@ -53,11 +53,11 @@ describe('Shell', () => {
|
||||
expect(screen.getByText('alice')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('main nav renders the three primary surfaces in order', () => {
|
||||
test('main nav renders the primary surfaces in order', () => {
|
||||
render(Shell);
|
||||
// Library is a parent for Artists / Albums / Liked / History /
|
||||
// Playlists (tabs under /library); only the parent appears here.
|
||||
const labels = ['Home', 'Library', 'Discover'];
|
||||
const labels = ['Home', 'Library'];
|
||||
for (const label of labels) {
|
||||
expect(screen.getByRole('link', { name: label })).toBeInTheDocument();
|
||||
}
|
||||
@@ -65,10 +65,9 @@ describe('Shell', () => {
|
||||
// Library jumps to the Artists tab directly so SPA navigation
|
||||
// bypasses the /library 308-redirect.
|
||||
expect(screen.getByRole('link', { name: 'Library' })).toHaveAttribute('href', '/library/artists');
|
||||
expect(screen.getByRole('link', { name: 'Discover' })).toHaveAttribute('href', '/discover');
|
||||
});
|
||||
|
||||
test('admins get Collection after Discover; others do not', () => {
|
||||
test('admins get Collection after Library; others do not', () => {
|
||||
const primary = () =>
|
||||
screen
|
||||
.getAllByRole('link')
|
||||
@@ -79,7 +78,7 @@ describe('Shell', () => {
|
||||
unmount();
|
||||
userState.current = { id: '1', username: 'alice', is_admin: true };
|
||||
render(Shell);
|
||||
expect(primary()).toEqual(['Home', 'Library', 'Discover', 'Collection']);
|
||||
expect(primary()).toEqual(['Home', 'Library', 'Collection']);
|
||||
expect(screen.getByRole('link', { name: 'Collection' })).toHaveAttribute('href', '/collection');
|
||||
});
|
||||
|
||||
@@ -97,7 +96,7 @@ describe('Shell', () => {
|
||||
.map((el) => el.textContent?.trim());
|
||||
for (const label of [
|
||||
'Artists', 'Albums', 'Liked', 'History', 'Playlists',
|
||||
'Search', 'Requests', 'Hidden', 'Settings', 'Admin'
|
||||
'Search', 'Hidden', 'Settings', 'Admin'
|
||||
]) {
|
||||
expect(navLinks).not.toContain(label);
|
||||
}
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
<script lang="ts" module>
|
||||
import type { RequestStatus } from '#lib/api/types.js';
|
||||
|
||||
type Tone = 'warning' | 'info' | 'success' | 'error';
|
||||
|
||||
type StatusEntry = { label: string; tone: Tone };
|
||||
|
||||
// Labels in Minstrel's voice. Pending requests
|
||||
// are an "awaiting" moment, completed requests are "kept" (Minstrel-voice for
|
||||
// success), rejected is "set aside", failed is the error register.
|
||||
const STATUS_TABLE: Record<RequestStatus, StatusEntry> = {
|
||||
pending: { label: 'Awaiting review', tone: 'warning' },
|
||||
approved: { label: 'Approved · downloading', tone: 'info' },
|
||||
completed: { label: 'Kept', tone: 'success' },
|
||||
rejected: { label: 'Set aside', tone: 'error' },
|
||||
failed: { label: "Couldn't add", tone: 'error' },
|
||||
};
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
let { status }: { status: RequestStatus } = $props();
|
||||
|
||||
const entry = $derived(STATUS_TABLE[status]);
|
||||
</script>
|
||||
|
||||
<span class="pill" data-tone={entry.tone} data-status={status}>{entry.label}</span>
|
||||
|
||||
<style>
|
||||
.pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.pill[data-tone='warning'] {
|
||||
background: color-mix(in srgb, var(--fs-warning) 15%, transparent);
|
||||
color: var(--fs-warning-fg);
|
||||
}
|
||||
.pill[data-tone='info'] {
|
||||
background: color-mix(in srgb, var(--fs-info) 15%, transparent);
|
||||
color: var(--fs-info-fg);
|
||||
}
|
||||
.pill[data-tone='success'] {
|
||||
background: color-mix(in srgb, var(--fs-moss) 15%, transparent);
|
||||
color: var(--fs-success-fg);
|
||||
}
|
||||
.pill[data-tone='error'] {
|
||||
background: color-mix(in srgb, var(--fs-error) 15%, transparent);
|
||||
color: var(--fs-error-fg);
|
||||
}
|
||||
</style>
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import StatusPill from './StatusPill.svelte';
|
||||
|
||||
// Labels in Minstrel's voice, and their semantic tones.
|
||||
// Each row is the contract: input status -> rendered label + data-tone attr.
|
||||
const CASES = [
|
||||
{ status: 'pending', label: 'Awaiting review', tone: 'warning' },
|
||||
{ status: 'approved', label: 'Approved · downloading', tone: 'info' },
|
||||
{ status: 'completed', label: 'Kept', tone: 'success' },
|
||||
{ status: 'rejected', label: 'Set aside', tone: 'error' },
|
||||
{ status: 'failed', label: "Couldn't add", tone: 'error' },
|
||||
] as const;
|
||||
|
||||
describe('StatusPill', () => {
|
||||
for (const { status, label, tone } of CASES) {
|
||||
test(`${status} renders "${label}" with tone=${tone}`, () => {
|
||||
render(StatusPill, { props: { status } });
|
||||
const pill = screen.getByText(label);
|
||||
expect(pill).toBeInTheDocument();
|
||||
expect(pill.getAttribute('data-tone')).toBe(tone);
|
||||
expect(pill.getAttribute('data-status')).toBe(status);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -1,212 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createSuggestionsQuery,
|
||||
createSnoozesQuery,
|
||||
snoozeSuggestion,
|
||||
unsnoozeSuggestion
|
||||
} from '#lib/api/suggestions.js';
|
||||
import { createRequest } from '#lib/api/requests.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import DiscoverResultCard from './DiscoverResultCard.svelte';
|
||||
import type { ArtistSuggestion, SeedContribution, SuggestionSnooze } from '#lib/api/types.js';
|
||||
|
||||
const client = useQueryClient();
|
||||
const queryStore = createSuggestionsQuery();
|
||||
const query = $derived($queryStore);
|
||||
const suggestions = $derived((query.data ?? []) as ArtistSuggestion[]);
|
||||
|
||||
const snoozeStore = createSnoozesQuery();
|
||||
const snoozeQuery = $derived($snoozeStore);
|
||||
const snoozes = $derived((snoozeQuery.data ?? []) as SuggestionSnooze[]);
|
||||
|
||||
// Track MBIDs the user just requested so the card flips immediately.
|
||||
let optimisticRequested = $state(new Set<string>());
|
||||
// Snoozed-just-now MBIDs. These keep their card in place showing an Undo,
|
||||
// rather than yanking it out of the grid under the cursor — the card is
|
||||
// gone on the next refetch, and the snoozed list below is the way back
|
||||
// after that.
|
||||
let optimisticSnoozed = $state(new Set<string>());
|
||||
|
||||
function visible(s: ArtistSuggestion): boolean {
|
||||
return !optimisticRequested.has(s.mbid);
|
||||
}
|
||||
|
||||
function cardState(s: ArtistSuggestion): 'requestable' | 'snoozed' {
|
||||
return optimisticSnoozed.has(s.mbid) ? 'snoozed' : 'requestable';
|
||||
}
|
||||
|
||||
function withMbid(set: Set<string>, mbid: string, present: boolean): Set<string> {
|
||||
const next = new Set(set);
|
||||
if (present) next.add(mbid);
|
||||
else next.delete(mbid);
|
||||
return next;
|
||||
}
|
||||
|
||||
// "Matches your taste in shoegaze and dream pop." — the reason line when the
|
||||
// candidate's own tags overlap the taste profile. Preferred over seed
|
||||
// attribution because it describes the MUSIC ("sounds like what you like")
|
||||
// rather than the graph ("adjacent to something you played"). Falls back
|
||||
// when there are no matched tags, which is the common case: coverage is
|
||||
// partial by nature.
|
||||
function reasonText(s: ArtistSuggestion): string {
|
||||
const tags = s.matched_tags ?? [];
|
||||
if (tags.length === 0) return attributionText(s.attribution);
|
||||
if (tags.length === 1) return `Matches your taste in ${tags[0]}.`;
|
||||
if (tags.length === 2) return `Matches your taste in ${tags[0]} and ${tags[1]}.`;
|
||||
return `Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}.`;
|
||||
}
|
||||
|
||||
function attributionText(attribution: SeedContribution[]): string {
|
||||
if (attribution.length === 0) return '';
|
||||
const verb = (s: SeedContribution) => (s.is_liked ? 'liked' : 'played');
|
||||
const phrases = attribution.map((s) => `${verb(s)} ${s.name}`);
|
||||
if (phrases.length === 1) {
|
||||
return `Because you ${phrases[0]}.`;
|
||||
}
|
||||
if (phrases.length === 2) {
|
||||
return `Because you ${phrases[0]} and ${phrases[1]}.`;
|
||||
}
|
||||
// 3 with Oxford comma
|
||||
return `Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}.`;
|
||||
}
|
||||
|
||||
// "in 3 months" / "in 12 days" — a relative phrase, because the exact
|
||||
// calendar date of a 90-day snooze is noise the user never asked for.
|
||||
function returnsIn(snoozedUntil: string): string {
|
||||
const ms = new Date(snoozedUntil).getTime() - Date.now();
|
||||
if (!Number.isFinite(ms) || ms <= 0) return 'shortly';
|
||||
const days = Math.round(ms / 86_400_000);
|
||||
if (days < 1) return 'today';
|
||||
if (days === 1) return 'tomorrow';
|
||||
// The 30 must not exceed the divisor below, or the singular "in about a
|
||||
// month" is unreachable — a rounded month count of 1 needs 15..44 days,
|
||||
// and any higher threshold sends all of those down the days branch. This
|
||||
// read 45 and the singular case was dead code (caught by the Android
|
||||
// unit test for the same logic).
|
||||
if (days < 30) return `in ${days} days`;
|
||||
const months = Math.round(days / 30);
|
||||
return months === 1 ? 'in about a month' : `in about ${months} months`;
|
||||
}
|
||||
|
||||
async function onRequest(s: ArtistSuggestion) {
|
||||
try {
|
||||
await createRequest({
|
||||
kind: 'artist',
|
||||
artist_mbid: s.mbid,
|
||||
artist_name: s.name
|
||||
});
|
||||
optimisticRequested = withMbid(optimisticRequested, s.mbid, true);
|
||||
// The server-side filter hides this candidate on next refetch.
|
||||
await client.invalidateQueries({ queryKey: qk.suggestions() });
|
||||
} catch {
|
||||
// Swallowed: the SPA will refetch on next mount and the card
|
||||
// stays requestable so the user can retry.
|
||||
}
|
||||
}
|
||||
|
||||
async function onSnooze(s: ArtistSuggestion) {
|
||||
// Flip first so the tap feels instant, then reconcile. On failure the
|
||||
// card goes back to requestable and says so — a snooze that silently
|
||||
// did nothing would leave the user tapping it again.
|
||||
optimisticSnoozed = withMbid(optimisticSnoozed, s.mbid, true);
|
||||
try {
|
||||
await snoozeSuggestion(s.mbid, s.name);
|
||||
await client.invalidateQueries({ queryKey: qk.suggestionSnoozes() });
|
||||
} catch {
|
||||
optimisticSnoozed = withMbid(optimisticSnoozed, s.mbid, false);
|
||||
pushToast(`Couldn't hide ${s.name}`, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function onUnsnooze(mbid: string, name: string) {
|
||||
optimisticSnoozed = withMbid(optimisticSnoozed, mbid, false);
|
||||
try {
|
||||
await unsnoozeSuggestion(mbid);
|
||||
} catch (e) {
|
||||
// 404 means it wasn't snoozed after all — the user's intended end
|
||||
// state, so it isn't an error worth showing them.
|
||||
if ((e as { status?: number })?.status !== 404) {
|
||||
optimisticSnoozed = withMbid(optimisticSnoozed, mbid, true);
|
||||
pushToast(`Couldn't bring ${name} back`, 'error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: qk.suggestionSnoozes() }),
|
||||
client.invalidateQueries({ queryKey: qk.suggestions() })
|
||||
]);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div>
|
||||
<header class="mb-4 space-y-1">
|
||||
<h2 class="font-display text-2xl font-medium text-text-primary">Suggested for you</h2>
|
||||
<p class="text-text-secondary">Out-of-library artists drawn from what you've liked and played.</p>
|
||||
</header>
|
||||
|
||||
{#if !query.isPending && suggestions.length === 0}
|
||||
<!--
|
||||
An empty deck means no listening signal yet, or "you parked them all",
|
||||
and telling the second user to go listen to something would be wrong
|
||||
advice.
|
||||
-->
|
||||
<p class="text-text-secondary">
|
||||
{snoozes.length === 0
|
||||
? 'Listen to something or like an artist to start getting suggestions.'
|
||||
: "Nothing new right now — the artists you've parked are below."}
|
||||
</p>
|
||||
{:else if suggestions.length > 0}
|
||||
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||
{#each suggestions.filter(visible) as s (s.mbid)}
|
||||
<DiscoverResultCard
|
||||
kind="artist"
|
||||
title={s.name}
|
||||
imageUrl={s.image_url}
|
||||
state={cardState(s)}
|
||||
attribution={reasonText(s)}
|
||||
onRequest={() => onRequest(s)}
|
||||
onSnooze={() => onSnooze(s)}
|
||||
onUnsnooze={() => onUnsnooze(s.mbid, s.name)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!--
|
||||
The snoozed list is not a nicety: a parked suggestion is by definition
|
||||
absent from the deck above, so without this there is no way back. Only
|
||||
rendered when non-empty, so the surface stays quiet for the common case.
|
||||
-->
|
||||
{#if snoozes.length > 0}
|
||||
<section class="mt-8 border-t border-border pt-6" aria-labelledby="snoozed-heading">
|
||||
<h3 id="snoozed-heading" class="font-display text-lg font-medium text-text-primary">
|
||||
Not right now
|
||||
</h3>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
These come back on their own. Nothing here counts against your taste profile.
|
||||
</p>
|
||||
<ul class="mt-3 divide-y divide-border">
|
||||
{#each snoozes as snoozed (snoozed.mbid)}
|
||||
<li class="flex items-center justify-between gap-4 py-2">
|
||||
<div class="min-w-0">
|
||||
<div class="truncate text-sm text-text-primary">{snoozed.name}</div>
|
||||
<div class="text-xs text-text-secondary">
|
||||
Back {returnsIn(snoozed.snoozed_until)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Bring ${snoozed.name} back now`}
|
||||
class="shrink-0 rounded-md border border-border px-3 py-1.5 text-sm text-text-primary hover:bg-surface-hover focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
onclick={() => onUnsnooze(snoozed.mbid, snoozed.name)}
|
||||
>
|
||||
Bring back
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,292 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
|
||||
const invalidateMock = vi.fn();
|
||||
vi.mock('@tanstack/svelte-query', async (orig) => {
|
||||
const actual = (await orig()) as Record<string, unknown>;
|
||||
return { ...actual, useQueryClient: () => ({ invalidateQueries: invalidateMock }) };
|
||||
});
|
||||
|
||||
vi.mock('#lib/api/suggestions.js', () => ({
|
||||
createSuggestionsQuery: vi.fn(),
|
||||
createSnoozesQuery: vi.fn(),
|
||||
snoozeSuggestion: vi.fn().mockResolvedValue(undefined),
|
||||
unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/requests.js', () => ({
|
||||
createRequest: vi.fn().mockResolvedValue({})
|
||||
}));
|
||||
|
||||
const pushToastMock = vi.fn();
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({
|
||||
pushToast: (...args: unknown[]) => pushToastMock(...args)
|
||||
}));
|
||||
|
||||
import SuggestionFeed from './SuggestionFeed.svelte';
|
||||
import {
|
||||
createSuggestionsQuery,
|
||||
createSnoozesQuery,
|
||||
snoozeSuggestion,
|
||||
unsnoozeSuggestion
|
||||
} from '#lib/api/suggestions.js';
|
||||
import { createRequest } from '#lib/api/requests.js';
|
||||
import type { ArtistSuggestion, SuggestionSnooze } from '#lib/api/types.js';
|
||||
|
||||
const oneSeed: ArtistSuggestion = {
|
||||
mbid: 'mb1',
|
||||
name: 'Outsider',
|
||||
score: 1.0,
|
||||
attribution: [
|
||||
{ artist_id: 'a1', name: 'Seed', contribution: 0.9, is_liked: true, play_count: 0 }
|
||||
]
|
||||
};
|
||||
|
||||
const twoSeeds: ArtistSuggestion = {
|
||||
mbid: 'mb2',
|
||||
name: 'Outsider Two',
|
||||
score: 2.0,
|
||||
attribution: [
|
||||
{ artist_id: 'a1', name: 'A', contribution: 0.8, is_liked: true, play_count: 0 },
|
||||
{ artist_id: 'a2', name: 'B', contribution: 0.5, is_liked: false, play_count: 3 }
|
||||
]
|
||||
};
|
||||
|
||||
const threeSeeds: ArtistSuggestion = {
|
||||
mbid: 'mb3',
|
||||
name: 'Outsider Three',
|
||||
score: 3.0,
|
||||
attribution: [
|
||||
{ artist_id: 'a1', name: 'X', contribution: 0.9, is_liked: true, play_count: 0 },
|
||||
{ artist_id: 'a2', name: 'Y', contribution: 0.6, is_liked: false, play_count: 5 },
|
||||
{ artist_id: 'a3', name: 'Z', contribution: 0.3, is_liked: false, play_count: 1 }
|
||||
]
|
||||
};
|
||||
|
||||
/** Days from now as an RFC3339 string, for snooze fixtures. */
|
||||
function inDays(n: number): string {
|
||||
return new Date(Date.now() + n * 86_400_000).toISOString();
|
||||
}
|
||||
|
||||
function setSuggestions(data: ArtistSuggestion[]) {
|
||||
(createSuggestionsQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data }));
|
||||
}
|
||||
|
||||
function setSnoozes(data: SuggestionSnooze[]) {
|
||||
(createSnoozesQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data }));
|
||||
}
|
||||
|
||||
beforeEach(() => setSnoozes([]));
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('SuggestionFeed', () => {
|
||||
test('renders one card per suggestion', () => {
|
||||
setSuggestions([oneSeed, twoSeeds]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText('Outsider')).toBeInTheDocument();
|
||||
expect(screen.getByText('Outsider Two')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('attribution copy: 1 seed → "Because you liked X."', () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('attribution copy: 2 seeds → "Because you liked A and played B."', () => {
|
||||
setSuggestions([twoSeeds]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/because you liked a and played b\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('attribution copy: 3 seeds → Oxford comma', () => {
|
||||
setSuggestions([threeSeeds]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/because you liked x, played y, and played z\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Request button calls createRequest with artist-kind body', async () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /request outsider/i }));
|
||||
expect(createRequest).toHaveBeenCalledWith({
|
||||
kind: 'artist',
|
||||
artist_mbid: 'mb1',
|
||||
artist_name: 'Outsider'
|
||||
});
|
||||
expect(invalidateMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('empty state when data is []', () => {
|
||||
setSuggestions([]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/listen to something or like an artist/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SuggestionFeed snooze (#2375)', () => {
|
||||
test('snooze sends BOTH mbid and name — the server 400s without the name', async () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /not right now/i }));
|
||||
expect(snoozeSuggestion).toHaveBeenCalledWith('mb1', 'Outsider');
|
||||
});
|
||||
|
||||
test('the card stays in place showing Undo, rather than vanishing', async () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /not right now/i }));
|
||||
// Still on screen — the disappearance happens on refetch, not under the
|
||||
// cursor.
|
||||
expect(screen.getByText('Outsider')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /bring outsider back/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Not right now');
|
||||
});
|
||||
|
||||
test('a failed snooze reverts the card and says so', async () => {
|
||||
(snoozeSuggestion as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('offline'));
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /not right now/i }));
|
||||
// Back to requestable — a snooze that silently did nothing would leave
|
||||
// the user tapping it again.
|
||||
expect(screen.getByRole('button', { name: /request outsider/i })).toBeInTheDocument();
|
||||
expect(pushToastMock).toHaveBeenCalledWith("Couldn't hide Outsider", 'error');
|
||||
});
|
||||
|
||||
test('undo on the card calls unsnoozeSuggestion', async () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /not right now/i }));
|
||||
await fireEvent.click(screen.getByRole('button', { name: /bring outsider back/i }));
|
||||
expect(unsnoozeSuggestion).toHaveBeenCalledWith('mb1');
|
||||
});
|
||||
|
||||
test('the snoozed list is the way back once the card is gone', async () => {
|
||||
// Deck empty, one parked artist: exactly the state after a refetch.
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByRole('heading', { name: /not right now/i })).toBeInTheDocument();
|
||||
expect(screen.getByText('Parked')).toBeInTheDocument();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i }));
|
||||
expect(unsnoozeSuggestion).toHaveBeenCalledWith('mbX');
|
||||
});
|
||||
|
||||
test('a 404 from unsnooze is not surfaced as an error', async () => {
|
||||
(unsnoozeSuggestion as ReturnType<typeof vi.fn>).mockRejectedValueOnce({ status: 404 });
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i }));
|
||||
// Already-unsnoozed IS the end state the user asked for.
|
||||
expect(pushToastMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('a non-404 unsnooze failure does surface', async () => {
|
||||
(unsnoozeSuggestion as ReturnType<typeof vi.fn>).mockRejectedValueOnce({ status: 500 });
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'mbX', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /bring parked back now/i }));
|
||||
expect(pushToastMock).toHaveBeenCalledWith("Couldn't bring Parked back", 'error');
|
||||
});
|
||||
|
||||
test('return time reads as a relative phrase, not a calendar date', () => {
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'a', name: 'Quarter', snoozed_until: inDays(90), created_at: inDays(0) },
|
||||
{ mbid: 'b', name: 'Fortnight', snoozed_until: inDays(14), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/back in about 3 months/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/back in 14 days/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Pins the days→months seam: with a threshold above the divisor (45 vs 30),
|
||||
// no day count could round to one month without hitting the days branch
|
||||
// first, and the singular branch would be dead code. Kept in lockstep with
|
||||
// SuggestionSnoozeRefTest on Android.
|
||||
test('the days-to-months boundary sits at 30 days, so "a month" is reachable', () => {
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'a', name: 'JustUnder', snoozed_until: inDays(29), created_at: inDays(0) },
|
||||
{ mbid: 'b', name: 'JustOver', snoozed_until: inDays(30), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/back in 29 days/i)).toBeInTheDocument();
|
||||
expect(screen.getByText(/back in about a month/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('no snoozed section when nothing is parked', () => {
|
||||
setSuggestions([oneSeed]);
|
||||
setSnoozes([]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.queryByRole('heading', { name: /not right now/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// An empty deck has two causes now, and the advice differs. Telling someone
|
||||
// who parked everything to go listen to music would be wrong.
|
||||
test('empty-deck copy distinguishes "no signal" from "you parked them all"', () => {
|
||||
setSuggestions([]);
|
||||
setSnoozes([
|
||||
{ mbid: 'a', name: 'Parked', snoozed_until: inDays(90), created_at: inDays(0) }
|
||||
]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/nothing new right now/i)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/listen to something or like an artist/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SuggestionFeed taste-tag reason (#2377)', () => {
|
||||
const tagged = (over: Partial<ArtistSuggestion> = {}): ArtistSuggestion => ({
|
||||
...oneSeed,
|
||||
mbid: 'mbT',
|
||||
name: 'Tag Match',
|
||||
...over
|
||||
});
|
||||
|
||||
test('matched tags replace seed attribution as the reason line', () => {
|
||||
setSuggestions([tagged({ matched_tags: ['shoegaze', 'dream pop'] })]);
|
||||
render(SuggestionFeed);
|
||||
expect(
|
||||
screen.getByText(/matches your taste in shoegaze and dream pop\./i)
|
||||
).toBeInTheDocument();
|
||||
// The graph-adjacency line is superseded — describing the music beats
|
||||
// describing the graph when we can do both.
|
||||
expect(screen.queryByText(/because you liked/i)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('one matched tag reads in the singular', () => {
|
||||
setSuggestions([tagged({ matched_tags: ['shoegaze'] })]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/matches your taste in shoegaze\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('three matched tags use an Oxford comma, matching the seed copy', () => {
|
||||
setSuggestions([tagged({ matched_tags: ['a', 'b', 'c'] })]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/matches your taste in a, b, and c\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// The common case: most candidates have no cached tags, and the card must
|
||||
// still explain itself rather than going blank.
|
||||
test('no matched tags falls back to seed attribution', () => {
|
||||
setSuggestions([oneSeed]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('an empty matched_tags array also falls back, not to an empty line', () => {
|
||||
setSuggestions([tagged({ matched_tags: [] })]);
|
||||
render(SuggestionFeed);
|
||||
expect(screen.getByText(/because you liked seed\./i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,181 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createCandidatesQuery,
|
||||
grabCandidate,
|
||||
blockCandidate,
|
||||
unblockRelease
|
||||
} from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import { formatBytes } from '#lib/utils/bytes.js';
|
||||
import type { Candidate, CandidateVerdict, GrabResult } from '#lib/api/types.js';
|
||||
|
||||
// Every release a want's last search found, with the verdict
|
||||
// and the reasons behind it, so a person can see why nothing was taken and
|
||||
// take something anyway, or set a release aside for good.
|
||||
|
||||
let { wantId, title }: { wantId: string; title: string } = $props();
|
||||
|
||||
const client = useQueryClient();
|
||||
const store = $derived(createCandidatesQuery(wantId));
|
||||
const query = $derived($store);
|
||||
const items = $derived(query.data ?? []);
|
||||
|
||||
let busy = $state<string | null>(null);
|
||||
|
||||
const verdictLabel: Record<CandidateVerdict, string> = {
|
||||
grab: 'Would take',
|
||||
review: 'Needs you',
|
||||
refused: 'Quality refused',
|
||||
rejected: 'Not the album',
|
||||
blocked: 'Set aside'
|
||||
};
|
||||
|
||||
const verdictClass: Record<CandidateVerdict, string> = {
|
||||
grab: 'bg-accent-tint text-accent-fg',
|
||||
review: 'bg-surface-hover text-text-primary',
|
||||
refused: 'bg-surface-hover text-text-secondary',
|
||||
rejected: 'bg-surface-hover text-text-muted',
|
||||
blocked: 'bg-surface-hover text-text-muted'
|
||||
};
|
||||
|
||||
function meta(c: Candidate): string {
|
||||
// An indexer that states no size sends 0.
|
||||
const parts = [c.format || 'format not stated', c.size_bytes > 0 ? formatBytes(c.size_bytes) : ''];
|
||||
parts.push(plural(c.seeders, 'seeder', 'seeders'));
|
||||
if (c.indexer) parts.push(c.folded_from.length ? `${c.indexer} +${c.folded_from.length}` : c.indexer);
|
||||
return parts.filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: qk.wantCandidates(wantId) }),
|
||||
client.invalidateQueries({ queryKey: ['adminWants'] })
|
||||
]);
|
||||
}
|
||||
|
||||
function grabbed(r: GrabResult): string {
|
||||
if (r.added) return r.replaced ? 'Taken, replacing the download that was running.' : `Taken for ${title}.`;
|
||||
if (r.kept) return r.reason ?? 'A download for this album is already running.';
|
||||
if (r.gone) return 'The indexers no longer offer that release.';
|
||||
if (r.unconfigured) {
|
||||
return r.missing === 'download_client'
|
||||
? 'No download client is set up. Add one under Admin › Acquisition.'
|
||||
: 'No indexer is set up. Add one under Admin › Acquisition.';
|
||||
}
|
||||
if (r.refused) return r.reason ? `Not taken: ${r.reason}` : 'Not taken.';
|
||||
return r.error ?? 'Not taken.';
|
||||
}
|
||||
|
||||
async function onGrab(c: Candidate) {
|
||||
busy = c.key;
|
||||
try {
|
||||
const r = await grabCandidate(wantId, c.key, c.verdict !== 'grab');
|
||||
pushToast(grabbed(r), r.added ? 'info' : 'error');
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onBlock(c: Candidate) {
|
||||
busy = c.key;
|
||||
try {
|
||||
await blockCandidate(wantId, c.key);
|
||||
pushToast('Set aside. No search will offer it again.');
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onUnblock(c: Candidate) {
|
||||
busy = c.key;
|
||||
try {
|
||||
await unblockRelease(c.info_hash);
|
||||
pushToast('Allowed again. The next search judges it afresh.');
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="space-y-2" data-testid="want-candidates">
|
||||
{#if query.isPending}
|
||||
<p class="text-xs text-text-secondary">Loading what the last search found…</p>
|
||||
{:else if query.isError}
|
||||
<p class="text-xs text-error-fg">Couldn't load the releases.</p>
|
||||
{:else if items.length === 0}
|
||||
<p class="text-xs text-text-secondary">
|
||||
Nothing kept from a search yet. Search now, or wait for the schedule.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-xs text-text-muted">
|
||||
{plural(items.length, 'release', 'releases')} found {relativeTime(items[0].searched_at)}, best first.
|
||||
</p>
|
||||
<ul class="divide-y divide-border rounded-md border border-border">
|
||||
{#each items as c (c.key)}
|
||||
<li class="flex flex-wrap items-start gap-2 p-2" data-testid="candidate-row">
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<div class="break-words text-xs text-text-primary">{c.name}</div>
|
||||
<div class="text-xs text-text-muted">{meta(c)}</div>
|
||||
<div class="flex flex-wrap items-center gap-1.5 text-xs">
|
||||
<span class="rounded-full px-2 py-0.5 {verdictClass[c.verdict]}">
|
||||
{c.downloading ? 'Downloading' : verdictLabel[c.verdict]}
|
||||
</span>
|
||||
<span class="text-text-secondary" data-testid="candidate-reason">{c.reason}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex shrink-0 gap-1.5">
|
||||
{#if c.verdict === 'blocked'}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onUnblock(c)}
|
||||
disabled={busy !== null}
|
||||
aria-label="Allow {c.name} again"
|
||||
class="rounded-md border border-border px-2 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Allow again
|
||||
</button>
|
||||
{:else if !c.downloading}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onGrab(c)}
|
||||
disabled={busy !== null}
|
||||
aria-label="{c.verdict === 'grab' ? 'Grab' : 'Grab anyway'} {c.name}"
|
||||
class="rounded-md px-2 py-1 text-xs disabled:opacity-50
|
||||
{c.verdict === 'grab'
|
||||
? 'bg-action-primary text-action-fg hover:opacity-90'
|
||||
: 'border border-border text-text-secondary hover:bg-surface-hover hover:text-text-primary'}"
|
||||
>
|
||||
{busy === c.key ? 'Taking…' : c.verdict === 'grab' ? 'Grab' : 'Grab anyway'}
|
||||
</button>
|
||||
{#if c.info_hash}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onBlock(c)}
|
||||
disabled={busy !== null}
|
||||
aria-label="Never take {c.name}"
|
||||
class="rounded-md px-2 py-1 text-xs text-text-muted hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Never this one
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,90 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import type { Candidate } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createCandidatesQuery: vi.fn(),
|
||||
grabCandidate: vi.fn().mockResolvedValue({ added: true, refused: false, gone: false, unconfigured: false, kept: false, replaced: false }),
|
||||
blockCandidate: vi.fn().mockResolvedValue(undefined),
|
||||
unblockRelease: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import WantCandidates from './WantCandidates.svelte';
|
||||
import { blockCandidate, createCandidatesQuery, grabCandidate, unblockRelease } from '#lib/api/wanted.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
|
||||
function cand(key: string, extra: Partial<Candidate> = {}): Candidate {
|
||||
return {
|
||||
key,
|
||||
name: `Daft Punk - Random Access Memories (2013) [${key}]`,
|
||||
info_hash: key,
|
||||
indexer: 'Knaben',
|
||||
size_bytes: 450_000_000,
|
||||
seeders: 12,
|
||||
files_count: 13,
|
||||
format: 'FLAC',
|
||||
quality: 'lossless',
|
||||
year: 2013,
|
||||
verdict: 'grab',
|
||||
reason: 'The album, FLAC.',
|
||||
reasons: [],
|
||||
folded_from: [],
|
||||
searched_at: new Date().toISOString(),
|
||||
downloading: false,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(items: Candidate[]) {
|
||||
vi.mocked(createCandidatesQuery).mockReturnValue(
|
||||
mockQuery({ data: items }) as unknown as ReturnType<typeof createCandidatesQuery>
|
||||
);
|
||||
return render(WantCandidates, { wantId: 'w1', title: 'Random Access Memories' });
|
||||
}
|
||||
|
||||
describe('WantCandidates', () => {
|
||||
test('every release shows its verdict and why', () => {
|
||||
setup([
|
||||
cand('aaaa'),
|
||||
cand('bbbb', { verdict: 'rejected', reason: 'This is a drumless edition (“drumless”).' })
|
||||
]);
|
||||
expect(screen.getAllByTestId('candidate-row')).toHaveLength(2);
|
||||
expect(screen.getByText('Would take')).toBeTruthy();
|
||||
expect(screen.getByText('Not the album')).toBeTruthy();
|
||||
expect(screen.getByText(/drumless edition/)).toBeTruthy();
|
||||
expect(screen.getAllByText(/FLAC · 450 MB · 12 seeders · Knaben/)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('a release the verdict would take is grabbed; any other is grabbed anyway', async () => {
|
||||
setup([cand('aaaa'), cand('bbbb', { verdict: 'review', reason: 'Nobody is sharing it right now.' })]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^grab daft punk.*\[aaaa\]/i }));
|
||||
await waitFor(() => expect(grabCandidate).toHaveBeenCalledWith('w1', 'aaaa', false));
|
||||
await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Taken for Random Access Memories.', 'info'));
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^grab anyway daft punk.*\[bbbb\]/i }));
|
||||
await waitFor(() => expect(grabCandidate).toHaveBeenCalledWith('w1', 'bbbb', true));
|
||||
});
|
||||
|
||||
test('a release can be set aside, and allowed again', async () => {
|
||||
setup([cand('aaaa'), cand('bbbb', { verdict: 'blocked', reason: 'You set this release aside.' })]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /never take .*\[aaaa\]/i }));
|
||||
await waitFor(() => expect(blockCandidate).toHaveBeenCalledWith('w1', 'aaaa'));
|
||||
await fireEvent.click(screen.getByRole('button', { name: /allow .*\[bbbb\] again/i }));
|
||||
await waitFor(() => expect(unblockRelease).toHaveBeenCalledWith('bbbb'));
|
||||
expect(screen.queryByRole('button', { name: /grab.*\[bbbb\]/i })).toBeNull();
|
||||
});
|
||||
|
||||
test('the release downloading says so and offers nothing', () => {
|
||||
setup([cand('aaaa', { downloading: true })]);
|
||||
expect(screen.getByText('Downloading')).toBeTruthy();
|
||||
expect(screen.queryByRole('button', { name: /grab/i })).toBeNull();
|
||||
});
|
||||
|
||||
test('before any search, it says how to get one', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/nothing kept from a search yet/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,95 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Ban } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { createReleaseBlocksQuery, unblockRelease } from '#lib/api/wanted.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import ListContinuation from '#lib/components/ListContinuation.svelte';
|
||||
import type { ReleaseBlock } from '#lib/api/types.js';
|
||||
|
||||
// The Blocked tab: releases the search will not take
|
||||
// again — set aside by a person, by what their files were, or by an
|
||||
// import's check that found they weren't the album; and, for a week,
|
||||
// releases given up on because they would not finish.
|
||||
|
||||
const client = useQueryClient();
|
||||
const blocksStore = createReleaseBlocksQuery();
|
||||
const blocks = $derived($blocksStore);
|
||||
const items = $derived((blocks.data?.pages ?? []).flatMap((p) => p.items) as ReleaseBlock[]);
|
||||
|
||||
let busy = $state<string | null>(null);
|
||||
|
||||
async function onAllow(b: ReleaseBlock) {
|
||||
busy = b.info_hash;
|
||||
try {
|
||||
await unblockRelease(b.info_hash);
|
||||
pushToast(`${b.name} may be taken again.`);
|
||||
await client.invalidateQueries({ queryKey: ['adminWants'] });
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
function by(b: ReleaseBlock): string {
|
||||
if (b.reason === 'operator') return 'Set aside by you';
|
||||
if (b.reason === 'files') return 'Set aside for its files';
|
||||
if (b.reason === 'stalled') return 'Given up on: it would not finish';
|
||||
if (b.reason === 'gone') return 'Held back: its download client lost track of it';
|
||||
return 'Refused on import';
|
||||
}
|
||||
|
||||
// A release given up on is held back for a while, then may be taken again.
|
||||
const until = (b: ReleaseBlock) =>
|
||||
b.expires_at ? ` · held back until ${new Date(b.expires_at).toLocaleDateString()}` : '';
|
||||
</script>
|
||||
|
||||
{#if blocks.isPending}
|
||||
<p class="text-text-secondary">Reading the blocked releases…</p>
|
||||
{:else if blocks.isError && !blocks.isFetchNextPageError}
|
||||
<p class="text-error-fg">Couldn't load the blocked releases.</p>
|
||||
{:else if items.length === 0}
|
||||
<div class="rounded-lg border border-border bg-surface p-6 text-center">
|
||||
<Ban size={28} strokeWidth={1} class="mx-auto text-text-muted" />
|
||||
<p class="mt-3 text-text-primary">No releases are blocked.</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
A release you set aside, or one an import found wasn't the album, lands here so it's never
|
||||
taken again.
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each items as b (b.info_hash)}
|
||||
<li class="flex flex-wrap items-start gap-3 p-3" data-testid="block-row">
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<div class="truncate text-sm font-medium text-text-primary" title={b.name}>{b.name || b.info_hash}</div>
|
||||
{#if b.want_title}
|
||||
<div class="truncate text-xs text-text-secondary">For {b.want_artist} – {b.want_title}</div>
|
||||
{/if}
|
||||
<div class="text-xs text-text-muted">{by(b)} {relativeTime(b.blocked_at)}{until(b)}</div>
|
||||
{#if b.detail}
|
||||
<p class="text-xs text-text-secondary">{b.detail}</p>
|
||||
{/if}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onAllow(b)}
|
||||
disabled={busy === b.info_hash}
|
||||
aria-label="Allow {b.name} again"
|
||||
class="shrink-0 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Allow again
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<ListContinuation
|
||||
hasMore={!!blocks.hasNextPage}
|
||||
loading={blocks.isFetchingNextPage}
|
||||
failed={blocks.isFetchNextPageError}
|
||||
onMore={() => blocks.fetchNextPage()}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockInfiniteQuery } from '../../../test-utils/query';
|
||||
import type { ReleaseBlock } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createReleaseBlocksQuery: vi.fn(),
|
||||
unblockRelease: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import BlockList from './BlockList.svelte';
|
||||
import { createReleaseBlocksQuery, unblockRelease } from '#lib/api/wanted.js';
|
||||
|
||||
const block: ReleaseBlock = {
|
||||
info_hash: 'abc123',
|
||||
name: 'Daft Punk - Random Access Memories (Drumless Edition)',
|
||||
reason: 'import',
|
||||
detail: 'The album tag says another version.',
|
||||
blocked_at: new Date(Date.now() - 3_600_000).toISOString(),
|
||||
expires_at: null,
|
||||
want_title: 'Random Access Memories',
|
||||
want_artist: 'Daft Punk'
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(items: ReleaseBlock[]) {
|
||||
vi.mocked(createReleaseBlocksQuery).mockReturnValue(
|
||||
mockInfiniteQuery({ pages: [{ items, total: items.length, limit: 50, offset: 0 }] }) as unknown as ReturnType<
|
||||
typeof createReleaseBlocksQuery
|
||||
>
|
||||
);
|
||||
return render(BlockList);
|
||||
}
|
||||
|
||||
describe('BlockList', () => {
|
||||
test('a blocked release says why and can be allowed again', async () => {
|
||||
setup([block]);
|
||||
expect(screen.getByText(/refused on import/i)).toBeTruthy();
|
||||
expect(screen.getByText(/another version/)).toBeTruthy();
|
||||
expect(screen.getByText(/for daft punk – random access memories/i)).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /allow .* again/i }));
|
||||
await waitFor(() => expect(unblockRelease).toHaveBeenCalledWith('abc123'));
|
||||
});
|
||||
|
||||
test('a release given up on says until when it is held back', () => {
|
||||
setup([{ ...block, reason: 'stalled', detail: 'Nobody was sharing it.', expires_at: '2026-10-17T12:00:00Z' }]);
|
||||
const line = screen.getByText(/given up on: it would not finish/i).textContent ?? '';
|
||||
expect(line).toMatch(/held back until/);
|
||||
});
|
||||
|
||||
test('with nothing blocked it says so', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/no releases are blocked/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
<script lang="ts">
|
||||
import Cover from '#lib/components/Cover.svelte';
|
||||
import type { WantArtist } from '#lib/api/types.js';
|
||||
|
||||
// One artist in the Collection's catalogue, as a poster: the
|
||||
// picture, a bar of how many of their albums on the list are held, and
|
||||
// whether Minstrel follows them for new releases.
|
||||
|
||||
let { artist: a }: { artist: WantArtist } = $props();
|
||||
|
||||
const pct = $derived(a.albums > 0 ? Math.round((a.held / a.albums) * 100) : 0);
|
||||
const notes = $derived(
|
||||
[
|
||||
a.following ? 'Following' : '',
|
||||
a.downloading ? `${a.downloading} downloading` : '',
|
||||
a.missing ? `${a.missing} missing` : ''
|
||||
].filter(Boolean)
|
||||
);
|
||||
</script>
|
||||
|
||||
<a
|
||||
href="/collection/artist/{encodeURIComponent(a.artist_mbid)}"
|
||||
class="group block overflow-hidden rounded-md border border-border bg-surface hover:border-accent focus-visible:ring-2 focus-visible:ring-accent"
|
||||
data-testid="catalogue-artist"
|
||||
>
|
||||
<div class="relative aspect-square w-full overflow-hidden bg-surface-hover">
|
||||
<Cover src={a.image_url} fallback="artist" class="transition-transform group-hover:scale-[1.03]" />
|
||||
</div>
|
||||
<div
|
||||
class="h-1.5 w-full bg-surface-hover"
|
||||
role="progressbar"
|
||||
aria-label="{a.held} of {a.albums} albums held"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={a.albums}
|
||||
aria-valuenow={a.held}
|
||||
>
|
||||
<div class="h-full bg-accent" style="width: {pct}%"></div>
|
||||
</div>
|
||||
<div class="space-y-0.5 px-2 py-1.5 text-center">
|
||||
<div class="truncate text-sm font-medium text-text-primary">{a.artist_name}</div>
|
||||
<div class="text-xs tabular-nums text-text-secondary">{a.held} / {a.albums} held</div>
|
||||
{#if notes.length}
|
||||
<div class="truncate text-xs text-text-muted">{notes.join(' · ')}</div>
|
||||
{/if}
|
||||
</div>
|
||||
</a>
|
||||
@@ -1,72 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { ListChecks } from 'lucide-svelte';
|
||||
import { createWantArtistsQuery } from '#lib/api/wanted.js';
|
||||
import AlphabeticalGrid from '#lib/components/AlphabeticalGrid.svelte';
|
||||
import ListContinuation from '#lib/components/ListContinuation.svelte';
|
||||
import QuickFilter from '#lib/components/QuickFilter.svelte';
|
||||
import CatalogueArtistCard from './CatalogueArtistCard.svelte';
|
||||
import type { WantArtist } from '#lib/api/types.js';
|
||||
|
||||
// The Collection's catalogue, its main page, an artist index: every
|
||||
// artist on the list A–Z, each card showing how many of their albums are
|
||||
// held. An artist opens on their albums. The library's albums were put on
|
||||
// the list as held once, each matched to MusicBrainz; the
|
||||
// ones no match was found for are listed under Unmatched.
|
||||
|
||||
let filter = $state('');
|
||||
const q = $derived(filter.trim());
|
||||
const artistsStore = $derived(createWantArtistsQuery(q));
|
||||
const artists = $derived($artistsStore);
|
||||
const items = $derived((artists.data?.pages ?? []).flatMap((p) => p.items) as WantArtist[]);
|
||||
const library = $derived(artists.data?.pages[0]?.library);
|
||||
</script>
|
||||
|
||||
{#if library && !library.listed_at}
|
||||
<p class="mb-3 text-sm text-text-secondary" data-testid="library-listing">
|
||||
Your library's albums are being added to the catalogue. Albums whose tags don't name them are
|
||||
matched on MusicBrainz first, by their artist, title and tracks, about one a second.
|
||||
</p>
|
||||
{/if}
|
||||
|
||||
{#if !artists.isPending && (items.length > 0 || q)}
|
||||
<div class="mb-3">
|
||||
<QuickFilter bind:value={filter} placeholder="Filter artists and albums" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if artists.isPending}
|
||||
<p class="text-text-secondary">Reading the catalogue…</p>
|
||||
{:else if artists.isError && !artists.isFetchNextPageError}
|
||||
<p class="text-error-fg">Couldn't load the catalogue.</p>
|
||||
{:else if items.length === 0 && q}
|
||||
<p class="text-text-secondary" data-testid="catalogue-filter-empty">
|
||||
No artist in the catalogue, or album of theirs, is named like <span class="font-medium">'{q}'</span>.
|
||||
</p>
|
||||
{:else if items.length === 0}
|
||||
<div class="rounded-lg border border-border bg-surface p-6 text-center">
|
||||
<ListChecks size={28} strokeWidth={1} class="mx-auto text-text-muted" />
|
||||
<p class="mt-3 text-text-primary">The catalogue is empty.</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
Your library's albums land here once it's been scanned, as do the albums users request and
|
||||
the releases of artists Minstrel follows.
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<AlphabeticalGrid
|
||||
{items}
|
||||
getKey={(a: WantArtist) => a.sort_name || a.artist_name}
|
||||
hasMore={!!artists.hasNextPage}
|
||||
onLoadMore={() => artists.fetchNextPage()}
|
||||
>
|
||||
{#snippet item(a: WantArtist)}
|
||||
<CatalogueArtistCard artist={a} />
|
||||
{/snippet}
|
||||
</AlphabeticalGrid>
|
||||
|
||||
<ListContinuation
|
||||
hasMore={!!artists.hasNextPage}
|
||||
loading={artists.isFetchingNextPage}
|
||||
failed={artists.isFetchNextPageError}
|
||||
onMore={() => artists.fetchNextPage()}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,86 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockInfiniteQuery } from '../../../test-utils/query';
|
||||
import type { LibraryListing, WantArtist, WantArtistsPage } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({ createWantArtistsQuery: vi.fn() }));
|
||||
|
||||
import CatalogueGrid from './CatalogueGrid.svelte';
|
||||
import { createWantArtistsQuery } from '#lib/api/wanted.js';
|
||||
|
||||
const DAY = 24 * 3_600_000;
|
||||
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
|
||||
|
||||
function artist(mbid: string, name: string, extra: Partial<WantArtist> = {}): WantArtist {
|
||||
return {
|
||||
artist_mbid: mbid,
|
||||
artist_name: name,
|
||||
sort_name: name,
|
||||
image_url: `/api/catalogue/art/artist/${mbid}`,
|
||||
albums: 4,
|
||||
held: 3,
|
||||
wanted: 1,
|
||||
missing: 0,
|
||||
downloading: 0,
|
||||
following: false,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
function setup(
|
||||
items: WantArtist[] = [
|
||||
artist('blur', 'Blur', { following: true, downloading: 1 }),
|
||||
artist('beatles', 'The Beatles', { sort_name: 'Beatles, The', albums: 13, held: 13, wanted: 0 })
|
||||
],
|
||||
library: LibraryListing = { listed_at: ago(DAY), unlisted: 0 }
|
||||
) {
|
||||
const page: WantArtistsPage = {
|
||||
items,
|
||||
total: items.length,
|
||||
limit: 96,
|
||||
offset: 0,
|
||||
counts: { artists: items.length, wanted: 1, missing: 0, held: 16, upgrades: 0, following: 1, activity: 1, attention: 0, blocked: 0, unmatched: 0 },
|
||||
library
|
||||
};
|
||||
vi.mocked(createWantArtistsQuery).mockReturnValue(
|
||||
mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType<typeof createWantArtistsQuery>
|
||||
);
|
||||
return render(CatalogueGrid);
|
||||
}
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('CatalogueGrid', () => {
|
||||
test('each artist is a card: how many albums are held, and whether they are followed', () => {
|
||||
setup();
|
||||
const cards = screen.getAllByTestId('catalogue-artist');
|
||||
expect(cards.map((c) => c.getAttribute('href'))).toEqual(['/collection/artist/blur', '/collection/artist/beatles']);
|
||||
expect(cards[0].textContent?.replace(/\s+/g, ' ')).toMatch(/Blur 3 \/ 4 held Following · 1 downloading/);
|
||||
const bar = screen.getByRole('progressbar', { name: '13 of 13 albums held' });
|
||||
expect(bar.getAttribute('aria-valuenow')).toBe('13');
|
||||
expect((bar.firstElementChild as HTMLElement).style.width).toBe('100%');
|
||||
});
|
||||
|
||||
test('the alphabet rail files an artist under their sort name', () => {
|
||||
setup();
|
||||
expect(document.getElementById('alpha-B')?.textContent).toMatch(/Blur/);
|
||||
});
|
||||
|
||||
test('the filter asks the server for artists by name or album', async () => {
|
||||
setup();
|
||||
await fireEvent.input(screen.getByRole('searchbox', { name: /filter artists and albums/i }), {
|
||||
target: { value: 'parklife' }
|
||||
});
|
||||
await waitFor(() => expect(createWantArtistsQuery).toHaveBeenLastCalledWith('parklife'));
|
||||
});
|
||||
|
||||
test('an empty catalogue says what lands there', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/the catalogue is empty/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
test('says while the library is being listed', () => {
|
||||
setup([], { listed_at: null, unlisted: 0 });
|
||||
expect(screen.getByTestId('library-listing').textContent).toMatch(/being added to the catalogue/i);
|
||||
});
|
||||
});
|
||||
@@ -1,33 +0,0 @@
|
||||
<script lang="ts">
|
||||
import SectionRail from '#lib/components/SectionRail.svelte';
|
||||
import { countOf } from '#lib/admin/queues.js';
|
||||
import type { AdminSummary, WantCounts } from '#lib/api/types.js';
|
||||
|
||||
// The Collection's sections, down the left: the catalogue of
|
||||
// artists first, then the sections that show state. Activity carries a
|
||||
// second, accented count when downloads are waiting on a person. Unmatched
|
||||
// holds the library albums no MusicBrainz album matched. Upgrades
|
||||
// holds the albums held but wanted for a better copy. Reports,
|
||||
// Duplicates, Suspect sources and Missing files are the library's health
|
||||
// queues: their counts come from the admin summary and are
|
||||
// accented, as they wait on a person. Missing files counts tracks.
|
||||
|
||||
let { counts, summary }: { counts?: WantCounts; summary?: AdminSummary } = $props();
|
||||
|
||||
// An artist's page belongs to the catalogue.
|
||||
const items = $derived([
|
||||
{ href: '/collection', label: 'Catalogue', count: counts?.artists, exact: true, also: ['/collection/artist/'] },
|
||||
{ href: '/collection/wanted', label: 'Wanted', count: counts?.wanted },
|
||||
{ href: '/collection/upgrades', label: 'Upgrades', count: counts?.upgrades },
|
||||
{ href: '/collection/activity', label: 'Activity', count: counts?.activity, attention: counts?.attention },
|
||||
{ href: '/collection/following', label: 'Following', count: counts?.following },
|
||||
{ href: '/collection/blocked', label: 'Blocked', count: counts?.blocked },
|
||||
{ href: '/collection/unmatched', label: 'Unmatched', count: counts?.unmatched },
|
||||
{ href: '/collection/reports', label: 'Reports', attention: countOf(summary, 'reports') },
|
||||
{ href: '/collection/duplicates', label: 'Duplicates', attention: countOf(summary, 'duplicates') },
|
||||
{ href: '/collection/suspect-sources', label: 'Suspect sources', attention: countOf(summary, 'suspect') },
|
||||
{ href: '/collection/missing', label: 'Missing files', attention: countOf(summary, 'missing') }
|
||||
]);
|
||||
</script>
|
||||
|
||||
<SectionRail label="Collection sections" {items} />
|
||||
@@ -1,264 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { Download as DownloadIcon } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
abandonDownload,
|
||||
createDownloadsQuery,
|
||||
importAnyway,
|
||||
refuseDownload,
|
||||
retryImport
|
||||
} from '#lib/api/wanted.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import ListContinuation from '#lib/components/ListContinuation.svelte';
|
||||
import type { Download, DownloadCondition, ImportEvidence } from '#lib/api/types.js';
|
||||
|
||||
// The Activity tab: every download Minstrel took, running
|
||||
// ones first. A finished download is checked against MusicBrainz before it
|
||||
// is filed; one the check could not settle waits here for a person, who
|
||||
// imports it anyway or refuses it. A refused release is set aside (the
|
||||
// Blocked tab) and its album searched for again. A download that fails, or
|
||||
// that nobody shares, is retried and then given up the same way, held back
|
||||
// for a week; an imported one seeds, then is removed.
|
||||
|
||||
const client = useQueryClient();
|
||||
const downloadsStore = createDownloadsQuery();
|
||||
const downloads = $derived($downloadsStore);
|
||||
const items = $derived((downloads.data?.pages ?? []).flatMap((p) => p.items) as Download[]);
|
||||
const clientsDown = $derived(downloads.data?.pages[0]?.clients_down ?? []);
|
||||
|
||||
let busy = $state<string | null>(null);
|
||||
|
||||
async function act(d: Download, run: (id: string) => Promise<void>, said: string) {
|
||||
busy = d.id;
|
||||
try {
|
||||
await run(d.id);
|
||||
pushToast(said);
|
||||
await client.invalidateQueries({ queryKey: ['adminWants'] });
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
const onImport = (d: Download) =>
|
||||
act(d, importAnyway, `${d.name} will be imported within the minute.`);
|
||||
const onRetry = (d: Download) => act(d, retryImport, `${d.name} will be tried again within the minute.`);
|
||||
const onRefuse = (d: Download) =>
|
||||
act(d, refuseDownload, `Refused ${d.name}. It's set aside and the album will be searched for again.`);
|
||||
const onAbandon = (d: Download) =>
|
||||
act(d, abandonDownload, `Gave up on ${d.name}. It's set aside and the album will be searched for again.`);
|
||||
|
||||
// A download still downloading, or waiting to be: one a person may give up.
|
||||
const running = (d: Download) =>
|
||||
!d.ended_at && (d.import_state === '' || d.import_state === 'downloading' || d.import_state === 'waiting');
|
||||
|
||||
// How a download that ended without an import ended.
|
||||
const endings: Record<string, string> = {
|
||||
stalled: 'Given up',
|
||||
failed: 'Failed',
|
||||
abandoned: 'Given up by you',
|
||||
gone: 'Left the client',
|
||||
superseded: 'Replaced'
|
||||
};
|
||||
|
||||
// The state of a download as a short label, and whether it needs a person.
|
||||
function label(d: Download): string {
|
||||
if (d.ended_at && endings[d.end_reason]) return endings[d.end_reason];
|
||||
switch (d.import_state) {
|
||||
case 'downloading':
|
||||
case '':
|
||||
return d.ended_at ? 'Ended' : 'Downloading';
|
||||
case 'waiting':
|
||||
return 'Waiting';
|
||||
case 'importing':
|
||||
return 'Importing';
|
||||
case 'imported':
|
||||
return 'Imported';
|
||||
case 'refused':
|
||||
return 'Refused';
|
||||
case 'review':
|
||||
return 'Needs you';
|
||||
case 'held':
|
||||
return 'Already held';
|
||||
case 'failed':
|
||||
return 'Import failed';
|
||||
}
|
||||
return d.import_state;
|
||||
}
|
||||
|
||||
const needsYou = (d: Download) => !d.ended_at && (d.import_state === 'review' || d.import_state === 'failed');
|
||||
|
||||
function badge(d: Download): string {
|
||||
if (needsYou(d)) return 'border-accent text-text-primary';
|
||||
if (d.import_state === 'refused' || (d.ended_at && endings[d.end_reason])) return 'border-error-fg text-error-fg';
|
||||
return 'border-border text-text-secondary';
|
||||
}
|
||||
|
||||
// What the check counted, in a line.
|
||||
function counted(e: ImportEvidence): string {
|
||||
const parts = [`${e.files} files against ${e.tracks} tracks`];
|
||||
if (e.fingerprinted) parts.push(`${e.recordings} identified by AcoustID`);
|
||||
else parts.push('no AcoustID');
|
||||
parts.push(`${e.lengths} lengths agree`, `${e.titles} titles agree`);
|
||||
if (e.album_tag) parts.push(`album tag “${e.album_tag}”`);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
// What the lifecycle sees wrong with a running download, and what it did.
|
||||
function condition(c: DownloadCondition): string {
|
||||
let said = c.detail;
|
||||
if (c.trigger === 'no_peers' || c.trigger === 'no_metadata') {
|
||||
said += c.retries
|
||||
? ` Asked for again ${c.retries} of 3 times; given up after that.`
|
||||
: ' It will be asked for again three times, then given up.';
|
||||
}
|
||||
return said;
|
||||
}
|
||||
|
||||
// What ended a download that was not imported, in the lifecycle's words.
|
||||
const ending = (d: Download) => (d.ended_at && endings[d.end_reason] ? d.end_detail : '');
|
||||
|
||||
function seeded(d: Download): string | null {
|
||||
if (d.seed_released_at) return `Seeded, then removed from the download client ${relativeTime(d.seed_released_at)}.`;
|
||||
if (d.seeding) return `Seeding: share ratio ${d.ratio.toFixed(2)}.`;
|
||||
return null;
|
||||
}
|
||||
|
||||
function when(d: Download): string {
|
||||
const who = d.origin === 'operator' ? 'by you' : 'by the schedule';
|
||||
let said = `Taken ${who} ${relativeTime(d.grabbed_at)}`;
|
||||
if (d.indexer) said += ` from ${d.indexer}`;
|
||||
if (d.imported_at) said += ` · imported ${relativeTime(d.imported_at)}`;
|
||||
else if (d.ended_at) said += ` · ended ${relativeTime(d.ended_at)}`;
|
||||
return said;
|
||||
}
|
||||
|
||||
function filed(d: Download): string | null {
|
||||
if (d.import_state !== 'imported' && d.import_state !== 'held') return null;
|
||||
let said = plural(d.imported_files, 'track filed', 'tracks filed');
|
||||
if (d.skipped) said += `, ${d.skipped} already held`;
|
||||
if (d.destination) said += ` into ${d.destination}`;
|
||||
return said;
|
||||
}
|
||||
|
||||
const button =
|
||||
'rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50';
|
||||
</script>
|
||||
|
||||
{#each clientsDown as c (c.client)}
|
||||
<p
|
||||
class="mb-3 rounded-lg border border-error-fg bg-surface p-3 text-sm text-text-primary"
|
||||
role="status"
|
||||
data-testid="client-down"
|
||||
>
|
||||
Can't reach the download client {c.client} since {relativeTime(c.since)}: {c.detail}. Its
|
||||
downloads are left as they are until it answers.
|
||||
</p>
|
||||
{/each}
|
||||
|
||||
{#if downloads.isPending}
|
||||
<p class="text-text-secondary">Reading the downloads…</p>
|
||||
{:else if downloads.isError && !downloads.isFetchNextPageError}
|
||||
<p class="text-error-fg">Couldn't load the downloads.</p>
|
||||
{:else if items.length === 0}
|
||||
<div class="rounded-lg border border-border bg-surface p-6 text-center">
|
||||
<DownloadIcon size={28} strokeWidth={1} class="mx-auto text-text-muted" />
|
||||
<p class="mt-3 text-text-primary">Nothing has been downloaded yet.</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
A release the search takes, or one you take from a want's Releases, shows here while it
|
||||
downloads and once it's imported.
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each items as d (d.id)}
|
||||
<li class="space-y-1.5 p-3" data-testid="download-row">
|
||||
<div class="flex flex-wrap items-start gap-x-3 gap-y-1">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm font-medium text-text-primary">
|
||||
{d.want_artist ? `${d.want_artist} – ${d.want_title}` : d.name}
|
||||
</div>
|
||||
<div class="truncate text-xs text-text-secondary" title={d.name}>
|
||||
{d.name}{#if d.quality}<span class="text-text-muted"> · {d.quality}</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<span class="shrink-0 rounded-full border px-2 py-0.5 text-xs {badge(d)}" data-testid="download-state">
|
||||
{label(d)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{#if !d.ended_at && (d.import_state === 'downloading' || d.import_state === '')}
|
||||
<div
|
||||
class="h-1.5 overflow-hidden rounded-full bg-surface-hover"
|
||||
role="progressbar"
|
||||
aria-label="Downloaded"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={100}
|
||||
aria-valuenow={Math.floor(d.progress * 100)}
|
||||
>
|
||||
<div class="h-full bg-accent" style="width: {Math.floor(d.progress * 100)}%"></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if running(d) && d.condition}
|
||||
<p class="text-xs text-text-primary" data-testid="download-condition">{condition(d.condition)}</p>
|
||||
{/if}
|
||||
{#if ending(d)}
|
||||
<p class="text-xs text-text-secondary" data-testid="download-ending">{ending(d)}</p>
|
||||
{/if}
|
||||
{#if d.import_reason}
|
||||
<p class="text-xs {needsYou(d) ? 'text-text-primary' : 'text-text-secondary'}" data-testid="download-reason">
|
||||
{d.import_reason}
|
||||
</p>
|
||||
{/if}
|
||||
{#if d.evidence}
|
||||
<p class="text-xs text-text-muted">{counted(d.evidence)}</p>
|
||||
{/if}
|
||||
{#if filed(d)}
|
||||
<p class="truncate text-xs text-text-secondary" title={d.destination}>{filed(d)}</p>
|
||||
{/if}
|
||||
{#if seeded(d)}
|
||||
<p class="text-xs text-text-muted" data-testid="download-seeding">{seeded(d)}</p>
|
||||
{/if}
|
||||
{#if d.rehomed_from}
|
||||
<p class="text-xs text-text-muted">Taken for {d.rehomed_from}; it turned out to be this album.</p>
|
||||
{/if}
|
||||
<p class="text-xs text-text-muted">{when(d)}</p>
|
||||
|
||||
{#if running(d)}
|
||||
<div class="flex flex-wrap gap-1.5 pt-1">
|
||||
<button type="button" class={button} disabled={busy === d.id} onclick={() => onAbandon(d)}>
|
||||
Give up
|
||||
</button>
|
||||
</div>
|
||||
{:else if needsYou(d)}
|
||||
<div class="flex flex-wrap gap-1.5 pt-1">
|
||||
{#if d.import_state === 'review'}
|
||||
<button type="button" class={button} disabled={busy === d.id} onclick={() => onImport(d)}>
|
||||
Import anyway
|
||||
</button>
|
||||
{:else}
|
||||
<button type="button" class={button} disabled={busy === d.id} onclick={() => onRetry(d)}>
|
||||
Try again
|
||||
</button>
|
||||
{/if}
|
||||
<button type="button" class={button} disabled={busy === d.id} onclick={() => onRefuse(d)}>
|
||||
Refuse
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
<ListContinuation
|
||||
hasMore={!!downloads.hasNextPage}
|
||||
loading={downloads.isFetchingNextPage}
|
||||
failed={downloads.isFetchNextPageError}
|
||||
onMore={() => downloads.fetchNextPage()}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,160 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockInfiniteQuery } from '../../../test-utils/query';
|
||||
import type { ClientDown, Download } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createDownloadsQuery: vi.fn(),
|
||||
importAnyway: vi.fn().mockResolvedValue(undefined),
|
||||
retryImport: vi.fn().mockResolvedValue(undefined),
|
||||
refuseDownload: vi.fn().mockResolvedValue(undefined),
|
||||
abandonDownload: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import DownloadList from './DownloadList.svelte';
|
||||
import { abandonDownload, createDownloadsQuery, importAnyway, refuseDownload, retryImport } from '#lib/api/wanted.js';
|
||||
|
||||
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
|
||||
|
||||
function download(id: string, extra: Partial<Download> = {}): Download {
|
||||
return {
|
||||
id,
|
||||
want_id: 'w1',
|
||||
want_title: 'Random Access Memories',
|
||||
want_artist: 'Daft Punk',
|
||||
name: 'Daft Punk - Random Access Memories (2013) [FLAC]',
|
||||
indexer: 'Prowlarr',
|
||||
client: 'qbittorrent',
|
||||
quality: 'lossless',
|
||||
origin: 'schedule',
|
||||
grabbed_at: ago(3_600_000),
|
||||
ended_at: null,
|
||||
end_reason: '',
|
||||
progress: 0,
|
||||
import_state: 'downloading',
|
||||
import_reason: '',
|
||||
imported_at: null,
|
||||
imported_files: 0,
|
||||
destination: '',
|
||||
files: [],
|
||||
skipped: 0,
|
||||
end_detail: '',
|
||||
seeding: false,
|
||||
ratio: 0,
|
||||
seed_released_at: null,
|
||||
condition: null,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(items: Download[], clientsDown: ClientDown[] = []) {
|
||||
// The Activity page carries the clients not answering beside its items.
|
||||
const page = { items, total: items.length, limit: 50, offset: 0, clients_down: clientsDown };
|
||||
vi.mocked(createDownloadsQuery).mockReturnValue(
|
||||
mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType<
|
||||
typeof createDownloadsQuery
|
||||
>
|
||||
);
|
||||
return render(DownloadList);
|
||||
}
|
||||
|
||||
describe('DownloadList', () => {
|
||||
test('a running download shows how far it has got, and can be given up', async () => {
|
||||
setup([download('d1', { progress: 0.375 })]);
|
||||
expect(screen.getByTestId('download-state').textContent).toMatch(/downloading/i);
|
||||
expect(screen.getByRole('progressbar', { name: /downloaded/i }).getAttribute('aria-valuenow')).toBe('37');
|
||||
expect(screen.queryByTestId('download-condition')).toBeNull();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /give up/i }));
|
||||
await waitFor(() => expect(abandonDownload).toHaveBeenCalledWith('d1'));
|
||||
});
|
||||
|
||||
test('a stalled download says what is wrong and how often it was asked for again', () => {
|
||||
setup([
|
||||
download('d1', {
|
||||
progress: 0.4,
|
||||
condition: { trigger: 'no_peers', detail: 'Nobody has shared it in 7 hours; 40% downloaded.', retries: 2, since: ago(1_200_000) }
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('download-condition').textContent).toMatch(
|
||||
/nobody has shared it in 7 hours; 40% downloaded\. asked for again 2 of 3 times/i
|
||||
);
|
||||
});
|
||||
|
||||
test('a download given up on says why it ended', () => {
|
||||
setup([
|
||||
download('d1', {
|
||||
ended_at: ago(60_000),
|
||||
end_reason: 'stalled',
|
||||
end_detail: 'Taken 7 hours ago and never finished: nobody was sharing it. Held back until 17 Oct.'
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('download-state').textContent).toMatch(/given up/i);
|
||||
expect(screen.getByTestId('download-ending').textContent).toMatch(/nobody was sharing it/);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
|
||||
test('a download client that does not answer is named above the list', () => {
|
||||
setup([download('d1')], [{ client: 'qbittorrent', detail: 'connection refused', since: ago(600_000) }]);
|
||||
expect(screen.getByTestId('client-down').textContent).toMatch(/can't reach the download client qbittorrent .*connection refused/i);
|
||||
});
|
||||
|
||||
test('a doubtful download says why and can be imported anyway or refused', async () => {
|
||||
setup([
|
||||
download('d1', {
|
||||
import_state: 'review',
|
||||
import_reason: 'Only the lengths agree. A person decides.',
|
||||
evidence: { files: 13, tracks: 13, identified: 0, recordings: 0, lengths: 13, titles: 0, fingerprinted: false }
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('download-state').textContent).toMatch(/needs you/i);
|
||||
expect(screen.getByTestId('download-reason').textContent).toMatch(/a person decides/i);
|
||||
expect(screen.getByText(/13 files against 13 tracks · no AcoustID · 13 lengths agree/)).toBeTruthy();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /import anyway/i }));
|
||||
await waitFor(() => expect(importAnyway).toHaveBeenCalledWith('d1'));
|
||||
await fireEvent.click(screen.getByRole('button', { name: /refuse/i }));
|
||||
await waitFor(() => expect(refuseDownload).toHaveBeenCalledWith('d1'));
|
||||
});
|
||||
|
||||
test('a failed import can be tried again', async () => {
|
||||
setup([download('d1', { import_state: 'failed', import_reason: 'The library folder is not writable.' })]);
|
||||
expect(screen.queryByRole('button', { name: /import anyway/i })).toBeNull();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /try again/i }));
|
||||
await waitFor(() => expect(retryImport).toHaveBeenCalledWith('d1'));
|
||||
});
|
||||
|
||||
test('an imported download says what was filed where', () => {
|
||||
setup([
|
||||
download('d1', {
|
||||
ended_at: ago(60_000),
|
||||
end_reason: 'imported',
|
||||
import_state: 'imported',
|
||||
imported_at: ago(60_000),
|
||||
imported_files: 12,
|
||||
skipped: 1,
|
||||
destination: '/music/Daft Punk/Random Access Memories (2013)'
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('download-state').textContent).toMatch(/imported/i);
|
||||
expect(screen.getByText(/12 tracks filed, 1 already held into \/music\/Daft Punk/)).toBeTruthy();
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
|
||||
test('an imported download says how its seeding goes', () => {
|
||||
const imported = { ended_at: ago(60_000), end_reason: 'imported', import_state: 'imported' as const };
|
||||
setup([
|
||||
download('d1', { ...imported, seeding: true, ratio: 0.8 }),
|
||||
download('d2', { ...imported, seeding: true, ratio: 2.1, seed_released_at: ago(60_000) })
|
||||
]);
|
||||
const lines = screen.getAllByTestId('download-seeding').map((e) => e.textContent);
|
||||
expect(lines[0]).toMatch(/seeding: share ratio 0\.80/i);
|
||||
expect(lines[1]).toMatch(/seeded, then removed/i);
|
||||
});
|
||||
|
||||
test('with nothing downloaded it says what lands here', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/nothing has been downloaded yet/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,118 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { Disc3 } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createFollowsQuery,
|
||||
createReleaseProfilesQuery,
|
||||
putFollow,
|
||||
deleteFollow
|
||||
} from '#lib/api/wanted.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import type { Follow } from '#lib/api/types.js';
|
||||
|
||||
// The Following tab: every artist whose new releases are
|
||||
// wanted, each on a release-type profile saying which kinds of release.
|
||||
|
||||
const client = useQueryClient();
|
||||
const followsStore = createFollowsQuery();
|
||||
const follows = $derived($followsStore);
|
||||
const profilesStore = createReleaseProfilesQuery();
|
||||
const profiles = $derived($profilesStore.data?.profiles ?? []);
|
||||
|
||||
let busy = $state<string | null>(null);
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: ['adminWants'] }),
|
||||
client.invalidateQueries({ queryKey: ['adminFollows'] })
|
||||
]);
|
||||
}
|
||||
|
||||
async function onProfile(f: Follow, profileId: string) {
|
||||
busy = f.artist_mbid;
|
||||
try {
|
||||
await putFollow(f.artist_mbid, { artist_name: f.artist_name, profile_id: profileId });
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onUnfollow(f: Follow) {
|
||||
busy = f.artist_mbid;
|
||||
try {
|
||||
await deleteFollow(f.artist_mbid);
|
||||
pushToast(`No longer following ${f.artist_name}. What was already wanted stays wanted.`);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
function hideBroken(e: Event) {
|
||||
(e.currentTarget as HTMLImageElement).style.display = 'none';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if follows.isPending}
|
||||
<p class="text-text-secondary">Reading who's followed…</p>
|
||||
{:else if follows.isError}
|
||||
<p class="text-error-fg">Couldn't load the followed artists.</p>
|
||||
{:else if (follows.data ?? []).length === 0}
|
||||
<p class="text-text-secondary">No artists are followed. Follow one from its artist page.</p>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each follows.data ?? [] as f (f.artist_mbid)}
|
||||
<li class="flex flex-wrap items-center gap-3 p-3" data-testid="follow-row">
|
||||
<div class="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full bg-surface-hover" aria-hidden="true">
|
||||
<Disc3 size={20} strokeWidth={1} class="text-text-muted" />
|
||||
{#if f.image_url}
|
||||
<img src={f.image_url} alt="" class="absolute inset-0 h-full w-full object-cover" loading="lazy" onerror={hideBroken} />
|
||||
{/if}
|
||||
</div>
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<div class="truncate text-sm font-medium text-text-primary">
|
||||
{#if f.artist_id}
|
||||
<a href="/artists/{f.artist_id}" class="hover:underline">{f.artist_name}</a>
|
||||
{:else}
|
||||
{f.artist_name}
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-xs text-text-secondary">
|
||||
{plural(f.open_wants, 'album wanted', 'albums wanted')} ·
|
||||
{f.checked_at ? `checked ${relativeTime(f.checked_at)}` : 'not checked yet'}
|
||||
</div>
|
||||
</div>
|
||||
<label class="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<span class="sr-only">Profile for {f.artist_name}</span>
|
||||
<select
|
||||
value={f.profile_id}
|
||||
disabled={busy === f.artist_mbid}
|
||||
onchange={(e) => onProfile(f, (e.currentTarget as HTMLSelectElement).value)}
|
||||
class="rounded-md border border-border bg-background px-2 py-1 text-sm text-text-primary focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
>
|
||||
{#each profiles as p (p.id)}
|
||||
<option value={p.id}>{p.name}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onUnfollow(f)}
|
||||
disabled={busy === f.artist_mbid}
|
||||
aria-label="Unfollow {f.artist_name}"
|
||||
class="rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Unfollow
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../../test-utils/query';
|
||||
import type { Follow, ReleaseProfilesResponse } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createFollowsQuery: vi.fn(),
|
||||
createReleaseProfilesQuery: vi.fn(),
|
||||
putFollow: vi.fn().mockResolvedValue({ following: true }),
|
||||
deleteFollow: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import FollowList from './FollowList.svelte';
|
||||
import { createFollowsQuery, createReleaseProfilesQuery, deleteFollow, putFollow } from '#lib/api/wanted.js';
|
||||
|
||||
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
|
||||
|
||||
const follow: Follow = {
|
||||
artist_mbid: 'blur',
|
||||
artist_name: 'Blur',
|
||||
artist_id: 'art-1',
|
||||
profile_id: 'p-std',
|
||||
profile_name: 'Standard',
|
||||
followed_at: ago(10 * 86_400_000),
|
||||
checked_at: ago(3 * 3_600_000),
|
||||
open_wants: 2,
|
||||
image_url: ''
|
||||
};
|
||||
|
||||
const profiles: ReleaseProfilesResponse = {
|
||||
profiles: [
|
||||
{ id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 1 },
|
||||
{ id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 }
|
||||
],
|
||||
primary_types: ['Album'],
|
||||
secondary_types: ['Live']
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(follows: Follow[] = [follow]) {
|
||||
vi.mocked(createFollowsQuery).mockReturnValue(
|
||||
mockQuery({ data: follows }) as unknown as ReturnType<typeof createFollowsQuery>
|
||||
);
|
||||
vi.mocked(createReleaseProfilesQuery).mockReturnValue(
|
||||
mockQuery({ data: profiles }) as unknown as ReturnType<typeof createReleaseProfilesQuery>
|
||||
);
|
||||
return render(FollowList);
|
||||
}
|
||||
|
||||
describe('FollowList', () => {
|
||||
test('lists artists; the profile can change and the artist be unfollowed', async () => {
|
||||
setup();
|
||||
expect(screen.getAllByTestId('follow-row')).toHaveLength(1);
|
||||
expect(screen.getByText(/2 albums wanted/)).toBeTruthy();
|
||||
|
||||
const select = screen.getByLabelText(/profile for blur/i) as HTMLSelectElement;
|
||||
expect(select.value).toBe('p-std');
|
||||
await fireEvent.change(select, { target: { value: 'p-live' } });
|
||||
await waitFor(() =>
|
||||
expect(putFollow).toHaveBeenCalledWith('blur', { artist_name: 'Blur', profile_id: 'p-live' })
|
||||
);
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: /unfollow blur/i }));
|
||||
await waitFor(() => expect(deleteFollow).toHaveBeenCalledWith('blur'));
|
||||
});
|
||||
|
||||
test('with no follows it says where to follow from', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/follow one from its artist page/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,150 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { CircleCheck } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { createUnmatchedQuery, leaveUnmatchedOff, matchUnmatched, putUnmatchedBack } from '#lib/api/wanted.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import UnmatchedMatch from './UnmatchedMatch.svelte';
|
||||
import type { UnmatchedAlbum } from '#lib/api/types.js';
|
||||
|
||||
// The Collection's Unmatched section: the library albums no
|
||||
// MusicBrainz album matched by artist, title and tracks. Each can be
|
||||
// matched by hand, to a search result or a pasted link, and goes on the
|
||||
// list as held; or left off, as a local band's album MusicBrainz will
|
||||
// never have. Until then an album isn't fetched back if its files go
|
||||
// missing.
|
||||
|
||||
const client = useQueryClient();
|
||||
const unmatchedStore = createUnmatchedQuery();
|
||||
const unmatched = $derived($unmatchedStore);
|
||||
const all = $derived((unmatched.data ?? []) as UnmatchedAlbum[]);
|
||||
const toMatch = $derived(all.filter((u) => !u.left_off));
|
||||
const leftOff = $derived(all.filter((u) => u.left_off));
|
||||
|
||||
let open = $state<string | null>(null);
|
||||
let busy = $state<string | null>(null);
|
||||
|
||||
async function act(u: UnmatchedAlbum, run: () => Promise<string>) {
|
||||
busy = u.album_id;
|
||||
try {
|
||||
pushToast(await run());
|
||||
open = null;
|
||||
await client.invalidateQueries({ queryKey: ['adminWants'] });
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
const onMatch = (u: UnmatchedAlbum, ref: string) =>
|
||||
act(u, async () => {
|
||||
const m = await matchUnmatched(u.album_id, ref);
|
||||
const agree = m.tracks ? ` ${m.agree} of ${m.tracks} tracks agree.` : '';
|
||||
return `${u.title} is now ${m.title} by ${m.artist}, held.${agree}`;
|
||||
});
|
||||
|
||||
const onLeaveOff = (u: UnmatchedAlbum) =>
|
||||
act(u, async () => {
|
||||
await leaveUnmatchedOff(u.album_id);
|
||||
return `${u.title} is left off the list.`;
|
||||
});
|
||||
|
||||
const onPutBack = (u: UnmatchedAlbum) =>
|
||||
act(u, async () => {
|
||||
await putUnmatchedBack(u.album_id);
|
||||
return `${u.title} is back to be matched.`;
|
||||
});
|
||||
|
||||
</script>
|
||||
|
||||
{#if unmatched.isPending}
|
||||
<p class="text-text-secondary">Reading the unmatched albums…</p>
|
||||
{:else if unmatched.isError}
|
||||
<p class="text-error-fg">Couldn't load the unmatched albums.</p>
|
||||
{:else}
|
||||
{#if toMatch.length === 0}
|
||||
<div class="rounded-lg border border-border bg-surface p-6 text-center">
|
||||
<CircleCheck size={28} strokeWidth={1} class="mx-auto text-text-muted" />
|
||||
<p class="mt-3 text-text-primary">Every album in your library is matched.</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
An album no MusicBrainz album matches by its artist, title and tracks lands here, to be
|
||||
matched by hand or left off.
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<p class="mb-3 text-sm text-text-secondary">
|
||||
No MusicBrainz album matched {toMatch.length === 1 ? 'this album' : `these ${toMatch.length} albums`}
|
||||
by artist, title and tracks, so {toMatch.length === 1 ? "it isn't" : "they aren't"} fetched back if
|
||||
{toMatch.length === 1 ? 'its' : 'their'} files go missing. Match each to its MusicBrainz album, or
|
||||
leave it off if MusicBrainz doesn't have it.
|
||||
</p>
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each toMatch as u (u.album_id)}
|
||||
<li class="p-3" data-testid="unmatched-row">
|
||||
<div class="flex flex-wrap items-start gap-3">
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<a href="/albums/{u.album_id}" class="block truncate text-sm font-medium text-text-primary hover:underline"
|
||||
>{u.title}</a
|
||||
>
|
||||
<div class="truncate text-xs text-text-secondary">{u.artist} · {plural(u.tracks, 'track', 'tracks')}</div>
|
||||
<p class="text-xs text-text-muted">{u.detail}</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open === u.album_id}
|
||||
onclick={() => (open = open === u.album_id ? null : u.album_id)}
|
||||
class="rounded-md border border-border px-2.5 py-1 text-xs text-text-primary hover:bg-surface-hover"
|
||||
>
|
||||
Match…
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy === u.album_id}
|
||||
onclick={() => onLeaveOff(u)}
|
||||
class="rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Leave it off
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{#if open === u.album_id}
|
||||
<UnmatchedMatch album={u} busy={busy === u.album_id} onMatch={(ref) => onMatch(u, ref)} />
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
{#if leftOff.length > 0}
|
||||
<section class="mt-6" data-testid="left-off">
|
||||
<h2 class="mb-2 text-sm font-medium text-text-primary">Left off</h2>
|
||||
<p class="mb-3 text-xs text-text-secondary">
|
||||
Kept in the library, never matched again, and not fetched back if their files go missing.
|
||||
</p>
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each leftOff as u (u.album_id)}
|
||||
<li class="flex flex-wrap items-center gap-3 p-3" data-testid="left-off-row">
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<a href="/albums/{u.album_id}" class="block truncate text-sm text-text-primary hover:underline">{u.title}</a>
|
||||
<div class="truncate text-xs text-text-secondary">
|
||||
{u.artist} · {plural(u.tracks, 'track', 'tracks')} · left off {relativeTime(u.decided_at)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy === u.album_id}
|
||||
onclick={() => onPutBack(u)}
|
||||
class="shrink-0 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
Put back
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/if}
|
||||
{/if}
|
||||
@@ -1,109 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import type { CatalogueSearchResult, UnmatchedAlbum } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', async () => {
|
||||
const { mockQuery } = await import('../../../test-utils/query');
|
||||
return {
|
||||
createUnmatchedQuery: vi.fn(() => mockQuery({ data: [] })),
|
||||
matchUnmatched: vi.fn().mockResolvedValue({
|
||||
release_group_mbid: 'rg-1',
|
||||
title: 'Songs for the Deaf',
|
||||
artist: 'Queens of the Stone Age',
|
||||
agree: 9,
|
||||
tracks: 10
|
||||
}),
|
||||
leaveUnmatchedOff: vi.fn().mockResolvedValue(undefined),
|
||||
putUnmatchedBack: vi.fn().mockResolvedValue(undefined)
|
||||
};
|
||||
});
|
||||
vi.mock('#lib/api/catalogue.js', () => ({ createCatalogueSearchQuery: vi.fn() }));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import UnmatchedList from './UnmatchedList.svelte';
|
||||
import { mockQuery } from '../../../test-utils/query';
|
||||
import { createUnmatchedQuery, leaveUnmatchedOff, matchUnmatched, putUnmatchedBack } from '#lib/api/wanted.js';
|
||||
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
|
||||
const DAY = 24 * 3_600_000;
|
||||
|
||||
function album(id: string, title: string, artist: string, extra: Partial<UnmatchedAlbum> = {}): UnmatchedAlbum {
|
||||
return {
|
||||
album_id: id,
|
||||
title,
|
||||
artist,
|
||||
detail: `MusicBrainz has no album called "${title}" by ${artist}.`,
|
||||
tracks: 10,
|
||||
left_off: false,
|
||||
decided_at: new Date(Date.now() - 2 * DAY).toISOString(),
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
const result: CatalogueSearchResult = {
|
||||
mbid: 'rg-1',
|
||||
name: 'Songs for the Deaf',
|
||||
secondary_text: 'Queens of the Stone Age · 2002 · Album',
|
||||
image_url: '',
|
||||
artist_mbid: 'qotsa',
|
||||
album_mbid: '',
|
||||
in_library: false,
|
||||
requested: false
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(items: UnmatchedAlbum[], results: CatalogueSearchResult[] = [result]) {
|
||||
vi.mocked(createUnmatchedQuery).mockReturnValue(
|
||||
mockQuery({ data: items }) as unknown as ReturnType<typeof createUnmatchedQuery>
|
||||
);
|
||||
vi.mocked(createCatalogueSearchQuery).mockReturnValue(
|
||||
mockQuery({ data: results }) as unknown as ReturnType<typeof createCatalogueSearchQuery>
|
||||
);
|
||||
return render(UnmatchedList);
|
||||
}
|
||||
|
||||
describe('UnmatchedList', () => {
|
||||
test('each unmatched album says why, with its tracks, and links to the album', () => {
|
||||
setup([album('al-1', 'Dial Tone', 'Annadale', { tracks: 1 })]);
|
||||
const row = screen.getByTestId('unmatched-row');
|
||||
expect(row.textContent).toMatch(/Annadale · 1 track/);
|
||||
expect(row.textContent).toMatch(/no album called "Dial Tone"/);
|
||||
expect(screen.getByRole('link', { name: 'Dial Tone' }).getAttribute('href')).toBe('/albums/al-1');
|
||||
});
|
||||
|
||||
test('Match searches MusicBrainz for the album by its own title and artist, and matches a result', async () => {
|
||||
setup([album('al-2', 'Songs for the Deaf', 'Queens of the Stone Age')]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /match…/i }));
|
||||
expect(createCatalogueSearchQuery).toHaveBeenLastCalledWith('Songs for the Deaf Queens of the Stone Age', 'album');
|
||||
await fireEvent.click(screen.getByRole('button', { name: /match to songs for the deaf/i }));
|
||||
await waitFor(() => expect(matchUnmatched).toHaveBeenCalledWith('al-2', 'rg-1'));
|
||||
await waitFor(() => expect(pushToast).toHaveBeenCalledWith(expect.stringMatching(/9 of 10 tracks agree/)));
|
||||
});
|
||||
|
||||
test('a pasted MusicBrainz link matches the album', async () => {
|
||||
setup([album('al-3', '+++', 'DROELOE')]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /match…/i }));
|
||||
const link = 'https://musicbrainz.org/release/11111111-0000-4000-8000-000000000003';
|
||||
await fireEvent.input(screen.getByRole('textbox', { name: /musicbrainz album link/i }), { target: { value: link } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^match$/i }));
|
||||
await waitFor(() => expect(matchUnmatched).toHaveBeenCalledWith('al-3', link));
|
||||
});
|
||||
|
||||
test("a local band's album is left off, and one left off can be put back", async () => {
|
||||
setup([album('al-1', 'Dial Tone', 'Annadale'), album('al-4', 'Demo', 'Annadale', { left_off: true })]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /leave it off/i }));
|
||||
await waitFor(() => expect(leaveUnmatchedOff).toHaveBeenCalledWith('al-1'));
|
||||
const leftOff = screen.getByTestId('left-off-row');
|
||||
expect(leftOff.textContent).toMatch(/left off 2d ago/);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /put back/i }));
|
||||
await waitFor(() => expect(putUnmatchedBack).toHaveBeenCalledWith('al-4'));
|
||||
});
|
||||
|
||||
test('with every album matched it says so, and still lists those left off', () => {
|
||||
setup([album('al-4', 'Demo', 'Annadale', { left_off: true })]);
|
||||
expect(screen.getByText(/every album in your library is matched/i)).toBeTruthy();
|
||||
expect(screen.getByTestId('left-off')).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,106 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { Search } from 'lucide-svelte';
|
||||
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
|
||||
import type { CatalogueSearchResult, UnmatchedAlbum } from '#lib/api/types.js';
|
||||
|
||||
// Naming the MusicBrainz album an unmatched album is: a search of
|
||||
// MusicBrainz's albums, started from the album's own title and artist, or
|
||||
// a link pasted from musicbrainz.org. MusicBrainz takes a request a second,
|
||||
// so the search runs when it's asked for, not on each keystroke.
|
||||
|
||||
let {
|
||||
album,
|
||||
busy = false,
|
||||
onMatch
|
||||
}: { album: UnmatchedAlbum; busy?: boolean; onMatch: (ref: string) => void } = $props();
|
||||
|
||||
// svelte-ignore state_referenced_locally
|
||||
let text = $state(`${album.title} ${album.artist}`.trim());
|
||||
// svelte-ignore state_referenced_locally
|
||||
let asked = $state(`${album.title} ${album.artist}`.trim());
|
||||
let link = $state('');
|
||||
|
||||
const searchStore = $derived(createCatalogueSearchQuery(asked, 'album'));
|
||||
const search = $derived($searchStore);
|
||||
const results = $derived((search.data ?? []) as CatalogueSearchResult[]);
|
||||
</script>
|
||||
|
||||
<div class="mt-3 space-y-3 rounded-md border border-border bg-bg p-3" data-testid="unmatched-match">
|
||||
<form
|
||||
class="flex gap-2"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
asked = text.trim();
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="search"
|
||||
bind:value={text}
|
||||
aria-label="Search MusicBrainz albums"
|
||||
class="min-w-0 flex-1 rounded-md border border-border bg-surface px-2.5 py-1.5 text-sm text-text-primary placeholder:text-text-muted"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
class="inline-flex shrink-0 items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
<Search size={14} strokeWidth={1.75} aria-hidden="true" /> Search
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{#if search.isPending && asked}
|
||||
<p class="text-xs text-text-secondary">Asking MusicBrainz…</p>
|
||||
{:else if search.isError}
|
||||
<p class="text-xs text-error-fg">Couldn't reach MusicBrainz. A pasted link works the same.</p>
|
||||
{:else if asked && results.length === 0}
|
||||
<p class="text-xs text-text-secondary">MusicBrainz has no album like that.</p>
|
||||
{:else if results.length > 0}
|
||||
<ul class="divide-y divide-border">
|
||||
{#each results as r (r.mbid)}
|
||||
<li class="flex items-center gap-3 py-2" data-testid="unmatched-result">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm text-text-primary">{r.name}</div>
|
||||
<div class="truncate text-xs text-text-secondary">{r.secondary_text}</div>
|
||||
</div>
|
||||
<a
|
||||
href="https://musicbrainz.org/release-group/{r.mbid}"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="shrink-0 text-xs text-text-secondary hover:text-text-primary hover:underline">MusicBrainz</a
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
disabled={busy}
|
||||
onclick={() => onMatch(r.mbid)}
|
||||
aria-label="Match to {r.name}"
|
||||
class="shrink-0 rounded-md border border-border px-2.5 py-1 text-xs text-text-primary hover:bg-surface-hover disabled:opacity-50"
|
||||
>
|
||||
This one
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
|
||||
<form
|
||||
class="flex gap-2 border-t border-border pt-3"
|
||||
onsubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (link.trim()) onMatch(link.trim());
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
bind:value={link}
|
||||
placeholder="Or paste a MusicBrainz album link"
|
||||
aria-label="MusicBrainz album link"
|
||||
class="min-w-0 flex-1 rounded-md border border-border bg-surface px-2.5 py-1.5 text-sm text-text-primary placeholder:text-text-muted"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={busy || !link.trim()}
|
||||
class="shrink-0 rounded-md border border-border px-2.5 py-1 text-xs text-text-primary hover:bg-surface-hover disabled:opacity-50"
|
||||
>
|
||||
Match
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -1,308 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { Album, ChevronDown, ListChecks, ListMusic, Search, X } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { createWantsQuery, removeWant, searchWant } from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import ListContinuation from '#lib/components/ListContinuation.svelte';
|
||||
import Cover from '#lib/components/Cover.svelte';
|
||||
import FollowControl from '#lib/components/FollowControl.svelte';
|
||||
import QuickFilter from '#lib/components/QuickFilter.svelte';
|
||||
import WantCandidates from '#lib/components/WantCandidates.svelte';
|
||||
import WantTracks from './WantTracks.svelte';
|
||||
import { needsYou, searched, wantStatus } from '#lib/wanted/wantStatus.js';
|
||||
import type { Want, WantState } from '#lib/api/types.js';
|
||||
|
||||
// Albums on the Collection's list: the ones still
|
||||
// wanted, the missing ones wanted back, or, given an artist, every album
|
||||
// of theirs in the catalogue, held or not, under a header. Each
|
||||
// open want says what its last search found and how its download is
|
||||
// getting on; Releases lists every candidate with its verdict, and Search
|
||||
// runs one now. Taking a held album off leaves its files and stops it
|
||||
// being fetched back if they go.
|
||||
//
|
||||
// Upgrades are held albums wanted for a better copy: below the
|
||||
// quality set under Acquisition, or holding a video rip. They search and
|
||||
// download like an open want, and say what copy they have.
|
||||
//
|
||||
// The list reads like the library: artists A–Z, each with its
|
||||
// albums oldest first, and each album's tracks a click away. The filter
|
||||
// narrows it to an artist or album by name, on the server, so it finds
|
||||
// what has not been scrolled to yet.
|
||||
|
||||
let { list = 'wanted', artist = '' }: { list?: WantState; artist?: string } = $props();
|
||||
|
||||
const client = useQueryClient();
|
||||
let filter = $state('');
|
||||
const q = $derived(filter.trim());
|
||||
const wantsStore = $derived(artist ? createWantsQuery('all', '', artist) : createWantsQuery(list, q));
|
||||
const wants = $derived($wantsStore);
|
||||
const items = $derived((wants.data?.pages ?? []).flatMap((p) => p.items) as Want[]);
|
||||
const head = $derived(wants.data?.pages[0]?.artist);
|
||||
|
||||
// The server sends the list artist by artist; each run of one artist's
|
||||
// albums is a section.
|
||||
type ArtistSection = { key: string; name: string; mbid: string; wants: Want[] };
|
||||
const sections = $derived.by(() => {
|
||||
const out: ArtistSection[] = [];
|
||||
for (const w of items) {
|
||||
const key = w.artist_mbid || w.artist_name;
|
||||
const last = out[out.length - 1];
|
||||
if (last && last.key === key) last.wants.push(w);
|
||||
else out.push({ key, name: w.artist_name, mbid: w.artist_mbid, wants: [w] });
|
||||
}
|
||||
return out;
|
||||
});
|
||||
|
||||
let busy = $state<string | null>(null);
|
||||
let searching = $state<string | null>(null);
|
||||
let open = $state<string | null>(null);
|
||||
let shown = $state<string | null>(null);
|
||||
|
||||
async function onRemove(w: Want) {
|
||||
busy = w.id;
|
||||
try {
|
||||
await removeWant(w.id);
|
||||
pushToast(
|
||||
w.held_at
|
||||
? `${w.title} is off the list. Its files stay, and it won't be fetched back if they go missing.`
|
||||
: `${w.title} is off the wanted list.`
|
||||
);
|
||||
await client.invalidateQueries({ queryKey: ['adminWants'] });
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onSearch(w: Want) {
|
||||
searching = w.id;
|
||||
try {
|
||||
const r = await searchWant(w.id);
|
||||
pushToast(searched(w, r), r.outcome === 'error' ? 'error' : 'info');
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: ['adminWants'] }),
|
||||
client.invalidateQueries({ queryKey: qk.wantCandidates(w.id) })
|
||||
]);
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
searching = null;
|
||||
}
|
||||
}
|
||||
|
||||
// How a held album arrived, when Minstrel fetched it.
|
||||
function arrived(w: Want): string | null {
|
||||
const g = w.grab;
|
||||
if (!g || g.import_state !== 'imported' || !g.imported_at) return null;
|
||||
return `Imported ${plural(g.imported_files, 'track', 'tracks')} ${relativeTime(g.imported_at)} from ${g.name}`;
|
||||
}
|
||||
|
||||
// A want the schedule still searches for: open, or held but wanted for a
|
||||
// better copy.
|
||||
const searchable = (w: Want) => !w.held_at || !!w.upgrade;
|
||||
|
||||
function upgradeLine(w: Want): string {
|
||||
if (w.upgrade === 'rip') return 'A track is a video rip; looking for a clean copy';
|
||||
return w.held_quality ? `You have ${w.held_quality}; looking for better` : 'Looking for a better copy';
|
||||
}
|
||||
|
||||
|
||||
function why(w: Want): string {
|
||||
if (w.reason === 'request') return w.requested_by ? `Requested by ${w.requested_by}` : 'Requested';
|
||||
if (w.reason === 'follow') return 'New from a followed artist';
|
||||
if (w.reason === 'library') return 'In your library when the list began';
|
||||
return 'Its files went missing';
|
||||
}
|
||||
|
||||
|
||||
function kind(w: Want): string {
|
||||
const parts = [w.primary_type, ...w.secondary_types].filter(Boolean);
|
||||
if (w.year) parts.push(w.year);
|
||||
return parts.join(' · ');
|
||||
}
|
||||
|
||||
function hideBroken(e: Event) {
|
||||
(e.currentTarget as HTMLImageElement).style.display = 'none';
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if artist && head}
|
||||
<header class="mb-4 flex items-center gap-4" data-testid="catalogue-artist-head">
|
||||
<div class="relative h-24 w-24 shrink-0 overflow-hidden rounded-md bg-surface-hover">
|
||||
<Cover src={head.image_url} fallback="artist" />
|
||||
</div>
|
||||
<div class="min-w-0 space-y-1">
|
||||
<a href="/collection" class="text-xs text-text-secondary hover:text-text-primary">← Catalogue</a>
|
||||
<h2 class="truncate text-xl font-medium text-text-primary">{head.artist_name}</h2>
|
||||
<p class="text-sm text-text-secondary" data-testid="catalogue-artist-counts">
|
||||
{head.held} of {plural(head.albums, 'album', 'albums')} held{head.wanted ? ` · ${head.wanted} wanted` : ''}{head.missing
|
||||
? ` · ${head.missing} with files missing`
|
||||
: ''}{head.downloading ? ` · ${head.downloading} downloading` : ''}
|
||||
</p>
|
||||
<div class="flex flex-wrap items-center gap-3 text-sm">
|
||||
<FollowControl artistMbid={head.artist_mbid} artistName={head.artist_name} />
|
||||
{#if head.artist_id}
|
||||
<a href="/artists/{head.artist_id}" class="text-accent-fg hover:underline">Open in the library</a>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
{/if}
|
||||
|
||||
{#if !artist && !wants.isPending && (items.length > 0 || q)}
|
||||
<div class="mb-3">
|
||||
<QuickFilter bind:value={filter} placeholder="Filter artists and albums" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if wants.isPending}
|
||||
<p class="text-text-secondary">Reading the wanted list…</p>
|
||||
{:else if wants.isError && !wants.isFetchNextPageError}
|
||||
<p class="text-error-fg">Couldn't load {artist ? "this artist's albums" : 'the wanted list'}.</p>
|
||||
{:else if items.length === 0 && q}
|
||||
<p class="text-text-secondary" data-testid="want-filter-empty">
|
||||
Nothing on this list has an artist or album named like <span class="font-medium">'{q}'</span>.
|
||||
</p>
|
||||
{:else if items.length === 0}
|
||||
<div class="rounded-lg border border-border bg-surface p-6 text-center">
|
||||
<ListChecks size={28} strokeWidth={1} class="mx-auto text-text-muted" />
|
||||
<p class="mt-3 text-text-primary">
|
||||
{#if artist}None of this artist's albums are in the catalogue.
|
||||
{:else if list === 'upgrade'}No album is wanted for a better copy.
|
||||
{:else}Nothing is wanted.{/if}
|
||||
</p>
|
||||
<p class="mt-1 text-sm text-text-secondary">
|
||||
{#if list === 'upgrade'}
|
||||
An album you have below the quality set under
|
||||
<a href="/admin/acquisition" class="text-accent-fg hover:underline">Acquisition</a>, or with a video
|
||||
rip among its tracks, lands here.
|
||||
{:else}
|
||||
A request you approve, a new release from a followed artist, or an album whose files went
|
||||
missing lands here.
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="space-y-4">
|
||||
{#each sections as a, i (a.key + ':' + i)}
|
||||
<section data-testid="want-artist" aria-label={a.name}>
|
||||
{#if !artist}<h2 class="mb-1.5 flex items-baseline gap-2 px-1">
|
||||
<span class="truncate text-sm font-medium text-text-primary">
|
||||
{#if a.mbid}
|
||||
<a href="/collection/artist/{encodeURIComponent(a.mbid)}" class="hover:underline">{a.name}</a>
|
||||
{:else}
|
||||
{a.name}
|
||||
{/if}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs text-text-muted">{plural(a.wants.length, 'album', 'albums')}</span>
|
||||
</h2>{/if}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each a.wants as w (w.id)}
|
||||
<li class="space-y-2 p-3" data-testid="want-row">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="relative flex h-14 w-14 shrink-0 items-center justify-center overflow-hidden rounded-md bg-surface-hover" aria-hidden="true">
|
||||
<Album size={22} strokeWidth={1} class="text-text-muted" />
|
||||
{#if w.image_url}
|
||||
<img src={w.image_url} alt="" class="absolute inset-0 h-full w-full object-cover" loading="lazy" onerror={hideBroken} />
|
||||
{/if}
|
||||
</div>
|
||||
<div class="min-w-0 flex-1 space-y-0.5">
|
||||
<div class="truncate text-sm font-medium text-text-primary">
|
||||
{#if w.album_id && w.held_at}
|
||||
<a href="/albums/{w.album_id}" class="hover:underline">{w.title}</a>
|
||||
{:else}
|
||||
{w.title}
|
||||
{/if}
|
||||
{#if kind(w)}<span class="text-xs font-normal text-text-muted"> · {kind(w)}</span>{/if}
|
||||
</div>
|
||||
<div class="text-xs text-text-muted" data-testid="want-why">
|
||||
{why(w)} · {w.held_at ? `held ${relativeTime(w.held_at)}` : `wanted ${relativeTime(w.wanted_at)}`}
|
||||
</div>
|
||||
{#if w.held_at && w.upgrade}
|
||||
<div class="truncate text-xs text-text-secondary" data-testid="want-upgrade">{upgradeLine(w)}</div>
|
||||
{/if}
|
||||
{#if searchable(w)}
|
||||
<div
|
||||
class="text-xs {needsYou(w) ? 'text-text-primary' : 'truncate text-text-secondary'}"
|
||||
data-testid="want-search"
|
||||
>
|
||||
{wantStatus(w)}
|
||||
{#if needsYou(w)}
|
||||
<a href="/collection/activity" class="ml-1 text-accent-fg hover:underline">Decide on Activity</a>
|
||||
{/if}
|
||||
</div>
|
||||
{:else if arrived(w)}
|
||||
<div class="truncate text-xs text-text-secondary" data-testid="want-arrived">{arrived(w)}</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex shrink-0 flex-wrap justify-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (shown = shown === w.id ? null : w.id)}
|
||||
aria-expanded={shown === w.id}
|
||||
aria-label="Tracks of {w.title}"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
<ListMusic size={12} strokeWidth={2} /> Tracks
|
||||
<ChevronDown size={12} strokeWidth={2} class={shown === w.id ? 'rotate-180' : ''} />
|
||||
</button>
|
||||
{#if searchable(w)}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onSearch(w)}
|
||||
disabled={searching !== null || !!w.grab?.live}
|
||||
aria-label="Search for {w.title} now"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
<Search size={12} strokeWidth={2} /> {searching === w.id ? 'Searching…' : 'Search'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (open = open === w.id ? null : w.id)}
|
||||
aria-expanded={open === w.id}
|
||||
aria-label="Releases found for {w.title}"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Releases <ChevronDown size={12} strokeWidth={2} class={open === w.id ? 'rotate-180' : ''} />
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onRemove(w)}
|
||||
disabled={busy === w.id}
|
||||
aria-label={w.held_at ? `Take ${w.title} off the list` : `Stop wanting ${w.title}`}
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
<X size={12} strokeWidth={2} /> Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{#if shown === w.id}
|
||||
<div class="sm:pl-[4.25rem]">
|
||||
<WantTracks wantId={w.id} />
|
||||
</div>
|
||||
{/if}
|
||||
{#if open === w.id && searchable(w)}
|
||||
<div class="sm:pl-[4.25rem]">
|
||||
<WantCandidates wantId={w.id} title={w.title} />
|
||||
</div>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</section>
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<ListContinuation
|
||||
hasMore={!!wants.hasNextPage}
|
||||
loading={wants.isFetchingNextPage}
|
||||
failed={wants.isFetchNextPageError}
|
||||
onMore={() => wants.fetchNextPage()}
|
||||
/>
|
||||
{/if}
|
||||
@@ -1,345 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { mockInfiniteQuery, mockQuery } from '../../../test-utils/query';
|
||||
import type { LibraryListing, Want, WantGrab, WantsPage } from '#lib/api/types.js';
|
||||
|
||||
vi.mock('#lib/api/wanted.js', async () => {
|
||||
const { mockQuery } = await import('../../../test-utils/query');
|
||||
return {
|
||||
// The artist page's FollowControl.
|
||||
createFollowQuery: vi.fn(() => mockQuery({ data: { following: true } })),
|
||||
createReleaseProfilesQuery: vi.fn(() => mockQuery({ data: { profiles: [], primary_types: [], secondary_types: [] } })),
|
||||
putFollow: vi.fn(),
|
||||
deleteFollow: vi.fn(),
|
||||
createWantsQuery: vi.fn(),
|
||||
removeWant: vi.fn().mockResolvedValue(undefined),
|
||||
searchWant: vi.fn().mockResolvedValue({
|
||||
outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', narrowed: []
|
||||
}),
|
||||
createCandidatesQuery: vi.fn(),
|
||||
createWantTracksQuery: vi.fn(),
|
||||
grabCandidate: vi.fn(),
|
||||
blockCandidate: vi.fn(),
|
||||
unblockRelease: vi.fn()
|
||||
};
|
||||
});
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
import WantList from './WantList.svelte';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { createCandidatesQuery, createWantTracksQuery, createWantsQuery, removeWant, searchWant } from '#lib/api/wanted.js';
|
||||
import type { WantState, WantTracks } from '#lib/api/types.js';
|
||||
|
||||
const DAY = 24 * 3_600_000;
|
||||
const ago = (ms: number) => new Date(Date.now() - ms).toISOString();
|
||||
|
||||
function want(id: string, extra: Partial<Want> = {}): Want {
|
||||
return {
|
||||
id,
|
||||
release_group_mbid: `rg-${id}`,
|
||||
title: 'The Ballad of Darren',
|
||||
artist_mbid: 'blur',
|
||||
artist_name: 'Blur',
|
||||
artist_id: 'art-1',
|
||||
primary_type: 'Album',
|
||||
secondary_types: [],
|
||||
year: '2023',
|
||||
reason: 'follow',
|
||||
wanted_at: ago(2 * DAY),
|
||||
held_at: null,
|
||||
image_url: '',
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
function page(
|
||||
items: Want[],
|
||||
library: LibraryListing = { listed_at: ago(DAY), unlisted: 0 },
|
||||
artist?: WantsPage['artist']
|
||||
): WantsPage {
|
||||
return {
|
||||
artist,
|
||||
items,
|
||||
total: items.length,
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
counts: { artists: 2, wanted: 2, missing: 1, held: 4, upgrades: 0, following: 1, activity: 1, attention: 0, blocked: 0, unmatched: 0 },
|
||||
library
|
||||
};
|
||||
}
|
||||
|
||||
function grab(extra: Partial<WantGrab> = {}): WantGrab {
|
||||
return {
|
||||
id: 'g1',
|
||||
name: 'Blur - Blur (1997) [FLAC]',
|
||||
grabbed_at: ago(60_000),
|
||||
origin: 'schedule',
|
||||
quality: 'lossless',
|
||||
live: true,
|
||||
end_reason: '',
|
||||
progress: 0,
|
||||
import_state: '',
|
||||
import_reason: '',
|
||||
end_detail: '',
|
||||
imported_at: null,
|
||||
imported_files: 0,
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(
|
||||
items: Want[] = [want('w1'), want('w2', { reason: 'request', requested_by: 'sam', title: 'Parklife' })],
|
||||
state: WantState = 'wanted',
|
||||
library?: LibraryListing,
|
||||
tracks: WantTracks = {
|
||||
source: 'musicbrainz',
|
||||
edition: '2023 · CD · GB',
|
||||
tracks: [
|
||||
{ disc: 1, number: 1, title: 'The Ballad', length_ms: 214000, missing: false },
|
||||
{ disc: 1, number: 2, title: 'St. Charles Square', length_ms: 3_725_000, missing: false }
|
||||
]
|
||||
}
|
||||
) {
|
||||
vi.mocked(createWantsQuery).mockReturnValue(
|
||||
mockInfiniteQuery({ pages: [page(items, library)] }) as unknown as ReturnType<typeof createWantsQuery>
|
||||
);
|
||||
vi.mocked(createCandidatesQuery).mockReturnValue(
|
||||
mockQuery({ data: [] }) as unknown as ReturnType<typeof createCandidatesQuery>
|
||||
);
|
||||
vi.mocked(createWantTracksQuery).mockReturnValue(
|
||||
mockQuery({ data: tracks }) as unknown as ReturnType<typeof createWantTracksQuery>
|
||||
);
|
||||
return render(WantList, { list: state });
|
||||
}
|
||||
|
||||
describe('WantList', () => {
|
||||
test('asks for its own state', () => {
|
||||
setup([], 'upgrade');
|
||||
expect(createWantsQuery).toHaveBeenCalledWith('upgrade', '');
|
||||
expect(screen.getByText(/no album is wanted for a better copy/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
test('a want says why it is wanted', () => {
|
||||
setup();
|
||||
const why = screen.getAllByTestId('want-why').map((e) => e.textContent ?? '');
|
||||
expect(why[0]).toMatch(/new from a followed artist/i);
|
||||
expect(why[1]).toMatch(/requested by sam/i);
|
||||
});
|
||||
|
||||
test('remove takes a want off the list', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /stop wanting parklife/i }));
|
||||
await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w2'));
|
||||
});
|
||||
|
||||
test('a held album can be taken off the list, and is not searched for', async () => {
|
||||
setup([want('w1', { held_at: ago(DAY), album_id: 'al-1', reason: 'library' })], 'held');
|
||||
expect(screen.queryByRole('button', { name: /stop wanting|search for/i })).toBeNull();
|
||||
expect(screen.getByRole('link', { name: /the ballad of darren/i }).getAttribute('href')).toBe('/albums/al-1');
|
||||
expect(screen.getByTestId('want-why').textContent).toMatch(/in your library when the list began/i);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /take the ballad of darren off the list/i }));
|
||||
await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w1'));
|
||||
});
|
||||
|
||||
test('an empty list explains what lands there', () => {
|
||||
setup([]);
|
||||
expect(screen.getByText(/nothing is wanted/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
test('each open want says what its last search found', () => {
|
||||
setup([
|
||||
want('w1'),
|
||||
want('w2', {
|
||||
title: 'Parklife',
|
||||
search: { searched_at: ago(3_600_000), outcome: 'nothing', considered: 4, best_release: 'x', best_verdict: 'rejected', error: '' }
|
||||
}),
|
||||
want('w3', { title: 'Blur', grab: grab() }),
|
||||
want('w4', { title: '13', grab: grab({ import_state: 'downloading', progress: 0.42 }) })
|
||||
]);
|
||||
const lines = screen.getAllByTestId('want-search').map((e) => e.textContent ?? '');
|
||||
expect(lines[0]).toMatch(/not searched yet/i);
|
||||
expect(lines[1]).toMatch(/4 found, none of them this album/i);
|
||||
expect(lines[2]).toMatch(/downloading blur - blur \(1997\) \[flac\], taken by the schedule/i);
|
||||
expect(lines[3]).toMatch(/downloading 42%/i);
|
||||
});
|
||||
|
||||
test('a download waiting on a person says why and points to Activity', () => {
|
||||
setup([
|
||||
want('w1', { grab: grab({ import_state: 'review', import_reason: 'Only the lengths agree. A person decides.' }) })
|
||||
]);
|
||||
const line = screen.getByTestId('want-search');
|
||||
expect(line.textContent).toMatch(/needs you: only the lengths agree/i);
|
||||
expect(screen.getByRole('link', { name: /decide on activity/i }).getAttribute('href')).toBe('/collection/activity');
|
||||
// A live download can't be searched for again.
|
||||
expect((screen.getByRole('button', { name: /search for the ballad of darren now/i }) as HTMLButtonElement).disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('a refused download is named beside the search that follows it', () => {
|
||||
setup([
|
||||
want('w1', {
|
||||
search: { searched_at: ago(3_600_000), outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', error: '' },
|
||||
grab: grab({ live: false, end_reason: 'refused', import_state: 'refused', import_reason: 'Another album.' })
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('want-search').textContent).toMatch(/last download refused: another album/i);
|
||||
});
|
||||
|
||||
test('a download given up on is named beside the search that follows it', () => {
|
||||
setup([
|
||||
want('w1', {
|
||||
search: { searched_at: ago(3_600_000), outcome: 'waiting', considered: 4, best_release: '', best_verdict: '', error: '' },
|
||||
grab: grab({ live: false, end_reason: 'stalled', import_state: 'downloading', end_detail: 'Nobody was sharing it.' })
|
||||
})
|
||||
]);
|
||||
expect(screen.getByTestId('want-search').textContent).toMatch(/last download given up: nobody was sharing it/i);
|
||||
});
|
||||
|
||||
test('a held album says how it arrived', () => {
|
||||
setup(
|
||||
[
|
||||
want('w1', {
|
||||
held_at: ago(DAY),
|
||||
album_id: 'al-1',
|
||||
grab: grab({ live: false, end_reason: 'imported', import_state: 'imported', imported_at: ago(DAY), imported_files: 11 })
|
||||
})
|
||||
],
|
||||
'held'
|
||||
);
|
||||
expect(screen.getByTestId('want-arrived').textContent).toMatch(/imported 11 tracks .* from blur - blur/i);
|
||||
});
|
||||
|
||||
test('Search runs one now and says what came of it', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /search for parklife now/i }));
|
||||
await waitFor(() => expect(searchWant).toHaveBeenCalledWith('w2'));
|
||||
await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Nothing found for Parklife.', 'info'));
|
||||
});
|
||||
|
||||
test('Releases opens what the last search found', async () => {
|
||||
setup();
|
||||
expect(screen.queryByTestId('want-candidates')).toBeNull();
|
||||
const toggle = screen.getByRole('button', { name: /releases found for parklife/i });
|
||||
await fireEvent.click(toggle);
|
||||
expect(toggle.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(screen.getByTestId('want-candidates')).toBeTruthy();
|
||||
expect(createCandidatesQuery).toHaveBeenCalledWith('w2');
|
||||
});
|
||||
|
||||
test('albums sit under their artist, as in the library', () => {
|
||||
setup([
|
||||
want('w1', { artist_mbid: 'blur', artist_name: 'Blur', artist_id: 'art-1', title: 'Parklife' }),
|
||||
want('w2', { artist_mbid: 'blur', artist_name: 'Blur', artist_id: 'art-1', title: '13' }),
|
||||
want('w3', { artist_mbid: 'camel', artist_name: 'Camel', artist_id: undefined, title: 'Moonmadness' })
|
||||
]);
|
||||
const sections = screen.getAllByTestId('want-artist');
|
||||
expect(sections.map((s) => s.getAttribute('aria-label'))).toEqual(['Blur', 'Camel']);
|
||||
expect(sections[0].querySelectorAll('[data-testid="want-row"]').length).toBe(2);
|
||||
expect(sections[0].textContent).toMatch(/2 albums/);
|
||||
expect(sections[1].textContent).toMatch(/1 album/);
|
||||
// Each artist opens on their page in the catalogue.
|
||||
expect(screen.getByRole('link', { name: 'Blur' }).getAttribute('href')).toBe('/collection/artist/blur');
|
||||
expect(screen.getByRole('link', { name: 'Camel' }).getAttribute('href')).toBe('/collection/artist/camel');
|
||||
});
|
||||
|
||||
test('Tracks shows the album\'s tracks, with the edition they come from', async () => {
|
||||
setup();
|
||||
expect(screen.queryByTestId('want-tracks')).toBeNull();
|
||||
const toggle = screen.getByRole('button', { name: /tracks of parklife/i });
|
||||
await fireEvent.click(toggle);
|
||||
expect(toggle.getAttribute('aria-expanded')).toBe('true');
|
||||
expect(createWantTracksQuery).toHaveBeenCalledWith('w2');
|
||||
const panel = screen.getByTestId('want-tracks');
|
||||
expect(panel.textContent).toMatch(/MusicBrainz's standard edition\s+·\s+2023 · CD · GB/);
|
||||
const rows = screen.getAllByTestId('want-track').map((e) => e.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(rows).toEqual(['1 The Ballad 3:34', '2 St. Charles Square 1:02:05']);
|
||||
});
|
||||
|
||||
test('a held album\'s tracks are its own, a lost file marked', async () => {
|
||||
setup([want('w1', { held_at: ago(DAY), album_id: 'al-1' })], 'held', undefined, {
|
||||
source: 'library',
|
||||
tracks: [
|
||||
{ disc: 1, number: 1, title: 'The Ballad', length_ms: 214000, missing: true },
|
||||
{ disc: 2, number: 1, title: 'Bonus', length_ms: 0, missing: false }
|
||||
]
|
||||
});
|
||||
await fireEvent.click(screen.getByRole('button', { name: /tracks of the ballad of darren/i }));
|
||||
const panel = screen.getByTestId('want-tracks');
|
||||
expect(panel.textContent).not.toMatch(/MusicBrainz/);
|
||||
const rows = screen.getAllByTestId('want-track').map((e) => e.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(rows).toEqual(['1-1 The Ballad file missing 3:34', '2-1 Bonus']);
|
||||
});
|
||||
|
||||
test('the filter asks the server for the artists and albums it names', async () => {
|
||||
setup();
|
||||
await fireEvent.input(screen.getByRole('searchbox', { name: /filter artists and albums/i }), {
|
||||
target: { value: ' park ' }
|
||||
});
|
||||
await waitFor(() => expect(createWantsQuery).toHaveBeenLastCalledWith('wanted', 'park'));
|
||||
});
|
||||
|
||||
test("an artist's page lists every album of theirs under a header", () => {
|
||||
vi.mocked(createWantsQuery).mockReturnValue(
|
||||
mockInfiniteQuery({
|
||||
pages: [
|
||||
page([want('w1', { held_at: ago(DAY), album_id: 'al-1', title: 'Parklife' }), want('w2')], undefined, {
|
||||
artist_mbid: 'blur',
|
||||
artist_name: 'Blur',
|
||||
sort_name: 'Blur',
|
||||
artist_id: 'art-1',
|
||||
image_url: '/art/blur',
|
||||
albums: 2,
|
||||
held: 1,
|
||||
wanted: 1,
|
||||
missing: 0,
|
||||
downloading: 0,
|
||||
following: true
|
||||
})
|
||||
]
|
||||
}) as unknown as ReturnType<typeof createWantsQuery>
|
||||
);
|
||||
vi.mocked(createCandidatesQuery).mockReturnValue(
|
||||
mockQuery({ data: [] }) as unknown as ReturnType<typeof createCandidatesQuery>
|
||||
);
|
||||
render(WantList, { artist: 'blur' });
|
||||
expect(createWantsQuery).toHaveBeenCalledWith('all', '', 'blur');
|
||||
const head = screen.getByTestId('catalogue-artist-head');
|
||||
expect(head.textContent).toMatch(/Blur/);
|
||||
expect(screen.getByTestId('catalogue-artist-counts').textContent).toMatch(/1 of 2 albums held\s+·\s+1 wanted/);
|
||||
expect(screen.getByRole('link', { name: /open in the library/i }).getAttribute('href')).toBe('/artists/art-1');
|
||||
expect(screen.getByRole('link', { name: /catalogue/i }).getAttribute('href')).toBe('/collection');
|
||||
// One artist: no filter, no artist headings, both albums.
|
||||
expect(screen.queryByRole('searchbox')).toBeNull();
|
||||
expect(screen.getAllByTestId('want-row')).toHaveLength(2);
|
||||
expect(screen.queryByRole('link', { name: 'Blur' })).toBeNull();
|
||||
});
|
||||
|
||||
test('an upgrade is a held album searched for a better copy', async () => {
|
||||
setup(
|
||||
[
|
||||
want('u1', { held_at: ago(DAY), reason: 'library', upgrade: 'quality', held_quality: 'MP3, about 192 kbps' }),
|
||||
want('u2', { held_at: ago(DAY), reason: 'library', upgrade: 'rip', title: 'Humanz' })
|
||||
],
|
||||
'upgrade'
|
||||
);
|
||||
expect(createWantsQuery).toHaveBeenCalledWith('upgrade', '');
|
||||
const lines = screen.getAllByTestId('want-upgrade').map((e) => e.textContent ?? '');
|
||||
expect(lines[0]).toMatch(/you have mp3, about 192 kbps; looking for better/i);
|
||||
expect(lines[1]).toMatch(/video rip; looking for a clean copy/i);
|
||||
expect(screen.getAllByTestId('want-search')[0].textContent).toMatch(/not searched yet/i);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /search for humanz now/i }));
|
||||
await waitFor(() => expect(searchWant).toHaveBeenCalledWith('u2'));
|
||||
});
|
||||
|
||||
test('a held album not wanted for a better copy has no search', () => {
|
||||
setup([want('h1', { held_at: ago(DAY), reason: 'library' })], 'held');
|
||||
expect(screen.queryByTestId('want-upgrade')).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /search for/i })).toBeNull();
|
||||
});
|
||||
|
||||
test('with no upgrades it says what would land here', () => {
|
||||
setup([], 'upgrade');
|
||||
expect(screen.getByText(/no album is wanted for a better copy/i)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { createWantTracksQuery } from '#lib/api/wanted.js';
|
||||
import { formatDuration } from '#lib/media/duration.js';
|
||||
import { errCode } from '#lib/api/errors.js';
|
||||
import type { WantTrack } from '#lib/api/types.js';
|
||||
|
||||
// An album's tracks under its row in the Wanted view: the
|
||||
// library's own for an album it holds, a lost file marked, otherwise
|
||||
// MusicBrainz's standard edition of what is wanted.
|
||||
|
||||
let { wantId }: { wantId: string } = $props();
|
||||
|
||||
const tracksStore = $derived(createWantTracksQuery(wantId));
|
||||
const tracks = $derived($tracksStore);
|
||||
const list = $derived(tracks.data?.tracks ?? []);
|
||||
const discs = $derived(list.some((t) => t.disc > 1));
|
||||
const away = $derived(tracks.isError && errCode(tracks.error) === 'musicbrainz_unreachable');
|
||||
|
||||
const position = (t: WantTrack) => (discs ? `${t.disc}-${t.number}` : String(t.number || ''));
|
||||
</script>
|
||||
|
||||
<div class="text-xs" data-testid="want-tracks">
|
||||
{#if tracks.isPending}
|
||||
<p class="text-text-secondary">Reading the tracks…</p>
|
||||
{:else if tracks.isError}
|
||||
<p class="text-text-secondary">
|
||||
{away ? "MusicBrainz can't be reached, so the tracks can't be shown." : "Couldn't load the tracks."}
|
||||
</p>
|
||||
{:else if tracks.data.source === 'none' || list.length === 0}
|
||||
<p class="text-text-secondary">MusicBrainz lists no edition of this album, so there are no tracks to show.</p>
|
||||
{:else}
|
||||
{#if tracks.data.source === 'musicbrainz'}
|
||||
<p class="mb-1 text-text-muted">
|
||||
MusicBrainz's standard edition{tracks.data.edition ? ` · ${tracks.data.edition}` : ''}
|
||||
</p>
|
||||
{/if}
|
||||
<ol class="space-y-0.5">
|
||||
{#each list as t, i (i)}
|
||||
<li class="flex items-baseline gap-2" data-testid="want-track">
|
||||
<span class="w-8 shrink-0 text-right tabular-nums text-text-muted">{position(t)}</span>
|
||||
<span class="min-w-0 flex-1 truncate {t.missing ? 'text-text-muted line-through' : 'text-text-primary'}">
|
||||
{t.title}
|
||||
</span>
|
||||
{#if t.missing}<span class="shrink-0 text-text-secondary">file missing</span>{/if}
|
||||
{#if t.length_ms > 0}
|
||||
<span class="shrink-0 tabular-nums text-text-muted">{formatDuration(t.length_ms / 1000)}</span>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
import { liveDownloadLine } from './downloadState.js';
|
||||
|
||||
describe('liveDownloadLine', () => {
|
||||
const g = (import_state: Parameters<typeof liveDownloadLine>[0]['import_state'], import_reason = '') => ({
|
||||
import_state,
|
||||
progress: 0.428,
|
||||
import_reason
|
||||
});
|
||||
|
||||
test('says each state of a running download', () => {
|
||||
expect(liveDownloadLine(g('downloading'))).toBe('Downloading 42%');
|
||||
expect(liveDownloadLine(g('importing'))).toBe('Downloaded; checking it is the album and filing it');
|
||||
expect(liveDownloadLine(g('waiting'))).toBe('Downloaded; waiting to be imported');
|
||||
expect(liveDownloadLine(g('waiting', 'the library is busy'))).toBe('Downloaded; the library is busy');
|
||||
expect(liveDownloadLine(g('review', '9 files against 12 tracks'))).toBe('Needs you: 9 files against 12 tracks');
|
||||
expect(liveDownloadLine(g('failed', 'disk full'))).toBe('Import failed: disk full');
|
||||
});
|
||||
|
||||
test('has nothing to say before the client reports', () => {
|
||||
expect(liveDownloadLine(g(''))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { ImportState } from '#lib/api/types.js';
|
||||
|
||||
// A running download's state in a line: how far it has got, or what its
|
||||
// import is doing or waiting on. The wanted list and the admin Overview say
|
||||
// it the same way. Null before the download client has reported on it.
|
||||
export function liveDownloadLine(g: { import_state: ImportState; progress: number; import_reason: string }): string | null {
|
||||
switch (g.import_state) {
|
||||
case 'downloading':
|
||||
return `Downloading ${Math.floor(g.progress * 100)}%`;
|
||||
case 'importing':
|
||||
return 'Downloaded; checking it is the album and filing it';
|
||||
case 'waiting':
|
||||
return `Downloaded; ${g.import_reason || 'waiting to be imported'}`;
|
||||
case 'review':
|
||||
return `Needs you: ${g.import_reason}`;
|
||||
case 'failed':
|
||||
return `Import failed: ${g.import_reason}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import type { SearchResult, Want } from '#lib/api/types.js';
|
||||
import { liveDownloadLine } from './downloadState.js';
|
||||
|
||||
// How a want reads in a line, wherever it is shown: the Collection's lists
|
||||
// and the Missing page's folders.
|
||||
|
||||
// What a Search an admin ran found, for its toast.
|
||||
export function searched(w: Want, r: SearchResult): string {
|
||||
let said: string;
|
||||
switch (r.outcome) {
|
||||
case 'grabbed':
|
||||
said = `Took ${r.grabbed ?? r.best_release}.`;
|
||||
break;
|
||||
case 'waiting':
|
||||
said = `Found ${r.considered}; nothing taken. Releases shows why.`;
|
||||
break;
|
||||
case 'nothing':
|
||||
said = r.considered ? `Found ${r.considered}, none of them ${w.title}.` : `Nothing found for ${w.title}.`;
|
||||
break;
|
||||
default:
|
||||
said = r.error ?? 'The search failed.';
|
||||
}
|
||||
if (r.narrowed.length) said += ` ${r.narrowed.map((n) => n.label).join(', ')} didn't answer.`;
|
||||
return said;
|
||||
}
|
||||
|
||||
// A download still running, in a line: how far it has got, or what its
|
||||
// import is doing or waiting on.
|
||||
export function downloading(w: Want): string | null {
|
||||
const g = w.grab;
|
||||
if (!g?.live) return null;
|
||||
const line = liveDownloadLine(g);
|
||||
// While it downloads or files, the line names the release it took.
|
||||
if (line) return g.import_state === 'downloading' || g.import_state === 'importing' ? `${line} · ${g.name}` : line;
|
||||
const who = g.origin === 'operator' ? 'taken by you' : 'taken by the schedule';
|
||||
return `Downloading ${g.name}, ${who} ${relativeTime(g.grabbed_at)}`;
|
||||
}
|
||||
|
||||
// A download waiting on a person: an import to review, or one that failed.
|
||||
export const needsYou = (w: Want) =>
|
||||
!!w.grab?.live && (w.grab.import_state === 'review' || w.grab.import_state === 'failed');
|
||||
|
||||
// What the schedule last did about a want, in a line.
|
||||
export function wantStatus(w: Want): string {
|
||||
const live = downloading(w);
|
||||
if (live) return live;
|
||||
const s = w.search;
|
||||
let said = 'Not searched yet';
|
||||
if (s) {
|
||||
const when = `Searched ${relativeTime(s.searched_at)}`;
|
||||
switch (s.outcome) {
|
||||
case 'nothing':
|
||||
said = s.considered ? `${when}: ${s.considered} found, none of them this album` : `${when}: nothing found`;
|
||||
break;
|
||||
case 'waiting':
|
||||
said = `${when}: ${s.considered} found, nothing taken`;
|
||||
break;
|
||||
case 'grabbed':
|
||||
said = `${when}: took ${s.best_release}`;
|
||||
break;
|
||||
default:
|
||||
said = `${when}: ${s.error}`;
|
||||
}
|
||||
}
|
||||
const g = w.grab;
|
||||
if (g?.import_state === 'refused') said += `. Last download refused: ${g.import_reason}`;
|
||||
else if (g && !g.live && ['stalled', 'failed', 'gone'].includes(g.end_reason) && g.end_detail)
|
||||
said += `. Last download given up: ${g.end_detail}`;
|
||||
return said;
|
||||
}
|
||||
@@ -1,43 +1,21 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from 'svelte';
|
||||
import { page } from '$app/state';
|
||||
import SectionRail, { type RailItem } from '#lib/components/SectionRail.svelte';
|
||||
import { createAdminSummaryQuery } from '#lib/api/admin.js';
|
||||
import { countOf } from '#lib/admin/queues.js';
|
||||
|
||||
let { children } = $props<{ children: import('svelte').Snippet }>();
|
||||
|
||||
// Admin: one page per section down a left rail, as Settings and
|
||||
// the Collection are, so the sections sit in the same place everywhere
|
||||
// and fit a phone. Each queue carries how many wait on you, from one
|
||||
// summary read that is refreshed whenever you move between admin pages.
|
||||
// The library's health queues are under Collection.
|
||||
const summaryStore = createAdminSummaryQuery();
|
||||
const summary = $derived($summaryStore.data);
|
||||
|
||||
// Refetch when the admin moves to another admin page, where they may have
|
||||
// just cleared something. Not on first mount (the query is fetching
|
||||
// already), and untracked, so the refetch's own result doesn't loop.
|
||||
let lastPath = page.url.pathname;
|
||||
$effect(() => {
|
||||
const path = page.url.pathname;
|
||||
if (path === lastPath) return;
|
||||
lastPath = path;
|
||||
untrack(() => $summaryStore.refetch?.());
|
||||
});
|
||||
|
||||
const items: RailItem[] = $derived([
|
||||
// and fit a phone. The library's health queues are under Collection.
|
||||
const items: RailItem[] = [
|
||||
{ href: '/admin', label: 'Overview', exact: true },
|
||||
{ href: '/admin/requests', label: 'Requests', attention: countOf(summary, 'requests') },
|
||||
{ href: '/admin/library', label: 'Library' },
|
||||
{ href: '/admin/acquisition', label: 'Acquisition' },
|
||||
{ href: '/admin/metadata', label: 'Metadata sources' },
|
||||
{ href: '/admin/email', label: 'Email & network' },
|
||||
{ href: '/admin/users', label: 'Users' },
|
||||
{ href: '/admin/backups', label: 'Backups' },
|
||||
{ href: '/admin/diagnostics', label: 'Diagnostics' },
|
||||
{ href: '/admin/tuning', label: 'Tuning' }
|
||||
]);
|
||||
];
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
|
||||
@@ -5,19 +5,16 @@
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import { formatBytes } from '#lib/utils/bytes.js';
|
||||
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
|
||||
import { liveDownloadLine } from '#lib/wanted/downloadState.js';
|
||||
import type { Download } from '#lib/api/types.js';
|
||||
|
||||
// The admin Overview answers "does anything need me?" first: a
|
||||
// verdict, then each queue that waits on you with how long its oldest has
|
||||
// waited, then the empty ones on one line. The queues themselves
|
||||
// are worked on their own pages; the Overview does not repeat them.
|
||||
//
|
||||
// Below the verdict, the server's state: who is listening, what is
|
||||
// downloading, what the library holds and how much room is left, and the
|
||||
// server's version, uptime and recent errors. A download waiting on you, a
|
||||
// download client not answering, or a library folder unreadable or nearly
|
||||
// full also count in the verdict.
|
||||
// Below the verdict, the server's state: who is listening, what the
|
||||
// library holds and how much room is left, and the server's version,
|
||||
// uptime and recent errors. A library folder unreadable or nearly full also
|
||||
// counts in the verdict.
|
||||
|
||||
const summaryStore = createAdminSummaryQuery();
|
||||
const summaryQ = $derived($summaryStore);
|
||||
@@ -44,18 +41,6 @@
|
||||
const statusProblems = $derived.by((): Problem[] => {
|
||||
if (!status) return [];
|
||||
const out: Problem[] = [];
|
||||
const dl = status.downloads;
|
||||
if (dl.needs_you > 0) {
|
||||
out.push({
|
||||
key: 'downloads',
|
||||
text: plural(dl.needs_you, 'download needs you', 'downloads need you'),
|
||||
since: dl.needs_you_since,
|
||||
href: '/collection/activity'
|
||||
});
|
||||
}
|
||||
for (const c of dl.clients_down) {
|
||||
out.push({ key: `client:${c.client}`, text: `${c.client} isn't answering: ${c.detail}`, since: c.since, href: '/admin/acquisition' });
|
||||
}
|
||||
if (status.server.dirty) {
|
||||
out.push({ key: 'migration', text: `The database migration to version ${status.server.migration} stopped part way`, href: '/admin' });
|
||||
}
|
||||
@@ -67,10 +52,6 @@
|
||||
return out;
|
||||
});
|
||||
|
||||
|
||||
// Worded as the wanted list words it; before the client reports, it is
|
||||
// simply downloading, as the Downloads list says.
|
||||
const downloadLine = (d: Download) => liveDownloadLine(d) ?? 'Downloading';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Admin · Overview')}</title></svelte:head>
|
||||
@@ -148,7 +129,6 @@
|
||||
</p>
|
||||
{:else if status}
|
||||
{@const l = status.listening}
|
||||
{@const dl = status.downloads}
|
||||
{@const lib = status.library}
|
||||
{@const srv = status.server}
|
||||
<section class="space-y-2" data-testid="overview-listening">
|
||||
@@ -180,29 +160,6 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="space-y-2" data-testid="overview-downloads">
|
||||
<h2 class="text-sm font-medium text-text-primary">Downloads</h2>
|
||||
<p class="text-sm text-text-secondary" data-testid="downloads-line">
|
||||
{dl.running === 0 ? 'Nothing downloading' : `${dl.running} downloading`}.
|
||||
In the last day, {dl.imported_day} imported{dl.given_up_day ? ` and ${dl.given_up_day} given up` : ''}.
|
||||
<a href="/collection/activity" class="text-accent-fg hover:underline">Activity</a>
|
||||
</p>
|
||||
{#if dl.live.length > 0}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each dl.live as d (d.id)}
|
||||
<li class="flex items-baseline gap-3 px-4 py-2" data-testid="download-row">
|
||||
<span class="min-w-0 flex-1 truncate text-sm text-text-primary" title={d.name}>
|
||||
{d.want_title ? `${d.want_title} · ${d.want_artist}` : d.name}
|
||||
</span>
|
||||
<span class="shrink-0 text-xs {d.import_state === 'review' || d.import_state === 'failed' ? 'text-text-primary' : 'text-text-muted'}"
|
||||
>{downloadLine(d)} · {relativeTime(d.grabbed_at)}</span
|
||||
>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
<section class="space-y-2" data-testid="overview-library">
|
||||
<h2 class="text-sm font-medium text-text-primary">Library</h2>
|
||||
<p class="text-sm text-text-secondary" data-testid="library-line">
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import AcquisitionCard from '#lib/components/AcquisitionCard.svelte';
|
||||
import SearchSettingsCard from '#lib/components/SearchSettingsCard.svelte';
|
||||
import ReacquisitionSettingsCard from '#lib/components/ReacquisitionSettingsCard.svelte';
|
||||
import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte';
|
||||
|
||||
// Admin › Acquisition: how Minstrel gets music. Where it searches
|
||||
// and what downloads, how it searches and what it takes, and what happens
|
||||
// to a file that goes missing.
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Admin · Acquisition')}</title></svelte:head>
|
||||
|
||||
<h2 class="sr-only">Acquisition</h2>
|
||||
|
||||
<SettingsColumns>
|
||||
{#snippet main()}
|
||||
<AcquisitionCard />
|
||||
<SearchSettingsCard />
|
||||
{/snippet}
|
||||
{#snippet side()}
|
||||
<div id="reacquisition"><ReacquisitionSettingsCard /></div>
|
||||
{/snippet}
|
||||
</SettingsColumns>
|
||||
@@ -67,7 +67,7 @@ describe('admin/+layout.ts load gate', () => {
|
||||
// Importing at module load means the mocks attach to the same handles the
|
||||
// page binds against.
|
||||
import { createAdminStatusQuery, createAdminSummaryQuery, createScanStatusQuery } from '#lib/api/admin.js';
|
||||
import type { AdminStatus, AdminSummary, Download } from '#lib/api/types.js';
|
||||
import type { AdminStatus, AdminSummary } from '#lib/api/types.js';
|
||||
import OverviewPage from './+page.svelte';
|
||||
import AdminLayout from './+layout.svelte';
|
||||
import { createRawSnippet } from 'svelte';
|
||||
@@ -78,7 +78,6 @@ const empty = { count: 0, since: null };
|
||||
|
||||
function summary(over: Partial<AdminSummary> = {}): AdminSummary {
|
||||
return {
|
||||
requests: empty,
|
||||
reports: empty,
|
||||
duplicates: empty,
|
||||
suspect: empty,
|
||||
@@ -103,9 +102,6 @@ const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString(
|
||||
function status(over: Partial<AdminStatus> = {}): AdminStatus {
|
||||
return {
|
||||
listening: { now: [], plays_day: 0, listeners_day: 0, last_play_at: null },
|
||||
downloads: {
|
||||
running: 0, needs_you: 0, needs_you_since: null, imported_day: 0, given_up_day: 0, live: [], clients_down: []
|
||||
},
|
||||
library: {
|
||||
tracks: 41_000, albums: 3_200, artists: 900, bytes: 1_400_000_000_000,
|
||||
disks: [{ path: '/music', total_bytes: 4_000_000_000_000, free_bytes: 2_000_000_000_000 }]
|
||||
@@ -127,24 +123,24 @@ describe('admin Overview page', () => {
|
||||
render(OverviewPage);
|
||||
expect(screen.getByTestId('verdict').textContent).toMatch(/nothing needs you/i);
|
||||
expect(screen.queryAllByTestId('needs-you')).toHaveLength(0);
|
||||
expect(screen.getByTestId('all-clear').textContent).toMatch(/no requests, reports, duplicates, suspect sources, missing files/i);
|
||||
expect(screen.getByTestId('all-clear').textContent).toMatch(/no reports, duplicates, suspect sources, missing files/i);
|
||||
});
|
||||
|
||||
test('each queue that waits on you is listed with how long its oldest has waited, and opens its page', () => {
|
||||
setupOverview(summary({
|
||||
requests: { count: 2, since: ago(3) },
|
||||
reports: { count: 2, since: ago(3) },
|
||||
missing: { count: 1, since: ago(10) }
|
||||
}));
|
||||
render(OverviewPage);
|
||||
expect(screen.getByTestId('verdict').textContent).toMatch(/2 things need you/);
|
||||
const rows = screen.getAllByTestId('needs-you').map((r) => r.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(rows).toEqual(['2 requests to decide oldest 3d ago Open', '1 missing file oldest 10d ago Open']);
|
||||
expect(screen.getByRole('link', { name: /2 requests to decide/i }).getAttribute('href')).toBe('/admin/requests');
|
||||
expect(screen.getByTestId('all-clear').textContent).not.toMatch(/requests/);
|
||||
expect(rows).toEqual(['2 broken tracks reported oldest 3d ago Open', '1 missing file oldest 10d ago Open']);
|
||||
expect(screen.getByRole('link', { name: /2 broken tracks reported/i }).getAttribute('href')).toBe('/collection/reports');
|
||||
expect(screen.getByTestId('all-clear').textContent).not.toMatch(/reports/);
|
||||
});
|
||||
|
||||
// The library's health queues live under Collection; the Overview
|
||||
// still lists them, linking there.
|
||||
// The health queues are worked under Collection; the Overview lists
|
||||
// them, linking there.
|
||||
test('a library queue that waits on you opens its Collection page', () => {
|
||||
setupOverview(summary({ duplicates: { count: 5, since: ago(4) } }));
|
||||
render(OverviewPage);
|
||||
@@ -226,55 +222,22 @@ describe('admin Overview status', () => {
|
||||
expect(screen.getAllByTestId('server-error')[0].textContent).toMatch(/admin: summary[\s\S]*err=boom/);
|
||||
});
|
||||
|
||||
test('a download waiting on you, a client not answering and a nearly full disk count in the verdict', () => {
|
||||
test('a nearly full disk counts in the verdict', () => {
|
||||
setupOverview(summary(), vi.fn(), status({
|
||||
downloads: {
|
||||
running: 1, needs_you: 2, needs_you_since: minutesAgo(90), imported_day: 4, given_up_day: 0, live: [],
|
||||
clients_down: [{ client: 'qbittorrent', detail: 'connection refused', since: minutesAgo(30) }]
|
||||
},
|
||||
library: {
|
||||
tracks: 1, albums: 1, artists: 1, bytes: 1,
|
||||
disks: [{ path: '/music', total_bytes: 1_000, free_bytes: 10 }]
|
||||
}
|
||||
}));
|
||||
render(OverviewPage);
|
||||
expect(screen.getByTestId('verdict').textContent).toMatch(/3 things need you/);
|
||||
expect(screen.getByTestId('verdict').textContent).toMatch(/1 thing needs you/);
|
||||
const needs = screen.getAllByTestId('needs-you').map((li) => li.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(needs).toEqual([
|
||||
'2 downloads need you since 1h ago Open',
|
||||
"qbittorrent isn't answering: connection refused since 30m ago Open",
|
||||
'/music is nearly full: 10 B free Open'
|
||||
]);
|
||||
expect(textOf('downloads-line')).toBe('1 downloading. In the last day, 4 imported. Activity');
|
||||
});
|
||||
|
||||
// Worded as the wanted list words a download.
|
||||
test('each live download says what it is doing, as the wanted list says it', () => {
|
||||
const d = (id: string, import_state: Download['import_state'], import_reason = ''): Download => ({
|
||||
id, want_id: null, want_title: `Album ${id}`, want_artist: 'Blur', name: id, indexer: '', client: 'qbittorrent',
|
||||
quality: 'FLAC', origin: 'schedule', grabbed_at: minutesAgo(5), ended_at: null, end_reason: '', progress: 0.42,
|
||||
import_state, import_reason, imported_at: null, imported_files: 0, destination: '', files: [], skipped: 0,
|
||||
end_detail: '', seeding: false, ratio: 0, seed_released_at: null, condition: null
|
||||
});
|
||||
setupOverview(summary(), vi.fn(), status({
|
||||
downloads: {
|
||||
running: 3, needs_you: 1, needs_you_since: minutesAgo(5), imported_day: 0, given_up_day: 0, clients_down: [],
|
||||
live: [d('a', 'review', '9 files against 12 tracks'), d('b', 'downloading'), d('c', '')]
|
||||
}
|
||||
}));
|
||||
render(OverviewPage);
|
||||
const rows = screen.getAllByTestId('download-row').map((li) => li.textContent?.replace(/\s+/g, ' ').trim());
|
||||
expect(rows).toEqual([
|
||||
'Album a · Blur Needs you: 9 files against 12 tracks · 5m ago',
|
||||
'Album b · Blur Downloading 42% · 5m ago',
|
||||
'Album c · Blur Downloading · 5m ago'
|
||||
]);
|
||||
expect(needs).toEqual(['/music is nearly full: 10 B free Open']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin layout', () => {
|
||||
test('the sections run down a rail, each queue carrying how many wait on you', () => {
|
||||
setupOverview(summary({ requests: { count: 2, since: ago(1) }, duplicates: { count: 5, since: ago(4) } }));
|
||||
test('the sections run down a rail', () => {
|
||||
const children = createRawSnippet(() => ({ render: () => '<p data-testid="admin-body">body</p>' }));
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
render(AdminLayout, { children } as any);
|
||||
@@ -285,9 +248,7 @@ describe('admin layout', () => {
|
||||
]);
|
||||
expect(links).toEqual([
|
||||
['/admin', 'Overview'],
|
||||
['/admin/requests', 'Requests 2'],
|
||||
['/admin/library', 'Library'],
|
||||
['/admin/acquisition', 'Acquisition'],
|
||||
['/admin/metadata', 'Metadata sources'],
|
||||
['/admin/email', 'Email & network'],
|
||||
['/admin/users', 'Users'],
|
||||
|
||||
@@ -147,13 +147,7 @@
|
||||
<SettingsColumns>
|
||||
{#snippet main()}
|
||||
<SettingsGroup title="Library" id="scan" hint="The folders Minstrel reads, and the scan that reads them.">
|
||||
<!-- The import's folder picker reads the folders through search settings. -->
|
||||
<LibraryFoldersSetting
|
||||
onSaved={() => {
|
||||
client.invalidateQueries({ queryKey: qk.scanStatus() });
|
||||
client.invalidateQueries({ queryKey: qk.searchSettings() });
|
||||
}}
|
||||
/>
|
||||
<LibraryFoldersSetting onSaved={() => client.invalidateQueries({ queryKey: qk.scanStatus() })} />
|
||||
<SettingRow label="Scan" hint={scanLine}>
|
||||
<button type="button" onclick={onRunScan} disabled={triggering || scanInFlight} class={button}>
|
||||
{scanInFlight ? 'Scanning…' : triggering ? 'Starting…' : 'Run scan'}
|
||||
|
||||
@@ -1,279 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import { Check, X, SlidersHorizontal } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import RowActionsMenu, { type RowAction } from '#lib/components/RowActionsMenu.svelte';
|
||||
import TabStrip from '#lib/components/TabStrip.svelte';
|
||||
import { createAdminRequestsQuery, approveRequest, rejectRequest } from '#lib/api/admin.js';
|
||||
import { createReleaseProfilesQuery } from '#lib/api/wanted.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import RequestRow, { requestName } from '#lib/components/RequestRow.svelte';
|
||||
import Modal from '#lib/components/Modal.svelte';
|
||||
import type { MusicRequest, RequestStatus } from '#lib/api/types.js';
|
||||
|
||||
// Approval queue. Tabs filter by status; rows expose Approve/Reject, and an
|
||||
// artist request can be approved on a chosen release-type profile. Approving
|
||||
// puts the request on the wanted list: an album or track wants
|
||||
// its album, an artist is followed.
|
||||
|
||||
const client = useQueryClient();
|
||||
|
||||
// The four tab filters. "Pending" is default — that's the actionable bucket;
|
||||
// the rest are review-only views.
|
||||
const tabs: { status: RequestStatus; label: string }[] = [
|
||||
{ status: 'pending', label: 'Pending' },
|
||||
{ status: 'approved', label: 'Approved' },
|
||||
{ status: 'completed', label: 'Completed' },
|
||||
{ status: 'rejected', label: 'Rejected' }
|
||||
];
|
||||
|
||||
let activeStatus = $state<RequestStatus>('pending');
|
||||
|
||||
// The query factory is re-created on every status flip so TanStack treats
|
||||
// each status as its own cache key. We don't need a single shared store.
|
||||
const queryStore = $derived(createAdminRequestsQuery(activeStatus));
|
||||
const query = $derived($queryStore);
|
||||
const rows = $derived((query.data ?? []) as MusicRequest[]);
|
||||
|
||||
// Release-type profiles for the "Approve on a profile" modal: which kinds of
|
||||
// release following the artist will want.
|
||||
const profilesStore = createReleaseProfilesQuery();
|
||||
const profiles = $derived($profilesStore.data?.profiles ?? []);
|
||||
|
||||
// Modal state. `profileOpen` and `rejectOpen` carry the request id when
|
||||
// open; null otherwise. The current row is looked up by id at render time.
|
||||
let profileOpen = $state<string | null>(null);
|
||||
let profileChoice = $state<string>('');
|
||||
|
||||
let rejectOpen = $state<string | null>(null);
|
||||
let rejectNotes = $state<string>('');
|
||||
|
||||
// Names the requester. The id is the fallback for a list that came back
|
||||
// without names; its first 8 characters are enough to tell users apart.
|
||||
function rowMeta(r: MusicRequest): string {
|
||||
const when = new Date(r.requested_at).toLocaleDateString();
|
||||
const who = r.username || `user ${r.user_id.slice(0, 8)}`;
|
||||
return `by ${who} · ${when}`;
|
||||
}
|
||||
|
||||
async function invalidate() {
|
||||
// Invalidate every status bucket so e.g. an approve flips a row from the
|
||||
// pending list to the approved list once an admin switches tabs.
|
||||
await client.invalidateQueries({ queryKey: ['adminRequests'] });
|
||||
await client.invalidateQueries({ queryKey: ['adminWants'] });
|
||||
}
|
||||
|
||||
async function onApprove(r: MusicRequest, profileId?: string) {
|
||||
try {
|
||||
await approveRequest(r.id, profileId);
|
||||
await invalidate();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function openProfile(r: MusicRequest) {
|
||||
profileOpen = r.id;
|
||||
// Start from the default each time, not the previous row's choice.
|
||||
profileChoice = profiles.find((p) => p.is_default)?.id ?? '';
|
||||
}
|
||||
|
||||
function cancelProfile() {
|
||||
profileOpen = null;
|
||||
}
|
||||
|
||||
async function confirmProfile(r: MusicRequest) {
|
||||
const choice = profileChoice;
|
||||
profileOpen = null;
|
||||
await onApprove(r, choice || undefined);
|
||||
}
|
||||
|
||||
function openReject(r: MusicRequest) {
|
||||
rejectOpen = r.id;
|
||||
rejectNotes = '';
|
||||
}
|
||||
|
||||
function cancelReject() {
|
||||
rejectOpen = null;
|
||||
}
|
||||
|
||||
async function confirmReject(r: MusicRequest) {
|
||||
const notes = rejectNotes.trim();
|
||||
rejectOpen = null;
|
||||
try {
|
||||
await rejectRequest(r.id, notes ? notes : undefined);
|
||||
await invalidate();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Modal lookups: if the active tab has been refetched while a modal is
|
||||
// open, the row may no longer be in `rows`. Guard against that by treating
|
||||
// missing-row as closed.
|
||||
const profileRow = $derived(
|
||||
profileOpen ? rows.find((r) => r.id === profileOpen) ?? null : null
|
||||
);
|
||||
const rejectRow = $derived(
|
||||
rejectOpen ? rows.find((r) => r.id === rejectOpen) ?? null : null
|
||||
);
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Admin · Requests')}</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<header class="space-y-1">
|
||||
<h2 class="font-display text-2xl font-medium text-text-primary">Requests</h2>
|
||||
<p class="text-text-secondary">
|
||||
Approve or set aside what users have asked for. An approved album or track goes on the
|
||||
<a href="/collection/wanted" class="text-accent-fg hover:underline">wanted list</a>; an approved
|
||||
artist is followed, wanting what they've released and what they release next.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<TabStrip
|
||||
ariaLabel="Request status filters"
|
||||
bind:value={activeStatus}
|
||||
items={tabs.map((tab) => ({
|
||||
id: tab.status,
|
||||
label: tab.label,
|
||||
count: activeStatus === tab.status ? rows.length : undefined
|
||||
}))}
|
||||
/>
|
||||
|
||||
{#if query.isPending}
|
||||
<p class="text-text-secondary">Reading the queue…</p>
|
||||
{:else if query.isError}
|
||||
<p class="text-sm text-error-fg">
|
||||
Couldn't load the requests.
|
||||
<button type="button" class="underline hover:no-underline" onclick={() => query.refetch()}>Try again</button>
|
||||
</p>
|
||||
{:else if rows.length === 0}
|
||||
<p class="text-text-secondary">Nothing here.</p>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each rows as r (r.id)}
|
||||
<RequestRow request={r} meta={rowMeta(r)} testid="admin-request-row">
|
||||
{#snippet details()}
|
||||
{#if r.kind === 'track' && r.album_title}
|
||||
<div class="text-sm text-text-secondary" data-testid="track-disclosure">
|
||||
Approving wants the album <em class="font-medium text-text-primary">{r.album_title}</em>.
|
||||
</div>
|
||||
{/if}
|
||||
{#if r.notes}
|
||||
<div class="text-sm text-text-secondary">{r.notes}</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
{#snippet actions()}
|
||||
{#if r.status === 'pending'}
|
||||
{@const primary: RowAction = {
|
||||
icon: Check,
|
||||
label: 'Approve',
|
||||
ariaLabel: `Approve ${requestName(r)}`,
|
||||
onclick: () => onApprove(r)
|
||||
}}
|
||||
{@const secondary: RowAction[] = [
|
||||
...(r.kind === 'artist'
|
||||
? [
|
||||
{
|
||||
icon: SlidersHorizontal,
|
||||
label: 'Approve on a profile',
|
||||
ariaLabel: `Approve ${requestName(r)} on a profile`,
|
||||
onclick: () => openProfile(r)
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
icon: X,
|
||||
label: 'Reject',
|
||||
ariaLabel: `Reject ${requestName(r)}`,
|
||||
onclick: () => openReject(r),
|
||||
danger: true
|
||||
}
|
||||
]}
|
||||
<RowActionsMenu {primary} {secondary} />
|
||||
{/if}
|
||||
{/snippet}
|
||||
</RequestRow>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
title="Approve on a profile"
|
||||
open={profileRow !== null}
|
||||
onClose={cancelProfile}
|
||||
>
|
||||
<p class="-mt-2 text-sm text-text-secondary">
|
||||
The profile says which kinds of release following
|
||||
{profileRow?.artist_name ?? 'this artist'} wants. Profiles are edited under <a href="/collection/following" class="underline hover:no-underline">Collection › Following</a>.
|
||||
</p>
|
||||
|
||||
<label class="mt-4 block">
|
||||
<span class="block text-sm text-text-secondary">Release-type profile</span>
|
||||
<select
|
||||
bind:value={profileChoice}
|
||||
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
>
|
||||
{#each profiles as p (p.id)}
|
||||
<option value={p.id}>{p.name}{p.is_default ? ' (default)' : ''}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
|
||||
onclick={cancelProfile}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg"
|
||||
onclick={() => profileRow && confirmProfile(profileRow)}
|
||||
>
|
||||
<Check size={14} strokeWidth={2} />
|
||||
Approve and follow
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
title="Reject request?"
|
||||
open={rejectRow !== null}
|
||||
onClose={cancelReject}
|
||||
>
|
||||
<p class="-mt-2 text-sm text-text-secondary">
|
||||
Notes are shown to the requester.
|
||||
</p>
|
||||
<label class="mt-3 block">
|
||||
<span class="block text-sm text-text-secondary">Notes</span>
|
||||
<textarea
|
||||
bind:value={rejectNotes}
|
||||
rows="3"
|
||||
placeholder="Optional — why this is being set aside"
|
||||
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
></textarea>
|
||||
</label>
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
|
||||
onclick={cancelReject}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg"
|
||||
onclick={() => rejectRow && confirmReject(rejectRow)}
|
||||
>
|
||||
<X size={14} strokeWidth={2} />
|
||||
Confirm reject
|
||||
</button>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -1,139 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../../test-utils/query';
|
||||
import type { MusicRequest } from '#lib/api/types.js';
|
||||
|
||||
// Wrap useQueryClient so the page can call invalidateQueries() without a
|
||||
// real QueryClient context. Everything else from svelte-query passes through.
|
||||
vi.mock('#lib/api/admin.js', () => ({
|
||||
createAdminRequestsQuery: vi.fn(),
|
||||
approveRequest: vi.fn(),
|
||||
rejectRequest: vi.fn()
|
||||
}));
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
createReleaseProfilesQuery: vi.fn()
|
||||
}));
|
||||
|
||||
import AdminRequestsPage from './+page.svelte';
|
||||
import { createAdminRequestsQuery, approveRequest, rejectRequest } from '#lib/api/admin.js';
|
||||
import { createReleaseProfilesQuery } from '#lib/api/wanted.js';
|
||||
|
||||
const baseRow: MusicRequest = {
|
||||
id: 'r1',
|
||||
user_id: 'u1234567-aaaa-bbbb-cccc-deadbeef0001',
|
||||
status: 'pending',
|
||||
kind: 'album',
|
||||
artist_mbid: 'a-mbid',
|
||||
album_mbid: 'al-mbid',
|
||||
artist_name: 'Boards of Canada',
|
||||
album_title: 'Geogaddi',
|
||||
requested_at: '2026-04-29T10:00:00Z',
|
||||
updated_at: '2026-04-29T10:00:00Z',
|
||||
imported_album_count: 0,
|
||||
imported_track_count: 0
|
||||
};
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function setup(rows: MusicRequest[] = [baseRow]) {
|
||||
(createAdminRequestsQuery as ReturnType<typeof vi.fn>).mockReturnValue(
|
||||
mockQuery({ data: rows })
|
||||
);
|
||||
(createReleaseProfilesQuery as ReturnType<typeof vi.fn>).mockReturnValue(
|
||||
mockQuery({
|
||||
data: {
|
||||
profiles: [
|
||||
{ id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 0 },
|
||||
{ id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 }
|
||||
],
|
||||
primary_types: ['Album'],
|
||||
secondary_types: ['Live']
|
||||
}
|
||||
})
|
||||
);
|
||||
return render(AdminRequestsPage);
|
||||
}
|
||||
|
||||
describe('/admin/requests', () => {
|
||||
test('Tab switch refetches with new status filter', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('tab', { name: /approved/i }));
|
||||
expect(createAdminRequestsQuery).toHaveBeenCalledWith('approved');
|
||||
});
|
||||
|
||||
test('Approve sends no profile', async () => {
|
||||
setup();
|
||||
(approveRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i }));
|
||||
expect(approveRequest).toHaveBeenCalledWith('r1', undefined);
|
||||
});
|
||||
|
||||
test('An album request has no profile choice', () => {
|
||||
setup();
|
||||
expect(screen.queryByRole('button', { name: /on a profile/i })).toBeNull();
|
||||
});
|
||||
|
||||
test('An artist request is approved on the chosen profile', async () => {
|
||||
setup([{ ...baseRow, kind: 'artist', album_mbid: undefined, album_title: undefined }]);
|
||||
await fireEvent.click(
|
||||
screen.getByRole('button', { name: /approve boards of canada on a profile/i })
|
||||
);
|
||||
const select = screen.getByLabelText(/release-type profile/i) as HTMLSelectElement;
|
||||
expect(select.value).toBe('p-std');
|
||||
await fireEvent.change(select, { target: { value: 'p-live' } });
|
||||
(approveRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
|
||||
await fireEvent.click(screen.getByRole('button', { name: /approve and follow/i }));
|
||||
expect(approveRequest).toHaveBeenCalledWith('r1', 'p-live');
|
||||
});
|
||||
|
||||
test('Reject opens notes textarea; confirm sends notes', async () => {
|
||||
setup();
|
||||
await fireEvent.click(screen.getByRole('button', { name: /reject geogaddi/i }));
|
||||
const textarea = screen.getByLabelText(/notes/i) as HTMLTextAreaElement;
|
||||
await fireEvent.input(textarea, { target: { value: 'duplicate' } });
|
||||
(rejectRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
...baseRow,
|
||||
status: 'rejected'
|
||||
});
|
||||
await fireEvent.click(
|
||||
screen.getByRole('button', { name: /confirm reject/i })
|
||||
);
|
||||
expect(rejectRequest).toHaveBeenCalledWith('r1', 'duplicate');
|
||||
});
|
||||
|
||||
test('An approve error shows a toast', async () => {
|
||||
setup();
|
||||
(approveRequest as ReturnType<typeof vi.fn>).mockRejectedValueOnce({
|
||||
code: 'request_not_pending',
|
||||
message: 'not pending',
|
||||
status: 409
|
||||
});
|
||||
await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i }));
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText(/no longer pending/i)).toBeInTheDocument()
|
||||
);
|
||||
});
|
||||
|
||||
test('Track-kind row renders disclosure copy about adding the album', () => {
|
||||
setup([
|
||||
{
|
||||
...baseRow,
|
||||
kind: 'track',
|
||||
track_title: 'Roygbiv',
|
||||
album_title: 'Geogaddi'
|
||||
}
|
||||
]);
|
||||
expect(screen.getByText(/wants the album/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('A row names who asked for it', () => {
|
||||
setup([{ ...baseRow, username: 'alice' }]);
|
||||
expect(screen.getByText(/^by alice · /)).toBeInTheDocument();
|
||||
expect(screen.queryByText(/u1234567/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('A row without a name falls back to the user id', () => {
|
||||
setup();
|
||||
expect(screen.getByText(/^by user u1234567 · /)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -10,7 +10,6 @@
|
||||
type TuningSnapshot,
|
||||
type WeightProfile,
|
||||
type TasteTuning,
|
||||
type DiscoverTuning,
|
||||
type TrendsResponse,
|
||||
type TrendSeries,
|
||||
type TrendMarker
|
||||
@@ -47,11 +46,6 @@
|
||||
{ key: 'mood_scale', label: 'Mood weight', hint: 'How much the mood counts. 0 ignores it.' }
|
||||
];
|
||||
|
||||
const discoverFields: { key: keyof DiscoverTuning; label: string; hint: string }[] = [
|
||||
{ key: 'tag_overlap_weight', label: 'Taste-tag weight', hint: 'Boost for a suggestion whose tags fit your taste. 0 ranks on likeness alone.' },
|
||||
{ key: 'snooze_days', label: 'Snooze length (days)', hint: 'How long "not right now" hides a suggestion.' }
|
||||
];
|
||||
|
||||
const profileScopes: { scope: WeightProfileScope; label: string; blurb: string }[] = [
|
||||
{ scope: 'radio', label: 'Radio', blurb: 'Listening that starts from a seed.' },
|
||||
{ scope: 'daily_mix', label: 'Daily mixes', blurb: 'For You, the discovery mixes and "You might like".' },
|
||||
@@ -73,14 +67,12 @@
|
||||
radio: {},
|
||||
daily_mix: {},
|
||||
songs_like: {},
|
||||
taste: {},
|
||||
discover: {}
|
||||
taste: {}
|
||||
};
|
||||
for (const p of profileScopes.map((s) => s.scope)) {
|
||||
for (const { key } of weightFields) f[p][key] = String(snap.profiles[p][key]);
|
||||
}
|
||||
for (const { key } of tasteFields) f.taste[key] = String(snap.taste[key]);
|
||||
for (const { key } of discoverFields) f.discover[key] = String(snap.discover[key]);
|
||||
form = f;
|
||||
}
|
||||
|
||||
@@ -104,12 +96,6 @@
|
||||
if (scope === 'taste') {
|
||||
return snapshot.taste[key as keyof TasteTuning] !== snapshot.shipped.taste[key as keyof TasteTuning];
|
||||
}
|
||||
if (scope === 'discover') {
|
||||
return (
|
||||
snapshot.discover[key as keyof DiscoverTuning] !==
|
||||
snapshot.shipped.discover[key as keyof DiscoverTuning]
|
||||
);
|
||||
}
|
||||
return (
|
||||
snapshot.profiles[scope][key as keyof WeightProfile] !==
|
||||
snapshot.shipped.profiles[scope][key as keyof WeightProfile]
|
||||
@@ -119,7 +105,6 @@
|
||||
function currentValue(scope: TuningScope, key: string): number {
|
||||
if (!snapshot) return 0;
|
||||
if (scope === 'taste') return snapshot.taste[key as keyof TasteTuning];
|
||||
if (scope === 'discover') return snapshot.discover[key as keyof DiscoverTuning];
|
||||
return snapshot.profiles[scope][key as keyof WeightProfile];
|
||||
}
|
||||
|
||||
@@ -277,7 +262,6 @@
|
||||
id="{scope}-{f.key}"
|
||||
type="number"
|
||||
step={step(f.key)}
|
||||
min={scope === 'discover' ? '0' : undefined}
|
||||
bind:value={form[scope][f.key]}
|
||||
class="w-24 rounded-md border border-border bg-background px-2 py-1.5 text-right text-sm tabular-nums"
|
||||
/>
|
||||
@@ -327,14 +311,6 @@
|
||||
(k) => (k === 'half_life_days' ? '1' : '0.05'),
|
||||
(k) => snap.shipped.taste[k as keyof TasteTuning]
|
||||
)}
|
||||
{@render knobs(
|
||||
'discover',
|
||||
'Discover requests',
|
||||
"How Discover ranks artists you don't have.",
|
||||
discoverFields,
|
||||
(k) => (k === 'snooze_days' ? '1' : '0.1'),
|
||||
(k) => snap.shipped.discover[k as keyof DiscoverTuning]
|
||||
)}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -43,12 +43,6 @@ const taste = (over: Partial<Record<string, number>> = {}) => ({
|
||||
...over
|
||||
});
|
||||
|
||||
const discover = (over: Partial<Record<string, number>> = {}) => ({
|
||||
tag_overlap_weight: 1,
|
||||
snooze_days: 90,
|
||||
...over
|
||||
});
|
||||
|
||||
// NOTE the `as TuningSnapshot` cast below: it silences the type error when the
|
||||
// server snapshot grows a field, so a missing key here surfaces as every test
|
||||
// on this page throwing inside fillForm rather than as a compile failure. Add
|
||||
@@ -61,15 +55,13 @@ function snapshot(over: Partial<TuningSnapshot> = {}): TuningSnapshot {
|
||||
songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 })
|
||||
},
|
||||
taste: taste(),
|
||||
discover: discover(),
|
||||
shipped: {
|
||||
profiles: {
|
||||
radio: weights({ taste_weight: 1 }),
|
||||
daily_mix: weights(),
|
||||
songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 })
|
||||
},
|
||||
taste: taste(),
|
||||
discover: discover()
|
||||
taste: taste()
|
||||
},
|
||||
...over
|
||||
} as TuningSnapshot;
|
||||
@@ -262,62 +254,4 @@ describe('Admin tuning page', () => {
|
||||
expect(screen.getByText(/trends appear once listening accumulates/i)).toBeInTheDocument()
|
||||
);
|
||||
});
|
||||
// --- Discover scope ---
|
||||
|
||||
test('renders the Discover card with its two knobs', async () => {
|
||||
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
render(TuningPage);
|
||||
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
|
||||
expect(screen.getByLabelText(/taste-tag weight/i)).toBeInTheDocument();
|
||||
expect(screen.getByLabelText(/snooze length/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('saving Discover patches only the changed field under the discover scope', async () => {
|
||||
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
(patchTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
render(TuningPage);
|
||||
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
|
||||
await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), {
|
||||
target: { value: '2.5' }
|
||||
});
|
||||
await fireEvent.click(screen.getByRole('button', { name: /save discover/i }));
|
||||
await waitFor(() =>
|
||||
expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 2.5 })
|
||||
);
|
||||
});
|
||||
|
||||
// 0 is an admin's off switch for the whole tag term, so the form must be
|
||||
// able to send it — a falsy-value bug here would silently make the feature
|
||||
// impossible to disable.
|
||||
test('a Discover weight of 0 is sent, not dropped as falsy', async () => {
|
||||
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
(patchTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
render(TuningPage);
|
||||
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
|
||||
await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), { target: { value: '0' } });
|
||||
await fireEvent.click(screen.getByRole('button', { name: /save discover/i }));
|
||||
await waitFor(() =>
|
||||
expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 0 })
|
||||
);
|
||||
});
|
||||
|
||||
test('reset targets the discover scope', async () => {
|
||||
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
(resetTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
|
||||
render(TuningPage);
|
||||
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
|
||||
await fireEvent.click(
|
||||
screen.getByRole('button', { name: /reset discover requests to defaults/i })
|
||||
);
|
||||
await waitFor(() => expect(resetTuning).toHaveBeenCalledWith('discover'));
|
||||
});
|
||||
|
||||
test('a deviating Discover knob is dotted', async () => {
|
||||
const snap = snapshot();
|
||||
snap.discover = discover({ tag_overlap_weight: 3 });
|
||||
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snap);
|
||||
render(TuningPage);
|
||||
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
|
||||
expect(screen.getByTitle(/deviates from the shipped default \(1\)/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
createUser,
|
||||
deleteUser,
|
||||
resetUserPassword,
|
||||
updateUserAutoApprove,
|
||||
updateUserDebugMode,
|
||||
createAdminUsersQuery,
|
||||
createAdminInvitesQuery,
|
||||
@@ -22,7 +21,7 @@
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import Modal from '#lib/components/Modal.svelte';
|
||||
import RowActionsMenu, { type RowAction } from '#lib/components/RowActionsMenu.svelte';
|
||||
import { Shield, ShieldOff, CheckCircle2, XCircle, KeyRound, Trash2, Copy, Bug, BugOff } from 'lucide-svelte';
|
||||
import { Shield, ShieldOff, KeyRound, Trash2, Copy, Bug, BugOff } from 'lucide-svelte';
|
||||
|
||||
const client = useQueryClient();
|
||||
|
||||
@@ -150,21 +149,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function onToggleAutoApprove(u: AdminUser) {
|
||||
saving = true;
|
||||
try {
|
||||
await updateUserAutoApprove(u.id, !u.auto_approve_requests);
|
||||
await client.invalidateQueries({ queryKey: qk.adminUsers() });
|
||||
pushToast(u.auto_approve_requests
|
||||
? `Auto-approve disabled for ${u.username}.`
|
||||
: `Auto-approve enabled for ${u.username}.`);
|
||||
} catch (e: unknown) {
|
||||
pushToast(`Toggle failed: ${errCode(e)}`, 'error');
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Debug mode makes the account's devices report diagnostics: a
|
||||
// row action here, with the badge linking to that account's events.
|
||||
async function onToggleDebug(u: AdminUser) {
|
||||
@@ -267,15 +251,6 @@
|
||||
disabled: saving
|
||||
}}
|
||||
{@const secondary: RowAction[] = [
|
||||
{
|
||||
icon: u.auto_approve_requests ? XCircle : CheckCircle2,
|
||||
label: u.auto_approve_requests ? 'Disable auto-approve' : 'Enable auto-approve',
|
||||
ariaLabel: u.auto_approve_requests
|
||||
? `Disable auto-approve for ${u.username}`
|
||||
: `Enable auto-approve for ${u.username}`,
|
||||
onclick: () => onToggleAutoApprove(u),
|
||||
disabled: saving
|
||||
},
|
||||
{
|
||||
icon: u.debug_mode_enabled ? BugOff : Bug,
|
||||
label: u.debug_mode_enabled ? 'Turn off debug mode' : 'Turn on debug mode',
|
||||
@@ -318,12 +293,6 @@
|
||||
data-testid="debug-badge"
|
||||
>debug on</a>
|
||||
{/if}
|
||||
{#if u.auto_approve_requests}
|
||||
<span
|
||||
class="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-xs text-text-secondary"
|
||||
data-testid="auto-approve-badge"
|
||||
>auto-approve</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-sm text-text-secondary">
|
||||
{#if u.display_name}{u.display_name} · {/if}created {formatDate(u.created_at)}
|
||||
|
||||
@@ -16,7 +16,6 @@ vi.mock('#lib/api/admin.js', () => ({
|
||||
createUser: vi.fn(),
|
||||
deleteUser: vi.fn(),
|
||||
resetUserPassword: vi.fn(),
|
||||
updateUserAutoApprove: vi.fn(),
|
||||
updateUserDebugMode: vi.fn()
|
||||
}));
|
||||
|
||||
@@ -30,7 +29,6 @@ import {
|
||||
createUser,
|
||||
deleteUser,
|
||||
resetUserPassword,
|
||||
updateUserAutoApprove,
|
||||
updateUserDebugMode
|
||||
} from '#lib/api/admin.js';
|
||||
|
||||
@@ -39,7 +37,6 @@ const alice: AdminUser = {
|
||||
username: 'alice',
|
||||
display_name: null,
|
||||
is_admin: true,
|
||||
auto_approve_requests: false,
|
||||
debug_mode_enabled: false,
|
||||
created_at: '2026-05-01T00:00:00Z'
|
||||
};
|
||||
@@ -49,7 +46,6 @@ const bob: AdminUser = {
|
||||
username: 'bob',
|
||||
display_name: 'Bob B',
|
||||
is_admin: false,
|
||||
auto_approve_requests: false,
|
||||
debug_mode_enabled: false,
|
||||
created_at: '2026-05-02T00:00:00Z'
|
||||
};
|
||||
@@ -201,15 +197,6 @@ describe('/admin/users', () => {
|
||||
expect(resetUserPassword).toHaveBeenCalledWith(expect.any(String), 'abcd1234');
|
||||
});
|
||||
|
||||
test('toggle-auto-approve calls updateUserAutoApprove', async () => {
|
||||
(updateUserAutoApprove as ReturnType<typeof vi.fn>).mockResolvedValue({});
|
||||
setup();
|
||||
await waitFor(() => screen.getByText('alice'));
|
||||
|
||||
await fireEvent.click(screen.getAllByRole('button', { name: /Enable auto-approve/i })[0]);
|
||||
expect(updateUserAutoApprove).toHaveBeenCalledWith(expect.any(String), true);
|
||||
});
|
||||
|
||||
test('debug mode is a row action, and an account with it on links to its events', async () => {
|
||||
(updateUserDebugMode as ReturnType<typeof vi.fn>).mockResolvedValue({});
|
||||
setup([alice, { ...bob, debug_mode_enabled: true }]);
|
||||
|
||||
@@ -14,8 +14,6 @@
|
||||
import CompactTrackCard from '#lib/components/CompactTrackCard.svelte';
|
||||
import HorizontalScrollRow from '#lib/components/HorizontalScrollRow.svelte';
|
||||
import LikeButton from '#lib/components/LikeButton.svelte';
|
||||
import FollowControl from '#lib/components/FollowControl.svelte';
|
||||
import { user } from '#lib/auth/store.svelte.js';
|
||||
import LibrarySkeleton from '#lib/components/LibrarySkeleton.svelte';
|
||||
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
|
||||
import { useDelayed } from '#lib/utils/useDelayed.svelte.js';
|
||||
@@ -25,7 +23,6 @@
|
||||
import type { ArtistRef, TrackRef } from '#lib/api/types.js';
|
||||
|
||||
const id = $derived(page.params.id ?? '');
|
||||
const isAdmin = $derived(user.value?.is_admin === true);
|
||||
const queryStore = $derived(createArtistQuery(id));
|
||||
const query = $derived($queryStore);
|
||||
const showSkeleton = useDelayed(() => query.isPending);
|
||||
@@ -114,11 +111,6 @@
|
||||
{onPlay}
|
||||
{onShuffle}
|
||||
/>
|
||||
<!-- Following is keyed by MusicBrainz id, so an artist whose tags
|
||||
never named one can't be followed. -->
|
||||
{#if isAdmin && detail.mbid}
|
||||
<FollowControl artistMbid={detail.mbid} artistName={detail.name} />
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -25,24 +25,6 @@ vi.mock('#lib/api/queries.js', () => ({
|
||||
|
||||
vi.mock('#lib/api/likes.js', () => emptyLikesMock());
|
||||
|
||||
const userState = vi.hoisted(() => ({
|
||||
current: null as { id: string; username: string; is_admin: boolean } | null
|
||||
}));
|
||||
|
||||
vi.mock('#lib/auth/store.svelte.js', () => ({
|
||||
user: { get value() { return userState.current; } }
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/wanted.js', async () => {
|
||||
const { mockQuery } = await import('../../../test-utils/query');
|
||||
return {
|
||||
createFollowQuery: vi.fn(() => mockQuery({ data: { following: false } })),
|
||||
createReleaseProfilesQuery: vi.fn(() => mockQuery({ data: { profiles: [], primary_types: [], secondary_types: [] } })),
|
||||
putFollow: vi.fn(),
|
||||
deleteFollow: vi.fn()
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('#lib/api/client.js', () => apiClientMock());
|
||||
|
||||
vi.mock('#lib/player/store.svelte.js', () => ({
|
||||
@@ -77,7 +59,6 @@ function album(id: string, title: string, year?: number): AlbumRef {
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
state.pageParams = { id: 'abc' };
|
||||
userState.current = null;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -194,34 +175,4 @@ describe('artist detail page', () => {
|
||||
expect(queued.map((t: { id: string }) => t.id).sort()).toEqual(tracks.map((t) => t.id).sort());
|
||||
});
|
||||
});
|
||||
|
||||
// Following is for the wanted list: an admin control, keyed by
|
||||
// the artist's MusicBrainz id.
|
||||
describe('Follow', () => {
|
||||
const detail = (mbid: string): ArtistDetail => ({
|
||||
id: 'abc', name: 'Alice', sort_name: 'Alice', album_count: 1, cover_url: '',
|
||||
albums: [album('a1', 'First', 2020)], genres: [], mbid
|
||||
});
|
||||
|
||||
test('an admin can follow an artist with a MusicBrainz id', () => {
|
||||
userState.current = { id: 'u1', username: 'admin', is_admin: true };
|
||||
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('mb-alice') }));
|
||||
render(ArtistPage);
|
||||
expect(screen.getByRole('button', { name: /^follow$/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('no follow control without a MusicBrainz id', () => {
|
||||
userState.current = { id: 'u1', username: 'admin', is_admin: true };
|
||||
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('') }));
|
||||
render(ArtistPage);
|
||||
expect(screen.queryByRole('button', { name: /^follow$/i })).toBeNull();
|
||||
});
|
||||
|
||||
test('no follow control for a non-admin', () => {
|
||||
userState.current = { id: 'u2', username: 'sam', is_admin: false };
|
||||
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('mb-alice') }));
|
||||
render(ArtistPage);
|
||||
expect(screen.queryByRole('button', { name: /^follow$/i })).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,82 +1,44 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { createWantArtistsQuery } from '#lib/api/wanted.js';
|
||||
import { createAdminSummaryQuery } from '#lib/api/admin.js';
|
||||
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
|
||||
import CollectionRail from '#lib/components/wanted/CollectionRail.svelte';
|
||||
import CollectionRail from '#lib/components/CollectionRail.svelte';
|
||||
|
||||
let { children } = $props<{ children: import('svelte').Snippet }>();
|
||||
|
||||
// The Collection: what the library holds and wants, and what
|
||||
// Minstrel is fetching for it. Web-only and admin-only. The catalogue of
|
||||
// artists is the main section, and the sections down the left show state. The
|
||||
// catalogue's first page carries every section's count; the Catalogue
|
||||
// shares it, so this costs no extra request there.
|
||||
const artistsStore = createWantArtistsQuery();
|
||||
const counts = $derived($artistsStore.data?.pages?.[0]?.counts);
|
||||
|
||||
// The one line that answers "does anything need me?"
|
||||
const verdict = $derived.by(() => {
|
||||
if (!counts) return '';
|
||||
if (counts.attention) {
|
||||
return `${plural(counts.attention, 'download needs', 'downloads need')} you.`;
|
||||
}
|
||||
const parts = [plural(counts.wanted, 'album wanted', 'albums wanted')];
|
||||
if (counts.activity) parts.push(`${counts.activity} downloading`);
|
||||
// Library albums no MusicBrainz album matched wait on a person too.
|
||||
if (counts.unmatched) {
|
||||
const n = plural(counts.unmatched, 'album in your library needs', 'albums in your library need');
|
||||
return parts.join(', ') + `. ${n} matching.`;
|
||||
}
|
||||
return parts.join(', ') + '. Nothing needs you.';
|
||||
});
|
||||
const needsYou = $derived(!!counts?.attention || !!counts?.unmatched);
|
||||
|
||||
// The library's health queues count from the admin summary, the
|
||||
// same read Admin's Overview makes. The line under the verdict names the
|
||||
// ones with something in them; each links to its page.
|
||||
// The Collection: the library's health. Web-only and admin-only. The
|
||||
// queues count from the admin summary, the same read Admin's Overview
|
||||
// makes, so a queue that needs you is counted the same in both places.
|
||||
const summaryStore = createAdminSummaryQuery();
|
||||
const summary = $derived($summaryStore.data);
|
||||
const health = $derived(
|
||||
QUEUES.filter((d) => d.href.startsWith('/collection/') && countOf(summary, d.key) > 0)
|
||||
);
|
||||
const waiting = $derived(QUEUES.filter((d) => countOf(summary, d.key) > 0));
|
||||
</script>
|
||||
|
||||
<div class="space-y-4">
|
||||
<header class="space-y-1">
|
||||
<h1 class="font-display text-2xl font-medium text-text-primary">Collection</h1>
|
||||
<p class="text-sm text-text-secondary">
|
||||
Every artist and album in your collection: what the library holds, and what Minstrel is
|
||||
getting for it, from user requests, new releases of the artists it follows, and albums whose
|
||||
files went missing. It searches your indexers on a schedule, checks each download against
|
||||
MusicBrainz, and files what's right into the library. Searching and quality are set under
|
||||
<a href="/admin/acquisition" class="text-accent-fg hover:underline">Acquisition</a>.
|
||||
What in the library needs looking at: tracks people reported, songs held twice, files from
|
||||
doubtful sources, and files that went missing.
|
||||
</p>
|
||||
{#if verdict}
|
||||
<p class="text-sm {needsYou ? 'text-text-primary' : 'text-text-secondary'}" data-testid="collection-verdict">
|
||||
{verdict}
|
||||
{#if counts?.attention}
|
||||
<a href="/collection/activity" class="ml-1 text-accent-fg hover:underline">See Activity</a>
|
||||
{:else if counts?.unmatched}
|
||||
<a href="/collection/unmatched" class="ml-1 text-accent-fg hover:underline">See Unmatched</a>
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
{#if health.length > 0}
|
||||
<p class="text-sm text-text-primary" data-testid="collection-health">
|
||||
To look at:
|
||||
{#each health as d, i (d.key)}<a href={d.href} class="text-accent-fg hover:underline"
|
||||
>{queueLabel(d, countOf(summary, d.key))}</a
|
||||
>{i < health.length - 1 ? ', ' : '.'}
|
||||
{/each}
|
||||
</p>
|
||||
{#if summary}
|
||||
{#if waiting.length > 0}
|
||||
<p class="text-sm text-text-primary" data-testid="collection-health">
|
||||
To look at:
|
||||
{#each waiting as d, i (d.key)}<a href={d.href} class="text-accent-fg hover:underline"
|
||||
>{queueLabel(d, countOf(summary, d.key))}</a
|
||||
>{i < waiting.length - 1 ? ', ' : '.'}
|
||||
{/each}
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-sm text-text-secondary" data-testid="collection-health">Nothing needs you.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
<div class="md:grid md:grid-cols-[11rem_minmax(0,1fr)] md:gap-6">
|
||||
<div class="mb-4 md:mb-0">
|
||||
<div class="md:sticky md:top-4">
|
||||
<CollectionRail {counts} {summary} />
|
||||
<CollectionRail {summary} />
|
||||
</div>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
|
||||
@@ -1,8 +1,49 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import CatalogueGrid from '#lib/components/wanted/CatalogueGrid.svelte';
|
||||
import { createAdminSummaryQuery } from '#lib/api/admin.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
|
||||
|
||||
// The Collection's overview: each health queue with something in it and
|
||||
// how long its oldest has waited, then the empty ones on one line.
|
||||
const summaryStore = createAdminSummaryQuery();
|
||||
const summaryQ = $derived($summaryStore);
|
||||
const summary = $derived(summaryQ.data);
|
||||
const waiting = $derived(QUEUES.filter((d) => countOf(summary, d.key) > 0));
|
||||
const clear = $derived(QUEUES.filter((d) => countOf(summary, d.key) === 0));
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection')}</title></svelte:head>
|
||||
|
||||
<CatalogueGrid />
|
||||
<section class="space-y-3" data-testid="collection-overview">
|
||||
{#if summaryQ.isPending}
|
||||
<p class="text-sm text-text-secondary">Reading the queues…</p>
|
||||
{:else if summaryQ.isError}
|
||||
<p class="text-sm text-error-fg">
|
||||
Couldn't read the queues.
|
||||
<button type="button" class="underline hover:no-underline" onclick={() => summaryQ.refetch()}>Try again</button>
|
||||
</p>
|
||||
{:else}
|
||||
{#if waiting.length > 0}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each waiting as d (d.key)}
|
||||
{@const q = summary?.[d.key]}
|
||||
<li data-testid="collection-queue">
|
||||
<a href={d.href} class="flex flex-wrap items-baseline gap-x-3 gap-y-1 px-4 py-3 hover:bg-surface-hover">
|
||||
<span class="text-sm text-text-primary">{queueLabel(d, countOf(summary, d.key))}</span>
|
||||
{#if q?.since}
|
||||
<span class="text-xs text-text-muted">oldest {relativeTime(q.since)}</span>
|
||||
{/if}
|
||||
<span class="ml-auto text-sm text-accent-fg">Open</span>
|
||||
</a>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
{#if clear.length > 0}
|
||||
<p class="text-xs text-text-muted" data-testid="collection-clear">
|
||||
No {clear.map((d) => d.none).join(', ')}.
|
||||
</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import DownloadList from '#lib/components/wanted/DownloadList.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Activity')}</title></svelte:head>
|
||||
|
||||
<DownloadList />
|
||||
@@ -1,15 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { page } from '$app/state';
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import WantList from '#lib/components/wanted/WantList.svelte';
|
||||
|
||||
// One artist in the Collection's catalogue: every album of theirs
|
||||
// on the list, held or not, with its tracks a click away.
|
||||
const mbid = $derived(page.params.mbid ?? '');
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Artist')}</title></svelte:head>
|
||||
|
||||
{#key mbid}
|
||||
<WantList artist={mbid} />
|
||||
{/key}
|
||||
@@ -1,8 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import BlockList from '#lib/components/wanted/BlockList.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Blocked')}</title></svelte:head>
|
||||
|
||||
<BlockList />
|
||||
@@ -1,97 +1,57 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { createRawSnippet } from 'svelte';
|
||||
import { mockInfiniteQuery } from '../../test-utils/query';
|
||||
import { pageUrlModule } from '#test-utils/mocks/appState.js';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import type { AdminSummary, WantArtistsPage, WantCounts } from '#lib/api/types.js';
|
||||
import type { AdminSummary } from '#lib/api/types.js';
|
||||
|
||||
const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/collection') }));
|
||||
vi.mock('$app/state', () => pageUrlModule(state));
|
||||
vi.mock('#lib/api/wanted.js', () => ({ createWantArtistsQuery: vi.fn() }));
|
||||
vi.mock('#lib/api/admin.js', () => ({ createAdminSummaryQuery: vi.fn() }));
|
||||
|
||||
import WantedLayout from './+layout.svelte';
|
||||
import { createWantArtistsQuery } from '#lib/api/wanted.js';
|
||||
import CollectionLayout from './+layout.svelte';
|
||||
import CollectionPage from './+page.svelte';
|
||||
import { createAdminSummaryQuery } from '#lib/api/admin.js';
|
||||
|
||||
const counts: WantCounts = { artists: 7, wanted: 5, missing: 1, held: 9, upgrades: 6, following: 2, activity: 3, attention: 0, blocked: 4, unmatched: 3 };
|
||||
const children = createRawSnippet(() => ({ render: () => `<p data-testid="tab-body">body</p>` }));
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
const none = { count: 0, since: null };
|
||||
const clear: AdminSummary = { requests: none, reports: none, duplicates: none, suspect: none, missing: none };
|
||||
const clear: AdminSummary = { reports: none, duplicates: none, suspect: none, missing: none };
|
||||
|
||||
function setup(c: WantCounts = counts, path = '/collection', summary: AdminSummary = clear) {
|
||||
state.pageUrl = new URL(`http://localhost${path}`);
|
||||
function mockSummary(summary: AdminSummary) {
|
||||
vi.mocked(createAdminSummaryQuery).mockReturnValue(
|
||||
mockQuery({ data: summary }) as unknown as ReturnType<typeof createAdminSummaryQuery>
|
||||
);
|
||||
const page: WantArtistsPage = {
|
||||
items: [],
|
||||
total: 0,
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
counts: c,
|
||||
library: { listed_at: null, unlisted: 0 }
|
||||
};
|
||||
vi.mocked(createWantArtistsQuery).mockReturnValue(
|
||||
mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType<typeof createWantArtistsQuery>
|
||||
);
|
||||
}
|
||||
|
||||
function setup(path = '/collection', summary: AdminSummary = clear) {
|
||||
state.pageUrl = new URL(`http://localhost${path}`);
|
||||
mockSummary(summary);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return render(WantedLayout, { children } as any);
|
||||
return render(CollectionLayout, { children } as any);
|
||||
}
|
||||
|
||||
describe('/collection layout', () => {
|
||||
test('the sections down the left carry their counts, the current one marked', () => {
|
||||
setup(counts, '/collection/activity');
|
||||
test('the sections down the left are the overview and the health queues, the current one marked', () => {
|
||||
setup('/collection/missing');
|
||||
const nav = screen.getByRole('navigation', { name: /collection sections/i });
|
||||
const links = Array.from(nav.querySelectorAll('a')).map((a) => [a.getAttribute('href'), a.textContent?.replace(/\s+/g, ' ').trim()]);
|
||||
expect(links).toEqual([
|
||||
['/collection', 'Catalogue 7'],
|
||||
['/collection/wanted', 'Wanted 5'],
|
||||
['/collection/upgrades', 'Upgrades 6'],
|
||||
['/collection/activity', 'Activity 3'],
|
||||
['/collection/following', 'Following 2'],
|
||||
['/collection/blocked', 'Blocked 4'],
|
||||
['/collection/unmatched', 'Unmatched 3'],
|
||||
['/collection', 'Overview'],
|
||||
['/collection/reports', 'Reports'],
|
||||
['/collection/duplicates', 'Duplicates'],
|
||||
['/collection/suspect-sources', 'Suspect sources'],
|
||||
['/collection/missing', 'Missing files']
|
||||
]);
|
||||
expect(screen.getByRole('link', { name: /activity/i })).toHaveAttribute('aria-current', 'page');
|
||||
expect(screen.getByRole('link', { name: /^catalogue/i })).not.toHaveAttribute('aria-current');
|
||||
expect(screen.getByRole('link', { name: /missing files/i })).toHaveAttribute('aria-current', 'page');
|
||||
expect(screen.getByRole('link', { name: /^overview/i })).not.toHaveAttribute('aria-current');
|
||||
expect(screen.getByTestId('tab-body')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('when nothing needs a person the verdict says so', () => {
|
||||
setup({ ...counts, unmatched: 0 });
|
||||
expect(screen.getByTestId('collection-verdict').textContent).toMatch(/5 albums wanted, 3 downloading\. Nothing needs you\./);
|
||||
expect(screen.queryByTestId('tab-attention')).toBeNull();
|
||||
});
|
||||
|
||||
test('downloads waiting on a person lead the page and mark Activity', () => {
|
||||
setup({ ...counts, attention: 2 });
|
||||
const verdict = screen.getByTestId('collection-verdict');
|
||||
expect(verdict.textContent).toMatch(/2 downloads need you/);
|
||||
expect(screen.getByRole('link', { name: /see activity/i }).getAttribute('href')).toBe('/collection/activity');
|
||||
expect(screen.getByTestId('tab-attention').textContent).toBe('2');
|
||||
});
|
||||
|
||||
test('library albums waiting to be matched need a person, and link to Unmatched', () => {
|
||||
setup();
|
||||
expect(screen.getByTestId('collection-verdict').textContent).toMatch(
|
||||
/5 albums wanted, 3 downloading\. 3 albums in your library need matching\./
|
||||
);
|
||||
expect(screen.getByRole('link', { name: /see unmatched/i }).getAttribute('href')).toBe('/collection/unmatched');
|
||||
});
|
||||
|
||||
// The library's health queues moved here from Admin: their counts
|
||||
// come from the admin summary, accented, and a line names the ones waiting.
|
||||
test('the library health queues carry what waits on you, and a line links to each', () => {
|
||||
setup(counts, '/collection', {
|
||||
test('the health queues carry what waits on you, and a line links to each', () => {
|
||||
setup('/collection', {
|
||||
...clear,
|
||||
reports: { count: 2, since: null },
|
||||
duplicates: { count: 5, since: null },
|
||||
@@ -111,13 +71,20 @@ describe('/collection layout', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('with nothing waiting there is no health line', () => {
|
||||
test('with nothing waiting the line says nothing needs you', () => {
|
||||
setup();
|
||||
expect(screen.queryByTestId('collection-health')).toBeNull();
|
||||
expect(screen.getByTestId('collection-health').textContent?.trim()).toBe('Nothing needs you.');
|
||||
});
|
||||
});
|
||||
|
||||
test("an artist's page sits under Catalogue", () => {
|
||||
setup(counts, '/collection/artist/blur');
|
||||
expect(screen.getByRole('link', { name: /^catalogue/i })).toHaveAttribute('aria-current', 'page');
|
||||
describe('/collection overview', () => {
|
||||
test('lists each queue with something in it, then the empty ones on one line', () => {
|
||||
mockSummary({ ...clear, missing: { count: 3, since: new Date().toISOString() } });
|
||||
render(CollectionPage);
|
||||
const rows = screen.getAllByTestId('collection-queue');
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0].textContent).toMatch(/3 missing files/);
|
||||
expect(rows[0].querySelector('a')?.getAttribute('href')).toBe('/collection/missing');
|
||||
expect(screen.getByTestId('collection-clear').textContent?.trim()).toBe('No reports, duplicates, suspect sources.');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -42,11 +42,10 @@
|
||||
//
|
||||
// Except for one recording filling several of an album's slots (class
|
||||
// mismatch), where a merge is the wrong answer: it keeps one copy's
|
||||
// title whether or not it is the audio's, and fetches nothing. There an
|
||||
// admin says which song the recording is, or that they can't tell, and the
|
||||
// group settles as the resolver would have: copies in other songs' slots are
|
||||
// removed, the release they came from is set aside, and the album is fetched
|
||||
// again.
|
||||
// title whether or not it is the audio's. There an admin says which song the
|
||||
// recording is, or that they can't tell, and the group settles as the
|
||||
// resolver would have: copies in other songs' slots are removed, and those
|
||||
// slots show as missing until a good copy is in the library folder.
|
||||
|
||||
type Tab = DuplicatesView | 'resolved';
|
||||
const fromUrl = page.url.searchParams.get('view');
|
||||
@@ -172,11 +171,7 @@
|
||||
try {
|
||||
const result = await refetchDuplicateGroup(group.id, { keep_track_id: slotPick[group.id] ?? '' });
|
||||
const removed = `Removed ${plural(result.removed_paths.length, 'file', 'files')}`;
|
||||
pushToast(
|
||||
result.blocked.length > 0
|
||||
? `${removed} and set aside the release they came from. The album will be fetched again.`
|
||||
: `${removed}. The album will be fetched again, but Minstrel didn't download these files, so the same ones may come back.`
|
||||
);
|
||||
pushToast(`${removed}. Their slots show as missing until a good copy is in the library.`);
|
||||
query.refetch();
|
||||
} catch (e: unknown) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
@@ -283,8 +278,8 @@
|
||||
<p class="text-text-secondary">
|
||||
Tracks that hold the same recording more than once. Most settle on their own: a song held twice
|
||||
on one album is merged, copies on different releases count as one song, two versions of a song
|
||||
are left alone, and a file filling another song's track slot is removed so the album is fetched
|
||||
again. What's left here needs you.
|
||||
are left alone, and a file filling another song's track slot is removed, leaving that slot
|
||||
missing. What's left here needs you.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -344,12 +339,12 @@
|
||||
{:else if item.action === 'duplicate_wrong_file' && !item.details.kept_title}
|
||||
<p class="text-text-primary">
|
||||
{item.details.artist}: one recording was filed as {removed.map((r) => r.title).join(' and ')},
|
||||
and it is none of them. Removed; the album will be fetched again.
|
||||
and it is none of them. Removed; those slots show as missing.
|
||||
</p>
|
||||
{:else if item.action === 'duplicate_wrong_file'}
|
||||
<p class="text-text-primary">
|
||||
{item.details.artist}: the recording of {item.details.kept_title} was also filed as
|
||||
{removed.map((r) => r.title).join(', ')}. Removed from there; the album will be fetched again.
|
||||
{removed.map((r) => r.title).join(', ')}. Removed from there; those slots show as missing.
|
||||
</p>
|
||||
{:else}
|
||||
<p class="text-text-primary">
|
||||
@@ -455,11 +450,11 @@
|
||||
{#if refetching === group.id}
|
||||
Removing…
|
||||
{:else if confirmingRefetch === group.id}
|
||||
Remove {plural(refetchRemoves(group).length, 'file', 'files')} and get it again
|
||||
Remove {plural(refetchRemoves(group).length, 'file', 'files')}
|
||||
{:else if picked}
|
||||
Keep “{picked.title}”…
|
||||
{:else}
|
||||
Get it again…
|
||||
Remove the copies…
|
||||
{/if}
|
||||
</button>
|
||||
{:else}
|
||||
@@ -527,8 +522,8 @@
|
||||
{:else}
|
||||
All {plural(group.members.length, 'copy', 'copies')} will be deleted from disk.
|
||||
{/if}
|
||||
Their tracks stay, marked missing, with their likes and plays. The release the files came
|
||||
from is set aside, and the album is fetched again from another one.
|
||||
Their tracks stay, marked missing, with their likes and plays, until a good copy is in the
|
||||
library folder.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -18,8 +18,7 @@ vi.mock('#lib/api/admin.js', () => ({
|
||||
}),
|
||||
refetchDuplicateGroup: vi.fn().mockResolvedValue({
|
||||
kept_track_id: null,
|
||||
removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3'],
|
||||
blocked: ['Moe Shop - WWW [WEB]']
|
||||
removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3']
|
||||
})
|
||||
}));
|
||||
vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() }));
|
||||
@@ -282,23 +281,23 @@ describe('admin duplicates', () => {
|
||||
return r;
|
||||
}
|
||||
|
||||
test('offers Get it again instead of Merge, with no copy proposed', () => {
|
||||
test('offers Remove the copies instead of Merge, with no copy proposed', () => {
|
||||
renderWith(slots());
|
||||
expect(screen.queryByRole('button', { name: 'Merge…' })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy();
|
||||
expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy();
|
||||
expect(screen.getAllByRole('radio').some((r) => (r as HTMLInputElement).checked)).toBe(false);
|
||||
expect(screen.queryByTestId('survivor-badge')).toBeNull();
|
||||
});
|
||||
|
||||
test("can't tell: every copy goes, after a second click", async () => {
|
||||
renderWith(slots());
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Get it again…' }));
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Remove the copies…' }));
|
||||
expect(refetchDuplicateGroup).not.toHaveBeenCalled();
|
||||
const confirm = text(screen.getByTestId('refetch-confirm'));
|
||||
expect(confirm).toContain('All 2 copies will be deleted from disk');
|
||||
expect(confirm).toContain('the album is fetched again from another one');
|
||||
expect(confirm).toContain('until a good copy is in the library folder');
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files and get it again' }));
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files' }));
|
||||
expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: '' });
|
||||
});
|
||||
|
||||
@@ -310,7 +309,7 @@ describe('admin duplicates', () => {
|
||||
expect(text(screen.getByTestId('refetch-confirm'))).toContain(
|
||||
'The copy titled “WWW (instrumental)” stays, and 1 copy under other titles will be deleted from disk'
|
||||
);
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file and get it again' }));
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file' }));
|
||||
expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' });
|
||||
});
|
||||
|
||||
@@ -318,7 +317,7 @@ describe('admin duplicates', () => {
|
||||
renderWith(slots());
|
||||
await fireEvent.click(screen.getAllByRole('radio')[0]);
|
||||
await fireEvent.click(screen.getByRole('button', { name: "I can't tell which song it is" }));
|
||||
expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy();
|
||||
expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy();
|
||||
expect(screen.queryByTestId('song-badge')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -491,11 +490,11 @@ describe('admin duplicates', () => {
|
||||
const items = screen.getAllByTestId('resolved-item').map(text);
|
||||
expect(items[0]).toContain('Moe Shop: Lovesick and Lovesick (Instrumental) are different versions, not duplicates. Both kept.');
|
||||
expect(items[1]).toContain(
|
||||
'Savant: the recording of Void was also filed as Reach. Removed from there; the album will be fetched again.'
|
||||
'Savant: the recording of Void was also filed as Reach. Removed from there; those slots show as missing.'
|
||||
);
|
||||
expect(items[1]).toContain('/data/Music/Savant/Void/17 - Reach.m4a');
|
||||
expect(items[2]).toContain(
|
||||
'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; the album will be fetched again.'
|
||||
'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those slots show as missing.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import FollowList from '#lib/components/wanted/FollowList.svelte';
|
||||
import ReleaseProfilesCard from '#lib/components/ReleaseProfilesCard.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Following')}</title></svelte:head>
|
||||
|
||||
<div class="space-y-6">
|
||||
<FollowList />
|
||||
<ReleaseProfilesCard />
|
||||
</div>
|
||||
@@ -1,31 +1,17 @@
|
||||
<script lang="ts">
|
||||
import { plural } from '#lib/utils/plural.js';
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import { ChevronDown, FolderX, Music2, Search, X } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import {
|
||||
createMissingFilesQuery,
|
||||
getReacquisitionSettings,
|
||||
type ReacquisitionSettings
|
||||
} from '#lib/api/admin.js';
|
||||
import { removeWant, searchWant } from '#lib/api/wanted.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { errMessage } from '#lib/api/errors.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
import { FolderX, Music2 } from 'lucide-svelte';
|
||||
import { createMissingFilesQuery } from '#lib/api/admin.js';
|
||||
import { relativeTime } from '#lib/utils/relativeTime.js';
|
||||
import { formatDuration } from '#lib/media/duration.js';
|
||||
import { coverUrl } from '#lib/media/covers.js';
|
||||
import { needsYou, searched, wantStatus } from '#lib/wanted/wantStatus.js';
|
||||
import WantCandidates from '#lib/components/WantCandidates.svelte';
|
||||
import { onMount } from 'svelte';
|
||||
import type { AdminMissingGroup, Want } from '#lib/api/types.js';
|
||||
import type { AdminMissingGroup } from '#lib/api/types.js';
|
||||
|
||||
// Files the scan looked for and could not find, by folder, with where each
|
||||
// folder's album stands on the wanted list. A
|
||||
// missing file keeps its track row, its play history and its likes,
|
||||
// because the file may come back: the scanner clears the mark by itself,
|
||||
// and adopts the row if it returns under a new name. Nothing on
|
||||
// this page deletes a track; its actions are the wanted list's own.
|
||||
// Files the scan looked for and could not find, by folder. A missing file
|
||||
// keeps its track row, its play history and its likes, because the file may
|
||||
// come back: the scanner clears the mark by itself, and adopts the row if it
|
||||
// returns under a new name. Nothing on this page deletes a track.
|
||||
|
||||
const PAGE_SIZE = 50;
|
||||
|
||||
@@ -39,56 +25,6 @@
|
||||
const total = $derived(query.data?.total ?? 0);
|
||||
const shown = $derived(groups.reduce((n, g) => n + g.tracks.length, 0));
|
||||
const hasMore = $derived(offset + shown < total);
|
||||
|
||||
// What happens to these is set under Acquisition; the line above
|
||||
// the list says what it is now, since this is where the question comes up.
|
||||
let policy = $state<ReacquisitionSettings | null>(null);
|
||||
onMount(async () => {
|
||||
try {
|
||||
policy = await getReacquisitionSettings();
|
||||
} catch {
|
||||
policy = null;
|
||||
}
|
||||
});
|
||||
|
||||
// A folder's want, acted on here as on the wanted list.
|
||||
const client = useQueryClient();
|
||||
let busy = $state<string | null>(null);
|
||||
let searching = $state<string | null>(null);
|
||||
let open = $state<string | null>(null);
|
||||
|
||||
const refresh = () =>
|
||||
Promise.all([
|
||||
client.invalidateQueries({ queryKey: ['adminMissingFiles'] }),
|
||||
client.invalidateQueries({ queryKey: ['adminWants'] })
|
||||
]);
|
||||
|
||||
async function onSearch(w: Want) {
|
||||
searching = w.id;
|
||||
try {
|
||||
const r = await searchWant(w.id);
|
||||
pushToast(searched(w, r), r.outcome === 'error' ? 'error' : 'info');
|
||||
await Promise.all([refresh(), client.invalidateQueries({ queryKey: qk.wantCandidates(w.id) })]);
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
searching = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function onRemove(w: Want) {
|
||||
busy = w.id;
|
||||
try {
|
||||
await removeWant(w.id);
|
||||
pushToast(`${w.title} is off the wanted list, and won't be fetched back.`);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
pushToast(errMessage(e), 'error');
|
||||
} finally {
|
||||
busy = null;
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Missing files')}</title></svelte:head>
|
||||
@@ -108,21 +44,11 @@
|
||||
</div>
|
||||
<p class="text-text-secondary">
|
||||
Tracks whose audio file the last scan couldn't find. They keep their play
|
||||
history and likes, and stop being offered anywhere until the file returns.
|
||||
history and likes, and stop being offered anywhere until a file is back in the library
|
||||
folder.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<p class="text-sm text-text-secondary" data-testid="reacquisition-policy">
|
||||
{#if policy}
|
||||
{policy.enabled
|
||||
? `Albums missing for ${policy.grace_hours} hours go back on the wanted list by themselves.`
|
||||
: 'Missing albums are not wanted back automatically.'}
|
||||
{/if}
|
||||
<a href="/admin/acquisition#reacquisition" class="text-accent-fg hover:underline">
|
||||
{policy ? 'Change' : 'Set what happens to missing files'}
|
||||
</a>
|
||||
</p>
|
||||
|
||||
{#if query.isPending}
|
||||
<p class="text-text-secondary">Checking what's missing…</p>
|
||||
{:else if query.isError}
|
||||
@@ -158,72 +84,6 @@
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<!-- Where this folder's album stands on the wanted list. Without it
|
||||
the only way to tell "not wanted yet" from "wanted, nothing has
|
||||
come" is to go and read the wanted list. -->
|
||||
{#if group.reacquisition}
|
||||
{@const r = group.reacquisition}
|
||||
{@const w = r.want}
|
||||
<div class="space-y-1.5 border-b border-border px-4 py-2" data-testid="reacquisition-state">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<div class="min-w-0 space-y-0.5 text-xs">
|
||||
<p class="text-text-secondary">
|
||||
{#if r.held_at}
|
||||
Held again {relativeTime(r.held_at)}. The rows here clear on the next scan.
|
||||
{:else if r.wanted_at}
|
||||
Wanted back since {relativeTime(r.wanted_at)}.
|
||||
{/if}
|
||||
</p>
|
||||
{#if w && !r.held_at}
|
||||
<p
|
||||
class={needsYou(w) ? 'text-text-primary' : 'text-text-secondary'}
|
||||
data-testid="missing-want-status"
|
||||
>
|
||||
{wantStatus(w)}
|
||||
{#if needsYou(w)}
|
||||
<a href="/collection/activity" class="ml-1 text-accent-fg hover:underline">Decide on Activity</a>
|
||||
{/if}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
{#if w && !r.held_at}
|
||||
<div class="flex shrink-0 flex-wrap justify-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onSearch(w)}
|
||||
disabled={searching !== null || !!w.grab?.live}
|
||||
aria-label="Search for {w.title} now"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
<Search size={12} strokeWidth={2} /> {searching === w.id ? 'Searching…' : 'Search'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => (open = open === w.id ? null : w.id)}
|
||||
aria-expanded={open === w.id}
|
||||
aria-label="Releases found for {w.title}"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
>
|
||||
Releases <ChevronDown size={12} strokeWidth={2} class={open === w.id ? 'rotate-180' : ''} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => onRemove(w)}
|
||||
disabled={busy === w.id}
|
||||
aria-label="Stop wanting {w.title}"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
|
||||
>
|
||||
<X size={12} strokeWidth={2} /> Remove
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{#if w && open === w.id}
|
||||
<WantCandidates wantId={w.id} title={w.title} />
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<ul class="divide-y divide-border">
|
||||
{#each group.tracks as t (t.track_id)}
|
||||
<li class="flex items-center gap-3 px-4 py-2" data-testid="missing-track-row">
|
||||
|
||||
@@ -1,36 +1,12 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
|
||||
import { render, screen } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../../test-utils/query';
|
||||
import type { AdminMissingResponse, Want } from '#lib/api/types.js';
|
||||
import type { AdminMissingResponse } from '#lib/api/types.js';
|
||||
|
||||
// The page reads the re-acquisition policy to say what happens to these;
|
||||
// the settings themselves are on Admin › Acquisition.
|
||||
vi.mock('#lib/api/admin.js', () => ({
|
||||
createMissingFilesQuery: vi.fn(),
|
||||
getReacquisitionSettings: vi.fn().mockResolvedValue({
|
||||
enabled: true,
|
||||
grace_hours: 24,
|
||||
max_per_pass: 20,
|
||||
unnameable_albums: 0
|
||||
})
|
||||
}));
|
||||
// A folder's want is acted on here as on the wanted list.
|
||||
vi.mock('#lib/api/wanted.js', () => ({
|
||||
removeWant: vi.fn().mockResolvedValue(undefined),
|
||||
searchWant: vi.fn().mockResolvedValue({
|
||||
outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', narrowed: []
|
||||
}),
|
||||
createCandidatesQuery: vi.fn(),
|
||||
grabCandidate: vi.fn(),
|
||||
blockCandidate: vi.fn(),
|
||||
unblockRelease: vi.fn()
|
||||
}));
|
||||
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
|
||||
vi.mock('#lib/api/admin.js', () => ({ createMissingFilesQuery: vi.fn() }));
|
||||
|
||||
import MissingPage from './+page.svelte';
|
||||
import { createMissingFilesQuery } from '#lib/api/admin.js';
|
||||
import { removeWant, searchWant } from '#lib/api/wanted.js';
|
||||
import { pushToast } from '#lib/stores/toast.svelte.js';
|
||||
|
||||
const DAY = 24 * 3_600_000;
|
||||
|
||||
@@ -57,7 +33,6 @@ const response: AdminMissingResponse = {
|
||||
{
|
||||
directory: '/music/Linkin Park/Minutes to Midnight',
|
||||
missing_since: new Date(Date.now() - 3 * DAY).toISOString(),
|
||||
reacquisition: null,
|
||||
tracks: [
|
||||
track('Given Up', { lastPlayed: new Date(Date.now() - 2 * DAY).toISOString() }),
|
||||
track('Bleed It Out')
|
||||
@@ -66,7 +41,6 @@ const response: AdminMissingResponse = {
|
||||
{
|
||||
directory: '/music/Boards of Canada/Geogaddi',
|
||||
missing_since: new Date(Date.now() - 9 * DAY).toISOString(),
|
||||
reacquisition: null,
|
||||
tracks: [track('1969')]
|
||||
}
|
||||
]
|
||||
@@ -74,13 +48,6 @@ const response: AdminMissingResponse = {
|
||||
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
// Whitespace-normalised text of a testid'd element. Svelte templates wrap
|
||||
// mid-sentence, so raw textContent has newlines where the rendered page has
|
||||
// single spaces — asserting on it directly makes tests fail on reflow.
|
||||
function text(testId: string): string {
|
||||
return (screen.getByTestId(testId).textContent ?? '').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
function renderWith(data: AdminMissingResponse | undefined, extra = {}) {
|
||||
vi.mocked(createMissingFilesQuery).mockReturnValue(
|
||||
mockQuery({ data, ...extra }) as ReturnType<typeof createMissingFilesQuery>
|
||||
@@ -88,46 +55,7 @@ function renderWith(data: AdminMissingResponse | undefined, extra = {}) {
|
||||
return render(MissingPage);
|
||||
}
|
||||
|
||||
function want(extra: Partial<Want> = {}): Want {
|
||||
return {
|
||||
id: 'w-1',
|
||||
release_group_mbid: 'rg-1',
|
||||
title: 'Minutes to Midnight',
|
||||
artist_mbid: 'lp',
|
||||
artist_name: 'Linkin Park',
|
||||
primary_type: 'Album',
|
||||
secondary_types: [],
|
||||
year: '2007',
|
||||
reason: 'missing',
|
||||
wanted_at: new Date(Date.now() - 2 * DAY).toISOString(),
|
||||
held_at: null,
|
||||
image_url: '',
|
||||
search: {
|
||||
searched_at: new Date(Date.now() - 3_600_000).toISOString(),
|
||||
outcome: 'nothing',
|
||||
considered: 0,
|
||||
best_release: '',
|
||||
best_verdict: '',
|
||||
error: ''
|
||||
},
|
||||
...extra
|
||||
};
|
||||
}
|
||||
|
||||
function wantedBack(w: Want | null = want()): AdminMissingResponse {
|
||||
const withState = structuredClone(response);
|
||||
withState.groups[0].reacquisition = { wanted_at: new Date(Date.now() - 2 * DAY).toISOString(), held_at: null, want: w };
|
||||
return withState;
|
||||
}
|
||||
|
||||
describe('/collection/missing', () => {
|
||||
test('says what happens to missing files, and links to where it is set', async () => {
|
||||
renderWith(response);
|
||||
const line = screen.getByTestId('reacquisition-policy');
|
||||
await screen.findByText(/missing for 24 hours go back on the wanted list/i);
|
||||
expect(line.querySelector('a')?.getAttribute('href')).toBe('/admin/acquisition#reacquisition');
|
||||
});
|
||||
|
||||
test('groups rows under their directory', () => {
|
||||
renderWith(response);
|
||||
expect(screen.getByText('/music/Linkin Park/Minutes to Midnight')).toBeTruthy();
|
||||
@@ -185,63 +113,6 @@ describe('/collection/missing', () => {
|
||||
expect(screen.getByText(/couldn't load the missing files/i)).toBeTruthy();
|
||||
});
|
||||
|
||||
// Not wanted yet is the common case for a folder that just went missing;
|
||||
// a line saying so would be noise on every row.
|
||||
test('no re-acquisition line before the album is wanted', () => {
|
||||
renderWith(response);
|
||||
expect(screen.queryByTestId('reacquisition-state')).toBeNull();
|
||||
});
|
||||
|
||||
test('an album wanted back says since when, and what its last search found', () => {
|
||||
renderWith(wantedBack());
|
||||
expect(text('reacquisition-state')).toMatch(/wanted back since 2d ago/i);
|
||||
expect(text('missing-want-status')).toBe('Searched 1h ago: nothing found');
|
||||
});
|
||||
|
||||
test('its download, when one is running, is the line', () => {
|
||||
renderWith(
|
||||
wantedBack(
|
||||
want({
|
||||
grab: {
|
||||
id: 'g', name: 'LP - MtM [FLAC]', grabbed_at: new Date().toISOString(), origin: 'schedule', quality: 'FLAC',
|
||||
live: true, end_reason: '', progress: 0.42, import_state: 'downloading', import_reason: '', end_detail: '',
|
||||
imported_at: null, imported_files: 0
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(text('missing-want-status')).toBe('Downloading 42% · LP - MtM [FLAC]');
|
||||
expect(screen.getByRole('button', { name: /search for minutes to midnight now/i })).toHaveProperty('disabled', true);
|
||||
});
|
||||
|
||||
test('Search runs one now and says what it found', async () => {
|
||||
renderWith(wantedBack());
|
||||
await fireEvent.click(screen.getByRole('button', { name: /search for minutes to midnight now/i }));
|
||||
await waitFor(() => expect(searchWant).toHaveBeenCalledWith('w-1'));
|
||||
await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Nothing found for Minutes to Midnight.', 'info'));
|
||||
});
|
||||
|
||||
test('Remove takes it off the wanted list', async () => {
|
||||
renderWith(wantedBack());
|
||||
await fireEvent.click(screen.getByRole('button', { name: /stop wanting minutes to midnight/i }));
|
||||
await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w-1'));
|
||||
expect(pushToast).toHaveBeenCalledWith("Minutes to Midnight is off the wanted list, and won't be fetched back.");
|
||||
});
|
||||
|
||||
test('an album held again says so', () => {
|
||||
const withState = structuredClone(response);
|
||||
withState.groups[0].reacquisition = {
|
||||
wanted_at: new Date(Date.now() - 5 * DAY).toISOString(),
|
||||
held_at: new Date(Date.now() - DAY).toISOString(),
|
||||
want: want({ held_at: new Date(Date.now() - DAY).toISOString() })
|
||||
};
|
||||
renderWith(withState);
|
||||
expect(text('reacquisition-state')).toMatch(/held again 1d ago/i);
|
||||
// Nothing left to search for.
|
||||
expect(screen.queryByTestId('missing-want-status')).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /search for/i })).toBeNull();
|
||||
});
|
||||
|
||||
// Paging only appears when it can do something: a single page of results
|
||||
// should not render dead Previous/Next buttons.
|
||||
test('no pager when everything fits on one page', () => {
|
||||
|
||||
@@ -17,9 +17,7 @@
|
||||
// The duplicate resolver holds each one back from radio and the mixes, and
|
||||
// merges it away where the library has a clean copy. A marker
|
||||
// is a reason to look, not proof, so each row says what was done and offers
|
||||
// the undo: "This one is fine" lets the track back for good. A rip's album
|
||||
// stays wanted for a clean copy, searched for weekly and filed over the rip
|
||||
// when it comes.
|
||||
// the undo: "This one is fine" lets the track back for good.
|
||||
|
||||
const queryStore = createSuspectSourcesQuery();
|
||||
const query = $derived($queryStore);
|
||||
@@ -99,9 +97,7 @@
|
||||
a video site, and can be the wrong audio: a live take, a music-video edit, or
|
||||
something else entirely. Each one is kept out of radio and the mixes, though it still
|
||||
plays when you choose it, and it is merged away where the library has a clean copy of the
|
||||
same song. Where it is the only copy, its album is searched for a clean copy once a week,
|
||||
under <a href="/collection/upgrades" class="text-accent-fg hover:underline">Upgrades</a>. If one
|
||||
is fine, say so and it goes back in.
|
||||
same song. If one is fine, say so and it goes back in.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
@@ -181,13 +177,6 @@
|
||||
<span class="text-xs text-text-secondary" data-testid="suspect-verdict">
|
||||
Held back{#if t.verdict_at && !changed[t.track_id]} {relativeTime(t.verdict_at)}{/if}
|
||||
</span>
|
||||
{#if t.replacing}
|
||||
<a href="/collection/upgrades" class="text-xs text-text-muted hover:underline" data-testid="suspect-searched">
|
||||
{t.searched_at
|
||||
? `Looked for a clean copy ${relativeTime(t.searched_at)}`
|
||||
: 'A clean copy is wanted'}
|
||||
</a>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => setVerdict(t, 'fine')}
|
||||
|
||||
@@ -30,8 +30,6 @@ function track(title: string, file: string, markers: string[], disc: number | nu
|
||||
markers,
|
||||
verdict: 'suspect',
|
||||
verdict_at: new Date(Date.now() - 3_600_000).toISOString(),
|
||||
replacing: false,
|
||||
searched_at: null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -138,17 +136,4 @@ describe('Suspect sources page', () => {
|
||||
expect(await screen.findByText('Marked fine')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Hold back again' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// A rip's album is wanted for a clean copy, and the row says when
|
||||
// one was last looked for.
|
||||
test('shows that a clean copy is wanted, and when it was looked for', () => {
|
||||
const t = track('Strobelite', 'Gorillaz - Strobelite (Official Video).mp3', ['music video']);
|
||||
t.replacing = true;
|
||||
t.searched_at = new Date(Date.now() - 7_200_000).toISOString();
|
||||
mocked.mockReturnValue(infinite([page(0, 1, [{ directory: HUMANZ, tracks: [t] }])]));
|
||||
render(SuspectSourcesPage);
|
||||
const line = screen.getByTestId('suspect-searched');
|
||||
expect(line).toHaveTextContent(/Looked for a clean copy/);
|
||||
expect(line).toHaveAttribute('href', '/collection/upgrades');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import UnmatchedList from '#lib/components/wanted/UnmatchedList.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Unmatched')}</title></svelte:head>
|
||||
|
||||
<UnmatchedList />
|
||||
@@ -1,8 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import WantList from '#lib/components/wanted/WantList.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Upgrades')}</title></svelte:head>
|
||||
|
||||
<WantList list="upgrade" />
|
||||
@@ -1,8 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import WantList from '#lib/components/wanted/WantList.svelte';
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Collection · Wanted')}</title></svelte:head>
|
||||
|
||||
<WantList list="wanted" />
|
||||
@@ -1,232 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
|
||||
import { createRequest } from '#lib/api/requests.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import DiscoverResultCard from '#lib/components/DiscoverResultCard.svelte';
|
||||
import DiscoverTabs from '#lib/components/DiscoverTabs.svelte';
|
||||
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
|
||||
import SuggestionFeed from '#lib/components/SuggestionFeed.svelte';
|
||||
import Modal from '#lib/components/Modal.svelte';
|
||||
import type {
|
||||
CatalogueSearchResult,
|
||||
RequestKind
|
||||
} from '#lib/api/types.js';
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Local input is the source of truth for the discover query — Shell's global
|
||||
// SearchInput targets /search, not /discover. We debounce by 250ms before
|
||||
// pushing into `debouncedQ`, which is what the query factory observes.
|
||||
let inputValue = $state('');
|
||||
let debouncedQ = $state('');
|
||||
let activeKind: RequestKind = $state('artist');
|
||||
|
||||
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
$effect(() => {
|
||||
const v = inputValue;
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
debounceTimer = setTimeout(() => {
|
||||
debouncedQ = v.trim();
|
||||
}, 250);
|
||||
return () => {
|
||||
if (debounceTimer) clearTimeout(debounceTimer);
|
||||
};
|
||||
});
|
||||
|
||||
const queryStore = $derived(createCatalogueSearchQuery(debouncedQ, activeKind));
|
||||
const query = $derived($queryStore);
|
||||
const results = $derived((query.data ?? []) as CatalogueSearchResult[]);
|
||||
|
||||
// Track-kind confirm modal: nulled out = closed.
|
||||
let modalResult: CatalogueSearchResult | null = $state(null);
|
||||
|
||||
// In-session optimistic flip — once a Request goes through, we flip the
|
||||
// card to 'requested' immediately. Cleared only on full page reload, which
|
||||
// is fine for a short-lived discover session.
|
||||
let optimisticRequested: Set<string> = $state(new Set());
|
||||
|
||||
function cardState(r: CatalogueSearchResult) {
|
||||
if (r.in_library) return 'kept' as const;
|
||||
if (r.requested || optimisticRequested.has(r.mbid)) return 'requested' as const;
|
||||
return 'requestable' as const;
|
||||
}
|
||||
|
||||
// Backend validates kind→required-MBID-fields, not the human strings, so
|
||||
// imperfect derivations of artist_name from secondary_text won't block the
|
||||
// request. We pass the data we have and let the server take care of the rest.
|
||||
function buildRequestParams(r: CatalogueSearchResult, kind: RequestKind) {
|
||||
if (kind === 'artist') {
|
||||
return {
|
||||
kind,
|
||||
artist_mbid: r.artist_mbid || r.mbid,
|
||||
artist_name: r.name
|
||||
};
|
||||
}
|
||||
if (kind === 'album') {
|
||||
return {
|
||||
kind,
|
||||
artist_mbid: r.artist_mbid,
|
||||
album_mbid: r.album_mbid || r.mbid,
|
||||
artist_name: r.secondary_text,
|
||||
album_title: r.name
|
||||
};
|
||||
}
|
||||
// track
|
||||
return {
|
||||
kind,
|
||||
artist_mbid: r.artist_mbid,
|
||||
album_mbid: r.album_mbid,
|
||||
track_mbid: r.mbid,
|
||||
artist_name: r.secondary_text,
|
||||
album_title: r.secondary_text,
|
||||
track_title: r.name
|
||||
};
|
||||
}
|
||||
|
||||
async function submitRequest(r: CatalogueSearchResult) {
|
||||
try {
|
||||
await createRequest(buildRequestParams(r, activeKind));
|
||||
const next = new Set(optimisticRequested);
|
||||
next.add(r.mbid);
|
||||
optimisticRequested = next;
|
||||
// Surface the new request on /requests right away (+ start its poll).
|
||||
queryClient.invalidateQueries({ queryKey: qk.myRequests() });
|
||||
} catch {
|
||||
// Swallowed, with no toast: the card stays in 'requestable' so the
|
||||
// user can retry.
|
||||
}
|
||||
}
|
||||
|
||||
function handleRequestClick(r: CatalogueSearchResult) {
|
||||
if (activeKind === 'track') {
|
||||
modalResult = r;
|
||||
} else {
|
||||
submitRequest(r);
|
||||
}
|
||||
}
|
||||
|
||||
function confirmModal() {
|
||||
if (modalResult) submitRequest(modalResult);
|
||||
modalResult = null;
|
||||
}
|
||||
|
||||
function cancelModal() {
|
||||
modalResult = null;
|
||||
}
|
||||
|
||||
const tabs: { kind: RequestKind; label: string }[] = [
|
||||
{ kind: 'artist', label: 'Artists' },
|
||||
{ kind: 'album', label: 'Albums' },
|
||||
{ kind: 'track', label: 'Tracks' }
|
||||
];
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Discover')}</title></svelte:head>
|
||||
|
||||
<!--
|
||||
Page layout: a full-height flex column so the persistent chrome
|
||||
(DiscoverTabs, search input, facet tabs) stays anchored at the top
|
||||
while only the result grid scrolls. Main has overflow-y-auto, but
|
||||
with h-full + flex-col + min-h-0 on the scroll region, this page
|
||||
contains its own overflow and main's scroll never triggers.
|
||||
-->
|
||||
<div class="flex h-full flex-col gap-4">
|
||||
<DiscoverTabs />
|
||||
|
||||
<input
|
||||
type="search"
|
||||
aria-label="Search MusicBrainz"
|
||||
placeholder="Search artists, albums, or tracks"
|
||||
bind:value={inputValue}
|
||||
class="w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary placeholder:text-text-muted focus:outline-hidden focus:ring-2 focus:ring-accent"
|
||||
/>
|
||||
|
||||
{#if debouncedQ === ''}
|
||||
<div class="min-h-0 flex-1 overflow-y-auto pb-4">
|
||||
<SuggestionFeed />
|
||||
</div>
|
||||
{:else}
|
||||
<header class="space-y-1">
|
||||
<h2 class="font-display text-2xl font-medium text-text-primary">
|
||||
Add music to the library
|
||||
</h2>
|
||||
<p class="text-text-secondary">
|
||||
Search MusicBrainz to add new artists, albums, or tracks.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<nav aria-label="Result kind" class="border-b border-border">
|
||||
<ul class="flex gap-2">
|
||||
{#each tabs as tab (tab.kind)}
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={activeKind === tab.kind}
|
||||
class="border-b-2 px-3 py-2 text-sm {activeKind === tab.kind
|
||||
? 'border-accent text-text-primary'
|
||||
: 'border-transparent text-text-secondary hover:text-text-primary'}"
|
||||
onclick={() => (activeKind = tab.kind)}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<div class="min-h-0 flex-1 overflow-y-auto pb-4">
|
||||
{#if query.isError}
|
||||
<ApiErrorBanner error={query.error} onRetry={query.refetch} />
|
||||
{:else if query.isPending}
|
||||
<p class="text-text-secondary">Searching…</p>
|
||||
{:else if results.length === 0}
|
||||
<p class="text-text-secondary">Nothing to add for that search yet.</p>
|
||||
{:else}
|
||||
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
|
||||
{#each results as r (r.mbid)}
|
||||
<DiscoverResultCard
|
||||
kind={activeKind}
|
||||
title={r.name}
|
||||
subtitle={r.secondary_text}
|
||||
imageUrl={r.image_url || undefined}
|
||||
state={cardState(r)}
|
||||
onRequest={() => handleRequestClick(r)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
title="Add the album?"
|
||||
open={modalResult !== null}
|
||||
onClose={cancelModal}
|
||||
>
|
||||
{#if modalResult}
|
||||
<p class="-mt-2 text-text-secondary">
|
||||
Requesting <em class="font-medium text-text-primary">{modalResult.name}</em>
|
||||
will add <em class="font-medium text-text-primary">{modalResult.secondary_text}</em>.
|
||||
Continue?
|
||||
</p>
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg"
|
||||
onclick={cancelModal}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg"
|
||||
onclick={confirmModal}
|
||||
>
|
||||
Add the album
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</Modal>
|
||||
@@ -1,319 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import { apiClientMock } from '../../test-utils/mocks/client';
|
||||
import type { CatalogueSearchResult } from '#lib/api/types.js';
|
||||
import { pageUrlModule } from '../../test-utils/mocks/appState';
|
||||
|
||||
// $app/state / $app/navigation must be mocked or rendering the page
|
||||
// pulls in SvelteKit's client runtime (`notifiable_store is not a
|
||||
// function`) at module load. Same pattern as the other route tests.
|
||||
const pageState = vi.hoisted(() => ({
|
||||
pageUrl: new URL('http://localhost/discover')
|
||||
}));
|
||||
vi.mock('$app/state', () => pageUrlModule(pageState));
|
||||
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
|
||||
|
||||
// The catalogue search query factory and createRequest are mocked at the module
|
||||
// level so each test can shape what the page sees without standing up a
|
||||
// real QueryClient + network.
|
||||
vi.mock('#lib/api/catalogue.js', () => ({
|
||||
createCatalogueSearchQuery: vi.fn()
|
||||
}));
|
||||
|
||||
// SuggestionFeed reaches for the snooze surface too. These are
|
||||
// stubbed here even though this page-level suite asserts nothing about
|
||||
// snoozing: a factory-shaped module mock must export everything the
|
||||
// component tree imports, or rendering the feed throws before any
|
||||
// assertion runs.
|
||||
vi.mock('#lib/api/suggestions.js', () => ({
|
||||
createSuggestionsQuery: vi.fn(),
|
||||
createSnoozesQuery: vi.fn(),
|
||||
snoozeSuggestion: vi.fn().mockResolvedValue(undefined),
|
||||
unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined)
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/requests.js', () => ({
|
||||
createRequest: vi.fn().mockResolvedValue({ id: 'r1' })
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/client.js', () => apiClientMock());
|
||||
|
||||
// The page calls useQueryClient() to invalidate qk.myRequests() after a
|
||||
// submit; stub it so rendering doesn't require a real QueryClient and
|
||||
// we can assert the invalidation fires.
|
||||
const queryClientMock = vi.hoisted(() => ({ invalidateQueries: vi.fn() }));
|
||||
vi.mock('@tanstack/svelte-query', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@tanstack/svelte-query')>();
|
||||
return { ...actual, useQueryClient: () => queryClientMock };
|
||||
});
|
||||
|
||||
import DiscoverPage from './+page.svelte';
|
||||
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
|
||||
import { createSuggestionsQuery, createSnoozesQuery } from '#lib/api/suggestions.js';
|
||||
import { createRequest } from '#lib/api/requests.js';
|
||||
|
||||
const mockedCreateQuery = createCatalogueSearchQuery as ReturnType<typeof vi.fn>;
|
||||
const mockedCreateSuggestionsQuery = createSuggestionsQuery as ReturnType<typeof vi.fn>;
|
||||
const mockedCreateSnoozesQuery = createSnoozesQuery as ReturnType<typeof vi.fn>;
|
||||
const mockedCreateRequest = createRequest as ReturnType<typeof vi.fn>;
|
||||
|
||||
function result(over: Partial<CatalogueSearchResult> = {}): CatalogueSearchResult {
|
||||
return {
|
||||
mbid: 'mbid-1',
|
||||
name: 'Boards of Canada',
|
||||
secondary_text: 'Electronic',
|
||||
image_url: '',
|
||||
artist_mbid: 'art-1',
|
||||
album_mbid: '',
|
||||
in_library: false,
|
||||
requested: false,
|
||||
...over
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
// Default: empty results, non-pending. Tests override per-case.
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [] }));
|
||||
// Default: empty suggestion feed so its empty-state copy renders without
|
||||
// interfering with search-mode tests.
|
||||
mockedCreateSuggestionsQuery.mockReturnValue(mockQuery({ data: [] }));
|
||||
// Nothing parked, which keeps the feed's empty-state copy on the
|
||||
// "no signal yet" branch that this suite's assertions expect.
|
||||
mockedCreateSnoozesQuery.mockReturnValue(mockQuery({ data: [] }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Discover page', () => {
|
||||
test('initial state (no query) shows the suggestion feed', () => {
|
||||
render(DiscoverPage);
|
||||
expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('empty input shows the suggestion feed', () => {
|
||||
render(DiscoverPage);
|
||||
expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
|
||||
// Kind tabs should NOT be visible when input is empty.
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Artists' })
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('typing replaces feed with search', async () => {
|
||||
vi.useFakeTimers();
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'miles' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
expect(screen.queryByText(/suggested for you/i)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/add music to the library/i)).toBeInTheDocument();
|
||||
// Kind tabs visible when searching.
|
||||
expect(screen.getByRole('button', { name: 'Artists' })).toBeInTheDocument();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('debounced input fires query factory with typed value after 250ms', async () => {
|
||||
vi.useFakeTimers();
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'boards' } });
|
||||
// Before the timer elapses, the factory was called only with the
|
||||
// initial empty string — never with 'boards'.
|
||||
expect(mockedCreateQuery).not.toHaveBeenCalledWith('boards', 'artist');
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'artist');
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('switching tabs refetches with the new kind', async () => {
|
||||
vi.useFakeTimers();
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'boards' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
// Switch to Albums.
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Albums' }));
|
||||
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'album');
|
||||
// Then to Tracks.
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
|
||||
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'track');
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('empty results state renders the voice-rule copy', async () => {
|
||||
vi.useFakeTimers();
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'zzz' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByText(/nothing to add for that search yet\./i)
|
||||
).toBeInTheDocument()
|
||||
);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
test('artist-kind Request click calls createRequest immediately (no modal)', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({
|
||||
mbid: 'art-mbid',
|
||||
artist_mbid: 'art-mbid',
|
||||
name: 'Boards of Canada'
|
||||
});
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'boards' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
vi.useRealTimers();
|
||||
|
||||
const requestBtn = await screen.findByRole('button', {
|
||||
name: /request boards of canada/i
|
||||
});
|
||||
await fireEvent.click(requestBtn);
|
||||
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
|
||||
expect(mockedCreateRequest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ kind: 'artist' })
|
||||
);
|
||||
// Modal must not be present for non-track kinds.
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('requestable card flips to "Requested" after a successful request', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({
|
||||
mbid: 'art-mbid',
|
||||
artist_mbid: 'art-mbid',
|
||||
name: 'Boards of Canada'
|
||||
});
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'boards' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
vi.useRealTimers();
|
||||
|
||||
const requestBtn = await screen.findByRole('button', {
|
||||
name: /request boards of canada/i
|
||||
});
|
||||
await fireEvent.click(requestBtn);
|
||||
await waitFor(() => {
|
||||
const flipped = screen.getByRole('button', { name: /already requested/i });
|
||||
expect(flipped).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
test('submitting a request invalidates myRequests so /requests updates (#369)', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({ mbid: 'art-mbid', artist_mbid: 'art-mbid', name: 'Boards of Canada' });
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'boards' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
vi.useRealTimers();
|
||||
|
||||
const requestBtn = await screen.findByRole('button', {
|
||||
name: /request boards of canada/i
|
||||
});
|
||||
await fireEvent.click(requestBtn);
|
||||
await waitFor(() => {
|
||||
expect(queryClientMock.invalidateQueries).toHaveBeenCalledWith({
|
||||
queryKey: ['myRequests']
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('track-kind Request click opens confirm modal; Confirm calls createRequest', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({
|
||||
mbid: 'tr-mbid',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'al-mbid',
|
||||
name: 'Roygbiv',
|
||||
secondary_text: 'Music Has The Right To Children · Boards of Canada'
|
||||
});
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
// Type first so the kind tabs become visible (empty-input mode shows the
|
||||
// suggestion feed and hides tabs).
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'roy' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
// Switch to track kind.
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
|
||||
vi.useRealTimers();
|
||||
|
||||
const requestBtn = await screen.findByRole('button', {
|
||||
name: /request roygbiv/i
|
||||
});
|
||||
await fireEvent.click(requestBtn);
|
||||
// Modal opens with the explanation copy.
|
||||
const dialog = await screen.findByRole('dialog');
|
||||
expect(dialog).toBeInTheDocument();
|
||||
expect(dialog.textContent).toMatch(/continue/i);
|
||||
// Confirm fires createRequest with kind=track.
|
||||
await fireEvent.click(screen.getByRole('button', { name: /add the album/i }));
|
||||
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
|
||||
expect(mockedCreateRequest).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'track',
|
||||
track_mbid: 'tr-mbid',
|
||||
album_mbid: 'al-mbid',
|
||||
artist_mbid: 'art-mbid'
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('track-kind modal Cancel does not call createRequest', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({
|
||||
mbid: 'tr-mbid',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'al-mbid',
|
||||
name: 'Roygbiv',
|
||||
secondary_text: 'Music Has The Right To Children · Boards of Canada'
|
||||
});
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'roy' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
|
||||
vi.useRealTimers();
|
||||
|
||||
const requestBtn = await screen.findByRole('button', {
|
||||
name: /request roygbiv/i
|
||||
});
|
||||
await fireEvent.click(requestBtn);
|
||||
await screen.findByRole('dialog');
|
||||
await fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
|
||||
expect(mockedCreateRequest).not.toHaveBeenCalled();
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('in_library result renders kept state regardless of requested', async () => {
|
||||
vi.useFakeTimers();
|
||||
const r = result({
|
||||
mbid: 'kept-1',
|
||||
name: 'Kind of Blue',
|
||||
in_library: true,
|
||||
requested: true
|
||||
});
|
||||
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
|
||||
render(DiscoverPage);
|
||||
const input = screen.getByLabelText(/search musicbrainz/i);
|
||||
await fireEvent.input(input, { target: { value: 'kind' } });
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
vi.useRealTimers();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,101 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { pageTitle } from '#lib/branding.js';
|
||||
import { Music2, X } from 'lucide-svelte';
|
||||
import { useQueryClient } from '@tanstack/svelte-query';
|
||||
import { createMyRequestsQuery, cancelRequest } from '#lib/api/requests.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
import RequestRow, { requestName } from '#lib/components/RequestRow.svelte';
|
||||
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
|
||||
import DiscoverTabs from '#lib/components/DiscoverTabs.svelte';
|
||||
import type { MusicRequest } from '#lib/api/types.js';
|
||||
|
||||
const queryStore = createMyRequestsQuery();
|
||||
const query = $derived($queryStore);
|
||||
const requests = $derived((query.data ?? []) as MusicRequest[]);
|
||||
|
||||
const client = useQueryClient();
|
||||
|
||||
async function onCancel(id: string) {
|
||||
try {
|
||||
await cancelRequest(id);
|
||||
await client.invalidateQueries({ queryKey: qk.myRequests() });
|
||||
} catch {
|
||||
// Swallow for v1; toast surface lands later. The row stays put so the
|
||||
// user can retry — failed cancel doesn't lie about success.
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the meta line short and readable. We always lead with the artist,
|
||||
// then a relative-ish date — locale formatting is good enough for v1
|
||||
// and keeps tests deterministic without pinning Intl.RelativeTimeFormat.
|
||||
function rowMeta(r: MusicRequest): string {
|
||||
const when = new Date(r.requested_at).toLocaleDateString();
|
||||
if (r.kind === 'artist') return `Requested ${when}`;
|
||||
return `by ${r.artist_name} · ${when}`;
|
||||
}
|
||||
|
||||
function listenHref(r: MusicRequest): string | null {
|
||||
if (r.matched_track_id) return `/tracks/${r.matched_track_id}`;
|
||||
if (r.matched_album_id) return `/albums/${r.matched_album_id}`;
|
||||
if (r.matched_artist_id) return `/artists/${r.matched_artist_id}`;
|
||||
return null;
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:head><title>{pageTitle('Requests')}</title></svelte:head>
|
||||
|
||||
<DiscoverTabs />
|
||||
|
||||
<div class="space-y-6 pt-6">
|
||||
<header class="space-y-1">
|
||||
<h2 class="font-display text-2xl font-medium text-text-primary">
|
||||
Your requests
|
||||
</h2>
|
||||
<p class="text-text-secondary">
|
||||
What you've asked Minstrel to add to the library.
|
||||
</p>
|
||||
</header>
|
||||
|
||||
{#if query.isError}
|
||||
<ApiErrorBanner error={query.error} onRetry={query.refetch} />
|
||||
{:else if query.isPending}
|
||||
<p class="text-text-secondary">Reading the ledger…</p>
|
||||
{:else if requests.length === 0}
|
||||
<p class="text-text-secondary">Nothing requested yet.</p>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
|
||||
{#each requests as r (r.id)}
|
||||
{@const href = listenHref(r)}
|
||||
<RequestRow request={r} meta={rowMeta(r)} testid="request-row">
|
||||
{#snippet details()}
|
||||
{#if r.status === 'rejected' && r.notes}
|
||||
<div class="text-sm text-text-secondary" data-testid="rejection-notes">
|
||||
{r.notes}
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
{#snippet actions()}
|
||||
{#if r.status === 'pending'}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Cancel request for ${requestName(r)}`}
|
||||
class="inline-flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover"
|
||||
onclick={() => onCancel(r.id)}
|
||||
>
|
||||
<X size={16} strokeWidth={1} /> Cancel
|
||||
</button>
|
||||
{:else if r.status === 'completed' && href}
|
||||
<a
|
||||
{href}
|
||||
aria-label={`Listen to ${requestName(r)}`}
|
||||
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline"
|
||||
>
|
||||
<Music2 size={16} strokeWidth={1} /> Listen
|
||||
</a>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</RequestRow>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -1,165 +0,0 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import { mockQuery } from '../../test-utils/query';
|
||||
import { apiClientMock } from '../../test-utils/mocks/client';
|
||||
import type { MusicRequest } from '#lib/api/types.js';
|
||||
import { pageUrlModule } from '../../test-utils/mocks/appState';
|
||||
|
||||
// $app/state / $app/navigation must be mocked or rendering the page
|
||||
// pulls in SvelteKit's client runtime (`notifiable_store is not a
|
||||
// function`) at module load. Same pattern as the other route tests.
|
||||
const pageState = vi.hoisted(() => ({
|
||||
pageUrl: new URL('http://localhost/requests')
|
||||
}));
|
||||
vi.mock('$app/state', () => pageUrlModule(pageState));
|
||||
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
|
||||
|
||||
// Capture invalidateQueries on the mocked QueryClient so the cancel test can
|
||||
// assert against the same instance the page consumed. Per-file mock OVERRIDES
|
||||
// the vitest.setup default so assertions see this named spy.
|
||||
const invalidateQueries = vi.fn().mockResolvedValue(undefined);
|
||||
vi.mock('@tanstack/svelte-query', async (orig) => {
|
||||
const actual = (await orig()) as Record<string, unknown>;
|
||||
return { ...actual, useQueryClient: () => ({ invalidateQueries }) };
|
||||
});
|
||||
|
||||
vi.mock('#lib/api/requests.js', () => ({
|
||||
createMyRequestsQuery: vi.fn(),
|
||||
cancelRequest: vi.fn().mockResolvedValue({ id: 'r1' })
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/queries.js', () => ({
|
||||
qk: {
|
||||
myRequests: () => ['myRequests']
|
||||
}
|
||||
}));
|
||||
|
||||
vi.mock('#lib/api/client.js', () => apiClientMock());
|
||||
|
||||
import RequestsPage from './+page.svelte';
|
||||
import { createMyRequestsQuery, cancelRequest } from '#lib/api/requests.js';
|
||||
import { qk } from '#lib/api/queries.js';
|
||||
|
||||
const mockedCreateMyRequestsQuery = createMyRequestsQuery as ReturnType<typeof vi.fn>;
|
||||
const mockedCancelRequest = cancelRequest as ReturnType<typeof vi.fn>;
|
||||
|
||||
function req(over: Partial<MusicRequest> = {}): MusicRequest {
|
||||
return {
|
||||
id: 'r1',
|
||||
user_id: 'u1',
|
||||
status: 'pending',
|
||||
kind: 'album',
|
||||
artist_mbid: 'art-mbid',
|
||||
album_mbid: 'al-mbid',
|
||||
track_mbid: null,
|
||||
artist_name: 'Boards of Canada',
|
||||
album_title: 'Music Has The Right To Children',
|
||||
track_title: null,
|
||||
decided_at: null,
|
||||
decided_by: null,
|
||||
notes: null,
|
||||
completed_at: null,
|
||||
matched_track_id: null,
|
||||
matched_album_id: null,
|
||||
matched_artist_id: null,
|
||||
requested_at: '2026-04-28T12:00:00Z',
|
||||
updated_at: '2026-04-28T12:00:00Z',
|
||||
imported_album_count: 0,
|
||||
imported_track_count: 0,
|
||||
...over
|
||||
};
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Requests page', () => {
|
||||
test('renders one row per request from the API', () => {
|
||||
const rows: MusicRequest[] = [
|
||||
req({ id: 'r1', kind: 'artist', artist_name: 'Boards of Canada' }),
|
||||
req({ id: 'r2', kind: 'album', album_title: 'Geogaddi', status: 'completed' }),
|
||||
req({ id: 'r3', kind: 'track', track_title: 'Roygbiv', status: 'rejected', notes: 'Already in library' })
|
||||
];
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
|
||||
render(RequestsPage);
|
||||
expect(screen.getAllByTestId('request-row')).toHaveLength(3);
|
||||
expect(screen.getByText('Boards of Canada')).toBeInTheDocument();
|
||||
expect(screen.getByText('Geogaddi')).toBeInTheDocument();
|
||||
expect(screen.getByText('Roygbiv')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('pending row exposes Cancel; clicking calls cancelRequest and invalidates myRequests', async () => {
|
||||
const rows: MusicRequest[] = [
|
||||
req({ id: 'r-pending', status: 'pending', kind: 'album', album_title: 'Geogaddi' })
|
||||
];
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
|
||||
render(RequestsPage);
|
||||
const cancelBtn = screen.getByRole('button', { name: /cancel request for geogaddi/i });
|
||||
await fireEvent.click(cancelBtn);
|
||||
await waitFor(() => {
|
||||
expect(mockedCancelRequest).toHaveBeenCalledWith('r-pending');
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.myRequests() });
|
||||
});
|
||||
});
|
||||
|
||||
test('completed row with matched_track_id renders Listen link to /tracks/<id>', () => {
|
||||
const rows: MusicRequest[] = [
|
||||
req({
|
||||
id: 'r-track',
|
||||
status: 'completed',
|
||||
kind: 'track',
|
||||
track_title: 'Roygbiv',
|
||||
matched_track_id: 'tr-9',
|
||||
matched_album_id: 'al-9',
|
||||
matched_artist_id: 'art-9'
|
||||
})
|
||||
];
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
|
||||
render(RequestsPage);
|
||||
const link = screen.getByRole('link', { name: /listen to roygbiv/i });
|
||||
expect(link).toHaveAttribute('href', '/tracks/tr-9');
|
||||
});
|
||||
|
||||
test('completed row with only matched_album_id renders Listen link to /albums/<id>', () => {
|
||||
const rows: MusicRequest[] = [
|
||||
req({
|
||||
id: 'r-album',
|
||||
status: 'completed',
|
||||
kind: 'album',
|
||||
album_title: 'Geogaddi',
|
||||
matched_track_id: null,
|
||||
matched_album_id: 'al-7',
|
||||
matched_artist_id: 'art-7'
|
||||
})
|
||||
];
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
|
||||
render(RequestsPage);
|
||||
const link = screen.getByRole('link', { name: /listen to geogaddi/i });
|
||||
expect(link).toHaveAttribute('href', '/albums/al-7');
|
||||
});
|
||||
|
||||
test('rejected row renders notes and hides Cancel and Listen', () => {
|
||||
const rows: MusicRequest[] = [
|
||||
req({
|
||||
id: 'r-rej',
|
||||
status: 'rejected',
|
||||
kind: 'album',
|
||||
album_title: 'Geogaddi',
|
||||
notes: 'Already kept in the library.'
|
||||
})
|
||||
];
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
|
||||
render(RequestsPage);
|
||||
expect(screen.getByTestId('rejection-notes')).toHaveTextContent('Already kept in the library.');
|
||||
expect(screen.queryByRole('button', { name: /cancel request/i })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('link', { name: /listen to/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('empty list shows the voice-rule "Nothing requested yet." copy', () => {
|
||||
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: [] }));
|
||||
render(RequestsPage);
|
||||
expect(screen.getByText(/nothing requested yet\./i)).toBeInTheDocument();
|
||||
expect(screen.queryAllByTestId('request-row')).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user