Commit fad9c417 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Survive navigating away from /upload, add a step checklist, and let uploaders…

Survive navigating away from /upload, add a step checklist, and let uploaders correct identification

Uploading used to live in Upload.tsx's own component state, so leaving
the page mid-upload abandoned the in-flight request with no way to see
it finish. Lifts the queue into a new UploadQueueProvider (same tier as
PlayerContext, above the router) so it keeps running and updating
regardless of navigation.

Each queued file now shows a Claude-Code-style step checklist (upload →
identify → artwork) instead of a bare progress bar. Completed results
show the system's 0-100 confidence score, and an "Edit details" form
lets the uploader correct title/artist/album/genre - doing so flips the
song to review_status "pending" ("community noted") via the new
PATCH /library/{id}, reflected immediately in the card without a
refetch. Also adds the review-queue API client functions AdminPanel's
community-review tab uses to approve or reject those songs.
parent 233bcb1f
...@@ -14,6 +14,16 @@ export interface LibrarySong { ...@@ -14,6 +14,16 @@ export interface LibrarySong {
/** Membership in the caller's own auto-created Liked Songs playlist - not a real column on /** Membership in the caller's own auto-created Liked Songs playlist - not a real column on
* the song, computed server-side on every endpoint that returns the caller's own songs. */ * the song, computed server-side on every endpoint that returns the caller's own songs. */
is_liked: boolean is_liked: boolean
/** 0-100, how confident identification was - null for a song with no identification step of
* its own (manually entered, claimed, or remixed). Optional (not just nullable) because every
* real backend response includes it, but the many existing test fixtures built before this
* field existed don't need updating just to keep constructing a LibrarySong-shaped mock. */
confidence?: number | null
/** "approved" (visible in the shared library to everyone) | "pending" (the owner edited the
* identification away from what the system found - stays in their own library, withheld from
* everyone else until a super admin reviews it) | "rejected" (reviewed and declined). Optional
* for the same reason as confidence above. */
review_status?: 'approved' | 'pending' | 'rejected'
} }
export function getLibrary() { export function getLibrary() {
...@@ -97,6 +107,55 @@ export function deleteLibrarySong(fileId: number) { ...@@ -97,6 +107,55 @@ export function deleteLibrarySong(fileId: number) {
return apiFetch<{ status: string }>(`/library/${fileId}`, { method: 'DELETE' }) return apiFetch<{ status: string }>(`/library/${fileId}`, { method: 'DELETE' })
} }
export interface LibrarySongEdit {
title?: string
artist?: string
album?: string
genre?: string
coverart?: string
}
/** Corrects what identification found - only call this when the uploader is actually changing
* something; accepting the system's result as-is needs no call at all. Any edit flips the song
* to review_status "pending" ("community noted") server-side: it stays fully visible and
* playable in the caller's own library immediately, but drops out of the shared library/Home
* feed for everyone else until a super admin reviews it (see the review-queue endpoints below). */
export function editLibrarySong(fileId: number, edit: LibrarySongEdit) {
return apiFetch<{ status: string; song: LibrarySong }>(`/library/${fileId}`, { method: 'PATCH', json: edit })
}
export interface LibraryReviewItem {
id: number
user_id: number
title: string
artist: string
album: string | null
genre: string | null
coverart: string | null
confidence: number | null
review_status: 'approved' | 'pending' | 'rejected'
added_at: string
}
/** Super-admin-only: songs community-noted away from the system's identification, waiting on a
* decision (see editLibrarySong above). */
export function getLibraryReviewQueue(status: 'pending' | 'approved' | 'rejected' = 'pending') {
const params = new URLSearchParams({ status })
return apiFetch<{ status: string; songs: LibraryReviewItem[] }>(`/library/admin/review-queue?${params}`)
}
export function approveLibraryReview(songId: number) {
return apiFetch<{ status: string; song: LibraryReviewItem }>(`/library/admin/review-queue/${songId}/approve`, {
method: 'POST',
})
}
export function rejectLibraryReview(songId: number) {
return apiFetch<{ status: string; song: LibraryReviewItem }>(`/library/admin/review-queue/${songId}/reject`, {
method: 'POST',
})
}
/** synced_lyrics is [seconds, text][] - real LRC line timing when a synced source was found /** synced_lyrics is [seconds, text][] - real LRC line timing when a synced source was found
* (see the backend's fetch_lyrics), used to drive the highlighted line-by-line lyrics view. * (see the backend's fetch_lyrics), used to drive the highlighted line-by-line lyrics view.
* Null when only plain-text lyrics (or nothing) exists - callers fall back to `lyrics`. */ * Null when only plain-text lyrics (or nothing) exists - callers fall back to `lyrics`. */
......
...@@ -10,6 +10,16 @@ export interface TagMetadata { ...@@ -10,6 +10,16 @@ export interface TagMetadata {
has_lyrics: boolean has_lyrics: boolean
lyrics: string | null lyrics: string | null
cover_art: string | null cover_art: string | null
// 0-100, how confident the identification was (null for a source with no comparable score -
// see music_identification.py). Optional, not just nullable - every real backend response
// includes it, but the pre-existing test fixtures built before this field existed don't need
// updating just to keep constructing a TagMetadata-shaped mock.
confidence?: number | null
// "approved" (shown in the shared library to everyone) | "pending" (the uploader edited the
// identification away from what the system found - private to them until a super admin
// reviews it) | "rejected" (reviewed and declined, stays private). Absent on a dedupe-cache
// hit from before this field existed.
review_status?: 'approved' | 'pending' | 'rejected'
} }
export interface TagResponse { export interface TagResponse {
......
import { createContext, useContext, useState, type ReactNode } from 'react'
import { uploadDirect, type TagMetadata, type TagResponse } from '../api/music'
export type ItemStage = 'queued' | 'uploading' | 'processing' | 'done' | 'error'
export interface UploadItem {
id: string
file: File
stage: ItemStage
uploadPercent: number
result: TagResponse | null
error: string | null
}
function makeId() {
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
}
interface UploadQueueContextValue {
items: UploadItem[]
busy: boolean
addFiles: (fileList: FileList | null) => void
removeItem: (id: string) => void
uploadAll: () => Promise<void>
/** Merges a successful editLibrarySong() response back into the item's already-tagged result -
* used right after the uploader corrects the identified title/artist/album/genre (see
* UploadItemRow's edit form), so the card immediately reflects the new values and the
* "pending review" state without needing a full re-upload. */
patchItemMetadata: (id: string, metadata: Partial<TagMetadata>) => void
}
const UploadQueueContext = createContext<UploadQueueContextValue | null>(null)
/** Lives above BrowserRouter (see main.tsx), same tier as PlayerContext - the upload queue and
* whichever item is mid-identify must survive the user navigating off /upload entirely, not just
* a re-render. Upload.tsx used to own this as local component state, which meant the in-flight
* uploadDirect() request kept running in the background after a route change (fetch/XHR aren't
* cancelled by React unmounting), but every setItems call after that point landed on a component
* that no longer existed - the user had no way to see it finish, and going back to /upload showed
* an empty queue as if nothing had ever started. */
export function UploadQueueProvider({ children }: { children: ReactNode }) {
const [items, setItems] = useState<UploadItem[]>([])
const [busy, setBusy] = useState(false)
function updateItem(id: string, patch: Partial<UploadItem>) {
setItems((prev) => prev.map((it) => (it.id === id ? { ...it, ...patch } : it)))
}
function addFiles(fileList: FileList | null) {
if (!fileList || fileList.length === 0) return
const newItems: UploadItem[] = Array.from(fileList).map((file) => ({
id: makeId(),
file,
stage: 'queued',
uploadPercent: 0,
result: null,
error: null,
}))
setItems((prev) => [...prev, ...newItems])
}
function removeItem(id: string) {
setItems((prev) => prev.filter((it) => it.id !== id))
}
function patchItemMetadata(id: string, metadata: Partial<TagMetadata>) {
setItems((prev) =>
prev.map((it) =>
it.id === id && it.result
? { ...it, result: { ...it.result, metadata: { ...it.result.metadata, ...metadata } } }
: it,
),
)
}
async function uploadAll() {
setBusy(true)
// Sequential, not Promise.all - the server's identify/tag pipeline is already network-
// and CPU-heavy per file (Shazam/AcoustID lookups, lyrics fetch, tagging), so racing
// several through it at once would just contend with itself for no real benefit. Reads
// `items` fresh each iteration (not a closed-over snapshot) since this whole function can
// now outlive the component that called it.
for (const item of items) {
if (item.stage !== 'queued') continue
updateItem(item.id, { stage: 'uploading', uploadPercent: 0, error: null })
try {
const res = await uploadDirect(item.file, (percent) => {
updateItem(item.id, { uploadPercent: percent, stage: percent >= 100 ? 'processing' : 'uploading' })
})
updateItem(item.id, { stage: 'done', result: res })
} catch (err) {
updateItem(item.id, { stage: 'error', error: err instanceof Error ? err.message : null })
}
}
setBusy(false)
}
return (
<UploadQueueContext.Provider value={{ items, busy, addFiles, removeItem, uploadAll, patchItemMetadata }}>
{children}
</UploadQueueContext.Provider>
)
}
export function useUploadQueue(): UploadQueueContextValue {
const ctx = useContext(UploadQueueContext)
if (!ctx) throw new Error('useUploadQueue must be used within an UploadQueueProvider')
return ctx
}
{ {
"title": "Upload &amp; Tag", "title": "Upload & Tag",
"intro": "Upload untagged tracks - each is fingerprinted, tagged with title/artist/album/art/lyrics, and added to your library.", "intro": "Upload untagged tracks - each is fingerprinted, tagged with title/artist/album/art/lyrics, and added to your library.",
"dropzone.label": "Choose audio files, or drag them here", "dropzone.label": "Choose audio files, or drag them here",
"aria.play": "Play", "aria.play": "Play",
"aria.pause": "Pause", "aria.pause": "Pause",
"button.addToPlaylist": "Add to playlist", "button.addToPlaylist": "Add to playlist",
"aria.remove": "Remove {{filename}}", "aria.remove": "Remove {{filename}}",
"progress.uploading": "Uploading", "steps.uploading": "Uploading ({{percent}}%)",
"progress.identifying": "Identifying & tagging…", "steps.uploaded": "Uploaded",
"steps.identifying": "Identifying song",
"steps.artwork": "Finding album art & lyrics",
"error.uploadFailed": "Upload failed", "error.uploadFailed": "Upload failed",
"button.uploading": "Uploading…", "button.uploading": "Uploading…",
"button.upload_one": "Upload {{count}} file", "button.upload_one": "Upload {{count}} file",
"button.upload_other": "Upload {{count}} files" "button.upload_other": "Upload {{count}} files",
"confidence.match": "{{percent}}% match",
"edit.editDetails": "Edit details",
"edit.communityNoted": "Community noted · pending review",
"edit.titleLabel": "Title",
"edit.artistLabel": "Artist",
"edit.albumLabel": "Album",
"edit.genreLabel": "Genre",
"edit.pendingNotice": "Changing these details marks this song as community noted - it stays in your library but won't appear in the shared library for others until reviewed.",
"edit.save": "Save",
"edit.saving": "Saving…",
"edit.cancel": "Cancel",
"error.editFailed": "Couldn't save changes"
} }
...@@ -6,10 +6,24 @@ ...@@ -6,10 +6,24 @@
"aria.pause": "توقف", "aria.pause": "توقف",
"button.addToPlaylist": "افزودن به پلی‌لیست", "button.addToPlaylist": "افزودن به پلی‌لیست",
"aria.remove": "حذف {{filename}}", "aria.remove": "حذف {{filename}}",
"progress.uploading": "در حال بارگذاری", "steps.uploading": "در حال بارگذاری ({{percent}}٪)",
"progress.identifying": "در حال شناسایی و برچسب‌گذاری…", "steps.uploaded": "بارگذاری شد",
"steps.identifying": "در حال شناسایی آهنگ",
"steps.artwork": "در حال یافتن کاور و متن ترانه",
"error.uploadFailed": "بارگذاری ناموفق بود", "error.uploadFailed": "بارگذاری ناموفق بود",
"button.uploading": "در حال بارگذاری…", "button.uploading": "در حال بارگذاری…",
"button.upload_one": "بارگذاری {{count}} فایل", "button.upload_one": "بارگذاری {{count}} فایل",
"button.upload_other": "بارگذاری {{count}} فایل" "button.upload_other": "بارگذاری {{count}} فایل",
"confidence.match": "{{percent}}٪ تطابق",
"edit.editDetails": "ویرایش جزئیات",
"edit.communityNoted": "یادداشت‌شده توسط کاربر · در انتظار بررسی",
"edit.titleLabel": "عنوان",
"edit.artistLabel": "هنرمند",
"edit.albumLabel": "آلبوم",
"edit.genreLabel": "ژانر",
"edit.pendingNotice": "تغییر این جزئیات این آهنگ را «یادداشت‌شده توسط کاربر» علامت می‌زند - در کتابخانه‌ات باقی می‌ماند اما تا بررسی، در کتابخانه مشترک برای دیگران نمایش داده نمی‌شود.",
"edit.save": "ذخیره",
"edit.saving": "در حال ذخیره…",
"edit.cancel": "لغو",
"error.editFailed": "ذخیره تغییرات ممکن نشد"
} }
...@@ -9,6 +9,7 @@ import { AuthProvider } from './context/AuthContext.tsx' ...@@ -9,6 +9,7 @@ import { AuthProvider } from './context/AuthContext.tsx'
import { PlayerProvider } from './context/PlayerContext.tsx' import { PlayerProvider } from './context/PlayerContext.tsx'
import { ThemeProvider } from './context/ThemeContext.tsx' import { ThemeProvider } from './context/ThemeContext.tsx'
import { LanguageProvider } from './context/LanguageContext.tsx' import { LanguageProvider } from './context/LanguageContext.tsx'
import { UploadQueueProvider } from './context/UploadQueueContext.tsx'
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
<StrictMode> <StrictMode>
...@@ -17,7 +18,9 @@ createRoot(document.getElementById('root')!).render( ...@@ -17,7 +18,9 @@ createRoot(document.getElementById('root')!).render(
<BrowserRouter> <BrowserRouter>
<AuthProvider> <AuthProvider>
<PlayerProvider> <PlayerProvider>
<UploadQueueProvider>
<App /> <App />
</UploadQueueProvider>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
</BrowserRouter> </BrowserRouter>
......
...@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' ...@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Upload } from './Upload' import { Upload } from './Upload'
import { AuthProvider } from '../context/AuthContext' import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider } from '../context/PlayerContext'
import { UploadQueueProvider } from '../context/UploadQueueContext'
import * as musicApi from '../api/music' import * as musicApi from '../api/music'
import * as libraryApi from '../api/library' import * as libraryApi from '../api/library'
...@@ -28,7 +29,9 @@ function renderPage() { ...@@ -28,7 +29,9 @@ function renderPage() {
<MemoryRouter> <MemoryRouter>
<AuthProvider> <AuthProvider>
<PlayerProvider> <PlayerProvider>
<UploadQueueProvider>
<Upload /> <Upload />
</UploadQueueProvider>
</PlayerProvider> </PlayerProvider>
</AuthProvider> </AuthProvider>
</MemoryRouter>, </MemoryRouter>,
...@@ -130,6 +133,58 @@ describe('Upload', () => { ...@@ -130,6 +133,58 @@ describe('Upload', () => {
expect(uploadDirect).toHaveBeenCalledTimes(2) expect(uploadDirect).toHaveBeenCalledTimes(2)
}) })
it('shows a confidence badge when the result includes one', async () => {
vi.spyOn(musicApi, 'uploadDirect').mockImplementation(async (_file, onProgress) => {
onProgress?.(100)
return { ...TAG_RESPONSE, metadata: { ...TAG_RESPONSE.metadata, confidence: 87 } }
})
renderPage()
const file = new File([new Uint8Array([1, 2, 3])], 'test.mp3', { type: 'audio/mpeg' })
const input = document.querySelector('input[type="file"]') as HTMLInputElement
await userEvent.upload(input, file)
await userEvent.click(screen.getByRole('button', { name: /Upload/ }))
expect(await screen.findByText('87% match')).toBeInTheDocument()
})
it('edits the identified details, marking the song community noted with the new values', async () => {
await uploadAndWaitForResult()
const editLibrarySong = vi.spyOn(libraryApi, 'editLibrarySong').mockResolvedValue({
status: 'success',
song: { ...TAG_RESPONSE.metadata, id: 42, user_id: 1, coverart: null, lyrics: null, file_path: '', added_at: '2026-01-01T00:00:00Z', is_liked: false, review_status: 'pending' },
})
await userEvent.click(screen.getByRole('button', { name: 'Edit details' }))
const titleInput = screen.getByLabelText('Title')
await userEvent.clear(titleInput)
await userEvent.type(titleInput, 'Corrected Title')
await userEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() =>
expect(editLibrarySong).toHaveBeenCalledWith(42, {
title: 'Corrected Title',
artist: 'Duran Duran',
album: 'Notorious',
genre: 'Pop',
}),
)
expect(await screen.findByText('Corrected Title')).toBeInTheDocument()
expect(screen.getByText('Community noted · pending review')).toBeInTheDocument()
})
it('cancels editing without saving', async () => {
await uploadAndWaitForResult()
const editLibrarySong = vi.spyOn(libraryApi, 'editLibrarySong')
await userEvent.click(screen.getByRole('button', { name: 'Edit details' }))
expect(screen.getByLabelText('Title')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(screen.queryByLabelText('Title')).not.toBeInTheDocument()
expect(editLibrarySong).not.toHaveBeenCalled()
})
it('lets a still-queued file be removed before uploading', async () => { it('lets a still-queued file be removed before uploading', async () => {
vi.spyOn(musicApi, 'uploadDirect') vi.spyOn(musicApi, 'uploadDirect')
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment