SPB Git

Repository Public

import.tsx 16.9 KB 231 lines tsx

1"use client";2import { useCallback, useEffect, useRef, useState } from "react";3import { api, ApiClientError, getCsrf } from "@/lib/client-api";4import { fmtBytes, fmtDate } from "@/lib/format";5import { useLocale, useT } from "@/i18n";6import type { Key } from "@/i18n/messages";7import { Confirm, useApi, useErrorText, useToast } from "@/components/ui";8import { IAlert, ICheck, IClose, IRefresh, ISpinner, IUpload } from "@/components/icons";910/**11 * Import. Files are sent in chunks (resumable): a failed chunk is retried, and a file whose upload broke can be12 * resumed from the offset the server holds. Extensions only pre-filter what is queued; the server decides from13 * the content.14 */15const ACCEPT_RE = /\.(flac|mp3|m4a|aac|wav|aiff?|ogg|opus|dsf|dff|zip)$/i;16const ACCEPT = ".flac,.mp3,.m4a,.aac,.wav,.aif,.aiff,.ogg,.opus,.dsf,.dff,.zip,audio/*";1718type Phase = "queued" | "sending" | "sent" | "failed" | "cancelled";19interface Item { key: string; file: File; phase: Phase; sent: number; uploadId?: string; error?: string; xhr?: XMLHttpRequest }20interface Limits { maxFileBytes: number; chunkBytes: number; maxFiles: number; quotaBytes: number }21interface ServerUpload { id: string; filename: string; sizeBytes: number; receivedBytes: number; status: string; errorCode: string | null; errorDetail: string | null; kind: string | null; trackId: string | null; duplicateOf: string | null; parentId: string | null; createdAt: string; trackTitle: string | null }2223function sendChunk(url: string, blob: Blob, onProgress: (n: number) => void, bind: (x: XMLHttpRequest) => void): Promise<{ status: number; body: { receivedBytes?: number; complete?: boolean; error?: { code?: string; message?: string; details?: { receivedBytes?: number } } } }> {24  return new Promise((resolve, reject) => {25    const x = new XMLHttpRequest();26    bind(x);27    x.open("PATCH", url);28    x.setRequestHeader("Content-Type", "application/octet-stream");29    const csrf = getCsrf(); if (csrf) x.setRequestHeader("X-CSRF-Token", csrf);30    x.upload.onprogress = (e) => onProgress(e.loaded);31    x.onload = () => { let body = {}; try { body = JSON.parse(x.responseText); } catch { /* not JSON */ } resolve({ status: x.status, body }); };32    x.onerror = () => reject(new Error("network"));33    x.onabort = () => reject(new Error("aborted"));34    x.send(blob);35  });36}3738async function filesFromDrop(dt: DataTransfer): Promise<File[]> {39  const entries = Array.from(dt.items).map((i) => i.webkitGetAsEntry?.()).filter((e): e is FileSystemEntry => !!e);40  if (entries.length === 0) return Array.from(dt.files);41  const out: File[] = [];42  const walk = async (e: FileSystemEntry): Promise<void> => {43    if (out.length > 5000) return;44    if (e.isFile) out.push(await new Promise<File>((res, rej) => (e as FileSystemFileEntry).file(res, rej)));45    else if (e.isDirectory) {46      const reader = (e as FileSystemDirectoryEntry).createReader();47      for (;;) { const batch = await new Promise<FileSystemEntry[]>((res, rej) => reader.readEntries(res, rej)); if (!batch.length) break; for (const c of batch) await walk(c); }48    }49  };50  for (const e of entries) await walk(e);51  return out;52}5354const STATUS_CHIP: Record<string, string> = { ready: "chip-ok", error: "chip-err", duplicate: "chip-warn", cancelled: "", uploading: "", received: "chip-accent", validating: "chip-accent", extracting: "chip-accent" };5556export function ImportPanel() {57  const t = useT(); const locale = useLocale(); const toast = useToast(); const text = useErrorText();58  const limits = useApi<Limits>("/api/v1/admin/uploads/limits");59  const [items, setItems] = useState<Item[]>([]);60  const itemsRef = useRef(items); itemsRef.current = items;61  const [over, setOver] = useState(false);62  const [filter, setFilter] = useState<"all" | "active" | "error" | "duplicate" | "ready">("all");63  const server = useApi<{ items: ServerUpload[]; total: number; counts: Record<string, number> }>(`/api/v1/admin/uploads?filter=${filter}&limit=200`);64  const [confirmReplace, setConfirmReplace] = useState<ServerUpload | null>(null);65  const running = useRef(0);66  const fileInput = useRef<HTMLInputElement>(null);67  const dirInput = useRef<HTMLInputElement>(null);6869  const patch = useCallback((key: string, p: Partial<Item>) => setItems((xs) => xs.map((x) => (x.key === key ? { ...x, ...p } : x))), []);7071  const run = useCallback(async (key: string) => {72    const lim = limits.data; const it = itemsRef.current.find((x) => x.key === key);73    if (!lim || !it) return;74    running.current++;75    try {76      let id = it.uploadId, offset = 0;77      if (id) { try { const u = await api<ServerUpload>(`/api/v1/admin/uploads/${id}`); if (u.status === "uploading") offset = u.receivedBytes; else id = undefined; } catch { id = undefined; } }78      if (!id) { const r = await api<{ id: string }>("/api/v1/admin/uploads", { body: { filename: it.file.name, size: it.file.size } }); id = r.id; }79      patch(key, { phase: "sending", uploadId: id, sent: offset, error: undefined });80      let failures = 0;81      while (offset < it.file.size) {82        if (itemsRef.current.find((x) => x.key === key)?.phase === "cancelled") return;83        const end = Math.min(offset + lim.chunkBytes, it.file.size);84        try {85          const base = offset;86          const r = await sendChunk(`/api/v1/admin/uploads/${id}?offset=${offset}`, it.file.slice(offset, end), (n) => patch(key, { sent: base + n }), (xhr) => patch(key, { xhr }));87          if (r.status === 200 && typeof r.body.receivedBytes === "number") { offset = r.body.receivedBytes; failures = 0; patch(key, { sent: offset }); continue; }88          const expected = r.body.error?.details?.receivedBytes;89          if (r.status === 409 && typeof expected === "number") { offset = expected; continue; }       // resume where the server is90          if (r.status === 401) { window.location.assign("/login"); return; }91          if (r.status >= 500 || r.status === 400) { if (++failures <= 3) { await new Promise((res) => setTimeout(res, 1000 * failures)); continue; } }92          throw new ApiClientError(r.status, r.body.error?.code ?? `http_${r.status}`, r.body.error?.message ?? "");93        } catch (e) {94          if ((e as Error).message === "aborted") return;95          if ((e as Error).message === "network" && ++failures <= 3) { await new Promise((res) => setTimeout(res, 1500 * failures)); continue; }96          throw e;97        }98      }99      patch(key, { phase: "sent", sent: it.file.size, xhr: undefined });100      server.reload();101    } catch (e) {102      patch(key, { phase: "failed", error: (e as Error).message === "network" ? t("err.network") : text(e), xhr: undefined });103    } finally { running.current--; pump(); }104    // eslint-disable-next-line react-hooks/exhaustive-deps105  }, [limits.data, patch, t, text]);106107  const pump = useCallback(() => {108    for (const it of itemsRef.current) {109      if (running.current >= 2) break;110      if (it.phase === "queued") { it.phase = "sending"; void run(it.key); }111    }112  }, [run]);113  useEffect(() => { pump(); }, [items, pump]);114115  const add = (files: File[]) => {116    const lim = limits.data; if (!lim) return;117    const accepted: Item[] = []; let skipped = 0, tooBig = 0;118    for (const f of files) {119      if (f.name.startsWith(".") || !ACCEPT_RE.test(f.name)) { skipped++; continue; }120      if (f.size > lim.maxFileBytes) { tooBig++; continue; }121      if (f.size === 0) { skipped++; continue; }122      accepted.push({ key: `${f.name}:${f.size}:${f.lastModified}:${Math.random().toString(36).slice(2)}`, file: f, phase: "queued", sent: 0 });123    }124    const room = lim.maxFiles - itemsRef.current.filter((x) => x.phase === "queued" || x.phase === "sending").length;125    if (accepted.length > room) { toast(t("import.tooMany", { n: lim.maxFiles }), "error"); accepted.length = Math.max(0, room); }126    if (tooBig) toast(t("import.tooBig", { n: tooBig, max: fmtBytes(lim.maxFileBytes, locale) }), "error");127    else if (skipped && accepted.length === 0) toast(t("import.noneAccepted"), "error");128    else if (skipped) toast(t("import.skipped", { n: skipped }));129    accepted.sort((a, b) => a.file.name.localeCompare(b.file.name, undefined, { numeric: true }));130    if (accepted.length) setItems((xs) => [...xs, ...accepted]);131  };132133  const cancel = async (it: Item) => {134    it.xhr?.abort(); patch(it.key, { phase: "cancelled", xhr: undefined });135    if (it.uploadId) await api(`/api/v1/admin/uploads/${it.uploadId}`, { method: "DELETE" }).catch(() => {});136    server.reload();137  };138139  // Poll the server-side list while anything is still being sent or analysed.140  const active = items.some((x) => x.phase === "queued" || x.phase === "sending") || (server.data?.items.some((u) => ["received", "validating", "extracting"].includes(u.status)) ?? false) || ((server.data?.counts.received ?? 0) + (server.data?.counts.validating ?? 0) + (server.data?.counts.extracting ?? 0) > 0);141  useEffect(() => { if (!active) return; const iv = setInterval(server.reload, 2000); return () => clearInterval(iv); }, [active, server.reload]);142143  const act = async (path: string, method = "POST") => { try { await api(path, { method, body: method === "POST" ? {} : undefined }); server.reload(); } catch (e) { toast(text(e), "error"); } };144  const local = items.filter((x) => x.phase !== "sent" && x.phase !== "cancelled");145  const counts = server.data?.counts ?? {};146147  return (148    <div className="max-w-4xl">149      <div onDragOver={(e) => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)}150        onDrop={async (e) => { e.preventDefault(); setOver(false); add(await filesFromDrop(e.dataTransfer)); }}151        className={`rounded-3xl border-2 border-dashed p-8 text-center transition-colors ${over ? "border-accent bg-raised" : "border-line bg-surface"}`}>152        <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-raised text-accent"><IUpload size={26} /></div>153        <p className="text-base font-bold">{t("import.dropTitle")}</p>154        <p className="mx-auto mt-1 max-w-lg text-sm leading-relaxed text-muted">{t("import.dropBody")}</p>155        <div className="mt-4 flex flex-wrap justify-center gap-2">156          <button className="btn btn-primary" onClick={() => fileInput.current?.click()} disabled={!limits.data}>{t("import.pickFiles")}</button>157          <button className="btn" onClick={() => dirInput.current?.click()} disabled={!limits.data}>{t("import.pickFolder")}</button>158        </div>159        <input ref={fileInput} type="file" multiple accept={ACCEPT} className="sr-only" tabIndex={-1} aria-hidden onChange={(e) => { add(Array.from(e.target.files ?? [])); e.target.value = ""; }} />160        <input ref={dirInput} type="file" multiple className="sr-only" tabIndex={-1} aria-hidden {...({ webkitdirectory: "", directory: "" } as Record<string, string>)} onChange={(e) => { add(Array.from(e.target.files ?? [])); e.target.value = ""; }} />161        {limits.data && <p className="mt-4 text-xs text-faint">{t("import.limits", { max: fmtBytes(limits.data.maxFileBytes, locale), n: limits.data.maxFiles })}{limits.data.quotaBytes ? ` · ${t("import.quota", { q: fmtBytes(limits.data.quotaBytes, locale) })}` : ""}</p>}162        {limits.error && <p className="mt-3 text-sm text-danger" role="alert">{text(limits.error)}</p>}163      </div>164165      {local.length > 0 && (166        <section className="mt-6" aria-labelledby="h-sending">167          <h2 id="h-sending" className="h-section mb-2">{t("import.sending")}</h2>168          <ul className="card divide-y divide-line">{local.map((it) => {169            const pct = it.file.size ? Math.round((it.sent / it.file.size) * 100) : 0;170            return (171              <li key={it.key} className="flex items-center gap-3 px-4 py-3">172                <div className="min-w-0 flex-1">173                  <p className="truncate text-sm font-medium">{it.file.name}</p>174                  {it.phase === "failed" ? <p className="flex items-center gap-1 text-xs text-danger" role="alert"><IAlert size={12} />{it.error}</p> : (175                    <div className="mt-1.5 flex items-center gap-2">176                      <div className="h-1.5 flex-1 overflow-hidden rounded-full bg-line" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={pct} aria-label={t("import.progressOf", { name: it.file.name })}><div className="h-full bg-accent transition-[width]" style={{ width: `${pct}%` }} /></div>177                      <span className="w-24 text-right text-xs tabular-nums text-muted">{it.phase === "queued" ? t("import.waiting") : `${pct} % · ${fmtBytes(it.file.size, locale)}`}</span>178                    </div>)}179                </div>180                {it.phase === "failed" && <button className="btn btn-sm" onClick={() => patch(it.key, { phase: "queued", error: undefined })}><IRefresh size={14} />{t("common.retry")}</button>}181                <button className="icon-btn text-muted" onClick={() => void cancel(it)} aria-label={t("import.cancelOf", { name: it.file.name })}><IClose size={18} /></button>182              </li>);183          })}</ul>184        </section>185      )}186187      <section className="mt-8" aria-labelledby="h-imports">188        <div className="mb-3 flex flex-wrap items-center justify-between gap-2">189          <h2 id="h-imports" className="h-section">{t("import.history")}</h2>190          <div className="flex flex-wrap items-center gap-2">191            <label htmlFor="imp-filter" className="sr-only">{t("import.filter")}</label>192            <select id="imp-filter" className="input !min-h-9 !w-auto !text-sm" value={filter} onChange={(e) => setFilter(e.target.value as typeof filter)}>193              <option value="all">{t("import.f.all")}</option>194              <option value="active">{t("import.f.active")} ({(counts.received ?? 0) + (counts.validating ?? 0) + (counts.extracting ?? 0) + (counts.uploading ?? 0)})</option>195              <option value="error">{t("import.f.error")} ({counts.error ?? 0})</option>196              <option value="duplicate">{t("import.f.duplicate")} ({counts.duplicate ?? 0})</option>197              <option value="ready">{t("import.f.ready")} ({counts.ready ?? 0})</option>198            </select>199            <button className="btn btn-sm" onClick={() => void act("/api/v1/admin/uploads/clear")}>{t("import.clear")}</button>200          </div>201        </div>202        {server.data && server.data.items.length === 0 ? <p className="card p-6 text-center text-sm text-muted">{t(filter === "all" ? "import.noneYet" : "import.noneFilter")}</p> : (203          <ul className="card divide-y divide-line" aria-live="polite">{server.data?.items.map((u) => (204            <li key={u.id} className={`flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-3 ${u.parentId ? "pl-8" : ""}`}>205              <div className="min-w-0 flex-1">206                <p className="truncate text-sm font-medium">{u.filename}</p>207                <p className="text-xs text-muted">208                  {fmtBytes(u.sizeBytes, locale)} · {fmtDate(u.createdAt, locale)}209                  {u.status === "ready" && u.kind === "zip" ? ` · ${t("import.archiveDone", { n: u.errorDetail ?? "0" })}` : ""}210                  {u.status === "ready" && u.trackTitle ? ` · ${u.trackTitle}` : ""}211                </p>212                {u.status === "error" && <p className="mt-0.5 text-xs text-danger">{t(`import.e.${u.errorCode}` as Key) === `import.e.${u.errorCode}` ? `${t("import.e.generic")} (${u.errorCode})` : t(`import.e.${u.errorCode}` as Key)}</p>}213                {u.status === "duplicate" && <p className="mt-0.5 text-xs text-warn">{t(u.errorCode === "same_file" ? "import.dupSameFile" : "import.dupSameTrack", { title: u.trackTitle ?? "—" })}</p>}214              </div>215              <span className={`chip ${STATUS_CHIP[u.status] ?? ""}`}>216                {["received", "validating", "extracting"].includes(u.status) ? <ISpinner size={12} /> : u.status === "ready" ? <ICheck size={12} /> : null}217                {t(`import.s.${u.status}` as Key)}218              </span>219              {u.status === "error" && <button className="btn btn-sm" onClick={() => void act(`/api/v1/admin/uploads/${u.id}/retry`)}>{t("import.retryAnalysis")}</button>}220              {u.status === "duplicate" && <><button className="btn btn-sm" onClick={() => setConfirmReplace(u)}>{t("import.replace")}</button><button className="btn btn-sm" onClick={() => void act(`/api/v1/admin/uploads/${u.id}`, "DELETE")}>{t("import.ignore")}</button></>}221              {(u.status === "uploading" || u.status === "error") && <button className="icon-btn !h-8 !w-8 text-muted" onClick={() => void act(`/api/v1/admin/uploads/${u.id}`, "DELETE")} aria-label={t("import.cancelOf", { name: u.filename })}><IClose size={16} /></button>}222            </li>))}</ul>223        )}224      </section>225      <Confirm open={!!confirmReplace} onClose={() => setConfirmReplace(null)} danger title={t("import.replaceTitle")} confirmLabel={t("import.replace")}226        body={t(confirmReplace?.errorCode === "same_file" ? "import.replaceBodySame" : "import.replaceBody", { title: confirmReplace?.trackTitle ?? "—" })}227        onConfirm={async () => { const u = confirmReplace!; setConfirmReplace(null); await act(`/api/v1/admin/uploads/${u.id}/replace`); }} />228    </div>229  );230}231
Files main
Menu

Theme