fix(sync,upload): keep tombstones honest and let an explicit upload bring a photo back

Sync:
- A server frame that has not been hashed is known by content only once it is
  downloaded: one this PC deleted (or holds as its replacement) is now deleted
  from staging instead of filed again, which also dropped its tombstone.
- An unhashed local original that turns out to be a photo the server deleted
  is not uploaded, and the archive verify then writes the hashes into the
  index, so the row settles instead of offering Upload for good.
- A tombstone leaves a photo out of the comparison only when its side no longer
  holds that content, so a tombstone left beside a held copy does not keep the
  other side's copy missing forever.

Uploads:
- StartUploadRequest.Restore (optional, never sent by sync or older clients)
  lets an explicit user upload file a photo deleted from the sequence again,
  also after the trash was emptied; the completion repeats it with
  ?restore=true and the ingest drops the tombstone.
- The completion checks the tombstone again: a photo deleted while its bytes
  were on the way is not filed (409 photo_removed, upload cancelled); the
  protocol client reports that as not sent.
- A tombstone of content a frame of the target still holds refuses no repair.
- Hidden dot names (AppleDouble "._" files) are refused, as the archive
  scanner leaves them out.

Web upload dialog:
- Upload again on rows marked Deleted before; the tooltip no longer promises
  a trash restore that may be impossible.
- Sends a capture time: the Exif DateTimeOriginal of a JPEG or TIFF-based file
  (minimal in-house reader, capture-time.js), else the file's time, so photos
  without Exif keep their order.
- Esc is stopped at keydown during a run (Chromium allows one prevented cancel
  per activation); hidden dot files are left out; a completion refused while
  another one files the upload waits for it; the same photo picked under two
  names waits for its first copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit d051bcfc351f5a08500ca864a6508576a95492a4)
This commit is contained in:
Alby96 committed 2026-10-27 12:45:33 +01:00
1 parent eb607d47aa
commit 316c182b19
18 files changed
+753 -63

No files matched your search

