diff --git a/internal/api/admin_duplicates.go b/internal/api/admin_duplicates.go index b43cea18..758834f5 100644 --- a/internal/api/admin_duplicates.go +++ b/internal/api/admin_duplicates.go @@ -452,21 +452,21 @@ func (h *handlers) handleMergeDuplicateGroup(w http.ResponseWriter, r *http.Requ writeJSON(w, http.StatusOK, resp) } -// refetchDuplicateRequest is an admin's answer for one recording filling +// wrongSlotRequest is an admin's answer for one recording filling // several of an album's slots. keep_track_id is the copy whose title the // recording is; empty means they cannot say, and every copy goes. -type refetchDuplicateRequest struct { +type wrongSlotRequest struct { KeepTrackID string `json:"keep_track_id"` } -// refetchDuplicateResponse reports what went. -type refetchDuplicateResponse struct { +// wrongSlotResponse reports what went. +type wrongSlotResponse struct { KeptTrackID *string `json:"kept_track_id"` RemovedPaths []string `json:"removed_paths"` } -// handleRefetchDuplicateGroup implements POST -// /api/admin/library/duplicates/{id}/refetch: settle a group of one +// handleRemoveWrongSlotFiles implements POST +// /api/admin/library/duplicates/{id}/remove-files: settle a group of one // recording in several slots of an album the way the resolver would, with an // admin's answer. The copies in slots that are not the recording's are // removed and marked missing, so the slot shows as missing until a good copy @@ -479,7 +479,7 @@ type refetchDuplicateResponse struct { // - 404 duplicate_group_not_pending when the group was already resolved // - 400 not_wrong_slot when the group is not one recording in several slots // - 400 survivor_not_in_group, invalid_id, invalid_body -func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Request) { +func (h *handlers) handleRemoveWrongSlotFiles(w http.ResponseWriter, r *http.Request) { admin, ok := requireUser(w, r) if !ok { return @@ -489,7 +489,7 @@ func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Re writeAdminJSONErr(w, http.StatusBadRequest, "invalid_id") return } - var body refetchDuplicateRequest + var body wrongSlotRequest if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, mergeRequestBodyLimit)).Decode(&body); err != nil && !errors.Is(err, io.EOF) { writeAdminJSONErr(w, http.StatusBadRequest, "invalid_body") return @@ -517,13 +517,13 @@ func (h *handlers) handleRefetchDuplicateGroup(w http.ResponseWriter, r *http.Re case errors.Is(err, library.ErrSurvivorNotInGroup): writeAdminJSONErr(w, http.StatusBadRequest, "survivor_not_in_group") default: - h.logger.Error("admin: refetch duplicate group", "group_id", uuidToString(groupID), "err", err) + h.logger.Error("admin: remove wrong-slot files", "group_id", uuidToString(groupID), "err", err) writeAdminJSONErr(w, http.StatusInternalServerError, "server_error") } return } - resp := refetchDuplicateResponse{RemovedPaths: make([]string, 0, len(res.Removed))} + resp := wrongSlotResponse{RemovedPaths: make([]string, 0, len(res.Removed))} if res.Kept != nil { id := uuidToString(res.Kept.TrackID) resp.KeptTrackID = &id diff --git a/internal/api/api.go b/internal/api/api.go index 7fa066df..b7cea155 100644 --- a/internal/api/api.go +++ b/internal/api/api.go @@ -247,7 +247,7 @@ func Mount(r chi.Router, pool *pgxpool.Pool, logger *slog.Logger, events *playev admin.Post("/library/duplicates/sweep", h.handleRunDuplicateSweep) admin.Post("/library/duplicates/{id}/dismiss", h.handleDismissDuplicateGroup) admin.Post("/library/duplicates/{id}/merge", h.handleMergeDuplicateGroup) - admin.Post("/library/duplicates/{id}/refetch", h.handleRefetchDuplicateGroup) + admin.Post("/library/duplicates/{id}/remove-files", h.handleRemoveWrongSlotFiles) admin.Get("/invites", h.handleListInvites) admin.Post("/invites", h.handleCreateInvite) diff --git a/web/src/lib/admin/queues.ts b/web/src/lib/admin/queues.ts index c1163e93..480b2cc5 100644 --- a/web/src/lib/admin/queues.ts +++ b/web/src/lib/admin/queues.ts @@ -10,10 +10,10 @@ export type QueueKey = keyof AdminSummary; export type QueueDef = { key: QueueKey; href: string; - // How the Overview names a count of them: "2 missing files". + // How the Overview names a count of them: "2 tracks need a file". one: string; many: string; - // How the Overview's healthy line names an empty one: "no missing files". + // How the Overview's healthy line names an empty one: "no tracks waiting for a file". none: string; }; @@ -21,7 +21,7 @@ export const QUEUES: QueueDef[] = [ { 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' }, - { key: 'missing', href: '/collection/missing', one: 'missing file', many: 'missing files', none: 'missing files' } + { key: 'missing', href: '/collection/missing', one: 'track needs a file', many: 'tracks need a file', none: 'tracks waiting for a file' } ]; export function countOf(summary: AdminSummary | undefined, key: QueueKey): number { diff --git a/web/src/lib/admin/reports.ts b/web/src/lib/admin/reports.ts index 7332b7ff..81b632bf 100644 --- a/web/src/lib/admin/reports.ts +++ b/web/src/lib/admin/reports.ts @@ -93,7 +93,8 @@ export type HandledRow = { key: string; title: string; artist: string; what: str const ACTION_LABELS: Record = { resolved: 'Reports cleared', - deleted_file: 'File deleted', + removed_file: 'File removed, track waits for a good copy', + deleted_file: 'Removed from the library', deleted_album: 'Album deleted' }; diff --git a/web/src/lib/api/admin.ts b/web/src/lib/api/admin.ts index fe811c09..8a8edbbb 100644 --- a/web/src/lib/api/admin.ts +++ b/web/src/lib/api/admin.ts @@ -9,7 +9,7 @@ import type { AdminDuplicatesResponse, DuplicatesView, MergeDuplicateResult, - RefetchDuplicateResult, + WrongSlotRemoval, ResolvedDuplicatesResponse, AdminPlaybackError, AdminQuarantineRow, @@ -61,6 +61,13 @@ export async function resolveQuarantine(trackID: string): Promise return api.post(`/api/admin/quarantine/${trackID}/resolve`, {}); } +// Removes the reported file and keeps the track, which waits in Needs a file +// for a good copy. Its reports and playback errors are settled with it. +export async function removeQuarantineFile(trackID: string): Promise { + return api.post(`/api/admin/quarantine/${trackID}/remove-file`, {}); +} + +// Removes the track from the library with its file, history and all. export async function deleteQuarantineFile(trackID: string): Promise { return api.post(`/api/admin/quarantine/${trackID}/delete-file`, {}); } @@ -834,14 +841,15 @@ export async function mergeDuplicateGroup( ); } -// One recording in several of an album's slots: keep the copy whose -// title it is, or none (empty keep_track_id), and fetch the album again. -export async function refetchDuplicateGroup( +// One recording in several of an album's slots: keep the copy whose title it +// is, or none (empty keep_track_id). The other copies' files go and their +// tracks wait in Needs a file for a good copy. +export async function removeWrongSlotFiles( id: string, body: { keep_track_id: string } -): Promise { - return api.post( - `/api/admin/library/duplicates/${encodeURIComponent(id)}/refetch`, +): Promise { + return api.post( + `/api/admin/library/duplicates/${encodeURIComponent(id)}/remove-files`, body ); } @@ -850,7 +858,7 @@ export async function dismissDuplicateGroup(id: string): Promise { await api.post(`/api/admin/library/duplicates/${encodeURIComponent(id)}/dismiss`, {}); } -// Missing files ----------------------------------------------------- +// Needs a file ------------------------------------------------------ export async function listMissingFiles( offset: number = 0, @@ -876,6 +884,16 @@ export function createMissingFilesQuery(offset: number = 0, limit: number = 50) }); } +// Forgets tracks waiting for a file, for good: each goes with its likes, plays +// and playlist places. All or nothing; a track whose file is back is refused. +export async function forgetMissingTracks(trackIds: string[]): Promise<{ forgotten: number }> { + return api.post<{ forgotten: number }>('/api/admin/library/missing/forget', { track_ids: trackIds }); +} + +// The whole list as a CSV, to hand to whatever finds music. A plain link +// downloads it: the session cookie goes with it. +export const MISSING_FILES_CSV_URL = '/api/admin/library/missing.csv'; + // Suspect sources -------------------------------------------------- export const SUSPECT_SOURCES_PAGE_SIZE = 50; @@ -910,6 +928,12 @@ export async function setSuspectVerdict(trackId: string, verdict: SuspectVerdict await api.put(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}`, { verdict }); } +// Removes a suspect source's file and keeps its track, which waits in Needs a +// file for a clean copy. +export async function removeSuspectFile(trackId: string): Promise { + await api.post(`/api/admin/library/suspect-sources/${encodeURIComponent(trackId)}/remove`, {}); +} + // Notification emails: when the grouped emails go out. export type NotificationEmailSettings = { summary_hour: number; diff --git a/web/src/lib/api/types.ts b/web/src/lib/api/types.ts index 324f6f6a..161faf91 100644 --- a/web/src/lib/api/types.ts +++ b/web/src/lib/api/types.ts @@ -215,7 +215,7 @@ export type AdminPlaybackError = { // deleted_album is history: an album removed whole, before Minstrel filed its // own music. -export type QuarantineAction = 'resolved' | 'deleted_file' | 'deleted_album'; +export type QuarantineAction = 'resolved' | 'removed_file' | 'deleted_file' | 'deleted_album'; export type QuarantineActionRow = { id: string; @@ -247,13 +247,18 @@ export type HomePayload = { you_might_like_artists: ArtistRef[]; }; -// Missing files ----------------------------------------------------- +// Needs a file ------------------------------------------------------ -// One track whose file the scan could not find. The text fields come from the -// tracks row rather than the filesystem — the recording is still a known thing -// with a history, only its bytes are absent. last_played_at is null for a file -// that was never played, which is the signal that separates "worth chasing" -// from "let it go". +// Which Collection queue a track's file was removed from. A track with none +// went missing from disk on its own. +export type RemovedFor = 'report' | 'duplicate' | 'suspect'; + +// One track waiting for a file. The text fields come from the tracks row +// rather than the filesystem — the recording is still a known thing with a +// history, only its bytes are absent. last_played_at is null for a file that +// was never played, which is the signal that separates "worth chasing" from +// "let it go". removed_by is the admin who removed it, null for the duplicate +// checker or a file gone from disk. export type AdminMissingTrack = { track_id: string; title: string; @@ -263,6 +268,12 @@ export type AdminMissingTrack = { album_title: string; file_path: string; duration_sec: number; + disc_number: number | null; + track_number: number | null; + recording_mbid: string | null; + release_group_mbid: string | null; + removed_for: RemovedFor | null; + removed_by: string | null; missing_since: string; last_played_at: string | null; }; @@ -381,7 +392,7 @@ export type MergeDuplicateResult = { // What settling one recording in several slots did. kept_track_id is // null when every copy went. -export type RefetchDuplicateResult = { +export type WrongSlotRemoval = { kept_track_id: string | null; removed_paths: string[]; }; diff --git a/web/src/lib/components/CollectionRail.svelte b/web/src/lib/components/CollectionRail.svelte index 8cb40464..c023cfc5 100644 --- a/web/src/lib/components/CollectionRail.svelte +++ b/web/src/lib/components/CollectionRail.svelte @@ -5,7 +5,7 @@ // 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. + // accented, as they wait on a person. Needs a file counts tracks. let { summary }: { summary?: AdminSummary } = $props(); @@ -14,7 +14,7 @@ { 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') } + { href: '/collection/missing', label: 'Needs a file', attention: countOf(summary, 'missing') } ]); diff --git a/web/src/routes/admin/admin.test.ts b/web/src/routes/admin/admin.test.ts index b65de352..973c57f8 100644 --- a/web/src/routes/admin/admin.test.ts +++ b/web/src/routes/admin/admin.test.ts @@ -123,7 +123,7 @@ 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 reports, duplicates, suspect sources, missing files/i); + expect(screen.getByTestId('all-clear').textContent).toMatch(/no reports, duplicates, suspect sources, tracks waiting for a file/i); }); test('each queue that waits on you is listed with how long its oldest has waited, and opens its page', () => { @@ -134,7 +134,7 @@ describe('admin Overview page', () => { 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 broken tracks reported oldest 3d ago Open', '1 missing file oldest 10d ago Open']); + expect(rows).toEqual(['2 broken tracks reported oldest 3d ago Open', '1 track needs a 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/); }); diff --git a/web/src/routes/collection/+layout.svelte b/web/src/routes/collection/+layout.svelte index d8947d22..4d15711c 100644 --- a/web/src/routes/collection/+layout.svelte +++ b/web/src/routes/collection/+layout.svelte @@ -18,7 +18,7 @@

