Spaces:
Sleeping
Sleeping
File size: 10,105 Bytes
b0798af | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | "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<void>;
confirm: (id?: string) => void;
pause: (id: string) => void;
resume: (id: string) => void;
cancel: (id: string) => Promise<void>;
setOpen: (open: boolean) => void;
sync: (records: UploadRecord[]) => void;
}
const running = new Set<string>(),
controllers = new Map<string, XMLHttpRequest>();
const patch = (id: string, update: Partial<UploadTask>) =>
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<UploadRecord>((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<UploadState>()(
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,
})),
}),
},
),
);
|