"use client"; import { create } from "zustand"; import { persist } from "zustand/middleware"; import { api, API_BASE_URL, apiRequest, currentUser, token, UploadRecord, } from "../api/apiClient"; export interface UploadTask { id: string; owner: string; name: string; size: number; folder: string; fingerprint: string; file?: File; session?: string; status: | "waiting" | "queued" | "uploading" | "paused" | "processing" | "ready" | "failed" | "cancelled"; offset: number; speed: number; elapsed: number; error?: string; duplicate?: boolean; backup_status?: string; track_id?: string; } interface UploadState { tasks: UploadTask[]; open: boolean; add: (files: File[]) => Promise; confirm: (id?: string) => void; pause: (id: string) => void; resume: (id: string) => void; cancel: (id: string) => Promise; setOpen: (open: boolean) => void; sync: (records: UploadRecord[]) => void; } const running = new Set(), controllers = new Map(); const patch = (id: string, update: Partial) => useUploadStore.setState((s) => ({ tasks: s.tasks.map((t) => (t.id === id ? { ...t, ...update } : t)), })); async function fingerprint(file: File) { const pieces = await new Blob([ file.slice(0, 65536), file.slice(Math.max(0, file.size - 65536)), ]).arrayBuffer(); const hash = await crypto.subtle.digest("SHA-256", pieces); return `${file.name}:${file.size}:${Array.from(new Uint8Array(hash)) .map((n) => n.toString(16).padStart(2, "0")) .join("")}`; } function sendChunk( task: UploadTask, offset: number, progress: (sent: number) => void, ) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); controllers.set(task.id, xhr); xhr.open( "PUT", `${API_BASE_URL}/uploads/${task.session}/chunk?offset=${offset}`, ); xhr.timeout = 120000; xhr.setRequestHeader("Content-Type", "application/octet-stream"); xhr.setRequestHeader("Authorization", "Bearer " + token()); xhr.upload.onprogress = (e) => progress(e.loaded); xhr.onload = () => { controllers.delete(task.id); let data; try { data = JSON.parse(xhr.responseText); } catch { data = {}; } if (xhr.status >= 200 && xhr.status < 300) resolve(data); else reject( Object.assign(new Error(data.message || "Upload interrupted"), { status: xhr.status, }), ); }; xhr.onerror = () => reject( new Error("Connection interrupted. Your received chunks are safe."), ); xhr.ontimeout = xhr.onerror; xhr.onabort = () => reject(new Error("Paused")); xhr.send(task.file!.slice(offset, offset + 1024 * 1024)); }); } async function runTask(id: string) { let task = useUploadStore.getState().tasks.find((t) => t.id === id)!; const started = performance.now(); let initial = task.offset; try { patch(id, { status: "uploading", error: undefined }); let session = task.session ? await api.upload(task.session) : await api.createUpload({ filename: task.name, size: task.size, folder: task.folder, confirmed: true, }); patch(id, { session: session.id, offset: session.offset }); initial = session.offset; task = { ...task, session: session.id }; if (["processing", "ready"].includes(session.status)) { patch(id, { status: session.status as "processing" | "ready", track_id: session.track_id, duplicate: session.duplicate, }); return; } if (session.status === "cancelled") throw new Error( "This upload was cancelled. Add the file again to start a new import.", ); while (session.offset < task.size) { if ( useUploadStore.getState().tasks.find((t) => t.id === id)?.status !== "uploading" ) return; let attempts = 0; while (true) { try { session = await sendChunk(task, session.offset, (sent) => { const seconds = Math.max(0.1, (performance.now() - started) / 1000); patch(id, { offset: session.offset + sent, speed: (session.offset + sent - initial) / seconds, elapsed: seconds, }); }); break; } catch (error: unknown) { if ( useUploadStore.getState().tasks.find((t) => t.id === id)?.status !== "uploading" ) return; if (++attempts >= 3) throw error; await new Promise((r) => setTimeout(r, 1000 * 2 ** attempts)); await apiRequest("/auth/me"); session = await api.upload(task.session!); } } patch(id, { offset: session.offset }); } if ( useUploadStore.getState().tasks.find((t) => t.id === id)?.status !== "uploading" ) return; session = await api.completeUpload(session.id); patch(id, { status: "processing", offset: task.size, speed: 0 }); } catch (error: unknown) { if ( useUploadStore.getState().tasks.find((t) => t.id === id)?.status === "uploading" ) patch(id, { status: "failed", speed: 0, error: error instanceof Error ? error.message : "Upload failed", }); } finally { running.delete(id); controllers.delete(id); pump(); } } function pump() { const owner = currentUser()?.id; if (!owner) return; for (const task of useUploadStore.getState().tasks) { if (running.size >= 2) break; if ( task.status === "queued" && task.file && task.owner === owner && !running.has(task.id) ) { running.add(task.id); void runTask(task.id); } } } export const useUploadStore = create()( persist( (set, get) => ({ tasks: [], open: false, setOpen: (open) => set({ open }), add: async (files) => { const owner = currentUser()?.id; if (!owner) throw new Error("Sign in to import your music"); if (files.length > 500) throw new Error("Choose up to 500 files at a time"); for (const file of files) { if (!file.size) continue; const fp = await fingerprint(file), existing = get().tasks.find( (t) => t.owner === owner && t.fingerprint === fp && !["ready", "cancelled"].includes(t.status), ); if (existing) { patch(existing.id, { file, status: existing.status === "waiting" ? "waiting" : "paused", error: undefined, }); continue; } const valid = /\.(mp3|m4a|flac|wav|ogg|opus|aac)$/i.test(file.name); const folder = (file.webkitRelativePath || "") .split("/") .slice(0, -1) .join("/"); const task: UploadTask = { id: crypto.randomUUID(), owner, name: file.name, size: file.size, file, folder, fingerprint: fp, status: valid ? file.size < 10_000_000 ? "queued" : "waiting" : "failed", offset: 0, speed: 0, elapsed: 0, error: valid ? undefined : "Unsupported file — skipped", }; set((s) => ({ tasks: [...s.tasks, task], open: true })); } pump(); }, confirm: (id) => { const owner = currentUser()?.id; set((s) => ({ tasks: s.tasks.map((t) => t.owner === owner && t.status === "waiting" && (!id || t.id === id) ? { ...t, status: "queued" } : t, ), })); pump(); }, pause: (id) => { patch(id, { status: "paused", speed: 0 }); controllers.get(id)?.abort(); }, resume: (id) => { const t = get().tasks.find((t) => t.id === id); if (!t?.file) { patch(id, { error: "Select the same file again to resume after a browser restart.", }); return; } patch(id, { status: "queued", error: undefined }); pump(); }, cancel: async (id) => { const task = get().tasks.find((t) => t.id === id); if (!task) return; patch(id, { status: "paused" }); controllers.get(id)?.abort(); try { if (task.session) await api.cancelUpload(task.session); patch(id, { status: "cancelled", file: undefined }); } catch (error) { patch(id, { status: "processing", error: error instanceof Error ? error.message : "Please try again", }); } }, sync: (records) => set((s) => ({ tasks: s.tasks.map((t) => { const record = records.find((r) => r.id === t.session); return record && ["processing", "ready", "failed"].includes(record.status) ? { ...t, status: record.status as UploadTask["status"], duplicate: record.duplicate, backup_status: record.backup_status, track_id: record.track_id, error: record.error, file: record.status === "ready" ? undefined : t.file, } : t; }), })), }), { name: "stillwave-imports-v1", partialize: (s) => ({ tasks: s.tasks .filter((t) => !["ready", "cancelled"].includes(t.status)) .map((t) => ({ ...t, file: undefined, status: ["uploading", "queued"].includes(t.status) ? "paused" : t.status, speed: 0, })), }), }, ), );