Compare commits

...
Author SHA1 Message Date
spark ae7f8eb6f9 Work offline: library from cache, local arrivals, queued changes (0.3.7)
ci / rust (push) Successful in 11m44s
ci / typescript (push) Successful in 13m59s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 18m44s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 33m41s
The desktop app opens and keeps working offline: events, photo lists, edit states, thumbnails and previews are kept on the computer; photos arriving by FTP show at once (filed by capture time) and can be culled, named and edited before upload; culling, IPTC and "send to" made offline wait in order and go when the server answers; uploads wait instead of failing. The autopilot never edits over a person's edit.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 18:34:30 +01:00
29 changed files with 1101 additions and 68 deletions

No files matched your search

+6 -1
View File
@@ -117,6 +117,10 @@ export class AutopilotService {
else if (angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand);
// Someone already edited it (on the desktop app without a network, before it was uploaded): their edit
// stands; the autopilot still scores the frame for its burst.
const human = await db.photoEdit.count({ where: { photoId, NOT: { clientId: "autopilot" } } });
if (human) ops.length = 0;
if (ops.length) {
await develop.append(photoId, photo.uploaderId ?? photo.event?.createdById ?? null, {
clientId: "autopilot",
@@ -176,7 +180,8 @@ export class AutopilotService {
}
// Variety: the second pick gets a slightly tighter frame than the first.
const second = best[1];
if (second?.rec?.crop && second.rec.subject && settings.crop) {
const secondEdited = second ? await db.photoEdit.count({ where: { photoId: second.id, NOT: { clientId: "autopilot" } } }) : 0;
if (second?.rec?.crop && second.rec.subject && settings.crop && !secondEdited) {
const rect = constrainRotated(tighter(second.rec.crop, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
await develop
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
+10
View File
@@ -181,6 +181,16 @@ describe("autopilot", () => {
expect(await autopilot.decideBursts(new Date(Date.now() + 40_000))).toBe(0);
});
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
const { orgId, userId, eventId } = await setup();
const photoId = await shot(orgId, userId, eventId, 0, 300);
await develop.append(photoId, userId, { clientId: "offline-queue", ops: [{ opId: "mine-1", command: { command: "develop.set", params: { values: { "light.exposure": -0.5 } } } }] });
await runQueue();
const edits = await ctx.db.photoEdit.findMany({ where: { photoId } });
expect(edits.map((e) => e.clientId)).toEqual(["offline-queue"]);
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE");
});
it("leaves events without autopilot alone", async () => {
const { orgId, userId, eventId } = await setup(false);
await shot(orgId, userId, eventId, 0, 100);
+29 -6
View File
@@ -1,7 +1,8 @@
import type { ApiClient, Me, Organization, Role } from "@photoreport/sdk";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { createApi } from "./api.js";
import { prefs } from "./platform.js";
import { isNetworkError } from "./offline/queue.js";
import { isDesktop, prefs } from "./platform.js";
type Status = "loading" | "signedOut" | "signedIn";
@@ -36,20 +37,41 @@ export function AuthProvider({ children, api: injected }: { children: ReactNode;
const next = await api.me();
setMe(next);
setStatus("signedIn");
// Desktop app: who is signed in, so the app opens without a network (the session itself is in the keychain).
if (isDesktop()) prefs.set("me", JSON.stringify(next));
}, [api]);
useEffect(() => {
let alive = true;
api
.resume()
.then(async (ok) => {
let retry: ReturnType<typeof setInterval> | undefined;
const start = () =>
api.resume().then(async (ok) => {
if (!alive) return;
if (ok) await reload();
else setStatus("signedOut");
})
.catch(() => alive && setStatus("signedOut"));
});
start().catch((err: unknown) => {
if (!alive) return;
// No network on the desktop app: carry on as the person last signed in here; the session is checked again
// once the server answers (a refused session still signs out then).
const kept = isDesktop() && isNetworkError(err) ? prefs.get("me") : null;
if (!kept) {
setStatus("signedOut");
return;
}
setMe(JSON.parse(kept) as Me);
setStatus("signedIn");
const again = () =>
void start().then(
() => clearInterval(retry),
() => {},
);
retry = setInterval(again, 20_000);
window.addEventListener("online", again, { once: true });
});
return () => {
alive = false;
clearInterval(retry);
};
}, [api, reload]);
@@ -72,6 +94,7 @@ export function AuthProvider({ children, api: injected }: { children: ReactNode;
completeDeviceSignIn: reload,
signOut: async () => {
await api.logout().catch(() => {});
prefs.set("me", "");
setMe(null);
setStatus("signedOut");
},
+43 -6
View File
@@ -19,6 +19,15 @@ export interface OutboxStore {
save(photoId: string, ops: PendingOp[]): void;
}
/** The last edit state seen per photo, so a photo opens in Revelar without a network (IndexedDB in the app). */
export interface StateStore {
get(photoId: string): Promise<{ settings: string; seq: number } | undefined>;
set(photoId: string, state: { settings: string; seq: number }): Promise<void> | void;
}
/** A photo still only on this computer (local FTP): edits wait for its upload (see offline/queue.ts). */
const isLocal = (photoId: string) => photoId.startsWith("local:");
export interface PendingOp {
opId: string;
command: EditCommand;
@@ -63,15 +72,32 @@ export class DevelopSession {
constructor(
readonly photoId: string,
private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined },
private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined; states?: StateStore | undefined; isOffline?: (err: unknown) => boolean },
) {}
async load(): Promise<void> {
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;
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;
}
}
this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? [];
this.loaded = true;
this.changed();
@@ -188,11 +214,13 @@ export class DevelopSession {
this.confirmedSeq = op.seq;
this.dropPending(op.opId);
}
this.remember();
this.changed();
}
/** Missed some ops (reconnect, a message lost): fetch everything after what we have, in order. */
async catchUp(): Promise<void> {
if (isLocal(this.photoId)) return;
const state = await this.deps.api.developState(this.photoId, this.confirmedSeq);
if (state.snapshot) {
// The server answered with a snapshot (we were too far behind): start over from it.
@@ -214,6 +242,11 @@ export class DevelopSession {
if (this.sending || this.closed) return;
const batch = this.pending.filter((p) => !p.sent).slice(0, 200);
if (!batch.length) return;
// A photo not uploaded yet: the edits stay in the outbox and follow it (offline/queue.ts).
if (isLocal(this.photoId)) {
this.persist();
return;
}
this.sending = true;
for (const op of batch) op.sent = true;
try {
@@ -253,6 +286,10 @@ export class DevelopSession {
if (i >= 0) this.pending.splice(i, 1);
}
private remember(): void {
if (!isLocal(this.photoId)) void this.deps.states?.set(this.photoId, { settings: this.base, seq: this.confirmedSeq });
}
private persist(): void {
this.deps.outbox?.save(
this.photoId,
+7
View File
@@ -34,6 +34,13 @@ export const t = {
soon: "Em breve",
events: "Eventos",
inbox: "Sem evento",
offline: {
label: "sem ligação",
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
},
moveToEvent: "Mover para evento",
movedToEvent: (n: number, name: string) => `${n} ${n === 1 ? "foto movida" : "fotos movidas"} para ${name}`,
newEvent: "Novo evento",
+14 -4
View File
@@ -1,6 +1,8 @@
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
import { memo, useEffect, useRef } from "react";
import { memo, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { useCachedImage } from "../offline/cache.js";
import { isDesktop } from "../platform.js";
export const LABEL_COLOR: Record<ColorLabel, string | null> = {
NONE: null,
@@ -27,6 +29,8 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
if (focused) ref.current?.scrollIntoView({ block: "nearest" });
}, [focused]);
const label = LABEL_COLOR[photo.colorLabel];
// Desktop app: thumbnails are kept on the computer, so the grid shows without a network.
const shown = useCachedImage(src, isDesktop());
return (
<button
ref={ref}
@@ -45,7 +49,7 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
</span>
<span className="flex min-h-0 w-full flex-1 items-center justify-center">
{photo.status === "READY" ? (
<img src={src} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
shown && <img src={shown} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
) : (
<span className="font-mono text-[10px] uppercase text-faint">{photo.status === "FAILED" ? "erro" : "…"}</span>
)}
@@ -111,11 +115,17 @@ export interface LoupeFace {
suggested: boolean;
}
export function Loupe({ photo, src, index, total, faces = [] }: { photo: PhotoSummary; src: string; index: number; total: number; faces?: LoupeFace[] }) {
export function Loupe({ photo, src, fallback, index, total, faces = [] }: { photo: PhotoSummary; src: string; fallback?: string; index: number; total: number; faces?: LoupeFace[] }) {
// Desktop app: previews seen once show again without a network; never seen, the thumbnail stands in.
const preview = useCachedImage(src, isDesktop());
const thumb = useCachedImage(fallback ?? null, isDesktop() && !!fallback);
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [src]);
const shown = (failed ? thumb : preview) ?? thumb ?? "";
return (
<section aria-label="Lupa" className="relative flex h-full min-h-[420px] items-center justify-center bg-[#121213] p-6">
<span className="relative inline-block max-h-full max-w-full">
<img src={src} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
<img src={shown} onError={() => setFailed(true)} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
{faces.map((f) => (
<span
key={f.id}
+3 -2
View File
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
import { ApiError, type ApiClient, type DeliveryTarget, type IptcIssue } from "@photoreport/sdk";
import { useEffect, useState } from "react";
import { t } from "../i18n.js";
import { deliver as deliverOrQueue } from "../offline/sync.js";
const dateTime = new Intl.DateTimeFormat("pt-PT", { dateStyle: "short", timeStyle: "medium", timeZone: "Europe/Lisbon" });
@@ -72,8 +73,8 @@ export function InfoPanel(props: {
setBusy(true);
setDeliveryNote(null);
try {
const r = await api.deliver(props.orgId, targetId, picks.map((p) => p.id));
setDeliveryNote(t.delivered(r.queued.length, r.skipped.length));
const r = await deliverOrQueue(api, props.orgId, targetId, picks.map((p) => p.id));
setDeliveryNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
} catch (err) {
setDeliveryNote(err instanceof ApiError ? err.code : t.unexpectedError);
} finally {
+4 -3
View File
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient, DeliveryTarget } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { deliver, setIptc } from "../offline/sync.js";
/** The fields of Photo Mechanic's Info window, in its order. Lists are comma separated. */
const FIELDS = [
@@ -72,10 +73,10 @@ export function IptcInfo(props: { api: ApiClient; orgId: string; photos: PhotoSu
set[f.id] = v === "" ? null : f.list ? v.split(",").map((x) => x.trim()).filter(Boolean) : v;
}
const ids = photos.map((p) => p.id);
if (Object.keys(set).length) await api.setPhotosIptc(props.orgId, ids, set);
if (Object.keys(set).length) await setIptc(api, props.orgId, ids, set);
if (send && targetId) {
const r = await api.deliver(props.orgId, targetId, ids);
setNote(t.delivered(r.queued.length, r.skipped.length));
const r = await deliver(api, props.orgId, targetId, ids);
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
setState("idle");
return;
}
+3
View File
@@ -3,6 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
import { describe, expect, it, vi } from "vitest";
import { type FtpStatus, type IncomingFile, type Invoke, useLocalFtp } from "./LocalFtp.js";
import type { UploadStatus } from "./uploads.js";
import { localPhotos } from "../offline/local.js";
const status = (running: boolean): FtpStatus => ({
running,
@@ -62,6 +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([]));
// 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" },
+28 -8
View File
@@ -1,4 +1,8 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { EventSummary } from "@photoreport/sdk";
import { cache } from "../offline/cache.js";
import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } from "../offline/local.js";
import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { asArrayBuffer, prefs } from "../platform.js";
@@ -50,7 +54,7 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/
const IN_FLIGHT = 6;
const POLL_MS = 1000;
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: DesktopOrigin) => void;
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => void;
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
@@ -74,7 +78,7 @@ const settingsError = (err: unknown): string => {
* a time, sends them to the target event and, once the server has each one, tells the shell to move the original
* into the event's work folder. Failed ones stay in the ingest folder and go again with "retry" (or next start).
*/
export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriInvoke) {
export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriInvoke, orgId = "") {
const [status, setStatus] = useState<FtpStatus | null>(null);
const [error, setError] = useState<string | null>(null);
/** An older desktop app without the FTP commands. */
@@ -105,22 +109,38 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
try {
// Working locally: a 2048 px preview with the original's metadata goes up, the original stays here.
const full = originalsRef.current;
const [bytes, original] = await Promise.all([
invoke<unknown>(full ? "ftp_read" : "ftp_preview", { path: f.path }).then(asArrayBuffer),
full ? Promise.resolve(undefined) : invoke<PreviewOf>("ftp_info", { path: f.path }),
]);
const [preview, info] = await Promise.all([invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer), invoke<PreviewOf>("ftp_info", { path: f.path })]);
// In the library at once (with or without a network), from the preview made here; the server's copy
// takes its place when the upload is done.
const capturedAt = lisbonInstant(exifDateTime(preview));
const eventId = to?.id ?? routeLocally((await cache.events(orgId))?.events ?? [], capturedAt);
if (!localPhotos.bySha(info.sha256)) {
let url = "";
try {
url = URL.createObjectURL(new Blob([preview], { type: "image/jpeg" }));
} catch {
/* no blob URLs here (tests): shown without a thumbnail */
}
localPhotos.put(localPhoto({ sha256: info.sha256, name: f.name, width: info.width, height: info.height, capturedAt, eventId, url }));
// 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 });
// A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload.
add([file], to?.id, (_file, result) => {
add([file], to?.id, (_file, result, photo) => {
inFlight.current--;
if (result === "done" || result === "duplicate") {
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
// Changes made to it meanwhile now go to the server's copy.
if (photo && orgId) offlineQueue(orgId).uploaded(info.sha256, photo.id);
} else {
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
}
localPhotos.remove(localId(info.sha256));
pump();
}, original ?? "original");
}, full ? "original" : info);
} catch {
inFlight.current--;
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
+4 -2
View File
@@ -3,6 +3,7 @@ import { ApiError, type ApiClient, type DeliveryTarget } from "@photoreport/sdk"
import { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { t } from "../i18n.js";
import { deliver } from "../offline/sync.js";
import { prefs } from "../platform.js";
const LAST_TARGET = "deliver.target";
@@ -38,10 +39,11 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
const send = async () => {
setBusy(true);
try {
const r = await api.deliver(orgId, targetId, photos.map((p) => p.id));
// Without a network (or photos still uploading) the request waits on this computer and goes when it can.
const r = await deliver(api, orgId, targetId, photos.map((p) => p.id));
prefs.set(LAST_TARGET, targetId);
props.onQueued(r.queued);
setNote(t.delivered(r.queued.length, r.skipped.length));
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
} catch (err) {
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
} finally {
+3 -1
View File
@@ -6,6 +6,7 @@ import { isDesktop, localOriginal } from "../platform.js";
import { useLocalFtp } from "./LocalFtp.js";
import { useLibraryLive } from "./realtime.js";
import { useUploadQueue } from "./uploads.js";
import { useOfflineSync } from "../offline/sync.js";
type Ingest = { uploads: ReturnType<typeof useUploadQueue>; localFtp: ReturnType<typeof useLocalFtp>; desktop: boolean };
@@ -27,7 +28,8 @@ export function IngestProvider({ children }: { children: ReactNode }) {
function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>["api"]; orgId: string; children: ReactNode }) {
const desktop = isDesktop();
const uploads = useUploadQueue(api, orgId);
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId);
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
useOfflineSync(api, orgId);
return (
<IngestContext.Provider value={{ uploads, localFtp, desktop }}>
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
+33 -1
View File
@@ -22,7 +22,9 @@ export type LibraryAction =
| { type: "patch"; ids: string[]; patch: PhotoPatch }
| { type: "select"; id: string; mode: "single" | "toggle" | "range"; visible: string[] }
| { type: "selectAll"; visible: string[] }
| { type: "move"; delta: number; visible: string[]; extend: boolean };
| { type: "move"; delta: number; visible: string[]; extend: boolean }
/** The photos still only on this computer (local FTP): those of this folder show, the others leave. */
| { type: "local"; photos: PhotoSummary[] };
const byCapture = (a: PhotoSummary, b: PhotoSummary) =>
(a.capturedAt ?? "￿").localeCompare(b.capturedAt ?? "￿") || a.originalName.localeCompare(b.originalName);
@@ -42,6 +44,20 @@ function inScope(scope: string | null, photo: PhotoSummary): boolean {
return scope === "inbox" ? photo.eventId === null : photo.eventId === scope;
}
/** The server's copy replaces a local photo: what was done to it here stays (it is being sent too). */
function replaceLocal(state: LibraryState, local: PhotoSummary, server: PhotoSummary): LibraryState {
const keep: Partial<PhotoSummary> = {
...(local.flag !== "NONE" && { flag: local.flag }),
...(local.rating && { rating: local.rating }),
...(local.colorLabel !== "NONE" && { colorLabel: local.colorLabel }),
...(local.players.length && { players: local.players }),
};
const merged = { ...server, ...keep };
const swap = (id: string | null) => (id === local.id ? server.id : id);
const photos = inScope(state.scope, merged) ? state.photos.map((p) => (p.id === local.id ? merged : p)).filter((p, i, all) => all.findIndex((q) => q.id === p.id) === i) : state.photos.filter((p) => p.id !== local.id);
return { ...state, photos, selected: new Set([...state.selected].map((id) => swap(id)!)), focus: swap(state.focus), anchor: swap(state.anchor), wanted: swap(state.wanted) };
}
export function libraryReducer(state: LibraryState, action: LibraryAction): LibraryState {
switch (action.type) {
case "load":
@@ -62,6 +78,9 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
case "message": {
const m = action.message;
if (m.type === "photo.added") {
// The server's copy of a photo shown from this computer: it takes the local one's place (and selection).
const local = state.photos.find((p) => p.id.startsWith("local:") && p.sha256 === m.photo.sha256);
if (local) return replaceLocal(state, local, m.photo);
if (!inScope(state.scope, m.photo) || state.photos.some((p) => p.id === m.photo.id)) return state;
return { ...state, photos: [...state.photos, m.photo].sort(byCapture) };
}
@@ -88,6 +107,19 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
if (action.patch.eventId !== undefined) photos = photos.filter((p) => inScope(state.scope, p));
return { ...state, photos };
}
case "local": {
const here = action.photos.filter((p) => inScope(state.scope, p) && !state.photos.some((q) => !q.id.startsWith("local:") && q.sha256 === p.sha256));
const ids = new Set(here.map((p) => p.id));
const kept = state.photos.filter((p) => !p.id.startsWith("local:") || ids.has(p.id));
const byId = new Map(here.map((p) => [p.id, p]));
const merged = kept.map((p) => byId.get(p.id) ?? p);
const added = here.filter((p) => !kept.some((q) => q.id === p.id));
if (!added.length && merged.length === state.photos.length && merged.every((p, i) => p === state.photos[i])) return state;
const photos = [...merged, ...added].sort(byCapture);
const gone = (id: string | null) => id !== null && id.startsWith("local:") && !ids.has(id);
const selected = new Set([...state.selected].filter((id) => !gone(id)));
return { ...state, photos, selected, focus: gone(state.focus) ? null : state.focus, anchor: gone(state.anchor) ? null : state.anchor };
}
case "select": {
const { id, mode, visible } = action;
// Picking a photo by hand wins over the one still being looked for.
+35 -9
View File
@@ -1,4 +1,6 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { isNetworkError } from "../offline/queue.js";
import { useCallback, useRef, useState } from "react";
export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed";
@@ -9,7 +11,7 @@ export interface UploadItem {
size: number;
status: UploadStatus;
progress: number;
error?: string;
error?: string | undefined;
}
const CONCURRENCY = 4;
@@ -134,21 +136,26 @@ export async function sendResumable(
*/
export function useUploadQueue(api: ApiClient, orgId: string) {
const [items, setItems] = useState<UploadItem[]>([]);
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus) => void }[]>([]);
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void }[]>([]);
const running = useRef(0);
/** No network: the queue waits (nothing fails) and carries on when the connection is back. */
const paused = useRef(false);
const resume = useRef<() => void>(() => {});
const update = useCallback((id: string, patch: Partial<UploadItem>) => {
setItems((list) => list.map((i) => (i.id === id ? { ...i, ...patch } : i)));
}, []);
const pump = useCallback(() => {
while (running.current < CONCURRENCY && queue.current.length) {
while (!paused.current && running.current < CONCURRENCY && queue.current.length) {
const next = queue.current.shift()!;
running.current++;
void (async () => {
const { item, file, eventId, original, onSettled } = next;
let final: UploadStatus = "failed";
update(item.id, { status: "uploading" });
let filed: PhotoSummary | undefined;
let waiting = false;
update(item.id, { status: "uploading", error: undefined });
try {
let lastTick = 0;
const res = await sendResumable(
@@ -166,26 +173,45 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
original,
);
// The server took the file but could not read it as a photo: not sent (FTP keeps the original in ingest).
const photo = (res.body as { photo?: { status?: string; error?: string | null } } | null)?.photo;
const photo = (res.body as { photo?: PhotoSummary } | null)?.photo;
if (photo?.status === "FAILED") res.body = { error: photo.error ? `processing_failed: ${photo.error}` : "processing_failed" };
else if (res.status === 201) final = "done";
else if (res.status === 200) final = "duplicate";
else if (res.status === 0 || res.status === 502 || res.status === 503 || res.status === 504) throw new Error("network");
if (photo && final !== "failed") filed = photo;
if (final === "failed") update(item.id, { status: "failed", error: (res.body as { error?: string } | null)?.error ?? `http_${res.status}` });
else update(item.id, { status: final, progress: 1 });
} catch (err) {
update(item.id, { status: "failed", error: (err as Error).message });
if (isNetworkError(err)) {
// No network (or the server is down): back to the front of the queue, which waits for the connection.
waiting = true;
update(item.id, { status: "queued", progress: 0, error: "offline" });
queue.current.unshift(next);
if (!paused.current) {
paused.current = true;
const again = () => {
window.removeEventListener("online", again);
clearTimeout(timer);
paused.current = false;
resume.current();
};
const timer = setTimeout(again, 15_000);
window.addEventListener("online", again);
}
} else update(item.id, { status: "failed", error: (err as Error).message });
} finally {
onSettled?.(final);
if (!waiting) onSettled?.(final, filed);
running.current--;
pump();
}
})();
}
}, [api, orgId, update]);
resume.current = pump;
const add = useCallback(
/** `onSettled` is called once per accepted file, after it is sent (or definitely failed). */
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: DesktopOrigin) => {
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => {
const added: UploadItem[] = [];
for (const file of files) {
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
@@ -195,7 +221,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
continue;
}
added.push(item);
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus) => onSettled(file, status) }) });
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }) });
}
setItems((list) => [...list.filter((i) => i.status !== "done" && i.status !== "duplicate"), ...added]);
pump();
+97
View File
@@ -0,0 +1,97 @@
import { useEffect, useState } from "react";
import type { PhotoSummary } from "@photoreport/contracts";
import type { EventSummary } from "@photoreport/sdk";
import { kv } from "./kv.js";
/**
* The last thing the server said, kept on this computer so the modules open without a network: the events, each
* folder's photos, the edit state of photos opened in Revelar, and the thumbnails and previews already seen.
*/
export interface CachedEvents {
events: EventSummary[];
inboxCount: number;
}
export const cache = {
events: (orgId: string) => kv.get<CachedEvents>(`events:${orgId}`),
setEvents: (orgId: string, v: CachedEvents) => kv.set(`events:${orgId}`, v),
photos: (orgId: string, scope: string) => kv.get<PhotoSummary[]>(`photos:${orgId}:${scope}`),
setPhotos: (orgId: string, scope: string, photos: PhotoSummary[]) => kv.set(`photos:${orgId}:${scope}`, photos.filter((p) => !p.id.startsWith("local:"))),
/** The edit state of a photo (settings JSON and the op-log position it stands for). */
develop: (photoId: string) => kv.get<{ settings: string; seq: number }>(`develop:${photoId}`),
setDevelop: (photoId: string, v: { settings: string; seq: number }) => kv.set(`develop:${photoId}`, v),
};
/** A stable key for an image URL: the path and the edit version (the signature and expiry change, the image doesn't). */
export function imageKey(url: string): string {
try {
const u = new URL(url, "http://x");
return `img:${u.pathname}@${u.searchParams.get("v") ?? "0"}`;
} catch {
return `img:${url}`;
}
}
/** A few downloads at a time: a grid of 500 thumbnails must not open 500 connections. */
const MAX_FETCHES = 6;
let active = 0;
const waiting: (() => void)[] = [];
async function slot<T>(fn: () => Promise<T>): Promise<T> {
if (active >= MAX_FETCHES) await new Promise<void>((r) => waiting.push(r));
active++;
try {
return await fn();
} finally {
active--;
waiting.shift()?.();
}
}
/**
* The image as a blob URL: from this computer when it was seen before, else downloaded once and kept. Null when it
* can't be had (offline and never seen). The caller revokes the URL when done.
*/
export async function cachedImage(url: string): Promise<string | null> {
if (url.startsWith("blob:") || url.startsWith("data:")) return url;
const key = imageKey(url);
const kept = await kv.get<Blob>(key);
if (kept) return URL.createObjectURL(kept);
try {
const blob = await slot(async () => {
const res = await fetch(url);
if (!res.ok) throw new Error(`http_${res.status}`);
return res.blob();
});
void kv.set(key, blob);
return URL.createObjectURL(blob);
} catch {
return null;
}
}
/**
* The image to show for `url`, through the cache on the desktop app (so it shows again without a network); in the
* browser, the URL itself.
*/
export function useCachedImage(url: string | null, enabled: boolean): string | null {
const [src, setSrc] = useState<string | null>(enabled ? null : url);
useEffect(() => {
if (!enabled || !url) {
setSrc(url);
return;
}
let alive = true;
let made: string | null = null;
void cachedImage(url).then((s) => {
if (s && s !== url && s.startsWith("blob:")) made = s;
if (alive) setSrc(s ?? url);
else if (made) URL.revokeObjectURL(made);
});
return () => {
alive = false;
if (made) URL.revokeObjectURL(made);
};
}, [url, enabled]);
return src;
}
+63
View File
@@ -0,0 +1,63 @@
/**
* A small key-value store on IndexedDB, for what the app keeps to work without a network (photo lists, thumbnails,
* edit states). Where IndexedDB is missing or refuses (tests, private windows) it falls back to memory: the app
* still works, it just doesn't keep anything across restarts.
*/
const DB = "photoreport-offline";
const STORE = "kv";
let opening: Promise<IDBDatabase | null> | null = null;
const memory = new Map<string, unknown>();
function open(): Promise<IDBDatabase | null> {
opening ??= new Promise((resolve) => {
try {
if (typeof indexedDB === "undefined") return resolve(null);
const req = indexedDB.open(DB, 1);
req.onupgradeneeded = () => req.result.createObjectStore(STORE);
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(null);
req.onblocked = () => resolve(null);
} catch {
resolve(null);
}
});
return opening;
}
function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T | undefined> {
return open().then(
(db) =>
new Promise<T | undefined>((resolve) => {
if (!db) return resolve(undefined);
try {
const req = fn(db.transaction(STORE, mode).objectStore(STORE));
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(undefined);
} catch {
resolve(undefined);
}
}),
);
}
export const kv = {
async get<T>(key: string): Promise<T | undefined> {
const db = await open();
if (!db) return memory.get(key) as T | undefined;
return (await run<T>("readonly", (s) => s.get(key) as IDBRequest<T>)) ?? undefined;
},
async set(key: string, value: unknown): Promise<void> {
const db = await open();
if (!db) {
memory.set(key, value);
return;
}
await run("readwrite", (s) => s.put(value, key));
},
async del(key: string): Promise<void> {
memory.delete(key);
await run("readwrite", (s) => s.delete(key));
},
};
+167
View File
@@ -0,0 +1,167 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { EventSummary } from "@photoreport/sdk";
import { localId } from "./queue.js";
/**
* Photos that arrived on this computer (local FTP) and are not on the server yet: they show in the library at once,
* from a preview made here, and can be culled, named and edited like any other. When the upload finishes the
* server's copy takes their place (with what was done to them meanwhile).
*/
/** The capture time in a JPEG's EXIF (DateTimeOriginal, else DateTime), as written by the camera (local wall time). */
export function exifDateTime(bytes: ArrayBuffer): string | null {
const v = new DataView(bytes);
if (v.byteLength < 4 || v.getUint16(0) !== 0xffd8) return null;
let off = 2;
while (off + 4 <= v.byteLength) {
const marker = v.getUint16(off);
const size = v.getUint16(off + 2);
if (marker === 0xffe1 && off + 10 <= v.byteLength && v.getUint32(off + 4) === 0x45786966) return readTiff(v, off + 10, off + 2 + size);
if ((marker & 0xff00) !== 0xff00 || marker === 0xffda) return null;
off += 2 + size;
}
return null;
}
function readTiff(v: DataView, start: number, end: number): string | null {
if (start + 8 > end) return null;
const little = v.getUint16(start) === 0x4949;
const u16 = (o: number) => v.getUint16(start + o, little);
const u32 = (o: number) => v.getUint32(start + o, little);
const ascii = (o: number, n: number) => {
let s = "";
for (let i = 0; i < n && start + o + i < end; i++) {
const c = v.getUint8(start + o + i);
if (!c) break;
s += String.fromCharCode(c);
}
return s;
};
const entries = (ifd: number) => {
const out = new Map<number, number>();
if (ifd <= 0 || start + ifd + 2 > end) return out;
const n = u16(ifd);
for (let i = 0; i < n; i++) {
const e = ifd + 2 + i * 12;
if (start + e + 12 > end) break;
out.set(u16(e), e);
}
return out;
};
const text = (entry: number | undefined) => {
if (entry === undefined) return null;
const count = u32(entry + 4);
return ascii(count <= 4 ? entry + 8 : u32(entry + 8), count);
};
const ifd0 = entries(u32(4));
const exifAt = ifd0.get(0x8769);
const exif = exifAt !== undefined ? entries(u32(exifAt + 8)) : new Map<number, number>();
return text(exif.get(0x9003)) ?? text(ifd0.get(0x0132));
}
/** "2026:10:09 20:26:47" (Lisbon wall time, as the API reads it) to an ISO instant. */
export function lisbonInstant(exif: string | null): string | null {
const m = exif?.match(/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
if (!m) return null;
const [y, mo, d, h, mi, s] = m.slice(1).map(Number) as [number, number, number, number, number, number];
if (!y) return null;
const guess = Date.UTC(y, mo - 1, d, h, mi, s);
// Lisbon's offset at that moment (summer +1, winter 0).
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: "Europe/Lisbon", hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(new Date(guess));
const get = (t: string) => Number(parts.find((p) => p.type === t)?.value);
const asLisbon = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour") % 24, get("minute"), get("second"));
return new Date(guess - (asLisbon - guess)).toISOString();
}
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
export function routeLocally(events: Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">[], at: string | null): string | null {
if (!at) return null;
const t = Date.parse(at);
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
open.sort((a, b) => Date.parse(b.startsAt) - Date.parse(a.startsAt));
return open[0]?.id ?? null;
}
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
return {
id: localId(p.sha256),
eventId: p.eventId,
originalName: p.name,
name: p.name,
sha256: p.sha256,
originalStored: false,
status: "READY",
delivery: "NONE",
width: p.width,
height: p.height,
capturedAt: p.capturedAt,
cameraModel: null,
lens: null,
focalLength: null,
aperture: null,
exposureTime: null,
iso: null,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: p.url, preview: p.url, source: p.url },
};
}
type Listener = () => void;
/** The photos waiting here, shared by the modules (the library shows them, the FTP feed adds and removes them). */
class LocalPhotos {
private photos = new Map<string, PhotoSummary>();
private listeners = new Set<Listener>();
/** Bumped on every change, for React's useSyncExternalStore. */
version = 0;
list(): PhotoSummary[] {
return [...this.photos.values()];
}
get(id: string): PhotoSummary | undefined {
return this.photos.get(id);
}
bySha(sha256: string): PhotoSummary | undefined {
return this.photos.get(localId(sha256));
}
put(photo: PhotoSummary): void {
this.photos.set(photo.id, photo);
this.changed();
}
/** Culling and naming done to a photo still here: kept so it goes up with the photo. */
patch(id: string, change: Partial<PhotoSummary>): void {
const p = this.photos.get(id);
if (!p) return;
this.photos.set(id, { ...p, ...change });
this.changed();
}
remove(id: string): void {
const p = this.photos.get(id);
if (!p) return;
this.photos.delete(id);
if (p.urls.thumb.startsWith("blob:")) setTimeout(() => URL.revokeObjectURL(p.urls.thumb), 60_000);
this.changed();
}
subscribe(fn: Listener): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
private changed(): void {
this.version++;
for (const fn of this.listeners) fn();
}
}
export const localPhotos = new LocalPhotos();
+139
View File
@@ -0,0 +1,139 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { ApiError, type ApiClient } from "@photoreport/sdk";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { initialLibrary, libraryReducer } from "../library/store.js";
import { exifDateTime, lisbonInstant, localPhoto, routeLocally } from "./local.js";
import { isNetworkError, localId, OfflineQueue } from "./queue.js";
function memoryStore() {
const m = new Map<string, string>();
return {
get: (k: string) => m.get(k) ?? null,
set: (k: string, v: string) => void m.set(k, v),
remove: (k: string) => void m.delete(k),
keys: () => [...m.keys()],
m,
};
}
const offline = () => new TypeError("Failed to fetch");
describe("offline queue", () => {
let store: ReturnType<typeof memoryStore>;
beforeEach(() => (store = memoryStore()));
it("tells a missing network from a refusal", () => {
expect(isNetworkError(offline())).toBe(true);
expect(isNetworkError(new ApiError(503, "down", null))).toBe(true);
expect(isNetworkError(new ApiError(403, "forbidden", null))).toBe(false);
});
it("keeps changes across restarts and sends them in order when the server answers", async () => {
const q = new OfflineQueue("o1", store);
q.add({ kind: "patch", ids: ["p1"], patch: { flag: "PICK" } });
q.add({ kind: "deliver", targetId: "t1", ids: ["p1"], again: false });
// Restarted: the same queue comes back from disk.
const again = new OfflineQueue("o1", store);
expect(again.size).toBe(2);
const calls: string[] = [];
let online = false;
const api = {
updatePhotos: vi.fn(async () => {
if (!online) throw offline();
calls.push("patch");
return { updated: 1 };
}),
deliver: vi.fn(async () => {
calls.push("deliver");
return { queued: [], skipped: [] };
}),
} as unknown as ApiClient;
await again.flush(api);
expect(again.size).toBe(2); // still no network: nothing lost, nothing out of order
online = true;
await again.flush(api);
expect(calls).toEqual(["patch", "deliver"]);
expect(again.size).toBe(0);
});
it("holds the changes of a photo still on this computer until it is uploaded, then sends them to its server copy", async () => {
const q = new OfflineQueue("o1", store);
const local = localId("abc");
q.add({ kind: "patch", ids: [local], patch: { rating: 4 } });
q.add({ kind: "patch", ids: ["p2"], patch: { flag: "REJECT" } });
store.set(`pr:outbox:${local}`, JSON.stringify([{ opId: "o-1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }]));
const sent: { ids: string[] }[] = [];
const edits: string[] = [];
const api = {
updatePhotos: vi.fn(async (_o: string, ids: string[]) => {
sent.push({ ids });
return { updated: ids.length };
}),
postEdits: vi.fn(async (photoId: string) => {
edits.push(photoId);
return { developSeq: 1, ops: [] };
}),
} as unknown as ApiClient;
await q.flush(api);
// The other photo's change goes; the local one waits (with its edits).
expect(sent).toEqual([{ ids: ["p2"] }]);
expect(edits).toEqual([]);
q.uploaded("abc", "server-1");
await q.flush(api);
expect(sent).toEqual([{ ids: ["p2"] }, { ids: ["server-1"] }]);
expect(edits).toEqual(["server-1"]);
expect(q.size).toBe(0);
});
it("drops what the server refuses for good", async () => {
const q = new OfflineQueue("o1", store);
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
const api = { updatePhotos: vi.fn(async () => Promise.reject(new ApiError(404, "photo_not_found", null))) } as unknown as ApiClient;
await q.flush(api);
expect(q.size).toBe(0);
});
});
/** A minimal JPEG with an EXIF DateTimeOriginal (big-endian TIFF). */
function jpegWithDate(date: string): ArrayBuffer {
const enc = new TextEncoder().encode(`${date}\0`);
const tiff: number[] = [0x4d, 0x4d, 0, 42, 0, 0, 0, 8];
// IFD0: one entry, ExifIFD pointer -> 26
tiff.push(0, 1, 0x87, 0x69, 0, 4, 0, 0, 0, 1, 0, 0, 0, 26, 0, 0, 0, 0);
// Exif IFD at 26: one entry, DateTimeOriginal ASCII count 20 at offset 44
tiff.push(0, 1, 0x90, 0x03, 0, 2, 0, 0, 0, enc.length, 0, 0, 0, 44, 0, 0, 0, 0);
tiff.push(...enc);
const app1 = [0x45, 0x78, 0x69, 0x66, 0, 0, ...tiff];
const size = app1.length + 2;
return new Uint8Array([0xff, 0xd8, 0xff, 0xe1, size >> 8, size & 0xff, ...app1, 0xff, 0xd9]).buffer;
}
describe("photos arriving on this computer", () => {
it("reads the capture time and files it in the event of that time, as the server would", () => {
const at = lisbonInstant(exifDateTime(jpegWithDate("2026:10:09 20:26:47")));
expect(at).toBe("2026-10-09T19:26:47.000Z"); // Lisbon summer time
expect(lisbonInstant("2026:12:05 21:14:07")).toBe("2026-12-05T21:14:07.000Z");
const events = [
{ id: "braga", startsAt: "2026-10-09T19:15:00Z", ingestFrom: "2026-10-09T17:15:00Z", ingestUntil: "2026-10-09T23:15:00Z", archivedAt: null },
{ id: "other", startsAt: "2026-10-10T15:00:00Z", ingestFrom: "2026-10-10T13:00:00Z", ingestUntil: "2026-10-10T19:00:00Z", archivedAt: null },
];
expect(routeLocally(events, at)).toBe("braga");
expect(routeLocally(events, "2026-09-03T15:00:00Z")).toBeNull();
});
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
const local = { ...localPhoto({ sha256: "abc", name: "PSR1.JPG", width: 6000, height: 4000, capturedAt: "2026-10-09T19:26:47Z", eventId: "e1", url: "blob:x" }), flag: "PICK" as const, rating: 3 };
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [], done: true });
s = libraryReducer(s, { type: "local", photos: [local] });
expect(s.photos.map((p) => p.id)).toEqual([localId("abc")]);
s = libraryReducer(s, { type: "select", id: localId("abc"), mode: "single", visible: [localId("abc")] });
const server = { ...local, id: "server-1", urls: { thumb: "/t", preview: "/p", source: "/s" }, flag: "NONE" as const, rating: 0 } as PhotoSummary;
s = libraryReducer(s, { type: "message", message: { type: "photo.added", photo: server } });
expect(s.photos.map((p) => [p.id, p.flag, p.rating])).toEqual([["server-1", "PICK", 3]]);
expect([...s.selected]).toEqual(["server-1"]);
// The local store then lets it go: nothing changes.
expect(libraryReducer(s, { type: "local", photos: [] }).photos.map((p) => p.id)).toEqual(["server-1"]);
});
});
+224
View File
@@ -0,0 +1,224 @@
import type { PhotoPatch } from "@photoreport/contracts";
import { ApiError, type ApiClient } from "@photoreport/sdk";
/**
* Working without a network: what the photographer does while the server can't be reached (culling, players,
* IPTC, "send to") is kept on this computer, in order, and sent when the connection comes back. Photos that only
* exist here yet (arrived by FTP while offline) have a local id, `local:<sha256>`; their changes wait until the photo
* is on the server and its id is known.
*/
export type QueuedOp =
| { id: string; kind: "patch"; ids: string[]; patch: PhotoPatch }
| { id: string; kind: "iptc"; ids: string[]; set: Record<string, string | string[] | null> }
| { id: string; kind: "deliver"; targetId: string; ids: string[]; again: boolean };
export type NewOp = QueuedOp extends infer O ? (O extends QueuedOp ? Omit<O, "id"> : never) : never;
const LOCAL = "local:";
export const isLocalId = (id: string) => id.startsWith(LOCAL);
export const localId = (sha256: string) => `${LOCAL}${sha256}`;
/** The server could not be reached (or is down): worth trying again later, unlike a refusal. */
export function isNetworkError(err: unknown): boolean {
if (err instanceof ApiError) return err.status === 0 || err.status === 502 || err.status === 503 || err.status === 504;
return err instanceof TypeError || (err instanceof Error && /network|fetch|timeout|offline|load failed/i.test(err.message));
}
type Store = { get(key: string): string | null; set(key: string, value: string): void; remove(key: string): void; keys(): string[] };
const browserStore: Store = {
get: (k) => {
try {
return window.localStorage.getItem(k);
} catch {
return null;
}
},
set: (k, v) => {
try {
window.localStorage.setItem(k, v);
} catch {
/* full or unavailable: kept in memory by the caller */
}
},
remove: (k) => {
try {
window.localStorage.removeItem(k);
} catch {
/* ignore */
}
},
keys: () => {
try {
return Object.keys(window.localStorage);
} catch {
return [];
}
},
};
/** The develop outbox of one photo (see develop/session.ts `localOutbox`). */
const OUTBOX = "pr:outbox:";
export class OfflineQueue {
private ops: QueuedOp[];
private listeners = new Set<() => void>();
private running: Promise<void> | null = null;
constructor(
readonly orgId: string,
private readonly store: Store = browserStore,
) {
this.ops = this.read();
}
private key = () => `pr.queue.${this.orgId}`;
private mapKey = () => `pr.localmap`;
private read(): QueuedOp[] {
try {
const v = JSON.parse(this.store.get(this.key()) ?? "[]") as QueuedOp[];
return Array.isArray(v) ? v : [];
} catch {
return [];
}
}
private save(): void {
if (this.ops.length) this.store.set(this.key(), JSON.stringify(this.ops));
else this.store.remove(this.key());
for (const fn of this.listeners) fn();
}
subscribe(fn: () => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
/** Changes waiting for the server (develop edits of photos not open count too). */
get size(): number {
return this.ops.length + this.outboxKeys().length;
}
get pending(): readonly QueuedOp[] {
return this.ops;
}
add(op: NewOp): void {
this.ops.push({ ...op, id: crypto.randomUUID() } as QueuedOp);
this.save();
}
/** The server id of a photo first seen here, once it is uploaded. */
serverId(id: string): string | null {
if (!isLocalId(id)) return id;
try {
const map = JSON.parse(this.store.get(this.mapKey()) ?? "{}") as Record<string, string>;
return map[id.slice(LOCAL.length)] ?? null;
} catch {
return null;
}
}
/** A photo first seen here is now on the server: its waiting changes (and develop edits) can go. */
uploaded(sha256: string, id: string): void {
let map: Record<string, string> = {};
try {
map = JSON.parse(this.store.get(this.mapKey()) ?? "{}") as Record<string, string>;
} catch {
/* start over */
}
map[sha256] = id;
// Only the recent ones are needed (photos are uploaded within hours).
const entries = Object.entries(map).slice(-5000);
this.store.set(this.mapKey(), JSON.stringify(Object.fromEntries(entries)));
const outbox = this.store.get(`${OUTBOX}${localId(sha256)}`);
if (outbox) {
const existing = this.store.get(`${OUTBOX}${id}`);
const merged = [...(existing ? (JSON.parse(existing) as unknown[]) : []), ...(JSON.parse(outbox) as unknown[])];
this.store.set(`${OUTBOX}${id}`, JSON.stringify(merged));
this.store.remove(`${OUTBOX}${localId(sha256)}`);
}
this.save();
}
private outboxKeys(): string[] {
return this.store.keys().filter((k) => k.startsWith(OUTBOX));
}
/**
* Sends what is waiting, in order. Stops at the first network failure (tries again later); drops what the server
* refuses for good. Changes to a photo not uploaded yet wait, and so do later changes to that photo.
*/
flush(api: ApiClient): Promise<void> {
this.running ??= this.doFlush(api).finally(() => {
this.running = null;
});
return this.running;
}
private async doFlush(api: ApiClient): Promise<void> {
const blocked = new Set<string>();
for (const op of [...this.ops]) {
const ids = op.ids.map((id) => this.serverId(id));
if (ids.some((id) => id === null) || op.ids.some((id) => blocked.has(id))) {
for (const id of op.ids) blocked.add(id);
continue;
}
const resolved = ids as string[];
try {
if (op.kind === "patch") await api.updatePhotos(this.orgId, resolved, op.patch);
else if (op.kind === "iptc") await api.setPhotosIptc(this.orgId, resolved, op.set);
else await api.deliver(this.orgId, op.targetId, resolved, op.again);
} catch (err) {
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
// Refused for good (photo deleted, no permission): nothing to retry.
}
this.ops = this.ops.filter((o) => o.id !== op.id);
this.save();
}
await this.flushOutboxes(api);
}
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
private async flushOutboxes(api: ApiClient): Promise<void> {
for (const key of this.outboxKeys()) {
const photoId = key.slice(OUTBOX.length);
if (isLocalId(photoId)) {
// Edited in Revelar before (and after) the upload: those edits follow the photo.
const id = this.serverId(photoId);
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
continue;
}
let ops: { opId: string; command: unknown }[];
try {
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
} catch {
this.store.remove(key);
continue;
}
if (!ops.length) {
this.store.remove(key);
continue;
}
try {
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
} catch (err) {
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
}
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
}
for (const fn of this.listeners) fn();
}
}
const queues = new Map<string, OfflineQueue>();
/** One queue per organization, shared by the modules. */
export function offlineQueue(orgId: string): OfflineQueue {
let q = queues.get(orgId);
if (!q) queues.set(orgId, (q = new OfflineQueue(orgId)));
return q;
}
+82
View File
@@ -0,0 +1,82 @@
import type { PhotoPatch } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useEffect, useSyncExternalStore } from "react";
import { localPhotos } from "./local.js";
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
/** How often waiting changes are tried while there are some (and whenever the system says the network is back). */
const EVERY_MS = 10_000;
/** Sends the changes kept while offline, in the background, for as long as the organization is open. */
export function useOfflineSync(api: ApiClient, orgId: string): void {
useEffect(() => {
if (!orgId) return;
const queue = offlineQueue(orgId);
const tick = () => {
if (queue.size) void queue.flush(api).catch(() => {});
};
tick();
const timer = setInterval(tick, EVERY_MS);
window.addEventListener("online", tick);
return () => {
clearInterval(timer);
window.removeEventListener("online", tick);
};
}, [api, orgId]);
}
/** How many changes are waiting for the server (for the "N à espera de ligação" note). */
export function useQueueSize(orgId: string): number {
const queue = orgId ? offlineQueue(orgId) : null;
return useSyncExternalStore(
(fn) => queue?.subscribe(fn) ?? (() => {}),
() => queue?.size ?? 0,
() => 0,
);
}
async function attempt(queue: OfflineQueue, ids: string[], send: (ids: string[]) => Promise<unknown>, keep: () => void): Promise<"sent" | "queued"> {
// Photos still only on this computer: their changes go up with them.
if (ids.some(isLocalId)) {
keep();
return "queued";
}
try {
await send(ids);
return "sent";
} catch (err) {
if (!isNetworkError(err)) throw err;
keep();
return "queued";
}
}
/**
* Culling, players and labels: sent now when the server answers, otherwise kept and sent when it does. Photos not
* uploaded yet also keep the change on their local copy (it shows, and goes up with them).
*/
export function patchPhotos(api: ApiClient, orgId: string, ids: string[], patch: PhotoPatch): Promise<"sent" | "queued"> {
for (const id of ids) if (isLocalId(id)) localPhotos.patch(id, patch as Record<string, unknown>);
const queue = offlineQueue(orgId);
return attempt(queue, ids, (x) => api.updatePhotos(orgId, x, patch), () => queue.add({ kind: "patch", ids, patch }));
}
export function setIptc(api: ApiClient, orgId: string, ids: string[], set: Record<string, string | string[] | null>): Promise<"sent" | "queued"> {
const queue = offlineQueue(orgId);
return attempt(queue, ids, (x) => api.setPhotosIptc(orgId, x, set), () => queue.add({ kind: "iptc", ids, set }));
}
/** "Send to": with no network (or photos still uploading) the request waits here and goes when it can. */
export async function deliver(api: ApiClient, orgId: string, targetId: string, ids: string[], again = false) {
const queue = offlineQueue(orgId);
let answer: Awaited<ReturnType<ApiClient["deliver"]>> | null = null;
const result = await attempt(
queue,
ids,
async (x) => {
answer = await api.deliver(orgId, targetId, x, again);
},
() => queue.add({ kind: "deliver", targetId, ids, again }),
);
return result === "sent" && answer ? { ...(answer as Awaited<ReturnType<ApiClient["deliver"]>>), waiting: false } : { queued: [], skipped: [], waiting: true };
}
+27 -8
View File
@@ -9,6 +9,10 @@ import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/sessi
import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
import { IptcInfo } from "../library/IptcInfo.js";
import { activePhoto, savedFilter, setActivePhoto } from "../library/active.js";
import { cache } from "../offline/cache.js";
import { localPhotos } from "../offline/local.js";
import { isNetworkError } from "../offline/queue.js";
import { patchPhotos } from "../offline/sync.js";
import { applyPatch, type LibraryFilter, matchesFilter, patchForKey } from "../library/store.js";
import { t } from "../i18n.js";
import { useLibraryLive } from "../library/realtime.js";
@@ -109,23 +113,37 @@ export function DevelopPage() {
setAll([...got]);
if (offset + page.photos.length >= page.total || page.photos.length === 0) break;
}
} catch {
if (alive) setAll((a) => a ?? []);
if (scope) void cache.setPhotos(orgId, scope, got);
} catch (err) {
// No network: the folder as last seen on this computer.
const kept = isNetworkError(err) && scope ? await cache.photos(orgId, scope) : undefined;
if (alive) setAll((a) => (a && a.length ? a : (kept ?? [])));
}
})();
return () => {
alive = false;
};
}, [api, orgId, scope]);
// Photos still only on this computer (local FTP) are in the filmstrip too, and can be edited already.
const localVersion = useSyncExternalStore(
(fn) => localPhotos.subscribe(fn),
() => localPhotos.version,
() => 0,
);
const withLocal = useMemo(() => {
if (!all) return null;
const here = localPhotos.list().filter((p) => (scope === "inbox" ? p.eventId === null : p.eventId === scope) && !all.some((q) => q.sha256 === p.sha256));
return here.length ? [...all, ...here].sort((a, b) => (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "")) : all;
}, [all, localVersion, scope]); // eslint-disable-line react-hooks/exhaustive-deps
// The filmstrip follows the library's filter, like Lightroom's (the open photo stays even if it doesn't match).
const filterJson = JSON.stringify(savedFilter(orgId));
const filter = useMemo(() => JSON.parse(filterJson) as LibraryFilter, [filterJson]);
useEffect(() => {
if (!all) return;
const ready = all.filter((p) => p.status === "READY");
if (!withLocal) return;
const ready = withLocal.filter((p) => p.status === "READY");
const shown = ready.filter((p) => matchesFilter(p, filter) || p.id === photoId);
setPhotos(shown.length ? shown : ready);
}, [all, filter]); // eslint-disable-line react-hooks/exhaustive-deps
}, [withLocal, filter]); // eslint-disable-line react-hooks/exhaustive-deps
const current = photos.find((p) => p.id === photoId) ?? null;
// Opened from the module link (no photo in the address): the active photo, the one you were on.
@@ -139,11 +157,11 @@ export function DevelopPage() {
if (current) setActivePhoto(orgId, scope, current.id);
}, [orgId, scope, current?.id]); // eslint-disable-line react-hooks/exhaustive-deps
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id);
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id || current.id.startsWith("local:"));
useEffect(() => {
if (!current || typeof engine !== "object") return;
const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox });
const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox, states: { get: cache.develop, set: cache.setDevelop }, isOffline: isNetworkError });
setSession(s);
setSourceSize(null);
setCropping(false);
@@ -188,7 +206,8 @@ export function DevelopPage() {
const patch = { ...change };
if (patch.colorLabel && current.colorLabel === patch.colorLabel) patch.colorLabel = "NONE";
setPhotos((list) => list.map((p) => (p.id === current.id ? applyPatch(p, patch) : p)));
api.updatePhotos(orgId, [current.id], patch).catch(() => {
// Without a network the change is kept here and sent when the connection is back.
patchPhotos(api, orgId, [current.id], patch).catch(() => {
setNote(t.unexpectedError);
setPhotos((list) => list.map((p) => (p.id === current.id ? current : p)));
});
+49 -10
View File
@@ -1,6 +1,6 @@
import type { GallerySummary, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
import { useCallback, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
import { useLocation, useNavigate } from "react-router";
import { useAuth } from "../auth.js";
import { pasteCommand } from "./DevelopPage.js";
@@ -17,6 +17,10 @@ import { LocalFtpButton } from "../library/LocalFtp.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
import { cache, type CachedEvents } from "../offline/cache.js";
import { localPhotos } from "../offline/local.js";
import { isNetworkError } from "../offline/queue.js";
import { patchPhotos, useQueueSize } from "../offline/sync.js";
import { FilterBar } from "../library/FilterBar.js";
import { SendButton } from "../library/SendButton.js";
import { prefs } from "../platform.js";
@@ -60,7 +64,16 @@ export function LibraryPage() {
const loadEvents = useCallback(async () => {
if (!orgId) return;
const r = await api.listEvents(orgId);
let r: CachedEvents;
try {
r = await api.listEvents(orgId);
void cache.setEvents(orgId, r);
} catch (err) {
// No network: the events as last seen here.
const kept = isNetworkError(err) ? await cache.events(orgId) : undefined;
if (!kept) throw err;
r = kept;
}
setEvents(r.events);
setInboxCount(r.inboxCount);
return r.events;
@@ -81,12 +94,22 @@ export function LibraryPage() {
return;
}
prefs.set(`scope:${orgId}`, scope);
for (let offset = 0; ; offset += PAGE) {
const page = await api.listPhotos(orgId, { event: scope, offset, limit: PAGE });
const done = offset + page.photos.length >= page.total || page.photos.length === 0;
dispatch({ type: "loaded", scope, photos: page.photos, done });
if (done) break;
const all: PhotoSummary[] = [];
try {
for (let offset = 0; ; offset += PAGE) {
const page = await api.listPhotos(orgId, { event: scope, offset, limit: PAGE });
const done = offset + page.photos.length >= page.total || page.photos.length === 0;
all.push(...page.photos);
dispatch({ type: "loaded", scope, photos: page.photos, done });
if (done) break;
}
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 });
}
dispatch({ type: "local", photos: localPhotos.list() });
},
[api, orgId],
);
@@ -135,6 +158,16 @@ export function LibraryPage() {
[dispatch, onMoved],
);
const live = useLibraryLive(api, onMessage);
// Photos still only on this computer (local FTP) join the folder they belong to.
const localVersion = useSyncExternalStore(
(fn) => localPhotos.subscribe(fn),
() => localPhotos.version,
() => 0,
);
useEffect(() => {
dispatch({ type: "local", photos: localPhotos.list() });
}, [localVersion]);
const waitingChanges = useQueueSize(orgId);
const { uploads, localFtp, desktop } = useIngest();
const fileInput = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
@@ -156,7 +189,8 @@ export function LibraryPage() {
if (!ids.length || !canCull) return;
dispatch({ type: "patch", ids, patch: change });
try {
await api.updatePhotos(orgId, ids, change);
// Without a network the change is kept here and sent when the connection is back.
await patchPhotos(api, orgId, ids, change);
} catch {
setError(t.unexpectedError);
if (state.scope) void open(state.scope);
@@ -380,12 +414,17 @@ export function LibraryPage() {
}}
/>
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
{waitingChanges > 0 && (
<span className="text-star" title={t.offline.waitingHelp}>
{t.offline.waiting(waitingChanges)}
</span>
)}
<span>
{t.ofTotal(visible.length, state.photos.length)} · {picks} ⚑
</span>
<span className="flex items-center gap-1.5" title={live}>
<span className={`h-2 w-2 rounded-full ${live === "live" ? "bg-ok" : live === "connecting" ? "bg-star" : "bg-danger"}`} />
{live === "live" ? "live" : live === "connecting" ? "…" : "offline"}
{live === "live" ? "live" : live === "connecting" ? "…" : t.offline.label}
</span>
</span>
</div>
@@ -412,7 +451,7 @@ export function LibraryPage() {
{view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") ? (
<FacesView api={api} orgId={orgId} eventId={state.scope} canAnalyse={canCreate} refreshKey={facesTick} />
) : loupe && focus ? (
<Loupe photo={focus} src={api.absolute(focus.urls.preview)} index={visibleIds.indexOf(focus.id)} total={visibleIds.length} faces={loupeFaces} />
<Loupe photo={focus} src={api.absolute(focus.urls.preview)} fallback={api.absolute(focus.urls.thumb)} index={visibleIds.indexOf(focus.id)} total={visibleIds.length} faces={loupeFaces} />
) : visible.length || suggested.length ? (
<>
<Grid photos={visible} selected={state.selected} focus={state.focus} srcFor={srcFor} onPick={onPick} onOpen={onOpenLoupe} />
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.6",
"version": "0.3.7",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.6"
version = "0.3.7"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
+8 -2
View File
@@ -738,12 +738,18 @@ pub async fn ftp_preview(
#[tauri::command]
pub async fn ftp_info(
state: tauri::State<'_, FtpState>,
index: tauri::State<'_, crate::local::LocalIndex>,
path: String,
) -> Result<crate::preview::OriginalInfo, String> {
let p = state.inside_ingest(&path)?;
tauri::async_runtime::spawn_blocking(move || crate::preview::original_info(&p))
let at = p.clone();
let info = tauri::async_runtime::spawn_blocking(move || crate::preview::original_info(&p))
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string())??;
// The editor can open it from disk right away, before it is uploaded (or with no network at all); `ftp_sent`
// records its new place once it is filed.
index.record(&info.sha256, &at);
Ok(info)
}
/// The server has the photo: file the original in the event's work folder and remember where it is, so the editor
+2 -1
View File
@@ -1,6 +1,7 @@
//! Originals on this computer, found by their SHA-256 (the same fingerprint the server keeps for each photo).
//! The editor asks for a photo's original here first: opening and rendering a photo you shot then needs no
//! download at all. Only files the app itself filed (the FTP work folders) are listed, and only those can be read.
//! download at all. Only files the app itself received (the FTP ingest and work folders) are listed, and only those
//! can be read.
use std::collections::HashMap;
use std::io::Read;
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.6",
"version": "0.3.7",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+17
View File
@@ -239,6 +239,23 @@ What organisations do with it:
- **People from squads:** squads become people (club, number, `sportsPlayerId`). With biometrics on, the Liga
headshot becomes the reference photo, and number suggestions for faces use the event's squads.
## Working without a network (desktop app)
A match does not stop when the venue's internet does. The desktop app keeps working and catches up on its own:
- **Opens offline.** The interface is on disk (`apps/desktop/src-tauri/src/ui.rs`); the person last signed in carries
on (`auth.tsx`), the session is checked again when the server answers.
- **Library and Revelar from cache** (`apps/app/src/offline/cache.ts`, IndexedDB): events, each folder's photos, the
edit state of photos opened in Revelar, thumbnails and previews already seen.
- **Photos arriving offline show at once** (`offline/local.ts`): the local FTP feed makes a preview here and files the
photo in the event of its capture time (the same rule as the server), with id `local:<sha256>`. It can be culled,
named and edited before it is uploaded; the server's copy replaces it when the upload is done, keeping what was done.
- **Changes wait, in order** (`offline/queue.ts`, localStorage): culling, players, IPTC and "send to" made without a
network are kept and sent when the server answers (every 10 s and on `online`); changes to a photo not uploaded yet
wait for it. Develop edits use the per-photo outbox (`develop/session.ts`) and follow the photo to its server id.
- **Uploads wait instead of failing**: the queue pauses on a network error and resumes when the connection is back.
- The autopilot runs on the server when the photo arrives, and never over a person's edit (made offline first).
## Library realtime
Socket.io on the API (`/v1/realtime`, WebSocket only, access token in the handshake, one room per
+1 -1
View File
@@ -74,7 +74,7 @@ export class ApiClient {
/** Absolute URL for an API path such as a signed photo URL. */
absolute(path: string): string {
return path.startsWith("http") ? path : `${this.opts.baseUrl}${path}`;
return path.startsWith("http") || path.startsWith("blob:") || path.startsWith("data:") ? path : `${this.opts.baseUrl}${path}`;
}
/**