Repository Public
1"use client";2import { ApiClientError, api } from "./client";34export type UploadPurpose = "master" | "resource" | "captions" | "transcript" | "archive" | "slides";5export interface UploadProgress { phase: "hash" | "upload" | "finalise"; fraction: number; detail: string }6interface InitResult { upload: { id: string; chunkSize: number; totalChunks: number }; received: number[]; resumed: boolean; duplicate: { sha256: string; filename: string; at: string } | null; warning: string | null }7export interface UploadOutcome<T = unknown> { result: T | null; duplicate: InitResult["duplicate"]; warning: string | null; resumed: boolean }89export const CHUNK_SIZE = 4 * 1024 * 1024;10const hex = (buf: ArrayBuffer) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");11const sha256 = async (data: ArrayBuffer | Uint8Array<ArrayBuffer>) => hex(await crypto.subtle.digest("SHA-256", data));12const sleep = (ms: number, signal: AbortSignal) => new Promise<void>((res, rej) => { const t = setTimeout(res, ms); signal.addEventListener("abort", () => { clearTimeout(t); rej(new DOMException("Annulé", "AbortError")); }, { once: true }); });13const mb = (n: number) => `${(n / 1e6).toFixed(n < 1e7 ? 1 : 0).replace(".", ",")} Mo`;1415/**16 * Sends a file in pieces of 4 MiB. Each piece carries its SHA-256 and is retried on failure; calling again17 * with the same file resumes where the transfer stopped (the server knows which pieces it holds).18 * `onDuplicate` decides what to do when the server already stores the same bytes: return true to stop there.19 */20export async function uploadFile<T = unknown>(file: File, purpose: UploadPurpose, context: Record<string, unknown>, o: { onProgress: (p: UploadProgress) => void; signal: AbortSignal; stopOnDuplicate?: boolean }): Promise<UploadOutcome<T>> {21 if (!crypto?.subtle) throw new Error("Ce navigateur ne peut pas calculer d’empreinte SHA-256 ici (contexte non sécurisé).");22 const total = Math.max(1, Math.ceil(file.size / CHUNK_SIZE)), digests: string[] = [];23 const piece = (n: number) => file.slice(n * CHUNK_SIZE, Math.min(file.size, (n + 1) * CHUNK_SIZE));24 // First pass: the SHA-256 of every piece. Their combination identifies the file (resume, duplicate detection).25 for (let n = 0; n < total; n++) {26 if (o.signal.aborted) throw new DOMException("Annulé", "AbortError");27 digests.push(await sha256(await piece(n).arrayBuffer()));28 o.onProgress({ phase: "hash", fraction: (n + 1) / total, detail: `Calcul de l’empreinte — ${mb(Math.min(file.size, (n + 1) * CHUNK_SIZE))} sur ${mb(file.size)}` });29 }30 const fingerprint = await sha256(new TextEncoder().encode(digests.join("")));31 const init = await api<InitResult>("uploads", { body: { purpose, filename: file.name, size: file.size, fingerprint, context }, signal: o.signal });32 if (init.duplicate && o.stopOnDuplicate) {33 await api(`uploads/${init.upload.id}`, { method: "DELETE" }).catch(() => undefined);34 return { result: null, duplicate: init.duplicate, warning: init.warning, resumed: false };35 }36 const have = new Set(init.received);37 let sent = [...have].reduce((a, n) => a + piece(n).size, 0);38 for (let n = 0; n < total; n++) {39 if (have.has(n)) continue;40 const body = piece(n);41 for (let attempt = 1; ; attempt++) {42 try {43 await api(`uploads/${init.upload.id}/chunks/${n}`, { method: "PUT", raw: body, headers: { "Content-Type": "application/octet-stream", "x-chunk-sha256": digests[n]! }, signal: o.signal });44 break;45 } catch (e) {46 if ((e as Error).name === "AbortError") throw e;47 // Worth another try: the network dropped, the gateway hiccuped, or the piece was damaged on the way.48 const retryable = e instanceof ApiClientError && (e.status === 0 || e.status >= 500 || e.code === "checksum" || e.status === 429);49 if (!retryable || attempt >= 4) throw e;50 o.onProgress({ phase: "upload", fraction: sent / file.size, detail: `Nouvel essai du morceau ${n + 1} sur ${total} (${attempt} sur 3)…` });51 await sleep(e.status === 429 ? 5000 : 800 * 2 ** (attempt - 1), o.signal);52 }53 }54 sent += body.size;55 o.onProgress({ phase: "upload", fraction: sent / file.size, detail: `${mb(sent)} sur ${mb(file.size)}${init.resumed ? " (reprise)" : ""}` });56 }57 o.onProgress({ phase: "finalise", fraction: 1, detail: "Vérification du fichier sur le serveur…" });58 const result = await api<T>(`uploads/${init.upload.id}/complete`, { body: {}, signal: o.signal });59 return { result, duplicate: init.duplicate, warning: init.warning, resumed: init.resumed };60}61