+114 -16
View File
@@ -1,18 +1,22 @@
// 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.
// SHA-256 first and refuses to hash when a check fails), started with its capture time (capture-time.js), sent in the
// chunks the server does not have yet and completed; the server verifies the hash again before it files the photo. A
// photo deleted from the sequence before is not filed again unless the user asks for it on its row (Upload again).
import { ApiFailure } from "./api.js";
import { t, plural, applyStrings, culture } from "./i18n.js";
import { escapeHtml, attr, bar, formatBytes, formatNumber, errorText } from "./ui.js";
import { icons } from "./icons.js";
import { captureTime } from "./capture-time.js";
/** Photos sent at once, and chunks in flight for each: four requests, half of what the server takes from one account. */
const FILES_AT_ONCE = 2;
const CHUNKS_AT_ONCE = 2;
/** Retries of a call that failed for a passing reason (no answer, 429, 503), after 1, 2 and 4 seconds. */
const RETRIES = 3;
/** Checks of an upload another completion is filing, after 1, 2, 4 and then every 8 seconds: about a minute in all. */
const SETTLE_CHECKS = 10;
const SEARCH_DELAY = 250;
const LIST_LIMIT = 50;
/** States of a photo already on the server: a later run leaves it alone. */
@@ -48,6 +52,8 @@ export function openUpload({ api, sequence, onDone } = {}) {
let searchTimer = null;
let searchToken = 0;
let frame = 0;
// Per run: by SHA-256, the send of the last photo of that content, which the next copy waits for.
let sameContent = new Map();
const items = [];
const skipped = { folders: 0, formats: 0, size: 0 };
const titles = new Map();
@@ -103,6 +109,17 @@ export function openUpload({ api, sequence, onDone } = {}) {
else dialog.close();
});
list.addEventListener("click", (e) => {
// Upload again: a photo deleted from the sequence before goes back into it with the next run, on the user's word.
const again = e.target.closest('[data-act="again"]');
if (again && !running) {
const item = items.find((i) => i.key === again.closest("[data-key]").dataset.key);
if (item?.state !== "deleted") return;
item.restore = true;
setState(item, "waiting");
drawButtons();
startButton.focus();
return;
}
const button = e.target.closest('[data-act="remove"]');
if (!button || running) return;
const index = items.findIndex((i) => i.key === button.closest("[data-key]").dataset.key);
@@ -134,7 +151,12 @@ export function openUpload({ api, sequence, onDone } = {}) {
take(files, folders);
});
// Esc closes only while nothing is being sent; Cancel stops a run.
// Esc closes only while nothing is being sent; Cancel stops a run. Chromium lets a dialog's cancel be prevented only
// once per user activation, so during a run Esc is stopped at its keydown; the cancel handler stays for close requests
// that do not come from the keyboard (a back gesture).
dialog.addEventListener("keydown", (e) => {
if (running && e.key === "Escape") e.preventDefault();
});
dialog.addEventListener("cancel", (e) => {
if (running) e.preventDefault();
});
@@ -234,13 +256,17 @@ export function openUpload({ api, sequence, onDone } = {}) {
`<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. */
/**
* Adds picked or dropped files: photos once each; folders, other files and files above the limit are counted. Hidden
* dot files (the AppleDouble "._" companions a Mac leaves on cards among them) are left out like the archive scanner
* leaves them out, and the server refuses them too.
*/
function take(files, folders) {
skipped.folders += folders;
for (const file of files) {
const dot = file.name.lastIndexOf(".");
const extension = dot < 0 ? "" : file.name.slice(dot + 1).toLowerCase();
if (file.size === 0 || !extensions?.has(extension)) {
if (file.size === 0 || file.name.startsWith(".") || !extensions?.has(extension)) {
skipped.formats++;
continue;
}
@@ -250,14 +276,16 @@ export function openUpload({ api, sequence, onDone } = {}) {
}
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 };
const item = { key, file, state: "waiting", hashed: 0, sent: 0, uploadId: null, restore: false, message: "", row: null };
item.row = document.createElement("li");
item.row.className = "upload-file";
item.row.dataset.key = key;
item.row.innerHTML = `<span class="name ellipsis" dir="auto" title="${attr(file.name)}">${escapeHtml(file.name)}</span>
<span class="size num muted">${escapeHtml(formatBytes(file.size))}</span><span class="status"></span>
<button class="btn icon small subtle" type="button" data-act="remove" title="${attr(t("Admin.Upload.Remove.Tip"))}"
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>`;
aria-label="${attr(t("Admin.Upload.Remove", file.name))}">${icons.close}</button>
<button class="btn icon small subtle" type="button" data-act="again" hidden title="${attr(t("Admin.Upload.Again.Tip"))}"
aria-label="${attr(t("Admin.Upload.Again", file.name))}">${icons.upload}</button>`;
list.appendChild(item.row);
items.push(item);
drawItem(item);
@@ -341,7 +369,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
}
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);
drawRowButtons(item);
}
/** A photo comes off the list only between runs, and only while it is not on the server. */
@@ -349,6 +377,12 @@ export function openUpload({ api, sequence, onDone } = {}) {
return !running && !FINISHED.has(item.state) && !ACTIVE.has(item.state);
}
/** Remove, or for a photo deleted from the sequence before, Upload again; both only between runs. */
function drawRowButtons(item) {
item.row.querySelector('[data-act="remove"]').hidden = !removable(item);
item.row.querySelector('[data-act="again"]').hidden = running || item.state !== "deleted";
}
/** Progress redraws at most once a frame: the worker reports every 8 MiB, chunks finish four at a time. */
function update(item) {
item.dirty = true;
@@ -400,7 +434,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
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);
for (const item of items) drawRowButtons(item);
targetHost.querySelectorAll("input, select").forEach((field) => {
field.disabled = running;
});
@@ -419,6 +453,7 @@ export function openUpload({ api, sequence, onDone } = {}) {
showError("");
running = true;
controller = new AbortController();
sameContent = new Map();
const signal = controller.signal;
window.addEventListener("beforeunload", guard);
drawButtons();
@@ -520,7 +555,9 @@ export function openUpload({ api, sequence, onDone } = {}) {
/**
* 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.
* chunks sent two at a time, completed. True when the library changed. The same photo picked under another name
* waits for the first copy, which settles it for both: two lanes would otherwise complete the one upload the server
* gives them and refuse each other.
*/
async function send(item, sequenceId, signal) {
const file = item.file;
@@ -533,12 +570,32 @@ export function openUpload({ api, sequence, onDone } = {}) {
});
if (signal.aborted) throw signal.reason;
setState(item, "starting");
const earlier = sameContent.get(sha256);
let settle;
sameContent.set(sha256, new Promise((resolve) => {
settle = resolve;
}));
try {
await earlier;
if (signal.aborted) throw signal.reason;
return await sendHashed(item, sha256, sequenceId, signal);
} finally {
settle();
}
}
/** A hashed photo: started (asking to bring it back when the user chose Upload again), its chunks sent, completed. */
async function sendHashed(item, sha256, sequenceId, signal) {
const file = item.file;
const restore = item.restore;
const capturedAt = await captureTime(file);
const start = await retry(() => api.post("/api/v1/uploads", {
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt: null, sessionKey: null,
sequenceId, fileName: file.name, size: file.size, sha256, capturedAt, sessionKey: null, restore,
}), signal);
if (start.alreadyExists) {
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back (R6).
setState(item, start.frameId ? "exists" : "deleted");
// No frame: the photo was deleted from this sequence; a restore from the trash brings it back while the trash
// holds it, or Upload again on its row (R6).
finish(item, start.frameId ? "exists" : "deleted");
return false;
}
item.uploadId = start.uploadId;
@@ -567,16 +624,57 @@ export function openUpload({ api, sequence, onDone } = {}) {
}
};
await Promise.all(Array.from({ length: Math.min(CHUNKS_AT_ONCE, missing.length) }, lane));
if (failure !== null) throw failure;
// A chunk refused because the upload is no longer receiving: another completion of it is filing it (or it ended),
// which the completion below waits for and reports.
if (failure !== null && !filing(failure)) throw failure;
setState(item, "verifying");
await retry(() => api.post(`/api/v1/uploads/${item.uploadId}/complete`), signal);
try {
await complete(item.uploadId, restore, signal);
} catch (err) {
if (!(err instanceof ApiFailure && err.status === 409 && err.code === "photo_removed")) throw err;
// Deleted from the sequence while it was on its way: not filed, and the server dropped the upload (R6).
item.uploadId = null;
finish(item, "deleted");
return false;
}
item.uploadId = null;
setState(item, "done");
finish(item, "done");
return true;
}
/** A photo is settled on the server: a later run leaves it alone, until Upload again asks to bring it back. */
function finish(item, state) {
item.restore = false;
setState(item, state);
}
});
}
/** 409 upload_state: the upload is not receiving now, because a completion is filing it or it ended. */
function filing(err) {
return err instanceof ApiFailure && err.status === 409 && err.code === "upload_state";
}
/**
* Completes an upload (with restore, a photo deleted from the sequence meanwhile is filed anyway). A completion refused
* while another one is filing the upload (the same photo started twice, a retry after a lost answer) waits for it: once
* the upload is committed, completing again answers its frame. Only an upload that failed or was cancelled, or one that
* stays busy for about a minute, fails the photo.
*/
async function complete(uploadId, restore, signal) {
const url = `/api/v1/uploads/${uploadId}/complete${restore ? "?restore=true" : ""}`;
for (let check = 0; ; check++) {
try {
return await retry(() => api.post(url), signal);
} catch (err) {
if (signal.aborted || !filing(err) || check >= SETTLE_CHECKS) throw err;
await sleep(1000 * Math.min(2 ** check, 8), signal);
const upload = await retry(() => api.get(`/api/v1/uploads/${uploadId}`), signal);
if (upload?.state === "failed" || upload?.state === "cancelled") throw err;
}
}
}
/** What dropped: the files, and how many folders were left out (the entries API tells them apart where it exists). */
function dropped(transfer) {
const files = [];