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:
Alby96 committed 2026-10-27 10:52:40 +01:00
1 parent aa1d4913a3
commit 0e52bf0e1b
12 files changed
+1315 -15

No files matched your search

+1 -1
View File
@@ -88,7 +88,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty), API errors, the WebSocket `EventHub` |
| `Server/Security` | Accounts, password hashing, tokens, session cookies, login guard, access rules, audit log |
| `Server/Storage`, `Server/Jobs` | Archive and processing modules, uploads (`UploadMaintenance`: recovery at start, and the sweep that is the `uploads` clean-up step), render store; `JobEngineHost`, `SchedulerHost` (the `Scheduler` on the engine, started after it; archive.json read every 10 minutes whatever the scan schedule does; every schedule change and run published as a `scheduleChanged` event) and `ServerScheduleHost` (time zone, archive refreshed from archive.json, system schedules), render node service, monitor and availability |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection and grid keyboard; the web upload `upload.js` is imported on demand) |
| `Server/Hosting`, `Server/Admin/web` | `ServerHost`, `ServerLogging` (console and file levels the logging filters read at every line, the file sink's limits, the engine's level; applied again when Settings › Logs is saved), certificates, discovery beacon, embedded static files, Windows service (start and stop failures in the Application event log); the admin panel (ES modules, one per page; `schedules.js` is the Jobs page's Scheduled tab; the Library's views in `pages/library/`: `sequence.js` a sequence and its photo viewer, `trash.js` the archive's trash, `shared.js` cards, selection and grid keyboard; `upload.js` the upload dialog the Library opens on demand, hashing in the module worker `hash-worker.js` with the in-house incremental SHA-256 of `sha256.js`, self-tested before its first use) |
### 2.5 Hosts
+55
View File
@@ -778,6 +778,61 @@
<data name="Admin.Trash.Sequence" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Trash.Size" xml:space="preserve"><value>Size</value></data>
<data name="Admin.Trash.Title" xml:space="preserve"><value>Trash</value></data>
<data name="Admin.Upload.Add" xml:space="preserve"><value>Add photos</value></data>
<data name="Admin.Upload.Add.Tip" xml:space="preserve"><value>Choose photos on this computer; you can also drop them on this dialog</value></data>
<data name="Admin.Upload.Bytes" xml:space="preserve"><value>{0} of {1}</value></data>
<data name="Admin.Upload.Cancel" xml:space="preserve"><value>Cancel</value></data>
<data name="Admin.Upload.Cancel.Tip" xml:space="preserve"><value>Stop now: the photos not finished yet are discarded on the server</value></data>
<data name="Admin.Upload.Close" xml:space="preserve"><value>Close</value></data>
<data name="Admin.Upload.Close.Tip" xml:space="preserve"><value>Close the upload dialog</value></data>
<data name="Admin.Upload.Count" xml:space="preserve"><value>Photos: {0} of {1}</value></data>
<data name="Admin.Upload.Drop" xml:space="preserve"><value>Drop photos here</value></data>
<data name="Admin.Upload.Existing" xml:space="preserve"><value>Existing sequence</value></data>
<data name="Admin.Upload.Existing.Tip" xml:space="preserve"><value>Add the photos to a sequence already on the server</value></data>
<data name="Admin.Upload.Failed" xml:space="preserve"><value>Failed: {0}</value></data>
<data name="Admin.Upload.HashFailed" xml:space="preserve"><value>Photos cannot be hashed in this browser, so nothing was uploaded.</value><comment>long</comment></data>
<data name="Admin.Upload.New" xml:space="preserve"><value>New sequence</value></data>
<data name="Admin.Upload.New.Tip" xml:space="preserve"><value>Create a sequence on the server for these photos</value></data>
<data name="Admin.Upload.NewTitle" xml:space="preserve"><value>Title</value></data>
<data name="Admin.Upload.NewTitle.Tip" xml:space="preserve"><value>Name of the new sequence; left empty, it is named after the date and camera of its photos</value></data>
<data name="Admin.Upload.NoMatch" xml:space="preserve"><value>No sequence found</value></data>
<data name="Admin.Upload.PhotoCount.one" xml:space="preserve"><value>{0} photo</value></data>
<data name="Admin.Upload.PhotoCount.other" xml:space="preserve"><value>{0} photos</value></data>
<data name="Admin.Upload.Photos" xml:space="preserve"><value>Photos</value></data>
<data name="Admin.Upload.PickFirst" xml:space="preserve"><value>Choose a sequence first.</value></data>
<data name="Admin.Upload.ReadFailed" xml:space="preserve"><value>The file could not be read.</value></data>
<data name="Admin.Upload.Remove" xml:space="preserve"><value>Remove {0}</value></data>
<data name="Admin.Upload.Remove.Tip" xml:space="preserve"><value>Take this photo off the list</value></data>
<data name="Admin.Upload.Search" xml:space="preserve"><value>Search sequences</value></data>
<data name="Admin.Upload.Search.Tip" xml:space="preserve"><value>Find a sequence by title, camera or tag</value></data>
<data name="Admin.Upload.SelfTestFailed" xml:space="preserve"><value>This browser computed a test SHA-256 wrongly, so nothing is uploaded from it.</value><comment>long</comment></data>
<data name="Admin.Upload.Sequences" xml:space="preserve"><value>Sequences</value></data>
<data name="Admin.Upload.Sequences.Tip" xml:space="preserve"><value>The sequence the photos go into</value></data>
<data name="Admin.Upload.Skipped.Folders" xml:space="preserve"><value>Folders skipped: {0}</value></data>
<data name="Admin.Upload.Skipped.Folders.Tip" xml:space="preserve"><value>Folders are imported with the desktop app; here only photos are uploaded</value></data>
<data name="Admin.Upload.Skipped.Formats" xml:space="preserve"><value>Not photos: {0}</value></data>
<data name="Admin.Upload.Skipped.Formats.Tip" xml:space="preserve"><value>Files in a format the server does not read as photos were left out</value></data>
<data name="Admin.Upload.Skipped.Size" xml:space="preserve"><value>Too large: {0}</value></data>
<data name="Admin.Upload.Skipped.Size.Tip" xml:space="preserve"><value>Files larger than the server's upload limit ({0}) were left out</value></data>
<data name="Admin.Upload.Start" xml:space="preserve"><value>Upload</value></data>
<data name="Admin.Upload.Start.Tip" xml:space="preserve"><value>Send the photos not on the server yet; the server checks each one against its SHA-256</value></data>
<data name="Admin.Upload.State.Cancelled" xml:space="preserve"><value>Cancelled</value></data>
<data name="Admin.Upload.State.Deleted" xml:space="preserve"><value>Deleted before</value></data>
<data name="Admin.Upload.State.Deleted.Tip" xml:space="preserve"><value>Deleted from this sequence earlier: restore it from the trash to bring it back</value></data>
<data name="Admin.Upload.State.Done" xml:space="preserve"><value>Uploaded</value></data>
<data name="Admin.Upload.State.Done.Tip" xml:space="preserve"><value>On the server and verified against its SHA-256</value></data>
<data name="Admin.Upload.State.Exists" xml:space="preserve"><value>Already there</value></data>
<data name="Admin.Upload.State.Exists.Tip" xml:space="preserve"><value>The server already has this photo</value></data>
<data name="Admin.Upload.State.Failed" xml:space="preserve"><value>Failed</value></data>
<data name="Admin.Upload.State.Hashing" xml:space="preserve"><value>Hashing {0}</value></data>
<data name="Admin.Upload.State.NotSent" xml:space="preserve"><value>Not sent</value></data>
<data name="Admin.Upload.State.NotSent.Tip" xml:space="preserve"><value>Not sent: the upload stopped before this photo</value></data>
<data name="Admin.Upload.State.Starting" xml:space="preserve"><value>Starting</value></data>
<data name="Admin.Upload.State.Uploading" xml:space="preserve"><value>Uploading {0}</value></data>
<data name="Admin.Upload.State.Verifying" xml:space="preserve"><value>Verifying</value></data>
<data name="Admin.Upload.State.Waiting" xml:space="preserve"><value>Waiting</value></data>
<data name="Admin.Upload.Target" xml:space="preserve"><value>Sequence</value></data>
<data name="Admin.Upload.Title" xml:space="preserve"><value>Upload photos</value></data>
<data name="Admin.Users.Accounts.one" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Accounts.other" xml:space="preserve"><value>{0} accounts</value></data>
<data name="Admin.Users.Active" xml:space="preserve"><value>Active</value></data>
+55
View File
@@ -775,6 +775,61 @@
<data name="Admin.Trash.Sequence" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Trash.Size" xml:space="preserve"><value>Dimensione</value></data>
<data name="Admin.Trash.Title" xml:space="preserve"><value>Cestino</value></data>
<data name="Admin.Upload.Add" xml:space="preserve"><value>Aggiungi foto</value></data>
<data name="Admin.Upload.Add.Tip" xml:space="preserve"><value>Scegli le foto su questo computer; puoi anche trascinarle in questa finestra</value></data>
<data name="Admin.Upload.Bytes" xml:space="preserve"><value>{0} di {1}</value></data>
<data name="Admin.Upload.Cancel" xml:space="preserve"><value>Annulla</value></data>
<data name="Admin.Upload.Cancel.Tip" xml:space="preserve"><value>Ferma ora: le foto non ancora finite vengono scartate sul server</value></data>
<data name="Admin.Upload.Close" xml:space="preserve"><value>Chiudi</value></data>
<data name="Admin.Upload.Close.Tip" xml:space="preserve"><value>Chiudi la finestra di caricamento</value></data>
<data name="Admin.Upload.Count" xml:space="preserve"><value>Foto: {0} di {1}</value></data>
<data name="Admin.Upload.Drop" xml:space="preserve"><value>Trascina qui le foto</value></data>
<data name="Admin.Upload.Existing" xml:space="preserve"><value>Sequenza esistente</value></data>
<data name="Admin.Upload.Existing.Tip" xml:space="preserve"><value>Aggiungi le foto a una sequenza già presente sul server</value></data>
<data name="Admin.Upload.Failed" xml:space="preserve"><value>Non riuscite: {0}</value></data>
<data name="Admin.Upload.HashFailed" xml:space="preserve"><value>In questo browser non si può calcolare l'hash delle foto, quindi non è stato caricato nulla.</value></data>
<data name="Admin.Upload.New" xml:space="preserve"><value>Nuova sequenza</value></data>
<data name="Admin.Upload.New.Tip" xml:space="preserve"><value>Crea sul server una sequenza per queste foto</value></data>
<data name="Admin.Upload.NewTitle" xml:space="preserve"><value>Titolo</value></data>
<data name="Admin.Upload.NewTitle.Tip" xml:space="preserve"><value>Nome della nuova sequenza; se resta vuoto, prende data e fotocamera delle sue foto</value></data>
<data name="Admin.Upload.NoMatch" xml:space="preserve"><value>Nessuna sequenza trovata</value></data>
<data name="Admin.Upload.PhotoCount.one" xml:space="preserve"><value>{0} foto</value></data>
<data name="Admin.Upload.PhotoCount.other" xml:space="preserve"><value>{0} foto</value></data>
<data name="Admin.Upload.Photos" xml:space="preserve"><value>Foto</value></data>
<data name="Admin.Upload.PickFirst" xml:space="preserve"><value>Scegli prima una sequenza.</value></data>
<data name="Admin.Upload.ReadFailed" xml:space="preserve"><value>Impossibile leggere il file.</value></data>
<data name="Admin.Upload.Remove" xml:space="preserve"><value>Togli {0}</value></data>
<data name="Admin.Upload.Remove.Tip" xml:space="preserve"><value>Togli questa foto dall'elenco</value></data>
<data name="Admin.Upload.Search" xml:space="preserve"><value>Cerca sequenze</value></data>
<data name="Admin.Upload.Search.Tip" xml:space="preserve"><value>Trova una sequenza per titolo, fotocamera o tag</value></data>
<data name="Admin.Upload.SelfTestFailed" xml:space="preserve"><value>Questo browser ha calcolato male uno SHA-256 di prova, quindi non carica nulla.</value></data>
<data name="Admin.Upload.Sequences" xml:space="preserve"><value>Sequenze</value></data>
<data name="Admin.Upload.Sequences.Tip" xml:space="preserve"><value>La sequenza in cui vanno le foto</value></data>
<data name="Admin.Upload.Skipped.Folders" xml:space="preserve"><value>Cartelle saltate: {0}</value></data>
<data name="Admin.Upload.Skipped.Folders.Tip" xml:space="preserve"><value>Le cartelle si importano con l'app desktop; qui si caricano solo foto</value></data>
<data name="Admin.Upload.Skipped.Formats" xml:space="preserve"><value>Non foto: {0}</value></data>
<data name="Admin.Upload.Skipped.Formats.Tip" xml:space="preserve"><value>Esclusi i file in un formato che il server non legge come foto</value></data>
<data name="Admin.Upload.Skipped.Size" xml:space="preserve"><value>Troppo grandi: {0}</value></data>
<data name="Admin.Upload.Skipped.Size.Tip" xml:space="preserve"><value>Esclusi i file oltre il limite di caricamento del server ({0})</value></data>
<data name="Admin.Upload.Start" xml:space="preserve"><value>Carica</value></data>
<data name="Admin.Upload.Start.Tip" xml:space="preserve"><value>Invia le foto non ancora sul server; il server controlla ognuna con il suo SHA-256</value></data>
<data name="Admin.Upload.State.Cancelled" xml:space="preserve"><value>Annullata</value></data>
<data name="Admin.Upload.State.Deleted" xml:space="preserve"><value>Eliminata prima</value></data>
<data name="Admin.Upload.State.Deleted.Tip" xml:space="preserve"><value>Eliminata in precedenza da questa sequenza: ripristinala dal cestino per riaverla</value></data>
<data name="Admin.Upload.State.Done" xml:space="preserve"><value>Caricata</value></data>
<data name="Admin.Upload.State.Done.Tip" xml:space="preserve"><value>Sul server e verificata con il suo SHA-256</value></data>
<data name="Admin.Upload.State.Exists" xml:space="preserve"><value>Già presente</value></data>
<data name="Admin.Upload.State.Exists.Tip" xml:space="preserve"><value>Il server ha già questa foto</value></data>
<data name="Admin.Upload.State.Failed" xml:space="preserve"><value>Non riuscita</value></data>
<data name="Admin.Upload.State.Hashing" xml:space="preserve"><value>Calcolo hash {0}</value></data>
<data name="Admin.Upload.State.NotSent" xml:space="preserve"><value>Non inviata</value></data>
<data name="Admin.Upload.State.NotSent.Tip" xml:space="preserve"><value>Non inviata: il caricamento si è fermato prima di questa foto</value></data>
<data name="Admin.Upload.State.Starting" xml:space="preserve"><value>Avvio</value></data>
<data name="Admin.Upload.State.Uploading" xml:space="preserve"><value>Invio {0}</value></data>
<data name="Admin.Upload.State.Verifying" xml:space="preserve"><value>Verifica</value></data>
<data name="Admin.Upload.State.Waiting" xml:space="preserve"><value>In attesa</value></data>
<data name="Admin.Upload.Target" xml:space="preserve"><value>Sequenza</value></data>
<data name="Admin.Upload.Title" xml:space="preserve"><value>Carica foto</value></data>
<data name="Admin.Users.Accounts.one" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Accounts.other" xml:space="preserve"><value>{0} account</value></data>
<data name="Admin.Users.Active" xml:space="preserve"><value>Attivo</value></data>
+6 -1
View File
@@ -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);
+18
View File
@@ -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; }
+6 -7
View File
@@ -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) });
}
}
+185
View File
@@ -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;
}
+693
View File
@@ -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"));
},
};
}
+6 -1
View File
@@ -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) =>
{
@@ -142,9 +142,10 @@ public sealed partial class SystemEndpointTests(TestContext context)
// The page container is not a live region: only toasts and form errors announce themselves.
Assert.True(!index.Contains("aria-live", StringComparison.Ordinal), index);
var seen = await ModulesAsync(server);
Assert.True(seen.Count >= 17, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js" })
Assert.True(seen.Count >= 20, string.Join(", ", seen.Keys));
// The Library's views (owner review 2, R6) are modules of their own under pages/library; the web upload (R3) is the
// dialog, its hash worker and the in-house SHA-256 the worker imports.
foreach (var module in new[] { "pages/library.js", "pages/library/sequence.js", "pages/library/trash.js", "pages/library/shared.js", "upload.js", "hash-worker.js", "sha256.js" })
Assert.True(seen.ContainsKey(module), module);
}
@@ -185,17 +186,19 @@ public sealed partial class SystemEndpointTests(TestContext context)
private static async Task<Dictionary<string, string>> ModulesAsync(TestServer server)
{
var app = await server.Client.GetStringAsync("/admin/app.js");
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("app.js"));
// The upload dialog is a module the Library opens on demand (owner review 2, R3); its hash worker is named by a URL.
var pending = new Queue<string>(MenuPages(app).SelectMany(group => group).Select(p => $"pages/{p}.js").Prepend("upload.js").Prepend("app.js"));
var seen = new Dictionary<string, string>(StringComparer.Ordinal);
while (pending.TryDequeue(out var module))
{
if (seen.ContainsKey(module)) continue;
using var response = await server.Client.GetAsync("/admin/" + module);
Assert.Equal(HttpStatusCode.OK, response.StatusCode, module);
Assert.Equal("text/javascript", response.Content.Headers.ContentType?.MediaType, module);
var source = await response.Content.ReadAsStringAsync();
seen[module] = source;
var folder = module.Contains('/', StringComparison.Ordinal) ? module[..(module.LastIndexOf('/') + 1)] : string.Empty;
foreach (Match import in StaticImport().Matches(source))
foreach (Match import in ModuleReference().Matches(source))
pending.Enqueue(Resolve(folder, import.Groups[1].Value));
}
return seen;
@@ -204,6 +207,45 @@ public sealed partial class SystemEndpointTests(TestContext context)
[GeneratedRegex(@"from ""(\.{1,2}/[^""]+)""")]
private static partial Regex StaticImport();
/// <summary>A module's static imports and the module workers it starts (<c>new URL("./…", import.meta.url)</c>).</summary>
[GeneratedRegex(@"(?:from |new URL\()""(\.{1,2}/[^""]+)""")]
private static partial Regex ModuleReference();
[Test]
public async Task TheUploadDialogsHashWorkerRunsUnderThePanelPolicy()
{
await using var server = await TestServer.StartAsync(context);
using var page = await server.Client.GetAsync("/admin/");
// CSP 3: a worker is allowed by worker-src, else child-src, else script-src, else default-src.
var policy = Directives(page);
var workers = new[] { "worker-src", "child-src", "script-src", "default-src" }.Select(d => policy.GetValueOrDefault(d)).First(v => v is not null);
Assert.SequenceEqual(["'self'"], Assert.NotNull(workers));
using var worker = await server.Client.GetAsync("/admin/hash-worker.js");
Assert.Equal(HttpStatusCode.OK, worker.StatusCode);
Assert.Equal("text/javascript", worker.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", worker.Headers.GetValues("X-Content-Type-Options").First());
// The worker runs under its own response's policy, which lets it import the hash from the same origin.
Assert.SequenceEqual(["'self'"], Assert.NotNull(Directives(worker).GetValueOrDefault("script-src")));
Assert.Contains(@"from ""./sha256.js""", await worker.Content.ReadAsStringAsync());
var upload = await server.Client.GetStringAsync("/admin/upload.js");
Assert.Contains(@"new Worker(new URL(""./hash-worker.js"", import.meta.url), { type: ""module"" })", upload);
Assert.Contains("api.putBytes(", upload);
// No folder picking on the web: importing a whole folder is a desktop feature (owner review 2, R9).
foreach (var picker in new[] { "webkitdirectory", "showDirectoryPicker", "mozdirectory" })
Assert.True(!upload.Contains(picker, StringComparison.OrdinalIgnoreCase), picker);
// The panel has no inline handlers for the policy to block (and none to allow).
Assert.True(!Regex.IsMatch(upload, @"\son[a-z]+="""), "inline handler");
}
/// <summary>The directives of a response's Content-Security-Policy, each with its sources.</summary>
private static Dictionary<string, string[]> Directives(HttpResponseMessage response) =>
string.Join(';', response.Headers.GetValues("Content-Security-Policy"))
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(d => d.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(d => d[0], d => d[1..], StringComparer.OrdinalIgnoreCase);
[Test]
public async Task AdminPanelDocksSettingsAtTheFootAndFoldsAboutIntoIt()
{
@@ -0,0 +1,201 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Storage;
/// <summary>
/// The admin panel's upload dialog (owner review 2, R3; <c>Admin/web/upload.js</c>) speaks the upload API through the
/// cookie session: requests shaped like <c>api.js</c> sends them (JSON bodies written as the page writes them, the
/// page's language, the CSRF header on every unsafe call, chunks as octet-stream), against the real archive engine.
/// </summary>
[Category("server")]
public sealed class BrowserUploadTests(TestContext context)
{
private const int Chunk = 64 * 1024;
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(30));
[Test]
public async Task TheUploadDialogFilesPhotosThroughTheCookieSession()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, ArchiveModule.Register);
var browser = await Browser.SignInAsync(server);
// What the dialog offers and checks before it hashes anything.
ServerInfo info;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/server/info"))
info = await response.ReadAsync(ProtocolJson.Default.ServerInfo);
var extensions = Assert.NotNull(info.Extensions);
foreach (var extension in new[] { "jpg", "jpeg", "tif", "dng", "cr3", "nef", "heic" }) Assert.Contains(extension, extensions);
Assert.True(extensions.All(e => e.Length > 0 && e == e.ToLowerInvariant() && !e.StartsWith('.')), string.Join(",", extensions));
// New sequence: the title as typed, no camera hint.
SequenceDto sequence;
using (var created = await browser.SendAsync(HttpMethod.Post, "/api/v1/sequences", Json("""{"title":"Roof","cameraHint":null}""")))
{
await created.ExpectAsync(HttpStatusCode.Created);
sequence = await created.ReadAsync(ProtocolJson.Default.SequenceDto);
}
var photos = new[] { Photo(1), Photo(2) };
var frames = new List<CompleteUploadResponse>();
for (var i = 0; i < photos.Length; i++)
{
var photo = photos[i];
var start = await StartAsync(browser, sequence.Id, $"IMG_{i + 1:0000}.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(start.UploadId);
Assert.Equal(Chunk, start.ChunkSize);
var count = (photo.Length + Chunk - 1) / Chunk;
Assert.True(count >= 2, $"{photo.Length} bytes make one chunk");
// putBytes sends the session's headers: a chunk without the CSRF header is refused like any other change.
using (var refused = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/0", Bytes(photo, 0), csrf: false))
await refused.ExpectErrorAsync(HttpStatusCode.Forbidden, "csrf_failed");
// Two chunks in flight, finishing in any order.
for (var last = count - 1; last >= 0; last -= 2)
{
var pair = new[] { last, last - 1 }.Where(n => n >= 0).Select(async n =>
{
using var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{id}/chunks/{n}", Bytes(photo, n));
return await put.ReadAsync(ProtocolJson.Default.ChunkReceived);
});
foreach (var received in await Task.WhenAll(pair)) Assert.Contains(received.Index, received.Received);
}
using var complete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/uploads/{id}/complete", Json("{}"));
var frame = await complete.ReadAsync(ProtocolJson.Default.CompleteUploadResponse);
Assert.Equal(sequence.Id, frame.SequenceId);
frames.Add(frame);
}
var stored = await server.Database.Frames.ListBySequenceAsync(sequence.Id);
Assert.SequenceEqual(frames.Select(f => f.FrameId).Order(), stored.Select(f => f.Id).Order());
for (var i = 0; i < photos.Length; i++)
{
var file = Path.Combine(server.Options.ArchivePath, stored.Single(f => f.Id == frames[i].FrameId).RelativePath);
await Http.BytesEqualAsync(photos[i], File.ReadAllBytesAsync(file));
}
// Picked again: already there, with its frame.
var again = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photos[0], HttpStatusCode.OK);
Assert.True(again.AlreadyExists);
Assert.Equal(frames[0].FrameId, again.FrameId);
// Deleted from the sequence: also answered as there, without a frame ("deleted before; restore it from the trash").
await UntilIdleAsync(server);
var current = Assert.NotNull(await server.Database.Sequences.GetAsync(sequence.Id));
using (var delete = await browser.SendAsync(HttpMethod.Post, $"/api/v1/sequences/{sequence.Id}/frames/delete",
Json($$"""{"frameIds":["{{frames[1].FrameId}}"],"expectedFramesVersion":{{current.FramesVersion}},"dryRun":false}""")))
Assert.NotNull((await delete.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
var deleted = await StartAsync(browser, sequence.Id, "IMG_0002.JPG", photos[1], HttpStatusCode.OK);
Assert.True(deleted.AlreadyExists);
Assert.Null(deleted.UploadId);
Assert.Null(deleted.FrameId);
// Cancel: an upload the dialog started is discarded on the server.
var cancelled = Photo(3);
var started = await StartAsync(browser, sequence.Id, "IMG_0003.JPG", cancelled, HttpStatusCode.Created);
var cancelledId = Assert.NotNull(started.UploadId);
using (var put = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/0", Bytes(cancelled, 0)))
await put.ExpectAsync(HttpStatusCode.OK);
using (var discard = await browser.SendAsync(HttpMethod.Delete, $"/api/v1/uploads/{cancelledId}"))
await discard.ExpectAsync(HttpStatusCode.NoContent);
using (var state = await browser.SendAsync(HttpMethod.Get, $"/api/v1/uploads/{cancelledId}"))
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
using (var late = await browser.SendAsync(HttpMethod.Put, $"/api/v1/uploads/{cancelledId}/chunks/1", Bytes(cancelled, 1)))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(cancelledId), "the partial file is gone");
}
[Test]
public async Task AQuotaRefusalCarriesTheMessageTheDialogShows()
{
// A quota or space refusal stops the dialog's run with the server's message, in the page's language.
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk);
var browser = await Browser.SignInAsync(server);
Guid me;
using (var response = await browser.SendAsync(HttpMethod.Get, "/api/v1/auth/me")) me = (await response.ReadAsync(ProtocolJson.Default.UserDto)).Id;
using (var quota = await browser.SendAsync(HttpMethod.Patch, $"/api/v1/users/{me}", Json("""{"quotaBytes":1000}""")))
await quota.ExpectAsync(HttpStatusCode.OK);
using var start = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(null, "IMG_0001.JPG", Uploads.Photo(Chunk + 10, 7)));
var error = await start.ExpectErrorAsync(HttpStatusCode.Forbidden, "quota_exceeded");
Assert.Equal(Loc.Get("Server.Error.QuotaExceeded", CultureInfo.GetCultureInfo("it")), error.Message);
}
/// <summary>The bootstrap administrator signed in to the panel (a cookie session over HTTPS), calling as <c>api.js</c> does.</summary>
private sealed class Browser(HttpClient client, string csrfToken)
{
public static async Task<Browser> SignInAsync(TestServer server)
{
await server.AdminAsync();
var cookies = new CookieContainer();
var client = server.NewCookieClient(cookies);
using var login = await client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest("admin", TestServer.Password, "admin-web", Cookie: true),
ProtocolJson.Default.LoginRequest);
await login.ExpectAsync(HttpStatusCode.OK);
return new Browser(client, Assert.NotNull(cookies.GetCookies(Assert.NotNull(server.HttpsBase))["chronos_csrf"]).Value);
}
/// <summary>JSON accepted, the page's language (Italian here), and the CSRF header on every call but a GET.</summary>
public async Task<HttpResponseMessage> SendAsync(HttpMethod method, string url, HttpContent? content = null, bool csrf = true)
{
using var request = new HttpRequestMessage(method, url) { Content = content };
request.Headers.Accept.ParseAdd("application/json");
request.Headers.AcceptLanguage.ParseAdd("it");
if (method != HttpMethod.Get && csrf) request.Headers.Add("X-CSRF-Token", csrfToken);
return await client.SendAsync(request);
}
}
private static StringContent Json(string json) => new(json, Encoding.UTF8, "application/json");
/// <summary>A chunk as <c>putBytes</c> sends a <c>File.slice()</c>: its bytes, octet-stream.</summary>
private static ByteArrayContent Bytes(byte[] data, int index)
{
var content = new ByteArrayContent(Uploads.Chunk(data, Chunk, index).ToArray());
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return content;
}
/// <summary>The start body upload.js writes: no capture time (the server reads it from the photo), no session key.</summary>
private static StringContent StartBody(Guid? sequenceId, string fileName, byte[] data) =>
Json($$"""{"sequenceId":{{(sequenceId is { } id ? $"\"{id}\"" : "null")}},"fileName":"{{fileName}}","size":{{data.Length}},"sha256":"{{Uploads.Sha(data)}}","capturedAt":null,"sessionKey":null}""");
private static async Task<StartUploadResponse> StartAsync(Browser browser, Guid sequenceId, string fileName, byte[] data, HttpStatusCode expected)
{
using var response = await browser.SendAsync(HttpMethod.Post, "/api/v1/uploads", StartBody(sequenceId, fileName, data));
await response.ExpectAsync(expected);
return await response.ReadAsync(ProtocolJson.Default.StartUploadResponse);
}
/// <summary>Waits until no job is queued or running (the thumbnails, proxies and analyses uploads queue).</summary>
private static async Task UntilIdleAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Count > 0)
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
/// <summary>A JPEG of a few chunks: noise does not compress below the chunk size.</summary>
private static byte[] Photo(int seed)
{
const int width = 512, height = 384;
var pixels = new byte[width * height * 3];
new Random(seed).NextBytes(pixels);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 95 });
}
}