Files
Chronos/src/Chronos.Server/Admin/web/upload.js
T
Alby96 81cf58227d fix(admin): complete web uploads, hold Esc during a run, keep focus and restores across job refreshes
The upload dialog's completion helper called `api`, which only exists inside
openUpload, so every web upload failed with a ReferenceError at its last step.
complete() now takes the dialog's api. A new test lexes every admin module and
fails when a top-level function uses api without taking it; it flags the old
upload.js.

During a run Esc is now stopped on the document in the capture phase. The old
listener sat on the dialog, so with the focus on the body (Start disables
itself, a click on the dialog's text) a second Esc closed the dialog and threw
the uploads away. The listener is added when a run starts and removed when it
ends or the dialog closes.

A sequence page refreshes after any ended job, because jobState names no
sequence. That refresh now redraws the header only when the sequence changed,
and the renders only when their list did. Stars, tags and renders are redrawn
through redraw(), so the keyboard focus stays put. restoreFocus finds an
unnamed control by its place, not as the first unnamed one. Failed thumbnails
are retried with a doubling wait and at most 8 tries, counted again once the
sequence changes.

The trash page reads the emptying it follows from /api/v1/jobs/{id} on every
load and after the event socket reconnects (api.events now emits
"reconnected"), so Empty no longer stays disabled when the job's end was lost.
A Restore in flight stays disabled across redraws.

The Library list counts cancelled jobs as ended (shared JOB_ENDED). Comments
are corrected in shared.js and library.js.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 641b9cd96b95d523990d1414c2bdead4138c5f4d)
2026-10-27 13:53:41 +01:00

796 lines
34 KiB
JavaScript