Collection

What in the library needs looking at: tracks people reported, songs held twice, files from - doubtful sources, and files that went missing. + doubtful sources, and the tracks waiting for a good file.

{#if summary} {#if waiting.length > 0} diff --git a/web/src/routes/collection/+layout.ts b/web/src/routes/collection/+layout.ts index 067439a6..0a1880c3 100644 --- a/web/src/routes/collection/+layout.ts +++ b/web/src/routes/collection/+layout.ts @@ -2,7 +2,7 @@ import { redirect } from '@sveltejs/kit'; import { user } from '#lib/auth/store.svelte.js'; import type { LayoutLoad } from './$types'; -// Hard route gate: the Wanted view is an admin's. Runs before the +// Hard route gate: the Collection is an admin's. Runs before the // layout renders; auth is bootstrapped by the root +layout.ts, so user.value is // either a settled User object or null. export const load: LayoutLoad = () => { diff --git a/web/src/routes/collection/collection.test.ts b/web/src/routes/collection/collection.test.ts index 01827c14..aacfc504 100644 --- a/web/src/routes/collection/collection.test.ts +++ b/web/src/routes/collection/collection.test.ts @@ -43,9 +43,9 @@ describe('/collection layout', () => { ['/collection/reports', 'Reports'], ['/collection/duplicates', 'Duplicates'], ['/collection/suspect-sources', 'Suspect sources'], - ['/collection/missing', 'Missing files'] + ['/collection/missing', 'Needs a file'] ]); - expect(screen.getByRole('link', { name: /missing files/i })).toHaveAttribute('aria-current', 'page'); + expect(screen.getByRole('link', { name: /needs a file/i })).toHaveAttribute('aria-current', 'page'); expect(screen.getByRole('link', { name: /^overview/i })).not.toHaveAttribute('aria-current'); expect(screen.getByTestId('tab-body')).toBeTruthy(); }); @@ -62,7 +62,7 @@ describe('/collection layout', () => { expect(dup.textContent?.replace(/\s+/g, ' ').trim()).toBe('Duplicates 5'); const health = screen.getByTestId('collection-health'); expect(health.textContent?.replace(/\s+/g, ' ').trim()).toBe( - 'To look at: 2 broken tracks reported, 5 sets of duplicates to review, 9 missing files.' + 'To look at: 2 broken tracks reported, 5 sets of duplicates to review, 9 tracks need a file.' ); expect(Array.from(health.querySelectorAll('a')).map((a) => a.getAttribute('href'))).toEqual([ '/collection/reports', @@ -83,7 +83,7 @@ describe('/collection overview', () => { render(CollectionPage); const rows = screen.getAllByTestId('collection-queue'); expect(rows).toHaveLength(1); - expect(rows[0].textContent).toMatch(/3 missing files/); + expect(rows[0].textContent).toMatch(/3 tracks need a file/); expect(rows[0].querySelector('a')?.getAttribute('href')).toBe('/collection/missing'); expect(screen.getByTestId('collection-clear').textContent?.trim()).toBe('No reports, duplicates, suspect sources.'); }); diff --git a/web/src/routes/collection/duplicates/+page.svelte b/web/src/routes/collection/duplicates/+page.svelte index 39250e4b..2b9cd679 100644 --- a/web/src/routes/collection/duplicates/+page.svelte +++ b/web/src/routes/collection/duplicates/+page.svelte @@ -10,7 +10,7 @@ runDuplicateSweep, dismissDuplicateGroup, mergeDuplicateGroup, - refetchDuplicateGroup + removeWrongSlotFiles } from '#lib/api/admin.js'; import { errMessage } from '#lib/api/errors.js'; import { pushToast } from '#lib/stores/toast.svelte.js'; @@ -45,7 +45,7 @@ // 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. + // tracks wait in Needs a file until a good copy is in the library folder. type Tab = DuplicatesView | 'resolved'; const fromUrl = page.url.searchParams.get('view'); @@ -64,8 +64,8 @@ // Per wrong-slot group: the copy whose title the recording is, absent when // an admin can't tell, and the same two-click confirm. let slotPick = $state>({}); - let confirmingRefetch = $state(null); - let refetching = $state(null); + let confirmingRemoveSlots = $state(null); + let removingSlots = $state(null); const queryStore = $derived(createDuplicatesQuery(groupView)); const query = $derived($queryStore); @@ -155,28 +155,28 @@ // The copies that go: every one when an admin can't tell, else those // under another title. A copy under the picked title is the song held twice, // and the next sweep merges it. - function refetchRemoves(g: AdminDuplicateGroup): AdminDuplicateMember[] { + function slotRemovals(g: AdminDuplicateGroup): AdminDuplicateMember[] { const picked = pickedOf(g); if (!picked) return g.members; return g.members.filter((m) => songKey(m.title) !== songKey(picked.title)); } - async function onRefetch(group: AdminDuplicateGroup) { - if (confirmingRefetch !== group.id) { - confirmingRefetch = group.id; + async function onRemoveSlots(group: AdminDuplicateGroup) { + if (confirmingRemoveSlots !== group.id) { + confirmingRemoveSlots = group.id; return; } - confirmingRefetch = null; - refetching = group.id; + confirmingRemoveSlots = null; + removingSlots = group.id; try { - const result = await refetchDuplicateGroup(group.id, { keep_track_id: slotPick[group.id] ?? '' }); + const result = await removeWrongSlotFiles(group.id, { keep_track_id: slotPick[group.id] ?? '' }); const removed = `Removed ${plural(result.removed_paths.length, 'file', 'files')}`; - pushToast(`${removed}. Their slots show as missing until a good copy is in the library.`); + pushToast(`${removed}. Their tracks wait in Needs a file until a good copy is in the library.`); query.refetch(); } catch (e: unknown) { pushToast(errMessage(e), 'error'); } finally { - refetching = null; + removingSlots = null; } } @@ -278,8 +278,8 @@

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, leaving that slot - missing. What's left here needs you. + are left alone, and a file filling another song's track slot is removed, its track waiting in + Needs a file. What's left here needs you.

@@ -339,12 +339,12 @@ {:else if item.action === 'duplicate_wrong_file' && !item.details.kept_title}

{item.details.artist}: one recording was filed as {removed.map((r) => r.title).join(' and ')}, - and it is none of them. Removed; those slots show as missing. + and it is none of them. Removed; those tracks wait in Needs a file.

{:else if item.action === 'duplicate_wrong_file'}

{item.details.artist}: the recording of {item.details.kept_title} was also filed as - {removed.map((r) => r.title).join(', ')}. Removed from there; those slots show as missing. + {removed.map((r) => r.title).join(', ')}. Removed from there; those tracks wait in Needs a file.

{:else}

@@ -432,7 +432,7 @@ diff --git a/web/src/routes/collection/duplicates/duplicates.test.ts b/web/src/routes/collection/duplicates/duplicates.test.ts index 415684d5..55915b2d 100644 --- a/web/src/routes/collection/duplicates/duplicates.test.ts +++ b/web/src/routes/collection/duplicates/duplicates.test.ts @@ -16,7 +16,7 @@ vi.mock('#lib/api/admin.js', () => ({ survivor_track_id: 'www-01', removed_paths: ['/music/Moe Shop/WWW (2020)/www-02.mp3'] }), - refetchDuplicateGroup: vi.fn().mockResolvedValue({ + removeWrongSlotFiles: 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'] }) @@ -30,7 +30,7 @@ import { createResolvedDuplicatesQuery, dismissDuplicateGroup, mergeDuplicateGroup, - refetchDuplicateGroup, + removeWrongSlotFiles, runDuplicateSweep } from '#lib/api/admin.js'; @@ -292,13 +292,13 @@ describe('admin duplicates', () => { test("can't tell: every copy goes, after a second click", async () => { renderWith(slots()); await fireEvent.click(screen.getByRole('button', { name: 'Remove the copies…' })); - expect(refetchDuplicateGroup).not.toHaveBeenCalled(); + expect(removeWrongSlotFiles).not.toHaveBeenCalled(); const confirm = text(screen.getByTestId('refetch-confirm')); expect(confirm).toContain('All 2 copies will be deleted from disk'); expect(confirm).toContain('until a good copy is in the library folder'); await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files' })); - expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: '' }); + expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: '' }); }); test('naming the song keeps that copy and removes the others', async () => { @@ -310,7 +310,7 @@ describe('admin duplicates', () => { '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' })); - expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' }); + expect(removeWrongSlotFiles).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' }); }); test("I can't tell takes the pick back", async () => { @@ -490,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; those slots show as missing.' + 'Savant: the recording of Void was also filed as Reach. Removed from there; those tracks wait in Needs a file.' ); 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; those slots show as missing.' + 'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those tracks wait in Needs a file.' ); }); }); diff --git a/web/src/routes/collection/missing/+page.svelte b/web/src/routes/collection/missing/+page.svelte index 77186343..3d2406f2 100644 --- a/web/src/routes/collection/missing/+page.svelte +++ b/web/src/routes/collection/missing/+page.svelte @@ -1,17 +1,22 @@ -{pageTitle('Collection · Missing files')} +{pageTitle('Collection · Needs a file')}

-
-

Missing files

+
+

Needs a file

{#if total > 0} {total} +
+ + Export CSV + + +
{/if}

- Tracks whose audio file the last scan couldn't find. They keep their play - history and likes, and stop being offered anywhere until a file is back in the library - folder. + Tracks without a file to play: removed from Reports, Duplicates or Suspect sources, or gone + from disk. Each keeps its play history and likes, and is not offered anywhere until a good + copy is in the library folder, which it then takes over. Export the list to find them.

{#if query.isPending} -

Checking what's missing…

+

Reading the list…

{:else if query.isError}

- Couldn't load the missing files. + Couldn't load the list.

{:else if groups.length === 0} + row here or what takes it away. -->
-

Every track's file is where it should be.

+

Every track has its file.

- A track lands here when a library scan can't find its file — moved outside - Minstrel, deleted, or on a drive that didn't mount. It leaves on its own - when the file comes back. + A track lands here when its file is removed from one of the Collection's queues, or when a + library scan can't find its file. It leaves on its own when a good copy is in the library, + or when you forget it.

{:else} @@ -75,13 +144,29 @@
  • -
    -

    +
    +

    {group.directory}

    - - {plural(group.tracks.length, 'track', 'tracks')} · gone {relativeTime(group.missing_since)} - +
    + + {plural(group.tracks.length, 'track', 'tracks')} · {relativeTime(group.missing_since)} + + {#if group.tracks.length > 1} + + {/if} +
      @@ -108,12 +193,15 @@
      {t.artist_name} · {t.album_title}
      +
      + {why(t)} · {relativeTime(t.missing_since)} +

    - + {formatDuration(t.duration_sec)} +
  • {/each} @@ -129,7 +225,7 @@ {#if hasMore || offset > 0} -
    + {/if} + diff --git a/web/src/routes/collection/missing/missing.test.ts b/web/src/routes/collection/missing/missing.test.ts index 89b00a4f..aa8e9076 100644 --- a/web/src/routes/collection/missing/missing.test.ts +++ b/web/src/routes/collection/missing/missing.test.ts @@ -1,16 +1,23 @@ import { afterEach, describe, expect, test, vi } from 'vitest'; -import { render, screen } from '@testing-library/svelte'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/svelte'; import { mockQuery } from '../../../test-utils/query'; -import type { AdminMissingResponse } from '#lib/api/types.js'; +import type { AdminMissingResponse, AdminMissingTrack } from '#lib/api/types.js'; -vi.mock('#lib/api/admin.js', () => ({ createMissingFilesQuery: vi.fn() })); +vi.mock('#lib/api/admin.js', () => ({ + createMissingFilesQuery: vi.fn(), + forgetMissingTracks: vi.fn().mockResolvedValue({ forgotten: 1 }), + MISSING_FILES_CSV_URL: '/api/admin/library/missing.csv' +})); import MissingPage from './+page.svelte'; -import { createMissingFilesQuery } from '#lib/api/admin.js'; +import { createMissingFilesQuery, forgetMissingTracks } from '#lib/api/admin.js'; const DAY = 24 * 3_600_000; -function track(title: string, opts: { lastPlayed?: string | null } = {}) { +function track( + title: string, + opts: { lastPlayed?: string | null; removedFor?: AdminMissingTrack['removed_for']; removedBy?: string } = {} +): AdminMissingTrack { return { track_id: `t-${title}`, title, @@ -20,6 +27,12 @@ function track(title: string, opts: { lastPlayed?: string | null } = {}) { album_title: 'Minutes to Midnight', file_path: `/music/Linkin Park/Minutes to Midnight/${title}.flac`, duration_sec: 185, + disc_number: 1, + track_number: 1, + recording_mbid: null, + release_group_mbid: null, + removed_for: opts.removedFor ?? null, + removed_by: opts.removedBy ?? null, missing_since: new Date(Date.now() - 3 * DAY).toISOString(), last_played_at: opts.lastPlayed === undefined ? null : opts.lastPlayed }; @@ -35,7 +48,7 @@ const response: AdminMissingResponse = { missing_since: new Date(Date.now() - 3 * DAY).toISOString(), tracks: [ track('Given Up', { lastPlayed: new Date(Date.now() - 2 * DAY).toISOString() }), - track('Bleed It Out') + track('Bleed It Out', { removedFor: 'report', removedBy: 'alice' }) ] }, { @@ -68,10 +81,10 @@ describe('/collection/missing', () => { expect(screen.getByTestId('missing-count-pill').textContent?.trim()).toBe('3'); }); - test('a group states how many tracks and how long gone', () => { + test('a group states how many tracks and how long they have waited', () => { renderWith(response); - expect(screen.getByText(/2 tracks · gone 3d ago/)).toBeTruthy(); - expect(screen.getByText(/1 track · gone 9d ago/)).toBeTruthy(); + expect(screen.getByText(/2 tracks · 3d ago/)).toBeTruthy(); + expect(screen.getByText(/1 track · 9d ago/)).toBeTruthy(); }); // The deciding fact for whether a missing file is worth chasing. @@ -96,35 +109,65 @@ describe('/collection/missing', () => { // An operator who has never seen this page should not have to guess what // would put a row here. - test('the empty state explains what missing means', () => { + test('the empty state says how a track gets here and how it leaves', () => { renderWith({ total: 0, limit: 50, offset: 0, groups: [] }); - expect(screen.getByText(/every track's file is where it should be/i)).toBeTruthy(); - expect(screen.getByText(/can't find its file/i)).toBeTruthy(); + expect(screen.getByText(/every track has its file/i)).toBeTruthy(); + expect(screen.getByText(/removed from one of the collection's queues/i)).toBeTruthy(); + expect(screen.getByText(/when a good copy is in the library/i)).toBeTruthy(); expect(screen.queryByTestId('missing-count-pill')).toBeNull(); }); test('shows a loading line while pending', () => { renderWith(undefined, { isPending: true }); - expect(screen.getByText(/checking what's missing/i)).toBeTruthy(); + expect(screen.getByText(/reading the list/i)).toBeTruthy(); }); test('shows an error line when the query fails', () => { renderWith(undefined, { isError: true }); - expect(screen.getByText(/couldn't load the missing files/i)).toBeTruthy(); + expect(screen.getByText(/couldn't load the list/i)).toBeTruthy(); }); // 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', () => { renderWith(response); - expect(screen.queryByLabelText('Missing files pages')).toBeNull(); + expect(screen.queryByLabelText('Needs a file pages')).toBeNull(); }); test('pager appears when the server reports more than this page holds', () => { renderWith({ ...response, total: 120 }); - expect(screen.getByLabelText('Missing files pages')).toBeTruthy(); + expect(screen.getByLabelText('Needs a file pages')).toBeTruthy(); expect(screen.getByText('1–3 of 120')).toBeTruthy(); expect(screen.getByRole('button', { name: 'Previous' })).toHaveProperty('disabled', true); expect(screen.getByRole('button', { name: 'Next' })).toHaveProperty('disabled', false); }); + + test('each track says why it waits', () => { + renderWith(response); + const why = screen.getAllByTestId('missing-track-why').map((e) => e.textContent ?? ''); + expect(why[0]).toMatch(/file went missing from disk/i); + expect(why[1]).toMatch(/file removed from a report by alice/i); + }); + + test('Forget asks first, then forgets the one track', async () => { + renderWith(response); + await fireEvent.click(screen.getByRole('button', { name: 'Forget Given Up' })); + expect(forgetMissingTracks).not.toHaveBeenCalled(); + await fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /confirm forget/i })); + await waitFor(() => expect(forgetMissingTracks).toHaveBeenCalledWith(['t-Given Up'])); + }); + + test('Forget all takes the whole folder', async () => { + renderWith(response); + await fireEvent.click( + screen.getByRole('button', { name: 'Forget the 2 tracks in /music/Linkin Park/Minutes to Midnight' }) + ); + await fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: /confirm forget/i })); + await waitFor(() => expect(forgetMissingTracks).toHaveBeenCalledWith(['t-Given Up', 't-Bleed It Out'])); + }); + + test('Export CSV links to the whole list', () => { + renderWith(response); + expect(screen.getByRole('link', { name: /export csv/i })).toHaveAttribute('href', '/api/admin/library/missing.csv'); + }); }); diff --git a/web/src/routes/collection/reports/+page.svelte b/web/src/routes/collection/reports/+page.svelte index 31c20752..9f4ee5a3 100644 --- a/web/src/routes/collection/reports/+page.svelte +++ b/web/src/routes/collection/reports/+page.svelte @@ -1,7 +1,7 @@