feat(admin): upload photos from the web panel
Owner review 2, R3: the panel can add photos to an existing or a new
sequence without the desktop app. upload.js is a dialog the library pages
open (openUpload({ api, sequence, onDone })): file picker or drag and drop
(folders are counted and left out: whole-folder import stays on the
desktop), per-photo state, a total bar, Cancel that deletes the started
uploads, and a leave-page guard while sending. Each photo is hashed in a
same-origin module worker with an in-house incremental SHA-256 (8 MiB
reads; crypto.subtle cannot hash in pieces), which runs the FIPS 180-4
known answers and a crypto.subtle cross-check before its first hash and
refuses to hash on any mismatch; the server verifies the hash again.
Chunks go through api.putBytes with the session's CSRF header, two files
and two chunks at a time, retrying no answer, 429 and 503; quota, space
and permission refusals stop the run with the server's message, and a
photo deleted from the sequence shows as deleted before.
server/info now lists the photo extensions the archive files, so the
dialog offers and sends only those. The CSP already allows the worker
(worker-src falls back to script-src 'self'); tests pin that, the module
walk follows the worker, and a browser-shaped upload runs end to end
through the cookie session.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c64c60ab8bb41c102182e284177ac04a56bf1058)
This commit is contained in:
1 parent
aa1d4913a3
commit
0e52bf0e1b
12 files changed
+1315
-15
No files matched your search
@@ -9,6 +9,10 @@ public sealed record ApiError(string Code, string Message, string? Details = nul
|
||||
public sealed record ServerLimits(long MaxUploadBytes, int ChunkSizeBytes, int PasswordMinLength = 10);
|
||||
|
||||
/// <summary><c>GET /api/v1/server/info</c>.</summary>
|
||||
/// <param name="Extensions">
|
||||
/// File extensions the archive files as photos (lower case, no dot): the admin panel's upload dialog offers and sends only
|
||||
/// these (owner review 2, R3). Null from servers that do not announce them.
|
||||
/// </param>
|
||||
public sealed record ServerInfo(
|
||||
string Name,
|
||||
string Version,
|
||||
@@ -16,7 +20,8 @@ public sealed record ServerInfo(
|
||||
IReadOnlyList<string> Capabilities,
|
||||
string? TlsFingerprint,
|
||||
IReadOnlyList<string> Formats,
|
||||
ServerLimits Limits);
|
||||
ServerLimits Limits,
|
||||
IReadOnlyList<string>? Extensions = null);
|
||||
|
||||
/// <summary><c>GET /health</c>.</summary>
|
||||
public sealed record HealthStatus(string Status, string Version, IReadOnlyDictionary<string, string> Checks);
|
||||
@@ -404,6 +404,24 @@ dialog.viewer .buttons { grid-column: 1 / -1; }
|
||||
.seq-card[aria-selected="true"], .frame[aria-selected="true"], .seq-row[aria-selected="true"] { outline: 3px solid Highlight; }
|
||||
}
|
||||
|
||||
/* Upload dialog (owner review 2, R3, upload.js): the target, a drop zone, the photos with their state, the total. */
|
||||
dialog.dialog.upload { width: 640px; }
|
||||
.upload-choice { border: 0; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 8px 20px; }
|
||||
.upload-choice legend { color: var(--text-muted); padding: 0; margin-block-end: 8px; }
|
||||
.upload-existing { display: grid; gap: 8px; margin-block-start: 10px; }
|
||||
.upload-new { display: grid; gap: 6px; margin-block-start: 10px; color: var(--text-muted); }
|
||||
.input.list { height: auto; padding: 4px 0; }
|
||||
.input.list option { padding: 3px 10px; }
|
||||
.drop { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; padding: 14px; border: 1px dashed var(--stroke-strong); border-radius: var(--radius-card); color: var(--text-muted); }
|
||||
dialog.upload.dragging .drop { border-color: var(--accent); background: var(--accent-selected); color: var(--text); }
|
||||
.upload-files { list-style: none; margin: 0; padding: 0; max-height: 40vh; overflow-y: auto; display: grid; grid-template-columns: minmax(0, 1fr) max-content minmax(110px, 170px) 28px; column-gap: 12px; align-content: start; }
|
||||
.upload-file { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; min-height: 36px; border-bottom: 1px solid var(--stroke); }
|
||||
.upload-file .status { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: 12px; }
|
||||
.upload-file .status svg.bar { flex: 1 1 0; min-width: 24px; }
|
||||
.upload-file .btn.icon.small { width: 28px; min-width: 28px; }
|
||||
.upload-total { display: flex; align-items: center; gap: 12px; font-size: 12px; }
|
||||
.upload-total .progress-cell { flex: 1 1 0; }
|
||||
|
||||
/* About: the last group of Settings (owner review 2); #/about scrolls to it below the sticky header and focuses its heading. */
|
||||
.about { scroll-margin-block-start: 84px; }
|
||||
.about h2:focus { outline: none; }
|
||||
|
||||
@@ -18,19 +18,18 @@ function csrfToken() {
|
||||
}
|
||||
|
||||
/**
|
||||
* One API call. The body is JSON (any value), raw bytes (a Blob, sent as application/octet-stream) or nothing. A call
|
||||
* aborted through signal rejects with the browser's AbortError, which callers tell apart from an ApiFailure.
|
||||
* One API call: a JSON body, or with raw the bytes of a Blob (upload chunks, sent as octet-stream). An abort through
|
||||
* signal rejects with the browser's AbortError; any other failure to reach the server with ApiFailure status 0.
|
||||
*/
|
||||
async function request(method, url, body, signal) {
|
||||
async function request(method, url, body, { raw = false, signal } = {}) {
|
||||
const headers = { Accept: "application/json", "Accept-Language": culture() };
|
||||
const raw = body instanceof Blob;
|
||||
if (body !== undefined) headers["Content-Type"] = raw ? "application/octet-stream" : "application/json";
|
||||
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, { method, headers, credentials: "same-origin", signal, body: body === undefined ? undefined : raw ? body : JSON.stringify(body) });
|
||||
} catch (err) {
|
||||
if (err?.name === "AbortError") throw err;
|
||||
if (signal?.aborted) throw err;
|
||||
throw new ApiFailure(0, "unreachable", "");
|
||||
}
|
||||
if (res.status === 401 && url !== "/api/v1/auth/login") {
|
||||
@@ -55,8 +54,8 @@ export const api = {
|
||||
put: (url, body) => request("PUT", url, body),
|
||||
patch: (url, body) => request("PATCH", url, body),
|
||||
del: (url) => request("DELETE", url),
|
||||
/** PUT of raw bytes (an upload chunk) with the session's CSRF header, like every other call; abortable through signal. */
|
||||
putBytes: (url, blob, signal) => request("PUT", url, blob, signal),
|
||||
/** PUT of a Blob's bytes (an upload chunk) with the session's headers: the parsed JSON answer; failures as the calls above. */
|
||||
putBytes: (url, blob, signal) => request("PUT", url, blob, { raw: true, signal }),
|
||||
user: () => currentUser,
|
||||
|
||||
/** Restores the session from the cookie; null when signed out. */
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Module worker of the upload dialog (owner review 2, R3): hashes a picked photo off the page's thread, reading it in
|
||||
// 8 MiB blocks so a large RAW never sits in memory whole. Before its first hash it runs the SHA-256 self-test and, if
|
||||
// any check fails, refuses every request (fail closed): the dialog then uploads nothing.
|
||||
//
|
||||
// Messages in: { id, file } a File or Blob to hash; requests are answered one after the other
|
||||
// Messages out: { id, type: "progress", done, total }
|
||||
// { id, type: "done", sha256 } lower-case hex
|
||||
// { id, type: "error", reason: "self_test" | "read", detail }
|
||||
import { Sha256, toHex, selfTest } from "./sha256.js";
|
||||
|
||||
const BLOCK = 8 * 1024 * 1024;
|
||||
let verdict = null;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
self.addEventListener("message", (e) => {
|
||||
const { id, file } = e.data ?? {};
|
||||
queue = queue.then(() => hash(id, file));
|
||||
});
|
||||
|
||||
async function hash(id, file) {
|
||||
try {
|
||||
verdict ??= selfTest().catch(() => "self_test_error");
|
||||
const failed = await verdict;
|
||||
if (failed) {
|
||||
self.postMessage({ id, type: "error", reason: "self_test", detail: failed });
|
||||
return;
|
||||
}
|
||||
const sha = new Sha256();
|
||||
const total = file.size;
|
||||
for (let done = 0; done < total;) {
|
||||
const bytes = new Uint8Array(await file.slice(done, Math.min(done + BLOCK, total)).arrayBuffer());
|
||||
// A file that shrank while it was read must not end with a digest of part of it.
|
||||
if (bytes.length === 0) throw new Error("short read");
|
||||
sha.update(bytes);
|
||||
done += bytes.length;
|
||||
self.postMessage({ id, type: "progress", done, total });
|
||||
}
|
||||
self.postMessage({ id, type: "done", sha256: toHex(sha.digest()) });
|
||||
} catch (err) {
|
||||
self.postMessage({ id, type: "error", reason: "read", detail: String(err?.name ?? err) });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
// Incremental SHA-256 (FIPS 180-4) for the upload dialog (owner review 2, R3): photos are hashed while they are read in
|
||||
// blocks, which crypto.subtle cannot do (it digests one buffer). In-house like everything else; the hash worker checks it
|
||||
// against known answers and crypto.subtle before using it (selfTest), and the server verifies every upload again.
|
||||
|
||||
const K = new Int32Array([
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
||||
]);
|
||||
|
||||
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
||||
|
||||
/** Hashes the whole 64-byte blocks of bytes[pos, end) into state h; returns where the first unprocessed byte is. */
|
||||
function blocks(h, w, bytes, pos, end) {
|
||||
let h0 = h[0], h1 = h[1], h2 = h[2], h3 = h[3], h4 = h[4], h5 = h[5], h6 = h[6], h7 = h[7];
|
||||
while (end - pos >= 64) {
|
||||
for (let i = 0; i < 16; i++, pos += 4) w[i] = (bytes[pos] << 24) | (bytes[pos + 1] << 16) | (bytes[pos + 2] << 8) | bytes[pos + 3];
|
||||
for (let i = 16; i < 64; i++) {
|
||||
const x = w[i - 15];
|
||||
const y = w[i - 2];
|
||||
const s0 = ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3);
|
||||
const s1 = ((y >>> 17) | (y << 15)) ^ ((y >>> 19) | (y << 13)) ^ (y >>> 10);
|
||||
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) | 0;
|
||||
}
|
||||
let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, k = h7;
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
||||
const t1 = (k + s1 + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
|
||||
const s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
||||
const t2 = (s0 + ((a & b) ^ (a & c) ^ (b & c))) | 0;
|
||||
k = g;
|
||||
g = f;
|
||||
f = e;
|
||||
e = (d + t1) | 0;
|
||||
d = c;
|
||||
c = b;
|
||||
b = a;
|
||||
a = (t1 + t2) | 0;
|
||||
}
|
||||
h0 = (h0 + a) | 0;
|
||||
h1 = (h1 + b) | 0;
|
||||
h2 = (h2 + c) | 0;
|
||||
h3 = (h3 + d) | 0;
|
||||
h4 = (h4 + e) | 0;
|
||||
h5 = (h5 + f) | 0;
|
||||
h6 = (h6 + g) | 0;
|
||||
h7 = (h7 + k) | 0;
|
||||
}
|
||||
h[0] = h0; h[1] = h1; h[2] = h2; h[3] = h3; h[4] = h4; h[5] = h5; h[6] = h6; h[7] = h7;
|
||||
return pos;
|
||||
}
|
||||
|
||||
function asBytes(data) {
|
||||
if (data instanceof Uint8Array) return data;
|
||||
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
||||
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
throw new TypeError("SHA-256 hashes bytes");
|
||||
}
|
||||
|
||||
/** SHA-256 fed in pieces of any size: update(bytes) as often as needed, then digest() once. */
|
||||
export class Sha256 {
|
||||
constructor() {
|
||||
this.h = new Int32Array(INITIAL);
|
||||
this.w = new Int32Array(64);
|
||||
this.buffer = new Uint8Array(64);
|
||||
this.buffered = 0;
|
||||
this.length = 0;
|
||||
this.finished = false;
|
||||
}
|
||||
|
||||
/** Adds bytes (Uint8Array, another typed array or an ArrayBuffer) to the message. */
|
||||
update(data) {
|
||||
if (this.finished) throw new Error("SHA-256 already digested");
|
||||
const bytes = asBytes(data);
|
||||
this.length += bytes.length;
|
||||
let pos = 0;
|
||||
if (this.buffered > 0) {
|
||||
const take = Math.min(64 - this.buffered, bytes.length);
|
||||
this.buffer.set(bytes.subarray(0, take), this.buffered);
|
||||
this.buffered += take;
|
||||
pos = take;
|
||||
if (this.buffered < 64) return this;
|
||||
blocks(this.h, this.w, this.buffer, 0, 64);
|
||||
this.buffered = 0;
|
||||
}
|
||||
pos = blocks(this.h, this.w, bytes, pos, bytes.length);
|
||||
if (pos < bytes.length) {
|
||||
this.buffer.set(bytes.subarray(pos), 0);
|
||||
this.buffered = bytes.length - pos;
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The 32-byte digest; the hash takes no more input afterwards. */
|
||||
digest() {
|
||||
if (this.finished) throw new Error("SHA-256 already digested");
|
||||
this.finished = true;
|
||||
const tail = new Uint8Array(this.buffered < 56 ? 64 : 128);
|
||||
tail.set(this.buffer.subarray(0, this.buffered));
|
||||
tail[this.buffered] = 0x80;
|
||||
// The message length in bits as a 64-bit big-endian number, split without losing precision above 2^32.
|
||||
const high = Math.floor(this.length / 0x20000000);
|
||||
const low = (this.length % 0x20000000) * 8;
|
||||
const view = new DataView(tail.buffer);
|
||||
view.setUint32(tail.length - 8, high);
|
||||
view.setUint32(tail.length - 4, low);
|
||||
blocks(this.h, this.w, tail, 0, tail.length);
|
||||
const out = new Uint8Array(32);
|
||||
const result = new DataView(out.buffer);
|
||||
for (let i = 0; i < 8; i++) result.setUint32(i * 4, this.h[i] >>> 0);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Lower-case hexadecimal, as the upload API takes a SHA-256. */
|
||||
export function toHex(bytes) {
|
||||
let hex = "";
|
||||
for (const b of bytes) hex += (b < 16 ? "0" : "") + b.toString(16);
|
||||
return hex;
|
||||
}
|
||||
|
||||
/** The hex SHA-256 of one buffer. */
|
||||
export function sha256Hex(data) {
|
||||
return toHex(new Sha256().update(data).digest());
|
||||
}
|
||||
|
||||
const ascii = (text) => new TextEncoder().encode(text);
|
||||
|
||||
/** FIPS 180-4 examples (and the NIST long-message test): message and expected digest. */
|
||||
const KNOWN_ANSWERS = [
|
||||
["", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"],
|
||||
["abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"],
|
||||
["abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"],
|
||||
[
|
||||
"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
|
||||
"cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1",
|
||||
],
|
||||
];
|
||||
const MILLION_A = "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0";
|
||||
|
||||
/** Feeds bytes in pieces of uneven sizes, so the partial-block buffer is exercised at every offset. */
|
||||
function piecewise(bytes) {
|
||||
const hash = new Sha256();
|
||||
const sizes = [1, 63, 64, 65, 0, 127, 128, 129, 1000, 4096, 55, 56, 57];
|
||||
let pos = 0;
|
||||
for (let i = 0; pos < bytes.length; i++) {
|
||||
const size = Math.min(sizes[i % sizes.length], bytes.length - pos);
|
||||
hash.update(bytes.subarray(pos, pos + size));
|
||||
pos += size;
|
||||
}
|
||||
return toHex(hash.digest());
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the known-answer tests (whole and piece by piece) and, where crypto.subtle exists (secure pages), compares a 1 MiB
|
||||
* random buffer with it. Resolves to null when every check passes, else to the name of the first one that failed: the
|
||||
* caller refuses to hash then (fail closed).
|
||||
*/
|
||||
export async function selfTest() {
|
||||
for (const [message, expected] of KNOWN_ANSWERS) {
|
||||
const bytes = ascii(message);
|
||||
if (sha256Hex(bytes) !== expected || piecewise(bytes) !== expected) return `kat:${message.length}`;
|
||||
}
|
||||
const million = new Uint8Array(1_000_000).fill(0x61);
|
||||
if (sha256Hex(million) !== MILLION_A || piecewise(million) !== MILLION_A) return "kat:million";
|
||||
const subtle = globalThis.crypto?.subtle;
|
||||
if (subtle) {
|
||||
const random = new Uint8Array(1 << 20);
|
||||
// getRandomValues fills at most 64 KiB per call.
|
||||
for (let pos = 0; pos < random.length; pos += 65536) globalThis.crypto.getRandomValues(random.subarray(pos, pos + 65536));
|
||||
let reference;
|
||||
try {
|
||||
reference = toHex(new Uint8Array(await subtle.digest("SHA-256", random)));
|
||||
} catch {
|
||||
reference = null;
|
||||
}
|
||||
if (reference !== null && (sha256Hex(random) !== reference || piecewise(random) !== reference)) return "subtle";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,693 @@
|
||||
// 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, sent in the chunks the server does not have yet and
|
||||
// completed; the server verifies the hash again before it files the photo.
|
||||
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";
|
||||
|
||||
/** 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;
|
||||
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;
|
||||
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) => {
|
||||
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.
|
||||
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);
|
||||
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. */
|
||||
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 || !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, 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>`;
|
||||
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>`;
|
||||
item.row.querySelector('[data-act="remove"]').hidden = !removable(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);
|
||||
}
|
||||
|
||||
/** 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) item.row.querySelector('[data-act="remove"]').hidden = !removable(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();
|
||||
const signal = controller.signal;
|
||||
window.addEventListener("beforeunload", guard);
|
||||
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);
|
||||
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.
|
||||
*/
|
||||
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 start = await retry(() => api.post("/api/v1/uploads", {
|
||||
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt: null, sessionKey: null,
|
||||
}), signal);
|
||||
if (start.alreadyExists) {
|
||||
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back (R6).
|
||||
setState(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));
|
||||
if (failure !== null) throw failure;
|
||||
setState(item, "verifying");
|
||||
await retry(() => api.post(`/api/v1/uploads/${item.uploadId}/complete`), signal);
|
||||
item.uploadId = null;
|
||||
setState(item, "done");
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 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"));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
@@ -28,6 +29,9 @@ public static class SystemEndpoints
|
||||
}
|
||||
})));
|
||||
|
||||
/// <summary>The extensions the archive scanner files as photos (BRIEF §8.1), which the admin panel's uploads keep to.</summary>
|
||||
private static readonly string[] PhotoExtensions = [.. ImageFormatInfo.Known.SelectMany(f => f.Extensions)];
|
||||
|
||||
public static string Version { get; } =
|
||||
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
@@ -42,7 +46,8 @@ public static class SystemEndpoints
|
||||
state.Capabilities,
|
||||
state.TlsFingerprint,
|
||||
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength)), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes, PasswordHasher.MinimumLength),
|
||||
PhotoExtensions), ProtocolJson.Default.ServerInfo)).AllowAnonymousCaller();
|
||||
|
||||
api.MapGet("/i18n/{culture}", (string culture) =>
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user