// Upload dialog of the admin panel (owner review 2, R3; BRIEF §14.4, §14.8): photos from this computer into an existing
// or a new sequence, chosen with the file picker or dropped on the dialog. Folders are not taken: importing a whole folder
// stays a feature of the desktop app. Each photo is hashed in a module worker (hash-worker.js, which self-tests its
// SHA-256 first and refuses to hash when a check fails), started with its capture time (capture-time.js), sent in the
// chunks the server does not have yet and completed; the server verifies the hash again before it files the photo. A
// photo deleted from the sequence before is not filed again unless the user asks for it on its row (Upload again).
import { ApiFailure } from "./api.js";
import { t, plural, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
import { icons } from "./icons.js";
import { captureTime } from "./capture-time.js";
/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
const FILES_AT_ONCE = 2;
const CHUNKS_AT_ONCE = 2;
/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
const RETRIES = 3;
/** Checks of an upload another completion is filing, after 1, 2, 4 and then every 8 seconds: about a minute in all. */
const SETTLE_CHECKS = 10;
const SEARCH_DELAY = 250;
const LIST_LIMIT = 50;
/** States of a photo already on the server: a later run leaves it alone. */
const FINISHED = new Set(["done", "exists", "deleted"]);
/** States of a photo a run is sending. */
const ACTIVE = new Set(["hashing", "starting", "uploading", "verifying"]);
/** A failure of the hash worker: kind self_test (its SHA-256 failed a check), worker (it did not run), read or stopped. */
class HashError extends Error {
constructor(kind, detail = "") {
super(`${kind} ${detail}`.trim());
this.kind = kind;
}
}
let dialogs = 0;
/**
* Opens the upload dialog. With sequence ({ id, title } or a SequenceDto) the photos go into it; without, the dialog
* lets the user pick an existing sequence or name a new one. onDone() runs after every run that changed the library
* (photos uploaded or a sequence created), so the page can refresh. Resolves when the dialog closes.
*/
export function openUpload({ api, sequence, onDone } = {}) {
return new Promise((resolve) => {
const id = `upload-${++dialogs}`;
let target = sequence?.id ? { id: sequence.id, title: sequence.displayTitle ?? sequence.title ?? "" } : null;
let extensions = null;
let maxBytes = 0;
let running = false;
let controller = null;
let broken = null;
let hasher = null;
let searchTimer = null;
let searchToken = 0;
let frame = 0;
// Per run: by SHA-256, the send of the last photo of that content, which the next copy waits for.
let sameContent = new Map();
const items = [];
const skipped = { folders: 0, formats: 0, size: 0 };
const titles = new Map();
const dialog = document.createElement("dialog");
dialog.className = "dialog upload";
dialog.setAttribute("aria-labelledby", `${id}-title`);
dialog.innerHTML = `
<form novalidate>
<h2 id="${id}-title" data-i18n="Admin.Upload.Title"></h2>
<div class="upload-target" id="${id}-target"></div>
<div class="drop">
<button class="btn" type="button" data-act="add" data-i18n="Admin.Upload.Add" data-i18n-title="Admin.Upload.Add.Tip"></button>
<span data-i18n="Admin.Upload.Drop"></span>
<input type="file" multiple hidden tabindex="-1">
</div>
<div class="chips upload-notes" hidden></div>
<ul class="upload-files" aria-label="${attr(t("Admin.Upload.Photos"))}" hidden></ul>
<div class="upload-total" hidden></div>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" data-act="close" data-i18n="Admin.Upload.Close" data-i18n-title="Admin.Upload.Close.Tip"></button>
<button class="btn primary" type="submit" data-act="start" data-i18n="Admin.Upload.Start" data-i18n-title="Admin.Upload.Start.Tip"></button>
</div>
</form>`;
document.body.appendChild(dialog);
applyStrings(dialog);
const form = dialog.querySelector("form");
const targetHost = dialog.querySelector(`#${id}-target`);
const input = dialog.querySelector('input[type="file"]');
const addButton = dialog.querySelector('[data-act="add"]');
const closeButton = dialog.querySelector('[data-act="close"]');
const startButton = dialog.querySelector('[data-act="start"]');
const notes = dialog.querySelector(".upload-notes");
const list = dialog.querySelector(".upload-files");
const total = dialog.querySelector(".upload-total");
const errorLine = dialog.querySelector(".error");
drawTarget();
drawButtons();
addButton.addEventListener("click", () => input.click());
input.addEventListener("change", () => {
take([...input.files], 0);
input.value = "";
});
form.addEventListener("submit", (e) => {
e.preventDefault();
run();
});
closeButton.addEventListener("click", () => {
if (running) cancel();
else dialog.close();
});
list.addEventListener("click", (e) => {
// Upload again: a photo deleted from the sequence before goes back into it with the next run, on the user's word.
const again = e.target.closest('[data-act="again"]');
if (again && !running) {
const item = items.find((i) => i.key === again.closest("[data-key]").dataset.key);
if (item?.state !== "deleted") return;
item.restore = true;
setState(item, "waiting");
drawButtons();
startButton.focus();
return;
}
const button = e.target.closest('[data-act="remove"]');
if (!button || running) return;
const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
if (index < 0) return;
const [item] = items.splice(index, 1);
const next = item.row.nextElementSibling ?? item.row.previousElementSibling;
item.row.remove();
(next?.querySelector('[data-act="remove"]:not([hidden])') ?? addButton).focus();
drawList();
});
// Drops: photos are taken, folders only counted (BRIEF §14.8: no folder upload on the web).
const hasFiles = (e) => [...(e.dataTransfer?.types ?? [])].includes("Files");
dialog.addEventListener("dragover", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = running || extensions === null ? "none" : "copy";
dialog.classList.add("dragging");
});
dialog.addEventListener("dragleave", (e) => {
if (!dialog.contains(e.relatedTarget)) dialog.classList.remove("dragging");
});
dialog.addEventListener("drop", (e) => {
if (!hasFiles(e)) return;
e.preventDefault();
dialog.classList.remove("dragging");
if (running || extensions === null) return;
const { files, folders } = dropped(e.dataTransfer);
take(files, folders);
});
// Esc closes only while nothing is being sent; Cancel stops a run. Chromium lets a dialog's cancel be prevented only
// once per user activation, so during a run Esc is stopped at its keydown, on the document in the capture phase: a
// click on the dialog's text moves the focus to the body, and Esc from there would pass the dialog by. The cancel
// handler stays for close requests that do not come from the keyboard (a back gesture).
const stopEscape = (e) => {
if (e.key === "Escape") e.preventDefault();
};
dialog.addEventListener("cancel", (e) => {
if (running) e.preventDefault();
});
// Leaving the page while photos are sent asks first (returnValue for browsers before preventDefault counted).
const guard = (e) => {
e.preventDefault();
e.returnValue = true;
};
const signedOut = () => {
controller?.abort();
dialog.close();
};
window.addEventListener("chronos:signed-out", signedOut);
dialog.addEventListener("close", () => {
controller?.abort();
hasher?.stop();
clearTimeout(searchTimer);
cancelAnimationFrame(frame);
window.removeEventListener("beforeunload", guard);
document.removeEventListener("keydown", stopEscape, true);
window.removeEventListener("chronos:signed-out", signedOut);
dialog.remove();
resolve();
});
dialog.showModal();
targetHost.querySelector('input[type="search"]')?.focus();
const firstFocus = document.activeElement;
// The photo extensions and the size limit the server announces: only those are offered and sent.
api.get("/api/v1/server/info").then((info) => {
extensions = new Set((info?.extensions ?? []).map((e) => String(e).toLowerCase()));
maxBytes = info?.limits?.maxUploadBytes ?? 0;
input.accept = [...extensions].map((e) => `.${e}`).join(",");
drawButtons();
// Into a given sequence the first step is adding photos, once the button can be used.
if (target && document.activeElement === firstFocus) addButton.focus();
}).catch((err) => showError(errorText(err)));
/** The target: fixed (given, or chosen when the first run started), else the choice of an existing or a new sequence. */
function drawTarget() {
if (target) {
targetHost.innerHTML = `<div class="field-label"><span data-i18n="Admin.Upload.Target"></span>
<strong class="ellipsis" dir="auto" title="${attr(target.title)}">${escapeHtml(target.title)}</strong></div>`;
applyStrings(targetHost);
return;
}
targetHost.innerHTML = `
<fieldset class="upload-choice"><legend data-i18n="Admin.Upload.Target"></legend>
<label class="check"><input type="radio" name="mode" value="existing" checked data-i18n-title="Admin.Upload.Existing.Tip"><span data-i18n="Admin.Upload.Existing"></span></label>
<label class="check"><input type="radio" name="mode" value="new" data-i18n-title="Admin.Upload.New.Tip"><span data-i18n="Admin.Upload.New"></span></label>
</fieldset>
<div class="upload-existing">
<input class="input" type="search" name="q" autocomplete="off" dir="auto" aria-label="${attr(t("Admin.Upload.Search"))}"
data-i18n-placeholder="Admin.Upload.Search" data-i18n-title="Admin.Upload.Search.Tip">
<select class="input list" name="sequence" size="5" aria-label="${attr(t("Admin.Upload.Sequences"))}" data-i18n-title="Admin.Upload.Sequences.Tip"></select>
</div>
<label class="upload-new" hidden><span data-i18n="Admin.Upload.NewTitle"></span>
<input class="input" name="title" maxlength="200" autocomplete="off" dir="auto" data-i18n-title="Admin.Upload.NewTitle.Tip"></label>`;
applyStrings(targetHost);
const existing = targetHost.querySelector(".upload-existing");
const fresh = targetHost.querySelector(".upload-new");
targetHost.querySelectorAll('input[name="mode"]').forEach((radio) => radio.addEventListener("change", () => {
const isNew = form.elements.mode.value === "new";
existing.hidden = isNew;
fresh.hidden = !isNew;
showError("");
}));
const search = targetHost.querySelector('input[name="q"]');
search.addEventListener("input", () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => loadSequences(search.value.trim()), SEARCH_DELAY);
});
// Enter in the search box picks nothing and sends nothing.
search.addEventListener("keydown", (e) => {
if (e.key === "Enter") e.preventDefault();
});
targetHost.querySelector("select").addEventListener("change", () => showError(""));
loadSequences("");
}
async function loadSequences(q) {
const token = ++searchToken;
const query = new URLSearchParams({ limit: String(LIST_LIMIT) });
if (q) query.set("q", q);
let page;
try {
page = await api.get(`/api/v1/sequences?${query}`);
} catch (err) {
if (token === searchToken) showError(errorText(err));
return;
}
const select = targetHost.querySelector("select");
if (token !== searchToken || !select) return;
const chosen = select.value;
for (const s of page.items) titles.set(s.id, s.displayTitle);
select.innerHTML = page.items.map((s) => `<option value="${attr(s.id)}" dir="auto" ${s.id === chosen ? "selected" : ""}>` +
`${escapeHtml(s.displayTitle)} · ${escapeHtml(plural("Admin.Upload.PhotoCount", s.frameCount))}</option>`).join("") ||
`<option disabled>${escapeHtml(t("Admin.Upload.NoMatch"))}</option>`;
}
/**
* Adds picked or dropped files: photos once each; folders, other files and files above the limit are counted. Hidden
* dot files (the AppleDouble "._" companions a Mac leaves on cards among them) are left out like the archive scanner
* leaves them out, and the server refuses them too.
*/
function take(files, folders) {
skipped.folders += folders;
for (const file of files) {
const dot = file.name.lastIndexOf(".");
const extension = dot < 0 ? "" : file.name.slice(dot + 1).toLowerCase();
if (file.size === 0 || file.name.startsWith(".") || !extensions?.has(extension)) {
skipped.formats++;
continue;
}
if (maxBytes > 0 && file.size > maxBytes) {
skipped.size++;
continue;
}
const key = `${file.name}\u0000${file.size}\u0000${file.lastModified}`;
if (items.some((i) => i.key === key)) continue;
const item = { key, file, state: "waiting", hashed: 0, sent: 0, uploadId: null, restore: false, message: "", row: null };
item.row = document.createElement("li");
item.row.className = "upload-file";
item.row.dataset.key = key;
item.row.innerHTML = `<span class="name ellipsis" dir="auto" title="${attr(file.name)}">${escapeHtml(file.name)}</span>
<span class="size num muted">${escapeHtml(formatBytes(file.size))}</span><span class="status"></span>
<button class="btn icon small subtle" type="button" data-act="remove" title="${attr(t("Admin.Upload.Remove.Tip"))}"
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>
<button class="btn icon small subtle" type="button" data-act="again" hidden title="${attr(t("Admin.Upload.Again.Tip"))}"
aria-label="${attr(t("Admin.Upload.Again", file.name))}">${icons.upload}</button>`;
list.appendChild(item.row);
items.push(item);
drawItem(item);
}
drawNotes();
drawList();
}
function drawNotes() {
const chip = (count, key, tip) => count === 0 ? "" : `<span class="chip warn" title="${attr(tip)}">${escapeHtml(t(key, formatNumber(count)))}</span>`;
notes.innerHTML = chip(skipped.folders, "Admin.Upload.Skipped.Folders", t("Admin.Upload.Skipped.Folders.Tip")) +
chip(skipped.formats, "Admin.Upload.Skipped.Formats", t("Admin.Upload.Skipped.Formats.Tip")) +
chip(skipped.size, "Admin.Upload.Skipped.Size", t("Admin.Upload.Skipped.Size.Tip", formatBytes(maxBytes)));
notes.hidden = notes.innerHTML === "";
}
function drawList() {
list.hidden = items.length === 0;
drawTotal();
drawButtons();
}
/** One photo's row: its state, a bar while it is hashed or sent, and the reason of a failure as the tooltip. */
function drawItem(item) {
const status = item.row.querySelector(".status");
const percent = (fraction) => new Intl.NumberFormat(culture(), { style: "percent", maximumFractionDigits: 0 }).format(fraction);
let text;
let tip = "";
let tone = "queued";
let fraction = null;
switch (item.state) {
case "hashing":
text = t("Admin.Upload.State.Hashing", percent(item.hashed));
fraction = item.hashed;
tone = "running";
break;
case "starting":
text = t("Admin.Upload.State.Starting");
tone = "running";
break;
case "uploading":
fraction = item.file.size > 0 ? item.sent / item.file.size : 1;
text = t("Admin.Upload.State.Uploading", percent(fraction));
tone = "running";
break;
case "verifying":
text = t("Admin.Upload.State.Verifying");
tone = "running";
break;
case "done":
text = t("Admin.Upload.State.Done");
tip = t("Admin.Upload.State.Done.Tip");
tone = "done";
break;
case "exists":
text = t("Admin.Upload.State.Exists");
tip = t("Admin.Upload.State.Exists.Tip");
tone = "done";
break;
case "deleted":
text = t("Admin.Upload.State.Deleted");
tip = t("Admin.Upload.State.Deleted.Tip");
tone = "paused";
break;
case "failed":
text = t("Admin.Upload.State.Failed");
tip = item.message;
tone = "failed";
break;
case "cancelled":
text = t("Admin.Upload.State.Cancelled");
tone = "cancelled";
break;
case "notSent":
text = t("Admin.Upload.State.NotSent");
tip = t("Admin.Upload.State.NotSent.Tip");
tone = "cancelled";
break;
default:
text = t("Admin.Upload.State.Waiting");
}
status.innerHTML = (fraction === null ? "" : bar(fraction)) +
`<span class="state ${tone} ellipsis"${tip ? ` title="${attr(tip)}"` : ""}>${escapeHtml(text)}</span>`;
drawRowButtons(item);
}
/** A photo comes off the list only between runs, and only while it is not on the server. */
function removable(item) {
return !running && !FINISHED.has(item.state) && !ACTIVE.has(item.state);
}
/** Remove, or for a photo deleted from the sequence before, Upload again; both only between runs. */
function drawRowButtons(item) {
item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
item.row.querySelector('[data-act="again"]').hidden = running || item.state !== "deleted";
}
/** Progress redraws at most once a frame: the worker reports every 8 MiB, chunks finish four at a time. */
function update(item) {
item.dirty = true;
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
for (const i of items) {
if (!i.dirty) continue;
i.dirty = false;
drawItem(i);
}
drawTotal();
});
}
function setState(item, state, message = "") {
item.state = state;
item.message = message;
drawItem(item);
drawTotal();
}
function drawTotal() {
total.hidden = items.length === 0;
if (items.length === 0) return;
let bytes = 0;
let done = 0;
let sent = 0;
let failed = 0;
for (const item of items) {
bytes += item.file.size;
if (FINISHED.has(item.state)) {
done++;
sent += item.file.size;
} else if (item.state === "uploading" || item.state === "verifying") {
sent += item.sent;
} else if (item.state === "failed") {
failed++;
}
}
const text = `${t("Admin.Upload.Count", formatNumber(done), formatNumber(items.length))} · ${t("Admin.Upload.Bytes", formatBytes(sent), formatBytes(bytes))}`;
total.innerHTML = `<div class="progress-cell">${bar(bytes > 0 ? sent / bytes : 0)}<span class="num" title="${attr(text)}">${escapeHtml(text)}</span></div>` +
(failed > 0 ? `<span class="state failed nowrap">${escapeHtml(t("Admin.Upload.Failed", formatNumber(failed)))}</span>` : "");
}
function drawButtons() {
const pending = items.some((i) => !FINISHED.has(i.state));
startButton.disabled = running || !pending || broken !== null || extensions === null;
addButton.disabled = running || extensions === null;
closeButton.textContent = t(running ? "Admin.Upload.Cancel" : "Admin.Upload.Close");
closeButton.title = t(running ? "Admin.Upload.Cancel.Tip" : "Admin.Upload.Close.Tip");
for (const item of items) drawRowButtons(item);
targetHost.querySelectorAll("input, select").forEach((field) => {
field.disabled = running;
});
}
function showError(text) {
errorLine.textContent = text;
}
/** Sends every photo not on the server yet, two at a time; a quota, space or permission refusal stops the rest. */
async function run() {
if (running) return;
const todo = items.filter((i) => !FINISHED.has(i.state));
if (todo.length === 0 || extensions === null) return;
if (broken) return showError(broken);
showError("");
running = true;
controller = new AbortController();
sameContent = new Map();
const signal = controller.signal;
window.addEventListener("beforeunload", guard);
document.addEventListener("keydown", stopEscape, true);
drawButtons();
let changed = false;
try {
const into = await resolveTarget();
if (!into) return;
changed = into.created;
if (signal.aborted) return;
todo.forEach((i) => setState(i, "waiting"));
let next = 0;
let stop = null;
const lane = async () => {
while (stop === null && !signal.aborted && next < todo.length) {
const item = todo[next++];
try {
changed = (await send(item, into.id, signal)) || changed;
} catch (err) {
// A completion cut short may still have filed the photo: the page refreshes to find out.
if (item.state === "verifying") changed = true;
if (signal.aborted) {
setState(item, "cancelled");
continue;
}
setState(item, "failed", messageOf(err));
if (stops(err)) stop = err;
}
}
};
await Promise.all(Array.from({ length: FILES_AT_ONCE }, lane));
if (signal.aborted) {
await discard(todo);
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "cancelled"));
} else if (stop !== null) {
if (stop instanceof HashError) broken = messageOf(stop);
showError(messageOf(stop));
todo.filter((i) => i.state === "waiting").forEach((i) => setState(i, "notSent"));
}
} finally {
running = false;
controller = null;
window.removeEventListener("beforeunload", guard);
document.removeEventListener("keydown", stopEscape, true);
todo.filter((i) => ACTIVE.has(i.state)).forEach((i) => setState(i, "cancelled"));
drawButtons();
drawTotal();
if (changed) onDone?.();
}
}
/** Stops the run: requests are aborted, the hash worker stopped and the server's unfinished uploads discarded. */
function cancel() {
controller?.abort();
hasher?.stop();
hasher = null;
}
/** DELETE of the uploads a cancelled run started and did not complete, so the server frees their space now. */
async function discard(todo) {
await Promise.all(todo.filter((i) => i.uploadId !== null && !FINISHED.has(i.state)).map(async (item) => {
try {
await api.del(`/api/v1/uploads/${item.uploadId}`);
} catch {
// Committed meanwhile, or already gone: nothing left to free.
}
item.uploadId = null;
}));
}
/**
* The sequence the run fills: the fixed one, the one picked, or a new one created now; from then on it is the
* dialog's fixed target, also when the run was cancelled meanwhile. Null (with the reason shown) when there is none.
*/
async function resolveTarget() {
if (target) return { id: target.id, created: false };
const mode = form.elements.mode.value;
if (mode === "existing") {
const select = targetHost.querySelector("select");
if (!select.value) {
showError(t("Admin.Upload.PickFirst"));
select.focus();
return null;
}
target = { id: select.value, title: titles.get(select.value) ?? "" };
drawTarget();
return { id: target.id, created: false };
}
const title = form.elements.title.value.trim();
try {
// Not retried: a lost answer must not create the sequence twice.
const created = await api.post("/api/v1/sequences", { title: title || null, cameraHint: null });
target = { id: created.id, title: created.displayTitle };
} catch (err) {
showError(errorText(err));
return null;
}
drawTarget();
return { id: target.id, created: true };
}
/**
* One photo: hashed, started (the server may already have it, or have had it before it was deleted), the missing
* chunks sent two at a time, completed. True when the library changed. The same photo picked under another name
* waits for the first copy, which settles it for both: two lanes would otherwise complete the one upload the server
* gives them and refuse each other.
*/
async function send(item, sequenceId, signal) {
const file = item.file;
item.hashed = 0;
setState(item, "hashing");
hasher ??= createHasher();
const sha256 = await hasher.hash(file, (done, size) => {
item.hashed = size > 0 ? done / size : 1;
update(item);
});
if (signal.aborted) throw signal.reason;
setState(item, "starting");
const earlier = sameContent.get(sha256);
let settle;
sameContent.set(sha256, new Promise((resolve) => {
settle = resolve;
}));
try {
await earlier;
if (signal.aborted) throw signal.reason;
return await sendHashed(item, sha256, sequenceId, signal);
} finally {
settle();
}
}
/** A hashed photo: started (asking to bring it back when the user chose Upload again), its chunks sent, completed. */
async function sendHashed(item, sha256, sequenceId, signal) {
const file = item.file;
const restore = item.restore;
const capturedAt = await captureTime(file);
const start = await retry(() => api.post("/api/v1/uploads", {
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt, sessionKey: null, restore,
}), signal);
if (start.alreadyExists) {
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back while the trash
// holds it, or Upload again on its row (R6).
finish(item, start.frameId ? "exists" : "deleted");
return false;
}
item.uploadId = start.uploadId;
const chunk = start.chunkSize;
const count = Math.ceil(file.size / chunk);
const received = new Set(start.received ?? []);
const length = (index) => Math.min(chunk, file.size - index * chunk);
item.sent = [...received].reduce((sum, index) => sum + length(index), 0);
const missing = [];
for (let index = 0; index < count; index++) if (!received.has(index)) missing.push(index);
setState(item, "uploading");
let cursor = 0;
let failure = null;
const lane = async () => {
while (failure === null && cursor < missing.length) {
const index = missing[cursor++];
const blob = file.slice(index * chunk, index * chunk + length(index));
try {
await retry(() => api.putBytes(`/api/v1/uploads/${item.uploadId}/chunks/${index}`, blob, signal), signal);
} catch (err) {
failure ??= err;
return;
}
item.sent += blob.size;
update(item);
}
};
await Promise.all(Array.from({ length: Math.min(CHUNKS_AT_ONCE, missing.length) }, lane));
// A chunk refused because the upload is no longer receiving: another completion of it is filing it (or it ended),
// which the completion below waits for and reports.
if (failure !== null && !filing(failure)) throw failure;
setState(item, "verifying");
try {
await complete(api, item.uploadId, restore, signal);
} catch (err) {
if (!(err instanceof ApiFailure && err.status === 409 && err.code === "photo_removed")) throw err;
// Deleted from the sequence while it was on its way: not filed, and the server dropped the upload (R6).
item.uploadId = null;
finish(item, "deleted");
return false;
}
item.uploadId = null;
finish(item, "done");
return true;
}
/** A photo is settled on the server: a later run leaves it alone, until Upload again asks to bring it back. */
function finish(item, state) {
item.restore = false;
setState(item, state);
}
});
}
/** 409 upload_state: the upload is not receiving now, because a completion is filing it or it ended. */
function filing(err) {
return err instanceof ApiFailure && err.status === 409 && err.code === "upload_state";
}
/**
* Completes an upload through api, the dialog's (with restore, a photo deleted from the sequence meanwhile is filed
* anyway). A completion refused while another one is filing the upload (the same photo started twice, a retry after a
* lost answer) waits for it: once the upload is committed, completing again answers its frame. Only an upload that
* failed or was cancelled, or one that stays busy for about a minute, fails the photo.
*/
async function complete(api, uploadId, restore, signal) {
const url = `/api/v1/uploads/${uploadId}/complete${restore ? "?restore=true" : ""}`;
for (let check = 0; ; check++) {
try {
return await retry(() => api.post(url), signal);
} catch (err) {
if (signal.aborted || !filing(err) || check >= SETTLE_CHECKS) throw err;
await sleep(1000 * Math.min(2 ** check, 8), signal);
const upload = await retry(() => api.get(`/api/v1/uploads/${uploadId}`), signal);
if (upload?.state === "failed" || upload?.state === "cancelled") throw err;
}
}
}
/** What dropped: the files, and how many folders were left out (the entries API tells them apart where it exists). */
function dropped(transfer) {
const files = [];
let folders = 0;
const entries = [...(transfer.items ?? [])].filter((i) => i.kind === "file");
if (entries.length > 0) {
for (const item of entries) {
if (item.webkitGetAsEntry?.()?.isDirectory) {
folders++;
continue;
}
const file = item.getAsFile();
if (file) files.push(file);
}
} else {
files.push(...(transfer.files ?? []));
}
return { files, folders };
}
/** Refusals that would refuse the next photos as well: quota, space, permission, a target gone, a broken hash. */
function stops(err) {
if (err instanceof HashError) return err.kind === "self_test" || err.kind === "worker";
if (!(err instanceof ApiFailure)) return false;
return err.status === 401 || err.status === 403 || err.status === 507 || (err.status === 404 && err.details === "sequence");
}
function messageOf(err) {
if (err instanceof HashError) {
if (err.kind === "self_test") return t("Admin.Upload.SelfTestFailed");
if (err.kind === "read") return t("Admin.Upload.ReadFailed");
return t("Admin.Upload.HashFailed");
}
return errorText(err);
}
/** Calls again after 1, 2 and 4 seconds when the server was not reached, was busy (429) or unavailable (503). */
async function retry(call, signal) {
for (let attempt = 0; ; attempt++) {
try {
return await call();
} catch (err) {
const passing = err instanceof ApiFailure && (err.status === 0 || err.status === 429 || err.status === 503);
if (signal.aborted || !passing || attempt >= RETRIES) throw err;
await sleep(1000 * 2 ** attempt, signal);
}
}
}
function sleep(ms, signal) {
return new Promise((resolve, reject) => {
const timer = setTimeout(resolve, ms);
signal.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
}
/**
* The hash worker behind a promise per file. A worker that fails to load or run rejects every request (worker); its
* refusal after a failed self-test is self_test. stop() ends the worker and rejects what it still had (stopped).
*/
function createHasher() {
let worker = null;
let failure = null;
let next = 0;
const pending = new Map();
const fail = (error) => {
for (const request of pending.values()) request.reject(error);
pending.clear();
};
const start = () => {
try {
worker = new Worker(new URL("./hash-worker.js", import.meta.url), { type: "module" });
} catch (err) {
failure = new HashError("worker", String(err?.name ?? err));
return;
}
worker.addEventListener("message", (e) => {
const message = e.data ?? {};
const request = pending.get(message.id);
if (!request) return;
if (message.type === "progress") {
request.progress(message.done, message.total);
return;
}
pending.delete(message.id);
if (message.type === "done" && /^[0-9a-f]{64}$/.test(message.sha256 ?? "")) request.resolve(message.sha256);
else request.reject(new HashError(message.reason === "self_test" ? "self_test" : message.reason === "read" ? "read" : "worker", message.detail));
});
worker.addEventListener("error", (e) => {
e.preventDefault();
failure = new HashError("worker", e.message ?? "");
fail(failure);
});
};
return {
hash(file, progress) {
if (!worker && !failure) start();
if (failure) return Promise.reject(failure);
return new Promise((resolve, reject) => {
const id = ++next;
pending.set(id, { resolve, reject, progress });
worker.postMessage({ id, file });
});
},
stop() {
worker?.terminate();
worker = null;
fail(new HashError("stopped"));
},
};
}