Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caf9ac6a37 | ||
|
|
76417fcdb6 | ||
|
|
7363753082 | ||
|
|
54a941101c | ||
|
|
4f5a2fd484 | ||
|
|
51e6e56880 |
No files matched your search
@@ -254,8 +254,9 @@ export class AutopilotService {
|
||||
picked += toFlag.length;
|
||||
}
|
||||
if (reportage) {
|
||||
// A sharp sequence: the second frame is a half body, the third a three-quarter. The first keeps the
|
||||
// whole person. A plan that cannot be made (too small, or the same as the full crop) is skipped.
|
||||
// A sharp sequence may carry a tighter plan (three-quarter; a half that would cut the hands is not made).
|
||||
// The first frame keeps the whole person. A plan that would cut a neck or the hands, or that matches
|
||||
// the open crop, is skipped: that frame stays open.
|
||||
for (const { f: framePick, key } of chosen) {
|
||||
if (!key) continue;
|
||||
const planned = framePick.rec?.plans?.[key];
|
||||
|
||||
@@ -444,9 +444,24 @@ function strayLimb(p: Detection, tallest: number): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* A second or third plan of the same moment (half body, three-quarter). The bottom sits mid-limb, the head and
|
||||
* the hands inside the subject box stay, and the foot is not where the cut falls. Null when that plan cannot
|
||||
* keep the delivery's resolution.
|
||||
* Where a sequence plan may end on this person, measured on their own box. A line taken from the top of the
|
||||
* group lands on the neck of whoever stands lower. The hands stay: at the hip on a standing figure, and at the
|
||||
* bottom of the box when the person is leaning (the box is wide because the arms are in it). Null: this plan
|
||||
* would cut the neck or the hands, so the open crop stands and no second frame is made just to show a worse one.
|
||||
*/
|
||||
function planCut(p: Detection, at: number): number | null {
|
||||
const line = p.y0 + at * h(p);
|
||||
if (line < p.y0 + 0.28 * h(p)) return null;
|
||||
if (line < p.y0 + 0.55 * h(p)) return null;
|
||||
if (h(p) < 1.8 * Math.max(w(p), 1e-6) && line < p.y1 - 0.08 * h(p)) return null;
|
||||
if (p.fragment && line < p.y1 - 0.04 * h(p)) return null;
|
||||
return line;
|
||||
}
|
||||
|
||||
/**
|
||||
* A second or third plan of the same moment (half body, three-quarter). The bottom sits below the hands, the
|
||||
* head stays, and the foot is not where the cut falls. Null when that plan would cut a neck or a hand, or cannot
|
||||
* keep the delivery's resolution: the photo keeps the open crop.
|
||||
*/
|
||||
export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null {
|
||||
const reportage = opts.context === "reportage";
|
||||
@@ -456,7 +471,9 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe
|
||||
const tallest = Math.max(...inSubject.map(h));
|
||||
const at = PLANS[which];
|
||||
if (at > FOOT_ZONE || JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND)) return null;
|
||||
const bottom = s.y0 + at * tallest;
|
||||
const lines = inSubject.map((p) => planCut(p, at));
|
||||
if (lines.some((line) => line === null)) return null;
|
||||
const bottom = Math.max(...(lines as number[]));
|
||||
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width);
|
||||
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
|
||||
const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage);
|
||||
|
||||
@@ -241,20 +241,27 @@ describe("reportage", () => {
|
||||
expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.92);
|
||||
});
|
||||
|
||||
it("makes a half-body plan above the hips and a three-quarter above the knee, head included", () => {
|
||||
it("makes a three-quarter plan below the hands, and refuses a half that would cut them", () => {
|
||||
const p = person(0.4, 0.1, 0.55, 0.9);
|
||||
const d = { ...frame, people: [p], balls: [] };
|
||||
const half = planCrop(d, "half")!;
|
||||
expect(planCrop(d, "half")).toBeNull();
|
||||
const three = planCrop(d, "threeQuarter")!;
|
||||
const at = (y: number) => (y - p.y0) / (p.y1 - p.y0);
|
||||
expect(half.y0).toBeLessThanOrEqual(p.y0);
|
||||
expect(half.x0).toBeLessThanOrEqual(p.x0);
|
||||
expect(half.x1).toBeGreaterThanOrEqual(p.x1);
|
||||
expect(at(half.y1)).toBeGreaterThan(0.35);
|
||||
expect(at(half.y1)).toBeLessThan(0.5);
|
||||
expect(three.y0).toBeLessThanOrEqual(p.y0);
|
||||
expect(three.x0).toBeLessThanOrEqual(p.x0);
|
||||
expect(three.x1).toBeGreaterThanOrEqual(p.x1);
|
||||
expect(at(three.y1)).toBeGreaterThan(0.58);
|
||||
expect(at(three.y1)).toBeLessThan(0.72);
|
||||
expect(half.y1).toBeLessThan(p.y1);
|
||||
expect(three.y1).toBeLessThan(p.y1);
|
||||
});
|
||||
|
||||
it("refuses a sequence crop that would cut a lower neck or the hands of someone leaning", () => {
|
||||
const high = person(0.3, 0.12, 0.48, 0.92);
|
||||
const low = person(0.5, 0.28, 0.68, 0.96);
|
||||
const group = { ...frame, people: [high, low], balls: [] };
|
||||
expect(planCrop(group, "half", null, { context: "reportage" })).toBeNull();
|
||||
const leaning = person(0.2, 0.18, 0.72, 0.86);
|
||||
expect(planCrop({ ...frame, people: [leaning], balls: [] }, "threeQuarter", null, { context: "reportage" })).toBeNull();
|
||||
expect(planCrop({ ...frame, people: [leaning], balls: [] }, "half", null, { context: "reportage" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { DevelopState, EditCommand, EditLogEntry, PostEdits } from "@photoreport/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine } from "./session.js";
|
||||
import { DevelopSession, type OutboxStore, type PendingOp, type SettingsEngine, type StateStore } from "./session.js";
|
||||
|
||||
/** Settings as a flat map of control values; enough to check ordering, undo and sync. */
|
||||
const engine: SettingsEngine = {
|
||||
@@ -132,4 +132,27 @@ describe("DevelopSession", () => {
|
||||
expect(web.value("light.whites")).toBe(5);
|
||||
expect(web.seq).toBe(3);
|
||||
});
|
||||
|
||||
it("opens on the last state when the server does not answer", async () => {
|
||||
server.developState = () => new Promise(() => {});
|
||||
const states: StateStore = {
|
||||
get: async () => ({ settings: JSON.stringify({ "light.exposure": 0.4 }), seq: 2 }),
|
||||
set: () => {},
|
||||
};
|
||||
const s = new DevelopSession("p", {
|
||||
engine,
|
||||
api: server,
|
||||
clientId: "web",
|
||||
states,
|
||||
isOffline: (err) => err instanceof Error && /timeout|offline/i.test(err.message),
|
||||
});
|
||||
const loading = s.load();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(s.loaded).toBe(true);
|
||||
expect(s.value("light.exposure")).toBe(0.4);
|
||||
await vi.advanceTimersByTimeAsync(8_000);
|
||||
await loading;
|
||||
expect(s.offline).toBe(true);
|
||||
expect(s.value("light.exposure")).toBe(0.4);
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,24 @@ interface Step {
|
||||
|
||||
const SEND_DELAY_MS = 120;
|
||||
const RETRY_MAX_MS = 30_000;
|
||||
/** A venue link can sit open without answering. Revelar opens on the last state instead of waiting on it. */
|
||||
const OPEN_WAIT_MS = 8_000;
|
||||
|
||||
function answerOrGiveUp<T>(work: Promise<T>, ms: number): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error("timeout")), ms);
|
||||
work.then(
|
||||
(value) => {
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
},
|
||||
(err: unknown) => {
|
||||
clearTimeout(timer);
|
||||
reject(err);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
const newOpId = () => `${Date.now().toString(36)}-${(++counter).toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
@@ -76,31 +94,40 @@ export class DevelopSession {
|
||||
) {}
|
||||
|
||||
async load(): Promise<void> {
|
||||
const paint = (base: string, seq: number, offline: boolean) => {
|
||||
this.base = base;
|
||||
this.confirmedSeq = seq;
|
||||
this.offline = offline;
|
||||
this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? [];
|
||||
this.loaded = true;
|
||||
this.changed();
|
||||
};
|
||||
if (isLocal(this.photoId)) {
|
||||
// Not on the server yet: starts from scratch; the edits go up after the photo.
|
||||
this.base = this.deps.engine.defaultSettings();
|
||||
this.confirmedSeq = 0;
|
||||
this.offline = true;
|
||||
} else {
|
||||
try {
|
||||
const state = await this.deps.api.developState(this.photoId);
|
||||
let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings();
|
||||
for (const op of state.ops) base = this.safeApply(base, op.command);
|
||||
this.base = base;
|
||||
this.confirmedSeq = state.developSeq;
|
||||
this.remember();
|
||||
} catch (err) {
|
||||
// No network: the state last seen here (or a fresh start); the edits are sent when the connection is back.
|
||||
if (!this.deps.isOffline?.(err)) throw err;
|
||||
const kept = await this.deps.states?.get(this.photoId);
|
||||
this.base = kept?.settings ?? this.deps.engine.defaultSettings();
|
||||
this.confirmedSeq = kept?.seq ?? 0;
|
||||
this.offline = true;
|
||||
}
|
||||
paint(this.deps.engine.defaultSettings(), 0, true);
|
||||
if (this.pending.length) this.schedule(0);
|
||||
return;
|
||||
}
|
||||
// Open on the last state this computer had, so a slow link does not block the preview or the edits.
|
||||
const kept = await this.deps.states?.get(this.photoId);
|
||||
paint(kept?.settings ?? this.deps.engine.defaultSettings(), kept?.seq ?? 0, false);
|
||||
try {
|
||||
const state = await answerOrGiveUp(this.deps.api.developState(this.photoId), OPEN_WAIT_MS);
|
||||
if (this.closed) return;
|
||||
let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings();
|
||||
for (const op of state.ops) base = this.safeApply(base, op.command);
|
||||
this.base = base;
|
||||
this.confirmedSeq = state.developSeq;
|
||||
this.offline = false;
|
||||
this.remember();
|
||||
this.changed();
|
||||
} catch (err) {
|
||||
// No answer: keep what was painted. Edits stay queued and go up when the connection is back.
|
||||
const timedOut = err instanceof Error && err.message === "timeout";
|
||||
if (!timedOut && !this.deps.isOffline?.(err)) throw err;
|
||||
this.offline = true;
|
||||
this.changed();
|
||||
}
|
||||
this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? [];
|
||||
this.loaded = true;
|
||||
this.changed();
|
||||
if (this.pending.length) this.schedule(0);
|
||||
}
|
||||
|
||||
|
||||
@@ -63,8 +63,8 @@ describe("local FTP feed", () => {
|
||||
await act(() => result.current.start());
|
||||
|
||||
await waitFor(() => expect(added).toHaveLength(2));
|
||||
// Each shows in the library as soon as it arrives (before the upload), and leaves once settled.
|
||||
await waitFor(() => expect(localPhotos.list()).toEqual([]));
|
||||
// Each shows as soon as it arrives. The one the server has leaves; the failed one stays so it can be edited.
|
||||
await waitFor(() => expect(localPhotos.list().map((p) => p.name)).toEqual(["B.JPG"]));
|
||||
// Working locally (the default): previews go up, each with the fingerprint of its original.
|
||||
expect(added).toEqual([
|
||||
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
@@ -73,6 +73,7 @@ describe("local FTP feed", () => {
|
||||
await waitFor(() => expect(result.current.counts).toEqual({ received: 2, sent: 1, failed: 1 }));
|
||||
// Only the one the server has moves to the event's work folder; the failed one stays in ingest.
|
||||
expect(shell.sent).toEqual([{ path: "/x/FTP/A.JPG", event: "ABC x Benfica", date: "2026-10-12" }]);
|
||||
for (const photo of localPhotos.list()) localPhotos.remove(photo.id);
|
||||
});
|
||||
|
||||
it("does nothing outside the desktop app", async () => {
|
||||
|
||||
@@ -52,6 +52,11 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/
|
||||
|
||||
/** Photos read from disk and in the upload queue at once (each is held in memory until sent). */
|
||||
const IN_FLIGHT = 6;
|
||||
/**
|
||||
* Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access
|
||||
* token expires, and the server answers 401. Two leaves room for the upload to leave.
|
||||
*/
|
||||
const IN_FLIGHT_ORIGINALS = 2;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
/** The shell put the file back on the queue because the camera has not finished sending it. */
|
||||
@@ -94,6 +99,9 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const [checkState, setCheckState] = useState<null | "busy" | "done" | "unsupported">(null);
|
||||
const backlog = useRef<IncomingFile[]>([]);
|
||||
const inFlight = useRef(0);
|
||||
/** One full original at a time. Several at once freeze the window, and the preview must not wait for that. */
|
||||
const reading = useRef(0);
|
||||
const readQueue = useRef<(() => void)[]>([]);
|
||||
const targetRef = useRef(target);
|
||||
targetRef.current = target;
|
||||
const originalsRef = useRef(false);
|
||||
@@ -106,10 +114,24 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (inFlight.current < IN_FLIGHT && backlog.current.length) {
|
||||
const takeOriginal = () => {
|
||||
if (reading.current < 1) {
|
||||
reading.current++;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise<void>((resume) => readQueue.current.push(resume));
|
||||
};
|
||||
const releaseOriginal = () => {
|
||||
const resume = readQueue.current.shift();
|
||||
if (resume) resume();
|
||||
else reading.current--;
|
||||
};
|
||||
const room = originalsRef.current ? IN_FLIGHT_ORIGINALS : IN_FLIGHT;
|
||||
while (inFlight.current < room && backlog.current.length) {
|
||||
const f = backlog.current.shift()!;
|
||||
const to = targetRef.current;
|
||||
inFlight.current++;
|
||||
let slot = true;
|
||||
void (async () => {
|
||||
try {
|
||||
// Working locally: a 2048 px preview with the original's metadata goes up, the original stays here.
|
||||
@@ -134,28 +156,59 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
// Culled before a restart (still offline): it comes back as it was left.
|
||||
for (const op of orgId ? offlineQueue(orgId).pending : []) if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
|
||||
}
|
||||
const bytes = full ? await invoke<unknown>("ftp_read", { path: f.path }).then(asArrayBuffer) : preview;
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
// The preview is on screen. The next photo does not wait for this one's upload: a slow network must
|
||||
// not stop the grid or Revelar.
|
||||
inFlight.current--;
|
||||
slot = false;
|
||||
pump();
|
||||
// A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload.
|
||||
const routed = pinned ? undefined : events.find((e) => e.id === eventId);
|
||||
add([file], eventId ?? undefined, (_file, result, photo) => {
|
||||
inFlight.current--;
|
||||
const settle = (_file: File, result: UploadStatus, photo?: PhotoSummary) => {
|
||||
if (result === "done" || result === "duplicate") {
|
||||
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
|
||||
invoke("ftp_sent", { path: f.path, event: pinned?.title ?? (routed ? eventLabel(routed) : ""), date: pinned?.date ?? (routed ? routed.startsAt.slice(0, 10) : "") }).catch(() => {});
|
||||
// Changes made to it meanwhile now go to the server's copy.
|
||||
if (photo && orgId) offlineQueue(orgId).uploaded(info.sha256, photo.id);
|
||||
localPhotos.remove(localId(info.sha256));
|
||||
} else {
|
||||
// The upload failed. The preview stays, so it can still be culled and edited; the file stays in
|
||||
// the ingest folder for "Reenviar as que ficaram".
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
localPhotos.remove(localId(info.sha256));
|
||||
pump();
|
||||
}, full ? "original" : info);
|
||||
};
|
||||
if (!full) {
|
||||
const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info);
|
||||
return;
|
||||
}
|
||||
// One original at a time, and only when it is this file's turn to go up. Several at once freeze the window.
|
||||
await takeOriginal();
|
||||
let held = true;
|
||||
const drop = () => {
|
||||
if (!held) return;
|
||||
held = false;
|
||||
releaseOriginal();
|
||||
};
|
||||
try {
|
||||
const bytes = await invoke<unknown>("ftp_read", { path: f.path }).then(asArrayBuffer);
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], eventId ?? undefined, (_file, result, photo) => {
|
||||
drop();
|
||||
settle(_file, result, photo);
|
||||
}, "original");
|
||||
} catch (err) {
|
||||
drop();
|
||||
if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
return;
|
||||
} catch (err) {
|
||||
inFlight.current--;
|
||||
if (slot) {
|
||||
slot = false;
|
||||
inFlight.current--;
|
||||
pump();
|
||||
}
|
||||
// A pause mid-transfer is not a failed photo: the shell hands it out again once the file is whole.
|
||||
if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
pump();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { sendResumable } from "./uploads.js";
|
||||
|
||||
class FakeXHR {
|
||||
static handler: (method: string, url: string, auth: string) => { status: number; body: unknown } = () => ({ status: 500, body: {} });
|
||||
method = "";
|
||||
url = "";
|
||||
auth = "";
|
||||
status = 0;
|
||||
responseText = "";
|
||||
timeout = 0;
|
||||
upload = { onprogress: null as ((e: { loaded: number }) => void) | null };
|
||||
onload: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
ontimeout: (() => void) | null = null;
|
||||
open(method: string, url: string) {
|
||||
this.method = method;
|
||||
this.url = url;
|
||||
}
|
||||
setRequestHeader(name: string, value: string) {
|
||||
if (name.toLowerCase() === "authorization") this.auth = value;
|
||||
}
|
||||
send() {
|
||||
const res = FakeXHR.handler(this.method, this.url, this.auth);
|
||||
this.status = res.status;
|
||||
this.responseText = JSON.stringify(res.body);
|
||||
this.onload?.();
|
||||
}
|
||||
}
|
||||
|
||||
const realXHR = globalThis.XMLHttpRequest;
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.XMLHttpRequest = realXHR;
|
||||
});
|
||||
|
||||
function apiWith(start: string) {
|
||||
let token = start;
|
||||
const replaced: string[] = [];
|
||||
const api = {
|
||||
absolute: (path: string) => `https://api${path}`,
|
||||
realtimeToken: async () => token,
|
||||
replaceRejectedToken: async (rejected: string) => {
|
||||
replaced.push(rejected);
|
||||
token = "new";
|
||||
return token;
|
||||
},
|
||||
} as unknown as ApiClient;
|
||||
return { api, replaced };
|
||||
}
|
||||
|
||||
describe("sendResumable", () => {
|
||||
it("refreshes and sends the same chunk again when the token expired", async () => {
|
||||
globalThis.XMLHttpRequest = FakeXHR as unknown as typeof XMLHttpRequest;
|
||||
const puts: string[] = [];
|
||||
FakeXHR.handler = (method, url, auth) => {
|
||||
if (method === "POST") return { status: 201, body: { id: "up-1", offset: 0, size: 8 } };
|
||||
puts.push(auth);
|
||||
if (auth === "Bearer old") return { status: 401, body: { error: "invalid_access_token" } };
|
||||
return { status: 201, body: { offset: 8, status: "ingested" } };
|
||||
};
|
||||
const { api, replaced } = apiWith("old");
|
||||
const file = new File([new Uint8Array(8)], "PSR.JPG", { type: "image/jpeg" });
|
||||
const res = await sendResumable(api, "org", file, "event", () => {});
|
||||
expect(res.status).toBe(201);
|
||||
expect(puts).toEqual(["Bearer old", "Bearer new"]);
|
||||
expect(replaced).toEqual(["old"]);
|
||||
});
|
||||
|
||||
it("does not retry a refusal that is not an expired token", async () => {
|
||||
globalThis.XMLHttpRequest = FakeXHR as unknown as typeof XMLHttpRequest;
|
||||
let puts = 0;
|
||||
FakeXHR.handler = (method) => {
|
||||
if (method === "POST") return { status: 201, body: { id: "up-1", offset: 0, size: 8 } };
|
||||
puts++;
|
||||
return { status: 415, body: { error: "unsupported_type" } };
|
||||
};
|
||||
const { api, replaced } = apiWith("old");
|
||||
const file = new File([new Uint8Array(8)], "PSR.JPG", { type: "image/jpeg" });
|
||||
const res = await sendResumable(api, "org", file, undefined, () => {});
|
||||
expect(res.status).toBe(415);
|
||||
expect(puts).toBe(1);
|
||||
expect(replaced).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
@@ -19,6 +19,8 @@ const ACCEPTED = /\.jpe?g$/i;
|
||||
|
||||
const CHUNK = 4 * 1024 * 1024;
|
||||
const RETRIES = 8;
|
||||
/** A chunk can wait this long behind other photos being read. Start it with a token that still outlasts that. */
|
||||
const CHUNK_TOKEN_SEC = 180;
|
||||
|
||||
function xhr(
|
||||
method: string,
|
||||
@@ -77,29 +79,34 @@ export async function sendResumable(
|
||||
origin?: DesktopOrigin,
|
||||
): Promise<{ status: number; body: unknown }> {
|
||||
const fingerprint = `${file.name}:${file.size}:${file.lastModified}`;
|
||||
const begin = await xhr(
|
||||
"POST",
|
||||
api.absolute(`/v1/orgs/${orgId}/uploads/resumable`),
|
||||
await api.realtimeToken(),
|
||||
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }),
|
||||
"application/json",
|
||||
);
|
||||
const beginBody = JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) });
|
||||
let failures = 0;
|
||||
let begin: { status: number; body: unknown };
|
||||
for (;;) {
|
||||
const token = await api.realtimeToken(CHUNK_TOKEN_SEC);
|
||||
begin = await xhr("POST", api.absolute(`/v1/orgs/${orgId}/uploads/resumable`), token, beginBody, "application/json");
|
||||
if (begin.status !== 401) break;
|
||||
if (++failures > RETRIES) return begin;
|
||||
await api.replaceRejectedToken(token);
|
||||
await sleep(Math.min(5_000, 400 * failures));
|
||||
}
|
||||
if (begin.status !== 200 && begin.status !== 201) return begin;
|
||||
// The server already has this photo (a preview of it, or the original): nothing to send.
|
||||
if ((begin.body as { status?: string }).status === "duplicate") return begin;
|
||||
const { id } = begin.body as { id: string };
|
||||
let offset = (begin.body as { offset: number }).offset;
|
||||
let failures = 0;
|
||||
/** The last bytes went out: the server may be busy filing the photo, or already done with it. */
|
||||
let sentAll = false;
|
||||
for (;;) {
|
||||
const end = Math.min(file.size, offset + CHUNK);
|
||||
const last = end >= file.size;
|
||||
let token = "";
|
||||
try {
|
||||
token = await api.realtimeToken(CHUNK_TOKEN_SEC);
|
||||
const res = await xhr(
|
||||
"PUT",
|
||||
api.absolute(`/v1/uploads/${id}?offset=${offset}`),
|
||||
await api.realtimeToken(),
|
||||
token,
|
||||
file.slice(offset, end),
|
||||
"application/offset+octet-stream",
|
||||
(loaded) => onProgress((offset + loaded) / file.size),
|
||||
@@ -108,6 +115,13 @@ export async function sendResumable(
|
||||
);
|
||||
// The upload is gone after all bytes went out earlier: the server filed the photo and our answer was lost.
|
||||
if (res.status === 404 && sentAll) return { status: 201, body: { status: "created" } };
|
||||
// Expired while this chunk waited to leave the computer. The server did not keep these bytes.
|
||||
if (res.status === 401) {
|
||||
if (++failures > RETRIES) return res;
|
||||
await api.replaceRejectedToken(token);
|
||||
await sleep(Math.min(5_000, 400 * failures));
|
||||
continue;
|
||||
}
|
||||
if (last) sentAll = true;
|
||||
if (res.status === 409) {
|
||||
offset = (res.body as { offset: number }).offset;
|
||||
@@ -120,10 +134,11 @@ export async function sendResumable(
|
||||
onProgress(offset / file.size);
|
||||
if (offset >= file.size) return res;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) throw err;
|
||||
if (++failures > RETRIES) throw err;
|
||||
await sleep(Math.min(30_000, 1000 * 2 ** failures));
|
||||
// Where did the server get to?
|
||||
const at = await xhr("GET", api.absolute(`/v1/uploads/${id}`), await api.realtimeToken(), null, "").catch(() => null);
|
||||
const at = await xhr("GET", api.absolute(`/v1/uploads/${id}`), await api.realtimeToken(CHUNK_TOKEN_SEC), null, "").catch(() => null);
|
||||
if (at?.status === 200) offset = (at.body as { offset: number }).offset;
|
||||
else if (at?.status === 404 && (sentAll || last)) return { status: 201, body: { status: "created" } };
|
||||
}
|
||||
|
||||
@@ -111,6 +111,10 @@ export function DevelopPage() {
|
||||
if (!orgId) return;
|
||||
let alive = true;
|
||||
void (async () => {
|
||||
const kept = scope ? await cache.photos(orgId, scope) : undefined;
|
||||
if (!alive) return;
|
||||
// The filmstrip (including photos still only on this computer) before the network answers.
|
||||
setAll(kept ?? []);
|
||||
const got: PhotoSummary[] = [];
|
||||
try {
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
|
||||
@@ -109,6 +109,10 @@ export function LibraryPage() {
|
||||
return;
|
||||
}
|
||||
prefs.set(`scope:${orgId}`, scope);
|
||||
// The folder as last seen here, and photos still only on this computer, before the network answers.
|
||||
const kept = await cache.photos(orgId, scope);
|
||||
if (kept?.length) dispatch({ type: "loaded", scope, photos: kept, done: false });
|
||||
dispatch({ type: "local", photos: localPhotos.list() });
|
||||
const all: PhotoSummary[] = [];
|
||||
try {
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
@@ -121,8 +125,8 @@ export function LibraryPage() {
|
||||
void cache.setPhotos(orgId, scope, all);
|
||||
} catch (err) {
|
||||
if (!isNetworkError(err)) throw err;
|
||||
// No network: the folder as last seen on this computer (plus what arrived here since).
|
||||
dispatch({ type: "loaded", scope, photos: (await cache.photos(orgId, scope)) ?? [], done: true });
|
||||
// No network: stay on the cache already shown. Mark the folder loaded so the empty state can appear.
|
||||
dispatch({ type: "loaded", scope, photos: [], done: true });
|
||||
}
|
||||
dispatch({ type: "local", photos: localPhotos.list() });
|
||||
},
|
||||
@@ -158,12 +162,32 @@ export function LibraryPage() {
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
let alive = true;
|
||||
void loadEvents().then((list) => {
|
||||
if (!alive || !list) return;
|
||||
let opened = false;
|
||||
let fresh = false;
|
||||
const choose = (list: { id: string; photoCount: number }[]) => {
|
||||
const remembered = prefs.get(`scope:${orgId}`);
|
||||
const scope = remembered && (remembered === "inbox" || list.some((e) => e.id === remembered)) ? remembered : (list.find((e) => e.photoCount > 0) ?? list[0])?.id;
|
||||
if (scope) void open(scope).catch(() => setError(t.unexpectedError));
|
||||
return remembered && (remembered === "inbox" || list.some((e) => e.id === remembered)) ? remembered : (list.find((e) => e.photoCount > 0) ?? list[0])?.id;
|
||||
};
|
||||
const go = (list: { id: string; photoCount: number }[]) => {
|
||||
if (!alive || opened) return;
|
||||
const scope = choose(list);
|
||||
if (!scope) return;
|
||||
opened = true;
|
||||
void open(scope).catch(() => setError(t.unexpectedError));
|
||||
};
|
||||
// The last event list, so a hanging request does not leave the library blank.
|
||||
void cache.events(orgId).then((kept) => {
|
||||
if (!alive || !kept || fresh) return;
|
||||
setEvents(kept.events);
|
||||
setInboxCount(kept.inboxCount);
|
||||
go(kept.events);
|
||||
});
|
||||
void loadEvents()
|
||||
.then((list) => {
|
||||
fresh = true;
|
||||
if (list) go(list);
|
||||
})
|
||||
.catch(() => setError(t.unexpectedError));
|
||||
if (canCull) api.listDeliveryTargets(orgId).then((r) => alive && setTargets(r.targets.filter((x) => !x.disabledAt)), () => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
|
||||
@@ -89,6 +89,46 @@ describe("ApiClient", () => {
|
||||
expect(lost).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function jwt(secondsFromNow: number): string {
|
||||
const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
|
||||
const payload = btoa(JSON.stringify({ exp })).replace(/\+/g, "-").replace(/\//g, "_");
|
||||
return `h.${payload}.s`;
|
||||
}
|
||||
|
||||
it("refreshes a token that would expire during an upload", async () => {
|
||||
const soon = jwt(500);
|
||||
const later = jwt(900);
|
||||
let refreshes = 0;
|
||||
const { fetch } = fakeFetch((url) => {
|
||||
if (!url.endsWith("/refresh")) return { status: 200, body: {} };
|
||||
refreshes++;
|
||||
return { status: 200, body: { accessToken: later, expiresIn: 900 } };
|
||||
});
|
||||
const api = new ApiClient({ baseUrl: "https://api", fetch, refreshStore: memoryStore("r") });
|
||||
(api as unknown as { accessToken: string }).accessToken = soon;
|
||||
expect(await api.realtimeToken()).toBe(soon);
|
||||
expect(await api.realtimeToken(600)).toBe(later);
|
||||
expect(refreshes).toBe(1);
|
||||
});
|
||||
|
||||
it("replaces a rejected token once for every caller that still holds it", async () => {
|
||||
const old = jwt(120);
|
||||
const next = jwt(900);
|
||||
let refreshes = 0;
|
||||
const { fetch } = fakeFetch((url) => {
|
||||
if (!url.endsWith("/refresh")) return { status: 200, body: {} };
|
||||
refreshes++;
|
||||
return { status: 200, body: { accessToken: next, expiresIn: 900 } };
|
||||
});
|
||||
const api = new ApiClient({ baseUrl: "https://api", fetch, refreshStore: memoryStore("r") });
|
||||
(api as unknown as { accessToken: string }).accessToken = old;
|
||||
const got = await Promise.all([api.replaceRejectedToken(old), api.replaceRejectedToken(old), api.replaceRejectedToken(old)]);
|
||||
expect(got).toEqual([next, next, next]);
|
||||
expect(refreshes).toBe(1);
|
||||
expect(await api.replaceRejectedToken(old)).toBe(next);
|
||||
expect(refreshes).toBe(1);
|
||||
});
|
||||
|
||||
it("maps device polling errors", async () => {
|
||||
const answers = ["authorization_pending", "slow_down", "access_denied", "expired_token"];
|
||||
const { fetch } = fakeFetch(() => ({ status: 400, body: { error: answers.shift() } }));
|
||||
|
||||
@@ -78,11 +78,22 @@ export class ApiClient {
|
||||
}
|
||||
|
||||
/**
|
||||
* An access token valid for at least another minute, for connections the client makes itself (realtime,
|
||||
* uploads with progress through XMLHttpRequest).
|
||||
* An access token valid for at least `minValidSeconds` (a minute, unless the caller says otherwise), for
|
||||
* connections the client makes itself (realtime, uploads with progress through XMLHttpRequest).
|
||||
* A chunk can sit in the webview while other photos are read from disk; the server rejects it once it expires.
|
||||
*/
|
||||
async realtimeToken(): Promise<string> {
|
||||
if ((!this.accessToken || expiresWithin(this.accessToken, 60)) && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null);
|
||||
async realtimeToken(minValidSeconds = 60): Promise<string> {
|
||||
if ((!this.accessToken || expiresWithin(this.accessToken, minValidSeconds)) && !(await this.refresh())) throw new ApiError(401, "not_signed_in", null);
|
||||
return this.accessToken as string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A new access token after a request that used `rejected` came back 401. Callers still holding that token share
|
||||
* one refresh, so several uploads failing together rotate the session once.
|
||||
*/
|
||||
async replaceRejectedToken(rejected: string): Promise<string> {
|
||||
if (this.accessToken && this.accessToken !== rejected && !expiresWithin(this.accessToken, 60)) return this.accessToken;
|
||||
if (!(await this.refresh())) throw new ApiError(401, "not_signed_in", null);
|
||||
return this.accessToken as string;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user