// 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 = `
`;
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 = `
`;
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) => ``).join("") ||
``;
}
/**
* 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 = `${escapeHtml(file.name)}${escapeHtml(formatBytes(file.size))}
`;
list.appendChild(item.row);
items.push(item);
drawItem(item);
}
drawNotes();
drawList();
}
function drawNotes() {
const chip = (count, key, tip) => count === 0 ? "" : `${escapeHtml(t(key, formatNumber(count)))}`;
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)) +
`${escapeHtml(text)}`;
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 = `
${bar(bytes > 0 ? sent / bytes : 0)}${escapeHtml(text)}
` +
(failed > 0 ? `${escapeHtml(t("Admin.Upload.Failed", formatNumber(failed)))}` : "");
}
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"));
},
};
}