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
spark f8611ad405 Desktop 0.3.6: the interface lives on the computer and updates itself
ci / rust (push) Successful in 11m30s
ci / typescript (push) Successful in 13m56s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 18m40s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 33m44s
The window always opens the interface from disk (no download to start, works offline). Each web deploy publishes ui-manifest.json; the app checks it in the background, downloads only the files that changed, verifies every hash and switches on the next start or reload. The installer's copy is the fallback and wins when newer.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 17:25:59 +01:00
spark cda3885fcd Library: Send button, combinable filters and delivery state
ci / rust (push) Successful in 7m47s
ci / typescript (push) Successful in 10m34s
The top bar sends the selection (rejects never) to a destination, or leads to setting one up. Filters combine as in Photo Mechanic (flag, stars at least, colour, delivery: to send / sending / sent / failed, without players); each thumbnail shows whether it was sent, live.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 17:11:29 +01:00
spark b58bc3129e Faces: only identify faces in focus
ci / rust (push) Successful in 8m14s
ci / typescript (push) Successful in 11m9s
Faces far softer than the sharpest in the photo (the crowd behind a player) or below the absolute sharpness are no longer stored, grouped or boxed; photos analysed before keep their rows but the loupe hides blurred boxes unless already named.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 16:54:11 +01:00
spark c16730f540 Autopilot: level by boards, not pitch lines; crops frame the upper body
ci / rust (push) Successful in 7m54s
ci / typescript (push) Successful in 11m21s
The level ignores lines on grass (pitch markings tilted by perspective) and only trusts near-level or near-plumb lines that agree; otherwise the photo is left as it is. The automatic crop puts the chest a little above the middle and the spare height above the subject, instead of the knees in the middle and a strip of pitch below.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 16:45:21 +01:00
spark 655ec1bba8 Library: one active photo across modules; events claim their inbox photos
ci / rust (push) Successful in 8m35s
ci / typescript (push) Successful in 11m30s
Library, loupe and Develop share the selected photo (per event), as in Lightroom: switching modules keeps it, Develop follows the library's filter and E goes back to the loupe. An event created or moved after its photos arrived takes them from "Sem evento"; photos can be moved to an event by hand; a failed photo says why.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 16:01:11 +01:00
spark b694e93a2b Event form: searching games also finds the last two weeks
ci / rust (push) Successful in 7m44s
ci / typescript (push) Successful in 10m35s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 15:34:40 +01:00
spark aae9ab8d0b Faces queue photos left unanalysed; local FTP originals count as camera ingest
ci / rust (push) Successful in 10m37s
ci / typescript (push) Successful in 12m58s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 15:20:51 +01:00
spark cceabdef06 Desktop updates: offer the newest release built for each platform
ci / typescript (push) Successful in 20m57s
ci / rust (push) Successful in 20m12s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 14:52:02 +01:00
spark 17784c8b22 Desktop: macOS installer and update build on a registered Mac (macos-runner.sh); 0.3.5
ci / typescript (push) Successful in 24m55s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 19m18s
ci / rust (push) Successful in 24m31s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 1h16m12s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 14:18:28 +01:00
spark 24ec8095f6 Desktop 0.3.4: allow ftp_check for the web app, and a test that every command is allowed
ci / typescript (push) Failing after 21m10s
ci / rust (push) Successful in 22m51s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 1h19m4s
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 14:13:22 +01:00
80 changed files with 2956 additions and 215 deletions

No files matched your search

+10 -6
View File
@@ -1,7 +1,8 @@
name: desktop-release
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
# Linux builds on the standard runner. macOS (.dmg) and Windows (.msi) need runners with those labels:
# register one on a Mac and one on a Windows machine, then uncomment the matrix entries.
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
# runner labelled "windows": register one, then uncomment its entry.
#
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
@@ -20,10 +21,10 @@ jobs:
- runner: ubuntu-latest
bundles: deb,appimage
platform: linux-x86_64
# - runner: macos
# bundles: dmg,app
# platform: darwin-universal
# args: --target universal-apple-darwin
- runner: macos
bundles: dmg,app
platform: darwin-universal
args: --target universal-apple-darwin
# - runner: windows
# bundles: msi
# platform: windows-x86_64
@@ -46,6 +47,9 @@ jobs:
with:
node-version: 22
- uses: dtolnay/rust-toolchain@stable
- name: Both Mac processors (universal app)
if: runner.os == 'macOS'
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
- name: Photo engine (WebAssembly)
run: |
rustup target add wasm32-unknown-unknown
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "pending_uploads" ADD COLUMN "from_desktop" BOOLEAN NOT NULL DEFAULT false;
+2
View File
@@ -1097,6 +1097,8 @@ model PendingUpload {
offset Int @default(0)
/// Set when this upload is a preview standing in for an original kept on the desktop: {sha256, size, width, height}.
original Json?
/// An original sent by the desktop app's ingest (its local FTP): edited by the event's autopilot like FTP photos.
fromDesktop Boolean @default(false) @map("from_desktop")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
+1 -1
View File
@@ -108,7 +108,7 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
await registerOrgRoutes(app, { db, sessions });
const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch });
await registerEventRoutes(app, { db, sessions, sports });
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
await registerSportsRoutes(app, { db, sessions, sports });
await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster });
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
+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, {
+40 -10
View File
@@ -5,8 +5,9 @@
*
* - The subject is who is in focus, not who is biggest: blurred players in the foreground are scenery.
* - With a ball near the subject, the ball and the sharp players contesting it come along.
* - The crop is usually two thirds of the frame (the same shape), moved to put the subject in the middle with
* room above the heads. Legs may be cut; heads and the ball may not.
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
* crowd and the stands). Legs may be cut; heads and the ball may not.
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
*
* Boxes are fractions of the upright photo (0..1, y down).
@@ -50,7 +51,23 @@ const MIN_BALL = 0.3;
/** Smaller people (in photo heights) are too far away to be what the photo is about. */
const MIN_HEIGHT = 0.08;
/** Tuning, fitted to Peter's crops (exported so the evaluation script can sweep it). */
export const TUNING = { inFocus: 0.55, usualScale: 0.72, wScale: 1.0, wFill: 0.6, wCentre: 1.2, wHead: 0.8, headAt: 0.1, wCut: 1.2, wJoint: 0.8 };
export const TUNING = {
inFocus: 0.55,
usualScale: 0.72,
wScale: 1.0,
wFill: 1.0,
fillAt: 0.6,
wCentre: 1.2,
wHead: 0.8,
headMin: 0.04,
headMax: 0.16,
wChest: 1.4,
chestAt: 0.42,
wBelow: 2.5,
belowMax: 0.08,
wCut: 1.2,
wJoint: 0.8,
};
/**
* Where the joints of a standing person roughly are, as fractions of their box from the top (neck, hips, knees,
@@ -151,13 +168,17 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
ch = cw / ratio;
}
if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom || cw < minWidth - 1e-9) continue;
// Vertical positions: from the heads just under the top edge to the bottom of the subject just above the
// bottom edge (all the spare height above them: the crowd, the stands, never a strip of empty pitch below).
const top = s.y0 - headroom;
const spare = Math.max(0, ch - (mustBottom - top));
for (let i = 0; i <= 24; i++) {
const x0 = Math.min(Math.max(0, s.x1 - cw + (i / 24) * (cw - w(s))), 1 - cw);
for (let j = 0; j <= 16; j++) {
const y0 = Math.min(Math.max(0, s.y0 - headroom - (j / 16) * 0.3 * ch), 1 - ch);
for (let j = 0; j <= 20; j++) {
const y0 = Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio) + jointCost(r, inSubject, others, mainSharp);
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject) + jointCost(r, inSubject, others, mainSharp);
if (!best || c < best.cost) best = { rect: r, cost: c };
}
}
@@ -166,7 +187,7 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
return { rect: best.rect, subject: s, reason, people: inSubject.length };
}
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number): number {
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[]): number {
let c = 0;
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
for (const p of others) {
@@ -181,11 +202,20 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
const k = Math.max(ch, w(r) / ratio);
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
// The subject fills a good part of the height (people tall in the frame).
c += TUNING.wFill * Math.max(0, 0.55 - tallest / ch);
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
// Centred across.
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
// Heads a little below the top.
c += TUNING.wHead * Math.abs((s.y0 - r.y0) / ch - TUNING.headAt);
// Heads a little below the top: not touching it, not floating in empty space.
const head = (s.y0 - r.y0) / ch;
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - TUNING.headMax));
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
// the middle with a strip of grass below.
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
c += TUNING.wChest * Math.abs(chest - TUNING.chestAt);
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
return c;
}
+24 -16
View File
@@ -60,7 +60,7 @@ export function newer(candidate: string, current: string): boolean {
}
export class DesktopReleases {
private cache: { at: number; release: GiteaRelease | null } | null = null;
private cache: { at: number; releases: GiteaRelease[] } | null = null;
constructor(
private readonly config: DesktopReleaseConfig,
@@ -71,15 +71,26 @@ export class DesktopReleases {
return { authorization: `token ${this.config.token}`, accept: "application/json" };
}
/** The newest published `desktop-v*` release. */
async latest(): Promise<GiteaRelease | null> {
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.release;
/** Published `desktop-v*` releases, newest first. */
async releases(): Promise<GiteaRelease[]> {
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.releases;
const res = await this.fetchImpl(`${this.config.api.replace(/\/$/, "")}/releases?limit=50`, { headers: this.headers() });
if (!res.ok) throw new Error(`gitea releases: ${res.status}`);
const all = ((await res.json()) as GiteaRelease[]).filter((r) => !r.draft && !r.prerelease && r.tag_name.startsWith("desktop-v"));
all.sort((x, y) => (newer(x.tag_name.slice(9), y.tag_name.slice(9)) ? -1 : 1));
this.cache = { at: Date.now(), release: all[0] ?? null };
return this.cache.release;
this.cache = { at: Date.now(), releases: all };
return all;
}
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
// Universal macOS builds serve both Apple chips.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
for (const release of await this.releases()) {
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
if (manifest) return { release, manifest };
}
return null;
}
private async download(asset: GiteaAsset): Promise<Response> {
@@ -90,13 +101,10 @@ export class DesktopReleases {
/** Tauri's dynamic update answer for one platform, or null when there is nothing newer. */
async updateFor(target: string, arch: string, current: string): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string } | null> {
const release = await this.latest();
if (!release) return null;
// Universal macOS builds serve both Apple chips.
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
const asset = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
if (!asset) return null;
const manifest = Manifest.parse(await (await this.download(asset)).json());
const found = await this.forPlatform(target, arch);
if (!found) return null;
const { release } = found;
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
if (!newer(manifest.version, current)) return null;
if (!release.assets.some((a) => a.name === manifest.file)) return null;
return {
@@ -108,10 +116,10 @@ export class DesktopReleases {
};
}
/** The installer itself, streamed from the release. */
/** The installer itself, streamed from a desktop release. */
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
const release = await this.latest();
if (!release || release.id !== releaseId) return null;
const release = (await this.releases()).find((r) => r.id === releaseId);
if (!release) return null;
const asset = release.assets.find((a) => a.name === name);
if (!asset || /\.json$/.test(name)) return null;
const res = await this.download(asset);
+15
View File
@@ -54,3 +54,18 @@ export const THRESHOLDS: Record<string, { match: number; group: number; margin:
* in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder.
*/
export const MIN_SHARPNESS = 45;
/**
* A face this much softer than the sharpest one in the same photo is out of the focus plane (the crowd behind the
* player, a bench in front), however textured: not worth identifying.
*/
export const RELATIVE_SHARPNESS = 0.25;
/**
* The faces worth identifying in one photo: the ones in focus. Faces with no measure (older analyses) stay.
* Editors only want names for who the photo is about; boxes on a blurred crowd are noise.
*/
export function inFocus<T extends { sharpness?: number | null }>(faces: T[]): T[] {
const sharpest = Math.max(0, ...faces.map((f) => f.sharpness ?? 0));
return faces.filter((f) => f.sharpness == null || (f.sharpness >= MIN_SHARPNESS && f.sharpness >= RELATIVE_SHARPNESS * sharpest));
}
+5 -2
View File
@@ -10,7 +10,7 @@ import { createReadStream } from "node:fs";
import sharp from "sharp";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { FaceRejected, JERSEY_MIN_SCORE, majorityNumber, type FaceService } from "./service.js";
import { MIN_SHARPNESS } from "./math.js";
import { inFocus, MIN_SHARPNESS } from "./math.js";
const EventParams = z.object({ eventId: z.uuid() });
const GroupParams = z.object({ groupId: z.uuid() });
@@ -139,7 +139,10 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
if (!photo) throw notFound("photo_not_found");
await requireMembership(db, req, photo.organizationId, "INGESTER");
const list = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
const all = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
// Blurred faces (photos analysed before they were left out) are not boxed, unless someone already named them.
const focused = new Set(inFocus(all).map((f) => f.id));
const list = all.filter((f) => focused.has(f.id) || f.group?.person);
// The previews are the edited photo: boxes are also given in its (cropped, straightened) frame.
const crop = photo.renderedSeq > 0 ? cropOfSettings(photo.developSnapshot) : null;
return {
+21 -2
View File
@@ -32,7 +32,7 @@ export function majorityNumber(faces: { jerseyNumber: string | null; jerseyScore
}
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
import { addToMean, cosine, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import type { FaceEngine } from "./process.js";
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
@@ -87,6 +87,18 @@ export class FaceService {
return r.count;
}
/**
* Photos left without analysis in an organization that has face analysis on (they arrived while it was off, or
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
*/
async queueMissed(): Promise<number> {
const r = await this.deps.db.photo.updateMany({
where: { facesStatus: "NONE", status: "READY", organization: { biometricsEnabled: true } },
data: { facesStatus: "PENDING" },
});
return r.count;
}
/** Detects, stores and groups the faces of one claimed photo. Never throws. */
async process(photoId: string): Promise<void> {
const { db, storage, log, engine } = this.deps;
@@ -94,7 +106,8 @@ export class FaceService {
if (!engine) throw new Error("face engine not configured");
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } });
const analysis = await engine.analyse(storage.resolve(photo.storageKey));
const faces = analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE);
// Only faces in focus are kept: the blurred crowd and benches are not who the photo is about.
const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE));
// The shirt number under each clear face, when a number model is installed.
const numbers = new Map<number, JerseyReading>();
if (this.deps.jersey) {
@@ -399,8 +412,14 @@ export class FaceWorker {
start(): void {
void this.service.requeueStale();
let missedAt = 0;
const tick = async () => {
try {
if (Date.now() - missedAt > 60_000) {
missedAt = Date.now();
const n = await this.service.queueMissed();
if (n) this.opts.log.info({ photos: n }, "faces: queued photos left without analysis");
}
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
for (const id of ids) {
+49
View File
@@ -0,0 +1,49 @@
import type { Db } from "../db.js";
import { applyRename } from "./rename.js";
/**
* Photos that just joined an event (moved by hand, or claimed from "Sem evento" when the event was created or its
* window changed) get what arriving in it would have given them: the event's arrival name, faces analysed again so
* they group with the event's people, and the event's autopilot edit (FTP and desktop photos only, as on arrival).
*/
export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise<void> {
if (!ids.length) return;
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } });
if (!event) return;
if (event.organization.biometricsEnabled) {
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED"] } }, data: { facesStatus: "PENDING" } });
}
if ((event.autopilot as { enabled?: boolean } | null)?.enabled === true) {
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "UPLOAD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } });
}
for (const id of ids) await applyRename(db, id);
}
/**
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
*/
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
const event = await db.event.findUnique({
where: { id: eventId },
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
});
if (!event || event.archivedAt) return [];
const photos = await db.photo.findMany({
where: {
organizationId: event.organizationId,
eventId: null,
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
},
select: { id: true },
take: 20_000,
});
const ids = photos.map((p) => p.id);
if (!ids.length) return [];
// Only the ones still in the inbox (another event may have claimed some meanwhile).
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
await joinedEvent(db, eventId, claimed);
return claimed;
}
+22 -2
View File
@@ -8,7 +8,9 @@ import type { Db } from "../db.js";
import { type Event, Prisma } from "../generated/prisma/client.js";
import { compact } from "../lib/compact.js";
import { badRequest, notFound } from "../lib/errors.js";
import type { Broadcaster } from "../realtime.js";
import type { SportsService } from "../sports/service.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
const OrgParams = z.object({ orgId: z.uuid() });
@@ -77,8 +79,20 @@ export function ingestWindow(startsAt: Date, from?: Date, until?: Date): { inges
return { ingestFrom, ingestUntil };
}
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService }) {
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService; broadcaster?: Broadcaster }) {
const { db } = deps;
/** Photos in "Sem evento" taken during the event join it (and the open libraries move them). */
async function claim(orgId: string, eventId: string): Promise<void> {
const ids = await claimInbox(db, eventId).catch((err) => {
app.log.warn({ err, eventId }, "event: claiming inbox photos failed");
return [] as string[];
});
if (ids.length) {
app.log.info({ eventId, photos: ids.length }, "event: claimed photos from the inbox");
deps.broadcaster?.library(orgId, { type: "photo.updated", ids, patch: { eventId } });
}
}
const authenticate = requireAuth(deps.sessions);
const loadEvent = async (req: FastifyRequest, eventId: string, minRole: "PHOTOGRAPHER" | "INGESTER" | "EDITOR") => {
@@ -156,7 +170,8 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
include,
});
if (event.homeTeamId || event.awayTeamId) syncSquads(event.id);
return reply.code(201).send(serialize(event));
await claim(orgId, event.id);
return reply.code(201).send(serialize(await db.event.findUniqueOrThrow({ where: { id: event.id }, include })));
});
app.get("/v1/events/:eventId", { preHandler: authenticate }, async (req) => {
@@ -196,6 +211,11 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
});
const teamsChanged = (match.homeTeamId !== undefined && match.homeTeamId !== current.homeTeamId) || (match.awayTeamId !== undefined && match.awayTeamId !== current.awayTeamId);
if (teamsChanged && (event.homeTeamId || event.awayTeamId)) syncSquads(event.id);
// New times, new photographers or back from the archive: photos waiting in "Sem evento" may now belong here.
if (startsAt || ingestFrom || ingestUntil || photographerIds || archived === false) {
await claim(event.organizationId, eventId);
return serialize(await db.event.findUniqueOrThrow({ where: { id: eventId }, include }));
}
return serialize(event);
});
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { applyRename } from "./rename.js";
import { joinedEvent } from "./adopt.js";
import { createReadStream } from "node:fs";
import { PhotoBatchPatch } from "@photoreport/contracts";
import { expandCodes, IptcTemplate, parseCodeList } from "@photoreport/metadata";
@@ -95,8 +95,8 @@ export async function registerPhotoRoutes(
if (patch.eventId !== undefined) data.eventId = patch.eventId;
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
if (result.count !== ids.length) throw notFound("photo_not_found");
// Moved to another event: arrival names that use the event follow it.
if (patch.eventId) for (const id of ids) await applyRename(db, id);
// Moved to another event: arrival names, faces and the autopilot follow it.
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
return { updated: result.count };
});
+5 -3
View File
@@ -1,11 +1,11 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { deliveryState, type PhotoSummary } from "@photoreport/contracts";
import type { Photo } from "../generated/prisma/client.js";
import type { UrlSigner } from "../storage/storage.js";
import { deliveredName } from "../delivery/service.js";
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null };
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null; deliveries?: { status: string }[] };
export const photoInclude = { uploader: { select: { id: true, name: true } } } as const;
export const photoInclude = { uploader: { select: { id: true, name: true } }, deliveries: { select: { status: true } } } as const;
export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSummary {
return {
@@ -16,6 +16,8 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum
sha256: photo.sha256,
originalStored: photo.originalStored,
status: photo.status,
...(photo.status === "FAILED" && { error: photo.error }),
...(photo.deliveries && { delivery: deliveryState(photo.deliveries.map((d) => d.status)) }),
width: photo.width,
height: photo.height,
capturedAt: photo.capturedAt?.toISOString() ?? null,
+4 -2
View File
@@ -78,6 +78,8 @@ export async function registerUploadRoutes(
height: z.number().int().positive().max(100_000).optional(),
})
.optional(),
/** A full original from the desktop app's ingest (its local FTP), not a hand upload. */
desktop: z.boolean().optional(),
});
app.post("/v1/orgs/:orgId/uploads/resumable", { preHandler: authenticate }, async (req, reply) => {
@@ -106,7 +108,7 @@ export async function registerUploadRoutes(
if (known && known.status !== "FAILED") return reply.code(200).send({ status: "duplicate", photo: toSummary(known, signer) });
}
const upload = await db.pendingUpload.create({
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }) },
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }), ...(body.desktop && { fromDesktop: true }) },
});
return reply.code(201).send({ id: upload.id, offset: 0, size: upload.size });
});
@@ -152,7 +154,7 @@ export async function registerUploadRoutes(
const outcome = await ingest.ingest(partPath(id), {
organizationId: upload.organizationId,
userId: upload.userId,
source: upload.original ? "DESKTOP" : "UPLOAD",
source: upload.original || upload.fromDesktop ? "DESKTOP" : "UPLOAD",
originalName: upload.fileName,
eventId: upload.eventId ?? undefined,
original: (upload.original as PreviewOf | null) ?? undefined,
+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);
+14
View File
@@ -61,6 +61,20 @@ describe("automatic crop", () => {
expect(minCropWidth(2048, 1365)).toBe(1);
});
it("frames the upper body near the middle, with the spare height above and not a strip of pitch below", () => {
// A player kneeling in celebration, small in a wide frame (Braga x Sporting, October 2026).
const kneeling = { ...person(0.41, 0.19, 0.58, 0.55), sharpness: 1 };
const c = compose({ width: 6000, height: 4000, people: [kneeling], balls: [] }, null, { minWidth: 0.4 })!;
const ch = c.rect.y1 - c.rect.y0;
const below = (c.rect.y1 - kneeling.y1) / ch;
const chest = (kneeling.y0 + 0.3 * (kneeling.y1 - kneeling.y0) - c.rect.y0) / ch;
expect(below).toBeLessThanOrEqual(0.12);
expect(chest).toBeGreaterThan(0.3);
expect(chest).toBeLessThan(0.5);
// Heads below the top edge, never touching it.
expect((kneeling.y0 - c.rect.y0) / ch).toBeGreaterThanOrEqual(0.03);
});
it("proposes nothing for an empty pitch or a distant crowd", () => {
expect(compose({ ...frame, people: [person(0.1, 0.4, 0.13, 0.45), person(0.5, 0.4, 0.52, 0.46)], balls: [] })).toBeNull();
});
+3
View File
@@ -202,6 +202,9 @@ describe("delivery", () => {
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries?targetId=${target.id}`, headers: bearer(token) });
expect((list.json() as { counts: Record<string, number> }).counts).toEqual({ DONE: 2 });
// The library shows them as sent (the "Enviadas" / "Por enviar" filters).
const photos = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(token) });
expect((photos.json() as { photos: { delivery: string }[] }).photos.map((p) => p.delivery)).toEqual(["DONE", "DONE"]);
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first] } });
expect(again.json()).toMatchObject({ queued: [], skipped: [{ photoId: first, reason: "already_delivered" }] });
const resend = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first], again: true } });
+17
View File
@@ -53,4 +53,21 @@ describe("desktop updates", () => {
expect(await r.file(3, "PhotoReport_universal.app.tar.gz")).toBeNull();
expect(await r.file(7, "update-darwin-universal.json")).toBeNull();
});
it("keeps offering the last release built for a platform while a newer one is still building", async () => {
const releases = [
// 0.3.5: Linux done, the Mac still building (or switched off).
{ id: 12, tag_name: "desktop-v0.3.5", draft: false, prerelease: false, body: "", published_at: null, assets: [asset(20, "update-linux-x86_64.json"), asset(21, "PhotoReport_0.3.5_amd64.AppImage")] },
{ id: 11, tag_name: "desktop-v0.3.4", draft: false, prerelease: false, body: "Mac", published_at: null, assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz")] },
];
const files = {
"update-linux-x86_64.json": { version: "0.3.5", file: "PhotoReport_0.3.5_amd64.AppImage", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
"update-darwin-universal.json": { version: "0.3.4", file: "PhotoReport.app.tar.gz", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
"PhotoReport.app.tar.gz": "mac bytes",
};
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
expect(await r.updateFor("linux", "x86_64", "0.3.2")).toMatchObject({ version: "0.3.5", url: "/v1/desktop/download/12/PhotoReport_0.3.5_amd64.AppImage" });
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
});
});
+22 -6
View File
@@ -83,7 +83,7 @@ describe("faces", () => {
/** Ingests a photo with the given people's faces in it. */
let n = 0;
async function photo(taken: string, people: number[], sharpness: number | null = 200): Promise<string> {
async function photo(taken: string, people: number[], sharpness: number | null | (number | null)[] = 200): Promise<string> {
n++;
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: n % 256, g: (n * 7) % 256, b: (n * 13) % 256 } } })
.jpeg()
@@ -97,7 +97,7 @@ describe("faces", () => {
engine.byColor.set(sha, {
width: 600,
height: 400,
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness, landmarks: [], embedding: personVector(p, n) })),
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness: Array.isArray(sharpness) ? sharpness[i]! : sharpness, landmarks: [], embedding: personVector(p, n) })),
});
const out = await ingest.ingestFile(file);
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
@@ -125,6 +125,20 @@ describe("faces", () => {
expect(await faces.claim(5)).toEqual([id]);
});
it("queues photos left without analysis while biometrics are on, and leaves other organizations alone", async () => {
await setup(true);
const id = await photo("2026:09:23 21:00:00", [1]);
expect(await faces.claim(5)).toEqual([id]);
await drain();
// A photo that slipped through as "no analysis" (it arrived while a toggle raced its ingest).
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE" } });
const other = await seedUser(ctx.db, "[email protected]", { org: "clube", role: "OWNER" });
const theirs = await ctx.db.photo.create({ data: { organizationId: other.org!.id, source: "UPLOAD", originalName: "x.jpg", sha256: "f".repeat(64), byteSize: 1, storageKey: "x", status: "READY" } });
expect(await faces.queueMissed()).toBe(1);
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id } })).facesStatus).toBe("PENDING");
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: theirs.id } })).facesStatus).toBe("NONE");
});
it("reads the faces again from the original when it replaces a desktop preview", async () => {
const { orgId } = await setup();
const user = await ctx.db.user.findFirstOrThrow();
@@ -219,17 +233,19 @@ describe("faces", () => {
expect((await list())[0]!.ignored).toBe(true);
});
it("keeps blurred faces out of the groups, and says how many", async () => {
it("only identifies faces in focus: not soft photos, not the blurred crowd behind a sharp player", async () => {
const { token, day1 } = await setup();
await photo("2026:09:23 21:00:00", [1]);
await photo("2026:09:23 21:01:00", [1]);
// The player sharp, two fans in the stand behind him out of focus (textured, but far softer).
const withCrowd = await photo("2026:09:23 21:01:00", [1, 8, 9], [400, 60, 50]);
await photo("2026:09:23 21:02:00", [8], 12);
await photo("2026:09:23 21:03:00", [9], 12);
await drain();
const body = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { size: number }[]; unclear: number };
expect(body.groups.map((g) => g.size)).toEqual([2]);
expect(body.unclear).toBe(2);
expect(await ctx.db.face.count()).toBe(4);
expect(await ctx.db.face.count()).toBe(2);
const boxes = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${withCrowd}/faces`, headers: bearer(token) })).json() as { faces: unknown[] };
expect(boxes.faces).toHaveLength(1);
});
it("learns a person from a reference photo and suggests them from the first match", async () => {
+35
View File
@@ -178,6 +178,41 @@ describe("library", () => {
expect((inbox.json() as { total: number }).total).toBe(1);
});
it("an event created (or moved) after its photos arrived claims them from the inbox, live", async () => {
const { orgId, admin, photographer } = await setup();
const early = await service.ingestFile(await drop("foto.r1", "early.jpg", await jpeg({ color: "#994400", taken: "2026:10:09 20:26:47" })));
const later = await service.ingestFile(await drop("foto.r1", "later.jpg", await jpeg({ color: "#004499", taken: "2026:10:09 22:17:05" })));
const elsewhere = await service.ingestFile(await drop("foto.r1", "other.jpg", await jpeg({ color: "#449900", taken: "2026:09:03 16:37:46" })));
expect([early, later, elsewhere].map((o) => (o as { eventId: string | null }).eventId)).toEqual([null, null, null]);
broadcaster.sent.length = 0;
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "SC Braga", away: "Sporting CP", startsAt: "2026-10-09T19:15:00Z", photographerIds: [photographer.id] },
});
expect(created.statusCode).toBe(201);
const event = created.json() as { id: string; photoCount: number };
expect(event.photoCount).toBe(2);
const ids = [early, later].map((o) => (o as { photoId: string }).photoId);
expect(broadcaster.sent.map((s) => s.message)).toContainEqual({ type: "photo.updated", ids: expect.arrayContaining(ids), patch: { eventId: event.id } });
const inbox = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=inbox`, headers: bearer(admin) });
expect((inbox.json() as { photos: { id: string }[] }).photos.map((p) => p.id)).toEqual([(elsewhere as { photoId: string }).photoId]);
// Moving its time to cover the September photo claims that one too.
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${event.id}`, headers: bearer(admin), payload: { startsAt: "2026-09-03T15:00:00Z" } });
expect((moved.json() as { photoCount: number }).photoCount).toBe(3);
});
it("says why a photo failed", async () => {
const { orgId, admin } = await setup();
await service.ingestFile(await drop("foto.r1", "cut.jpg", Buffer.from("not really a jpeg")));
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?status=FAILED`, headers: bearer(admin) });
const [photo] = (list.json() as { photos: { status: string; error?: string }[] }).photos;
expect(photo).toMatchObject({ status: "FAILED", error: expect.any(String) });
});
it("marks unreadable files as failed instead of losing them", async () => {
await setup();
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", Buffer.from("not really a jpeg")));
+15
View File
@@ -81,6 +81,21 @@ describe("resumable uploads", () => {
expect((await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) })).json()).toEqual({ stored: true });
});
it("counts a full original from the desktop app's FTP as camera ingest (the autopilot edits it), not a hand upload", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
const t = new Date("2026-10-13T15:00:00Z");
const event = await ctx.db.event.create({ data: { organizationId: org!.id, home: "ABC", away: "FCP", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {}, autopilot: { enabled: true } } });
const send = async (name: string, extra: object) => {
const jpeg = await sharp({ create: { width: 900, height: 600, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg().toBuffer();
const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name, size: jpeg.length, fingerprint: `${name}:${jpeg.length}`, eventId: event.id, ...extra } })).json() as { id: string };
const done = await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: jpeg });
return ctx.db.photo.findUniqueOrThrow({ where: { id: (done.json() as { photo: { id: string } }).photo.id } });
};
expect(await send("FTP_0001.JPG", { desktop: true })).toMatchObject({ source: "DESKTOP", autopilotStatus: "PENDING" });
expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "NONE" });
});
it("a photo that failed (a damaged file) is replaced when it is sent again", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
+1 -1
View File
@@ -5,7 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -p tsconfig.json --noEmit && vite build",
"build": "tsc -p tsconfig.json --noEmit && vite build && node scripts/ui-manifest.mjs",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"preview": "vite preview"
+32
View File
@@ -0,0 +1,32 @@
// Writes dist/ui-manifest.json after `vite build`: every file of the build with its size and SHA-256, the version and
// when it was built. The desktop app keeps the interface on disk and reads this to download only what changed
// (apps/desktop/src-tauri/src/ui.rs).
import { createHash } from "node:crypto";
import { readdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
const NAME = "ui-manifest.json";
const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../dist");
async function walk(dir) {
const out = [];
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...(await walk(full)));
else if (entry.isFile()) out.push(full);
}
return out;
}
const files = [];
for (const full of (await walk(dist)).sort()) {
const rel = path.relative(dist, full).split(path.sep).join("/");
if (rel === NAME) continue;
const bytes = await readFile(full);
files.push({ path: rel, size: (await stat(full)).size, sha256: createHash("sha256").update(bytes).digest("hex") });
}
const content = createHash("sha256").update(files.map((f) => `${f.path}:${f.sha256}`).join("\n")).digest("hex").slice(0, 16);
const manifest = { version: process.env.VITE_APP_VERSION?.slice(0, 40) || content, builtAt: new Date().toISOString(), files };
await writeFile(path.join(dist, NAME), JSON.stringify(manifest));
console.log(`${NAME}: ${files.length} files, version ${manifest.version}`);
+4
View File
@@ -7,4 +7,8 @@ describe("apiUrlFor", () => {
expect(apiUrlFor(undefined, { protocol: "https:", hostname: "app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
expect(apiUrlFor(undefined, { protocol: "http:", hostname: "localhost" })).toBe("http://localhost:3000");
});
it("inside the desktop app, uses the API the app names (its interface may be the web build)", () => {
expect(apiUrlFor(undefined, { protocol: "tauri:", hostname: "localhost" }, { api: "https://api.next.photoreport.pt/", app: "https://app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
});
});
+5 -3
View File
@@ -1,11 +1,13 @@
import { ApiClient } from "@photoreport/sdk";
import { desktopRefreshStore, isDesktop } from "./platform.js";
import { desktopConfig, desktopRefreshStore, isDesktop } from "./platform.js";
/**
* Where the API is: VITE_API_URL when the build sets it (the desktop app always does); otherwise next to this page,
* Where the API is: what the desktop app says; VITE_API_URL when the build sets it; otherwise next to this page,
* app.<domain> -> api.<domain>, so a web build works on any environment without rebuilding for it.
*/
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined): string {
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined, desktop = desktopConfig()): string {
// The desktop app says where its API is (its interface may be a version downloaded from the web build).
if (desktop?.api) return desktop.api.replace(/\/+$/, "");
if (configured) return configured.replace(/\/+$/, "");
if (location?.hostname.startsWith("app.")) return `${location.protocol}//api.${location.hostname.slice(4)}`;
return "http://localhost:3000";
+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");
},
+38
View File
@@ -10,6 +10,44 @@ interface UpdateInfo {
const EVERY_MS = 6 * 3600_000;
type Listen = (event: string, handler: () => void) => Promise<() => void>;
const tauriListen: Listen = async (event, handler) => (await import("@tauri-apps/api/event")).listen(event, handler);
/**
* Desktop only: a newer interface was downloaded in the background (apps/desktop/src-tauri/src/ui.rs). It is used
* from the next start; reloading now switches straight away (nothing is lost: edits wait in the local queue).
*/
export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), reload = () => window.location.reload() }: { listen?: Listen; enabled?: boolean; reload?: () => void }) {
const [ready, setReady] = useState(false);
const [dismissed, setDismissed] = useState(false);
useEffect(() => {
if (!enabled) return;
let stop: (() => void) | undefined;
let alive = true;
listen("ui-ready", () => setReady(true)).then(
(unlisten) => (alive ? (stop = unlisten) : unlisten()),
() => {},
);
return () => {
alive = false;
stop?.();
};
}, [enabled, listen]);
if (!ready || dismissed) return null;
return (
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
<span>{t.update.uiReady}</span>
<button className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong" onClick={reload}>
{t.update.reload}
</button>
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
{t.update.later}
</button>
</div>
);
}
/** Desktop only: a new version of the app's shell, installed with one click (it restarts). */
export function UpdateNotice({ invoke = desktopInvoke, enabled = isDesktop() }: { invoke?: Invoke; enabled?: boolean }) {
const [update, setUpdate] = useState<UpdateInfo | null>(null);
+18 -2
View File
@@ -1,8 +1,8 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { Invoke } from "../platform.js";
import { type CatalogFolder, LocalCatalog, type ScanStatus } from "./LocalCatalog.js";
import { UpdateNotice } from "./UpdateNotice.js";
import { UiReadyNotice, UpdateNotice } from "./UpdateNotice.js";
describe("local catalogue", () => {
it("adds a folder through the system picker, indexes it and shows the count", async () => {
@@ -37,6 +37,22 @@ describe("local catalogue", () => {
});
});
describe("interface update notice", () => {
it("says when a newer interface is ready and reloads into it", async () => {
let fire: () => void = () => {};
const listen = vi.fn(async (_event: string, handler: () => void) => {
fire = handler;
return () => {};
});
const reload = vi.fn();
render(<UiReadyNotice listen={listen} enabled reload={reload} />);
await waitFor(() => expect(listen).toHaveBeenCalledWith("ui-ready", expect.any(Function)));
act(() => fire());
fireEvent.click(await screen.findByText("Recarregar agora"));
expect(reload).toHaveBeenCalled();
});
});
describe("update notice", () => {
it("offers a newer shell and installs it", async () => {
const invoke = vi.fn(async (cmd: string) => (cmd === "update_check" ? { version: "0.3.0", currentVersion: "0.2.0", notes: "Catálogo local" } : null)) as unknown as Invoke;
+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,
+27 -2
View File
@@ -34,12 +34,35 @@ 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",
noEvents: "Sem eventos. Cria o primeiro.",
noPhotos: "Sem fotografias neste filtro.",
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
filter: "Filtro",
filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" },
flagFilter: { all: "Todas", PICK: "Escolhidas", UNFLAGGED: "Sem marca", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas" },
starsAtLeast: "Estrelas (pelo menos)",
starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`),
colorLabel: "Cor",
colors: { RED: "Vermelho", YELLOW: "Amarelo", GREEN: "Verde", BLUE: "Azul", PURPLE: "Roxo" },
deliveryFilter: "Envio:",
deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" },
noPlayersFilter: "Sem jogador",
clearFilter: "Limpar filtro",
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
sendTo: "Enviar para",
selectToSend: "Seleciona as fotografias a enviar (⌘A seleciona todas as do filtro).",
setUpDelivery: "Configurar envio",
noTargetsHelp: "Ainda não há destinos de envio (FTP da agência, pasta, etc.). Cria um em Entregar.",
deliveryBadge: { QUEUED: "A enviar", DONE: "Enviada", FAILED: "Envio falhou" },
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · I informação · E/Enter lupa · G/Esc grelha · D revelar",
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
ofTotal: (n: number, total: number) => `${n} de ${total}`,
@@ -264,7 +287,7 @@ export const t = {
startsAt: "Início",
photographers: "Fotógrafos",
pickMatch: "Escolher o jogo",
pickMatchHelp: "Jogos da Liga Portugal, FPF e FPA dos próximos dias. Preenche o evento e junta os plantéis às pessoas.",
pickMatchHelp: "Jogos da Liga Portugal, FPF e FPA dos próximos dias (ao pesquisar, também os das últimas duas semanas). Preenche o evento e junta os plantéis às pessoas.",
searchMatch: "Equipa, competição ou pavilhão",
noMatches: "Nenhum jogo encontrado.",
linked: "Ligado ao jogo oficial",
@@ -329,6 +352,8 @@ export const t = {
installing: "A instalar…",
failed: "Não foi possível instalar. Tenta mais tarde.",
later: "Mais tarde",
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
reload: "Recarregar agora",
},
editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.",
saved: "Guardado",
+13
View File
@@ -68,4 +68,17 @@ describe("new event form", () => {
expect(createEvent).toHaveBeenCalledWith("o1", expect.objectContaining({ home: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", iptcTemplate: expect.objectContaining({ caption: "Sérgio Conceição na antevisão do clássico" }) }));
expect(shiftDay("2026-10-31", 1)).toBe("2026-11-01");
});
it("searches the last two weeks too, for an event made after the match", async () => {
const sportsFixtures = vi.fn(async (_q: { from: string; q?: string }) => ({ fixtures: [] }));
const api = { createEvent: vi.fn(), sportsFixtures, listPeople: async () => ({ people: [] }), calendarStatus: async () => ({ connected: false }) } as unknown as ApiClient;
render(<EventForm api={api} orgId="o1" onClose={() => undefined} onCreated={() => undefined} />);
await waitFor(() => expect(sportsFixtures).toHaveBeenCalled());
const hours = (q: { from: string }) => (Date.now() - Date.parse(q.from)) / 3600_000;
expect(hours(sportsFixtures.mock.calls[0]![0])).toBeLessThan(13);
fireEvent.change(screen.getByLabelText("Equipa, competição ou pavilhão"), { target: { value: "braga" } });
await waitFor(() => expect(sportsFixtures.mock.calls.some(([q]) => q.q === "braga")).toBe(true));
const search = sportsFixtures.mock.calls.find(([q]) => q.q === "braga")![0];
expect(hours(search)).toBeGreaterThan(14 * 24 - 1);
});
});
+4 -2
View File
@@ -235,8 +235,10 @@ export function FixturePicker({ api, match, onPick, onClear }: { api: ApiClient;
useEffect(() => {
if (match) return;
const timer = setTimeout(() => {
const from = new Date(Date.now() - 12 * 3600_000).toISOString();
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim() }) }).then((r) => setList(r.fixtures), () => setList([]));
// Upcoming games by default; a search also finds the last two weeks (an event made after the match).
const from = new Date(Date.now() - (q.trim() ? 14 * 24 : 12) * 3600_000).toISOString();
const to = new Date(Date.now() + 14 * 24 * 3600_000).toISOString();
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim(), to }) }).then((r) => setList(r.fixtures), () => setList([]));
}, 250);
return () => clearTimeout(timer);
}, [api, q, match]);
+80
View File
@@ -0,0 +1,80 @@
import type { ColorLabel } from "@photoreport/contracts";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
import { ALL_PHOTOS, isAll, type LibraryFilter } from "./store.js";
const FLAGS: LibraryFilter["flag"][] = ["all", "PICK", "UNFLAGGED", "UNREJECTED", "REJECT"];
const DELIVERY: LibraryFilter["delivery"][] = ["any", "unsent", "queued", "sent", "failed"];
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
const chip = (on: boolean) => (on ? "font-semibold text-ink" : "text-faint hover:text-muted");
/**
* Photo Mechanic / Lightroom style filter bar: flag, stars (at least), colour, delivery state and photos without
* players, all combinable. Clicking an active stars or colour choice again turns it off.
*/
export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryFilter) => void }) {
const { filter: f, onChange } = props;
const set = (patch: Partial<LibraryFilter>) => onChange({ ...f, ...patch });
return (
<div role="group" aria-label={t.filter} className="flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="text-faint">{t.filter}:</span>
{FLAGS.map((flag) => (
<button key={flag} onClick={() => set({ flag })} aria-pressed={f.flag === flag} className={chip(f.flag === flag)}>
{t.flagFilter[flag]}
</button>
))}
<span aria-hidden="true" className="text-line">|</span>
<span className="flex items-center" role="group" aria-label={t.starsAtLeast}>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
onClick={() => set({ minRating: f.minRating === n ? 0 : n })}
aria-pressed={f.minRating === n}
aria-label={t.starsOrMore(n)}
title={t.starsOrMore(n)}
className={`px-[1px] text-[13px] ${n <= f.minRating ? "text-star" : "text-faint hover:text-muted"}`}
>
★
</button>
))}
</span>
<span className="flex items-center gap-1" role="group" aria-label={t.colorLabel}>
{COLORS.map((c) => (
<button
key={c}
onClick={() => set({ color: f.color === c ? null : c })}
aria-pressed={f.color === c}
aria-label={t.colors[c]}
title={t.colors[c]}
className={`h-3 w-3 rounded-[2px] ${f.color === c ? "outline outline-1 outline-offset-1 outline-white" : "opacity-60 hover:opacity-100"}`}
style={{ background: LABEL_COLOR[c] ?? undefined }}
/>
))}
</span>
<span aria-hidden="true" className="text-line">|</span>
<label className="flex items-center gap-1">
<span className="text-faint">{t.deliveryFilter}</span>
<select
value={f.delivery}
onChange={(e) => set({ delivery: e.target.value as LibraryFilter["delivery"] })}
className={`h-6 border border-black bg-cell px-1 text-[12px] ${f.delivery === "any" ? "text-muted" : "text-ink"}`}
>
{DELIVERY.map((d) => (
<option key={d} value={d}>
{t.deliveryStates[d]}
</option>
))}
</select>
</label>
<button onClick={() => set({ noPlayers: !f.noPlayers })} aria-pressed={f.noPlayers} className={chip(f.noPlayers)}>
{t.noPlayersFilter}
</button>
{!isAll(f) && (
<button onClick={() => onChange(ALL_PHOTOS)} className="text-accent hover:underline">
{t.clearFilter}
</button>
)}
</div>
);
}
+24 -4
View File
@@ -1,5 +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,
@@ -26,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}
@@ -44,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>
)}
@@ -58,6 +63,15 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
</span>
<span aria-hidden="true" className="h-2.5 w-2.5 rounded-[2px]" style={{ background: label ?? "transparent" }} />
</span>
{photo.delivery && photo.delivery !== "NONE" && (
<span
title={t.deliveryBadge[photo.delivery]}
aria-label={t.deliveryBadge[photo.delivery]}
className={`absolute left-1.5 top-1 text-[11px] font-bold ${photo.delivery === "DONE" ? "text-ok" : photo.delivery === "FAILED" ? "text-[#f0a35a]" : "text-[#7fb0ff]"}`}
>
{photo.delivery === "DONE" ? "✓" : photo.delivery === "FAILED" ? "!" : "↑"}
</span>
)}
{photo.players.length > 0 && (
<span className="absolute right-1.5 top-1 max-w-[70%] truncate text-[10px] text-muted">{photo.players[0]}</span>
)}
@@ -101,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;
}
+5 -2
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,
@@ -50,9 +51,9 @@ describe("local FTP feed", () => {
{ path: "/x/FTP/B.JPG", name: "B.JPG", size: 10, modifiedMs: 2 },
]);
const added: { name: string; eventId: string | undefined; size: number; sha?: string }[] = [];
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string }) => {
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
for (const f of files) {
added.push({ name: f.name, eventId, size: f.size, ...(original && { sha: original.sha256 }) });
added.push({ name: f.name, eventId, size: f.size, ...(original && original !== "original" && { sha: original.sha256 }) });
onSettled?.(f, f.name === "A.JPG" ? "done" : "failed");
}
};
@@ -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" },
+30 -9
View File
@@ -1,8 +1,12 @@
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";
import type { PreviewOf, UploadStatus } from "./uploads.js";
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
/** Settings kept by the desktop shell (apps/desktop/src-tauri/src/ftp.rs). */
export interface FtpSettings {
@@ -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?: PreviewOf) => 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,21 +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 });
add([file], to?.id, (_file, result) => {
// 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, 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);
}, full ? "original" : info);
} catch {
inFlight.current--;
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
+76
View File
@@ -0,0 +1,76 @@
import type { DeliveryItemSummary, PhotoSummary } from "@photoreport/contracts";
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";
/**
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to a
* destination. With no destination yet it leads to where one is set up.
*/
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; onQueued: (items: DeliveryItemSummary[]) => void }) {
const { api, orgId, selection, targets } = props;
const navigate = useNavigate();
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<string | null>(null);
useEffect(() => {
if (targets.length && !targets.some((x) => x.id === targetId)) setTargetId(targets[0]!.id);
}, [targets, targetId]);
useEffect(() => {
if (!note) return;
const timer = setTimeout(() => setNote(null), 5000);
return () => clearTimeout(timer);
}, [note]);
if (!targets.length) {
return (
<button onClick={() => navigate("/delivery")} title={t.noTargetsHelp} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.setUpDelivery}
</button>
);
}
const photos = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY");
const send = async () => {
setBusy(true);
try {
// 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(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
} catch (err) {
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
} finally {
setBusy(false);
}
};
return (
<span className="flex items-center gap-1">
{targets.length > 1 && (
<select aria-label={t.deliverTo} value={targetId} onChange={(e) => setTargetId(e.target.value)} className="h-6 max-w-[140px] border border-black bg-cell px-1 text-[12px] text-ink">
{targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
)}
<button
onClick={() => void send()}
disabled={busy || !photos.length || !targetId}
title={photos.length ? `${t.sendTo} ${targets.find((x) => x.id === targetId)?.name ?? ""}` : t.selectToSend}
className="h-6 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
>
{t.sendN(photos.length)}
</button>
{note && <span className="text-[11px] text-ok">{note}</span>}
</span>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { beforeEach, describe, expect, it } from "vitest";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "./active.js";
import { ALL_PHOTOS } from "./store.js";
describe("active photo across modules", () => {
beforeEach(() => window.localStorage.clear());
it("remembers the photo you were on for its folder, and the library filter", () => {
expect(activePhoto("o1", "e1")).toBeNull();
setActivePhoto("o1", "e1", "p7");
expect(activePhoto("o1", "e1")).toBe("p7");
// Another folder (or organization) does not open on it.
expect(activePhoto("o1", "e2")).toBeNull();
expect(activePhoto("o2", "e1")).toBeNull();
// Search results are not a folder to come back to.
setActivePhoto("o1", "search:Rui", "p9");
expect(activePhoto("o1", "e1")).toBe("p7");
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
const picksToSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
saveFilter("o1", picksToSend);
expect(savedFilter("o1")).toEqual(picksToSend);
// A filter saved by the previous version (one choice) still opens.
window.localStorage.setItem("pr.filter:o1", "stars");
expect(savedFilter("o1")).toEqual({ ...ALL_PHOTOS, minRating: 3 });
window.localStorage.setItem("pr.filter:o1", "nonsense");
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
});
});
+67
View File
@@ -0,0 +1,67 @@
import { prefs } from "../platform.js";
import { ALL_PHOTOS, type LibraryFilter } from "./store.js";
/**
* Lightroom's active photo: the one every module opens on. Library (grid and loupe) and Develop share it, so
* going from one to the other (D, G, E or the module links) stays on the photo you were on. Kept per
* organization with the folder (event, inbox) it belongs to, and survives a reload.
*/
interface ActivePhoto {
scope: string;
id: string;
}
const activeKey = (orgId: string) => `active:${orgId}`;
const filterKey = (orgId: string) => `filter:${orgId}`;
/** The active photo of that folder, if there is one. */
export function activePhoto(orgId: string, scope: string | null | undefined): string | null {
if (!orgId || !scope) return null;
try {
const v = JSON.parse(prefs.get(activeKey(orgId)) ?? "null") as ActivePhoto | null;
return v && typeof v.id === "string" && v.scope === scope ? v.id : null;
} catch {
return null;
}
}
export function setActivePhoto(orgId: string, scope: string | null | undefined, id: string | null | undefined): void {
if (!orgId || !scope || !id || scope.startsWith("search:")) return;
prefs.set(activeKey(orgId), JSON.stringify({ scope, id } satisfies ActivePhoto));
}
/** Filters saved by earlier versions (one choice at a time). */
const LEGACY: Record<string, Partial<LibraryFilter>> = {
all: {},
PICK: { flag: "PICK" },
UNREJECTED: { flag: "UNREJECTED" },
REJECT: { flag: "REJECT" },
stars: { minRating: 3 },
noPlayers: { noPlayers: true },
};
const FLAGS = ["all", "PICK", "UNREJECTED", "REJECT", "UNFLAGGED"];
const DELIVERY = ["any", "unsent", "queued", "sent", "failed"];
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"];
/** The library filter, which Develop's filmstrip follows too (as Lightroom's filmstrip does). */
export function savedFilter(orgId: string): LibraryFilter {
const raw = prefs.get(filterKey(orgId));
if (!raw) return ALL_PHOTOS;
if (raw in LEGACY) return { ...ALL_PHOTOS, ...LEGACY[raw] };
try {
const v = JSON.parse(raw) as Partial<LibraryFilter>;
return {
flag: FLAGS.includes(v.flag as string) ? v.flag! : "all",
minRating: Number.isInteger(v.minRating) && v.minRating! >= 0 && v.minRating! <= 5 ? v.minRating! : 0,
color: COLORS.includes(v.color as string) ? v.color! : null,
delivery: DELIVERY.includes(v.delivery as string) ? v.delivery! : "any",
noPlayers: v.noPlayers === true,
};
} catch {
return ALL_PHOTOS;
}
}
export function saveFilter(orgId: string, filter: LibraryFilter): void {
if (orgId) prefs.set(filterKey(orgId), JSON.stringify(filter));
}
+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} />}
+45 -3
View File
@@ -1,6 +1,6 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { initialLibrary, libraryReducer, matchesFilter, patchForKey } from "./store.js";
import { ALL_PHOTOS, initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "./store.js";
const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}): PhotoSummary => ({
id,
@@ -60,7 +60,49 @@ describe("library store", () => {
expect(patchForKey("4")).toEqual({ rating: 4 });
expect(patchForKey("6")).toEqual({ colorLabel: "RED" });
expect(patchForKey("q")).toBeUndefined();
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), "UNREJECTED")).toBe(false);
expect(matchesFilter(photo("a", "", { players: ["x"] }), "noPlayers")).toBe(false);
const f = (patch: Partial<LibraryFilter>) => ({ ...ALL_PHOTOS, ...patch });
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), f({ flag: "UNREJECTED" }))).toBe(false);
expect(matchesFilter(photo("a", "", { players: ["x"] }), f({ noPlayers: true }))).toBe(false);
});
it("combines filters as Photo Mechanic does: picks with 2+ stars not sent yet", () => {
const toSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3 }), toSend)).toBe(true);
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3, delivery: "DONE" }), toSend)).toBe(false);
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 1 }), toSend)).toBe(false);
expect(matchesFilter(photo("a", "", { flag: "NONE", rating: 5 }), toSend)).toBe(false);
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), { ...ALL_PHOTOS, color: "GREEN" })).toBe(false);
expect(matchesFilter(photo("a", "", { delivery: "FAILED" }), { ...ALL_PHOTOS, delivery: "failed" })).toBe(true);
});
it("follows deliveries live: on its way, then sent (a later failure elsewhere doesn't undo sent)", () => {
const item = (status: "QUEUED" | "DONE" | "FAILED") => ({ id: "i", targetId: "t", photoId: "a", eventId: "e1", sequence: 1, status, attempts: 0, lastError: null, remotePath: null, byteSize: null, updatedAt: "" });
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("QUEUED") } });
expect(s.photos[0]!.delivery).toBe("QUEUED");
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("DONE") } });
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("FAILED") } });
expect(s.photos[0]!.delivery).toBe("DONE");
});
it("comes back to the active photo from another module, once its page arrives, unless you pick one first", () => {
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "c" });
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
// Not on the first page yet: the first photo shows meanwhile.
expect(s.focus).toBe("a");
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
expect([s.focus, [...s.selected], s.wanted]).toEqual(["c", ["c"], null]);
let t = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "d" });
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
t = libraryReducer(t, { type: "select", id: "b", mode: "single", visible: ["a", "b"] });
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
expect(t.focus).toBe("b");
// Gone (deleted, moved): the first photo, and nothing left to look for.
let u = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "zz" });
u = libraryReducer(u, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
expect([u.focus, u.wanted]).toEqual(["a", null]);
});
});
+91 -24
View File
@@ -1,4 +1,4 @@
import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
import type { ColorLabel, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
/** Photos of the open event (or the inbox), in capture order, plus the selection. */
export interface LibraryState {
@@ -9,18 +9,22 @@ export interface LibraryState {
/** The photo keyboard actions start from (and the one shown in the loupe). */
focus: string | null;
anchor: string | null;
/** The active photo to come back to once its page has loaded (the folder may be long). */
wanted: string | null;
}
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null };
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null, wanted: null };
export type LibraryAction =
| { type: "load"; scope: string }
| { type: "load"; scope: string; focus?: string | null }
| { type: "loaded"; scope: string; photos: PhotoSummary[]; done: boolean }
| { type: "message"; message: LibraryMessage }
| { 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);
@@ -40,25 +44,59 @@ 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":
return { ...initialLibrary, scope: action.scope, loading: true };
return { ...initialLibrary, scope: action.scope, loading: true, wanted: action.focus ?? null };
case "loaded": {
if (action.scope !== state.scope) return state;
const seen = new Set(state.photos.map((p) => p.id));
const photos = [...state.photos, ...action.photos.filter((p) => !seen.has(p.id))];
// The active photo from another module (or the last visit): selected as soon as its page arrives.
if (state.wanted && photos.some((p) => p.id === state.wanted)) {
const id = state.wanted;
return { ...state, photos, loading: !action.done, focus: id, selected: new Set([id]), anchor: id, wanted: null };
}
const focus = state.focus ?? photos[0]?.id ?? null;
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus };
const wanted = action.done ? null : state.wanted;
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus, wanted };
}
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) };
}
if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch });
if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) };
if (m.type === "delivery.updated") {
const { photoId, status } = m.item;
return {
...state,
photos: state.photos.map((p) => {
if (p.id !== photoId || p.delivery === "DONE") return p;
const delivery = status === "DONE" ? "DONE" : status === "FAILED" ? (p.delivery === "QUEUED" ? "QUEUED" : "FAILED") : "QUEUED";
return { ...p, delivery };
}),
};
}
if (m.type === "photo.rendered") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)) };
return state;
}
@@ -69,9 +107,23 @@ 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;
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id };
// Picking a photo by hand wins over the one still being looked for.
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id, wanted: null };
if (mode === "toggle") {
const selected = new Set(state.selected);
if (selected.has(id)) selected.delete(id);
@@ -92,28 +144,43 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
const at = state.focus ? visible.indexOf(state.focus) : -1;
const next = visible[Math.max(0, Math.min(visible.length - 1, at < 0 ? 0 : at + delta))]!;
if (extend) return libraryReducer({ ...state }, { type: "select", id: next, mode: "range", visible });
return { ...state, selected: new Set([next]), focus: next, anchor: next };
return { ...state, selected: new Set([next]), focus: next, anchor: next, wanted: null };
}
}
}
export type FilterId = "all" | "PICK" | "UNREJECTED" | "REJECT" | "stars" | "noPlayers";
/**
* The library filter, combinable as in Photo Mechanic and Lightroom's filter bar: flag, minimum stars, colour,
* delivery state and photos still without players. Every part narrows; the defaults show everything.
*/
export interface LibraryFilter {
flag: "all" | "PICK" | "UNREJECTED" | "REJECT" | "UNFLAGGED";
minRating: number;
color: ColorLabel | null;
delivery: "any" | "unsent" | "queued" | "sent" | "failed";
noPlayers: boolean;
}
export function matchesFilter(photo: PhotoSummary, filter: FilterId): boolean {
switch (filter) {
case "all":
return true;
case "PICK":
return photo.flag === "PICK";
case "REJECT":
return photo.flag === "REJECT";
case "UNREJECTED":
return photo.flag !== "REJECT";
case "stars":
return photo.rating >= 3;
case "noPlayers":
return photo.players.length === 0;
}
export const ALL_PHOTOS: LibraryFilter = { flag: "all", minRating: 0, color: null, delivery: "any", noPlayers: false };
export function isAll(f: LibraryFilter): boolean {
return f.flag === "all" && !f.minRating && !f.color && f.delivery === "any" && !f.noPlayers;
}
export function matchesFilter(photo: PhotoSummary, f: LibraryFilter): boolean {
if (f.flag === "PICK" && photo.flag !== "PICK") return false;
if (f.flag === "REJECT" && photo.flag !== "REJECT") return false;
if (f.flag === "UNREJECTED" && photo.flag === "REJECT") return false;
if (f.flag === "UNFLAGGED" && photo.flag !== "NONE") return false;
if (f.minRating && photo.rating < f.minRating) return false;
if (f.color && photo.colorLabel !== f.color) return false;
const d = photo.delivery ?? "NONE";
if (f.delivery === "unsent" && d !== "NONE") return false;
if (f.delivery === "queued" && d !== "QUEUED") return false;
if (f.delivery === "sent" && d !== "DONE") return false;
if (f.delivery === "failed" && d !== "FAILED") return false;
if (f.noPlayers && photo.players.length) return false;
return true;
}
/** Lightroom keys: P pick, X reject, U unflag, 0–5 stars, 6–9 colour labels (red, yellow, green, blue). */
+41 -12
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;
@@ -63,20 +65,23 @@ export interface PreviewOf {
height: number;
}
/** What a desktop ingest sends: a preview standing for its original, or the full original ("original"). */
export type DesktopOrigin = PreviewOf | "original";
export async function sendResumable(
api: ApiClient,
orgId: string,
file: File,
eventId: string | undefined,
onProgress: (p: number) => void,
original?: PreviewOf,
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 }), ...(original && { original }) }),
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }),
"application/json",
);
if (begin.status !== 200 && begin.status !== 201) return begin;
@@ -131,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?: PreviewOf; 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(
@@ -163,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 unreadable = (res.body as { photo?: { status?: string } } | null)?.photo?.status === "FAILED";
if (unreadable) res.body = { error: "processing_failed" };
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?: PreviewOf) => {
(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 };
@@ -192,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 };
}
+68 -13
View File
@@ -8,7 +8,12 @@ import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js";
import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
import { IptcInfo } from "../library/IptcInfo.js";
import { applyPatch, patchForKey } from "../library/store.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";
import { isDesktop, localOriginal, prefs } from "../platform.js";
@@ -28,6 +33,8 @@ const ASPECTS: { label: string; value: [number, number] | "original" | null }[]
];
const CLIPBOARD = "develop.clipboard";
/** The filmstrip loads the whole folder in pages of this size (a match can have thousands of photos). */
const PAGE = 500;
/** The aspect a new crop starts with (the last one chosen): "free", "original" or "W:H". Lightroom's default is the original. */
const CROP_ASPECT = "develop.cropAspect";
type AspectChoice = (typeof ASPECTS)[number]["value"];
@@ -90,26 +97,71 @@ export function DevelopPage() {
api.listDeliveryTargets(orgId).then((r) => setTargets(r.targets.filter((x) => !x.disabledAt)), () => {});
}, [api, orgId, role]);
// The event (or inbox) the library has open.
// The event (or inbox) the library has open, all of it (page by page), as the library shows it.
const scope = orgId ? (prefs.get(`scope:${orgId}`) ?? null) : null;
const [all, setAll] = useState<PhotoSummary[] | null>(null);
useEffect(() => {
if (!orgId) return;
const scope = prefs.get(`scope:${orgId}`) ?? undefined;
api.listPhotos(orgId, { ...(scope && { event: scope }), limit: 500 }).then(
(r) => setPhotos(r.photos.filter((p) => p.status === "READY")),
() => setPhotos([]),
);
}, [api, orgId]);
let alive = true;
void (async () => {
const got: PhotoSummary[] = [];
try {
for (let offset = 0; ; offset += PAGE) {
const page = await api.listPhotos(orgId, { ...(scope && { event: scope }), offset, limit: PAGE });
got.push(...page.photos);
if (!alive) return;
setAll([...got]);
if (offset + page.photos.length >= page.total || page.photos.length === 0) break;
}
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 (!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);
}, [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.
useEffect(() => {
if (!photoId && photos[0]) navigate(`/develop/${photos[0].id}`, { replace: true });
}, [photoId, photos, navigate]);
if (photoId || !photos.length) return;
const active = activePhoto(orgId, scope);
const start = (active && photos.find((p) => p.id === active)) || photos[0]!;
navigate(`/develop/${start.id}`, { replace: true });
}, [photoId, photos, navigate, orgId, scope]);
useEffect(() => {
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);
@@ -154,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)));
});
@@ -192,6 +245,8 @@ export function DevelopPage() {
else if (e.key === "ArrowLeft") go(-1);
else if (e.key === "\\") setBefore((b) => !b);
else if (!mod && !e.altKey && e.key.toLowerCase() === "g") navigate("/", { state: { focus: current?.id } });
// Lightroom: E is the library loupe on the same photo.
else if (!mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "e") navigate("/", { state: { focus: current?.id, loupe: true } });
else if (!mod && e.shiftKey && e.key.toLowerCase() === "a" && canEdit) void autoAllRef.current();
else if (!mod && !e.shiftKey && e.key.toLowerCase() === "i" && canCull && current) setInfo(true);
else if (!mod && !e.altKey && patchForKey(e.key)) {
+130 -23
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";
@@ -16,11 +16,17 @@ import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { type FilterId, initialLibrary, libraryReducer, matchesFilter, patchForKey } from "../library/store.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";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
const PAGE = 500;
const FILTERS: FilterId[] = ["all", "PICK", "UNREJECTED", "REJECT", "stars", "noPlayers"];
const isTyping = (target: EventTarget | null) =>
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
@@ -37,7 +43,15 @@ export function LibraryPage() {
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false);
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilter] = useState<FilterId>("all");
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
const setFilter = useCallback(
(f: LibraryFilter) => {
setFilterState(f);
saveFilter(orgId, f);
},
[orgId],
);
const [loupe, setLoupe] = useState(false);
const [creating, setCreating] = useState(false);
const [view, setView] = useState<"grid" | "faces">("grid");
@@ -50,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;
@@ -58,7 +81,8 @@ export function LibraryPage() {
const open = useCallback(
async (scope: string) => {
dispatch({ type: "load", scope });
// Back on the photo that was active here, in any module (Lightroom keeps one active photo).
dispatch({ type: "load", scope, focus: activePhoto(orgId, scope) });
setLoupe(false);
setSuggested([]);
if (scope.startsWith("search:")) {
@@ -70,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],
);
@@ -95,18 +129,45 @@ export function LibraryPage() {
};
}, [api, orgId, canCull, loadEvents, open]);
// Photos moved between events (by hand, or claimed from "Sem evento" when an event is created or its times
// change): the counts follow, and the open event shows the ones that arrived in it.
const scopeRef = useRef(state.scope);
scopeRef.current = state.scope;
const moved = useRef<ReturnType<typeof setTimeout> | null>(null);
const onMoved = useCallback(
(eventId: string | null) => {
if (moved.current) clearTimeout(moved.current);
moved.current = setTimeout(() => {
void loadEvents().catch(() => {});
if (eventId !== null && scopeRef.current === eventId) void open(eventId).catch(() => {});
}, 400);
},
[loadEvents, open],
);
const onMessage = useCallback(
(message: LibraryMessage) => {
dispatch({ type: "message", message });
if (message.type === "photo.updated" && message.patch.eventId !== undefined) onMoved(message.patch.eventId);
if (message.type === "faces.updated") setFacesTick((n) => n + 1);
if (message.type === "photo.added") {
if (message.photo.eventId === null) setInboxCount((n) => n + 1);
else setEvents((list) => list.map((e) => (e.id === message.photo.eventId ? { ...e, photoCount: e.photoCount + 1 } : e)));
}
},
[dispatch],
[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);
@@ -128,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);
@@ -175,15 +237,22 @@ export function LibraryPage() {
return () => window.removeEventListener("keydown", onKey);
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull]);
// The photo you are on is the active one for every module (Develop opens on it).
useEffect(() => {
if (!state.wanted) setActivePhoto(orgId, state.scope, state.focus);
}, [orgId, state.scope, state.focus, state.wanted]);
// Back from Develop (G): the photo that was open there is the one selected here.
const location = useLocation();
const backFocus = (location.state as { focus?: string } | null)?.focus;
const back = location.state as { focus?: string; loupe?: boolean } | null;
const backFocus = back?.focus;
useEffect(() => {
if (!backFocus || !state.photos.some((p) => p.id === backFocus)) return;
dispatch({ type: "select", id: backFocus, mode: "single", visible: [] });
if (back?.loupe) setLoupe(true);
requestAnimationFrame(() => document.querySelector(`[data-photo-id="${backFocus}"]`)?.scrollIntoView({ block: "nearest" }));
navigate(".", { replace: true, state: null });
}, [backFocus, state.photos, navigate]);
}, [backFocus, back?.loupe, state.photos, navigate]);
const onPick = useCallback(
(id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }),
@@ -229,12 +298,7 @@ export function LibraryPage() {
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
<span className="text-faint">{t.filter}:</span>
{FILTERS.map((f) => (
<button key={f} onClick={() => setFilter(f)} aria-pressed={filter === f} className={filter === f ? "font-semibold text-ink" : "text-faint hover:text-muted"}>
{t.filters[f]}
</button>
))}
<FilterBar filter={filter} onChange={setFilter} />
{canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && (
<button
onClick={() => setView(view === "faces" ? "grid" : "faces")}
@@ -282,6 +346,44 @@ export function LibraryPage() {
))}
</select>
)}
{canCull && (
<SendButton
api={api}
orgId={orgId}
selection={selection}
targets={targets}
onQueued={(items) => items.forEach((item) => dispatch({ type: "message", message: { type: "delivery.updated", item } }))}
/>
)}
{canCull && selection.length > 0 && !state.scope?.startsWith("search:") && (
<select
aria-label={t.moveToEvent}
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
value=""
onChange={(e) => {
const target = events.find((x) => x.id === e.target.value);
if (!target) return;
const ids = selection.map((p) => p.id);
void api.updatePhotos(orgId, ids, { eventId: target.id }).then(
() => {
dispatch({ type: "patch", ids, patch: { eventId: target.id } });
setInfo(t.movedToEvent(ids.length, target.title));
setTimeout(() => setInfo(null), 4000);
},
() => setError(t.unexpectedError),
);
}}
>
<option value="">{t.moveToEvent}…</option>
{events
.filter((x) => x.id !== state.scope && !x.archivedAt)
.map((x) => (
<option key={x.id} value={x.id}>
{x.title}
</option>
))}
</select>
)}
{info && <span className="text-[11px] text-ok">{info}</span>}
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && (
<button
@@ -312,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>
@@ -344,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} />
+2 -1
View File
@@ -4,7 +4,7 @@ import { useAuth } from "../auth.js";
import { Bell } from "../components/Bell.js";
import { Logo } from "../components/ui.js";
import { t } from "../i18n.js";
import { UpdateNotice } from "../desktop/UpdateNotice.js";
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
import { IngestProvider } from "../library/ingest.js";
const moduleClass = ({ isActive }: { isActive: boolean }) =>
@@ -116,6 +116,7 @@ export function Shell() {
</details>
</header>
<UpdateNotice />
<UiReadyNotice />
<main className="min-h-0 flex-1 overflow-auto">
<IngestProvider>
<Outlet />
+5
View File
@@ -1,5 +1,10 @@
import type { RefreshTokenStore } from "@photoreport/sdk";
/** Set by the desktop app before the page runs (apps/desktop/src-tauri/src/lib.rs, `init_script`). */
export function desktopConfig(): { api: string; app: string } | undefined {
return typeof window === "undefined" ? undefined : (window as { __PHOTOREPORT__?: { api: string; app: string } }).__PHOTOREPORT__;
}
/** True inside the Tauri desktop shell. */
export const isDesktop = (): boolean => typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.3",
"version": "0.3.7",
"private": true,
"type": "module",
"scripts": {
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.3"
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."
@@ -30,6 +30,9 @@ sha2 = "0.10"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] }
rustls = { version = "0.23", default-features = false, features = ["ring"] }
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
# a disassembler what machine code does, not what the functions were called.
+3
View File
@@ -9,6 +9,7 @@ fn main() {
"ftp_start",
"ftp_stop",
"ftp_status",
"ftp_check",
"ftp_take",
"ftp_retry",
"ftp_read",
@@ -26,6 +27,8 @@ fn main() {
"catalog_cancel",
"update_check",
"update_install",
"ui_status",
"ui_check",
]),
))
.expect("failed to run tauri-build");
@@ -1,7 +1,7 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the web app from the server (always the latest version), so the server's pages get the same access.",
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the interface kept on this computer (updated in the background from the server); the server's pages keep the same access.",
"windows": [
"main"
],
@@ -24,6 +24,7 @@
"allow-ftp-start",
"allow-ftp-stop",
"allow-ftp-status",
"allow-ftp-check",
"allow-ftp-take",
"allow-ftp-retry",
"allow-ftp-read",
@@ -40,7 +41,9 @@
"allow-catalog-status",
"allow-catalog-cancel",
"allow-update-check",
"allow-update-install"
"allow-update-install",
"allow-ui-status",
"allow-ui-check"
],
"remote": {
"urls": [
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-ftp-check"
description = "Enables the ftp_check command without any pre-configured scope."
commands.allow = ["ftp_check"]
[[permission]]
identifier = "deny-ftp-check"
description = "Denies the ftp_check command without any pre-configured scope."
commands.deny = ["ftp_check"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-ui-check"
description = "Enables the ui_check command without any pre-configured scope."
commands.allow = ["ui_check"]
[[permission]]
identifier = "deny-ui-check"
description = "Denies the ui_check command without any pre-configured scope."
commands.deny = ["ui_check"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-ui-status"
description = "Enables the ui_status command without any pre-configured scope."
commands.allow = ["ui_status"]
[[permission]]
identifier = "deny-ui-status"
description = "Denies the ui_status command without any pre-configured scope."
commands.deny = ["ui_status"]
+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
+37 -29
View File
@@ -8,35 +8,31 @@ mod catalog;
mod ftp;
mod local;
mod preview;
mod ui;
mod updater;
use keyring::Entry;
use tauri::{WebviewUrl, WebviewWindowBuilder};
/// The web app the window shows. Loading it from the server means the desktop app is always on the latest version:
/// every web deploy updates it, with no installer to rebuild. Set at build time (`PHOTOREPORT_APP_URL`).
const APP_URL: &str = match option_env!("PHOTOREPORT_APP_URL") {
/// Where new versions of the interface are published (`ui-manifest.json`, see `ui`). Set at build time
/// (`PHOTOREPORT_APP_URL`).
pub(crate) const APP_URL: &str = match option_env!("PHOTOREPORT_APP_URL") {
Some(url) => url,
None => "https://app.next.photoreport.pt",
};
/// Whether the server answers: without a network the window opens the copy of the web app bundled in the installer
/// (same interface, the photo engine included), so local work (catalogue, local FTP, editing originals on disk with
/// the offline queue) still goes on. A TCP connection within 2.5 s is enough: a slow network still gets the live app.
fn server_reachable(url: &str) -> bool {
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
let Ok(parsed) = url.parse::<tauri::Url>() else {
return false;
};
let Some(host) = parsed.host_str() else {
return false;
};
let port = parsed.port_or_known_default().unwrap_or(443);
let Ok(mut addrs) = (host, port).to_socket_addrs() else {
return false;
};
addrs.any(|a| TcpStream::connect_timeout(&a, Duration::from_millis(2500)).is_ok())
const API_URL: &str = match option_env!("PHOTOREPORT_API_URL") {
Some(url) => url,
None => "https://api.next.photoreport.pt",
};
/// Tells the interface (whichever version is on disk) where the API is and where its updates come from.
fn init_script() -> String {
format!(
"window.__PHOTOREPORT__ = Object.freeze({{ api: {}, app: {} }});",
serde_json::to_string(API_URL).unwrap(),
serde_json::to_string(APP_URL).unwrap()
)
}
const KEYCHAIN_SERVICE: &str = "pt.photoreport.desktop";
@@ -70,6 +66,14 @@ fn refresh_token_clear() -> Result<(), String> {
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// The interface is served from disk: the downloaded version in use, else the installer's copy (see `ui`).
let shared = ui::Ui::default();
let mut context = tauri::generate_context!();
let embedded = context.set_assets(Box::new(ui::NoAssets));
context.set_assets(Box::new(ui::UiAssets {
embedded,
shared: shared.clone(),
}));
let result = tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_dialog::init())
@@ -77,17 +81,19 @@ pub fn run() {
.manage(ftp::FtpState::default())
.manage(local::LocalIndex::default())
.manage(catalog::Catalog::default())
.manage(shared)
.setup(|app| {
use tauri::Manager;
ftp::auto_start(&app.state::<ftp::FtpState>());
// `tauri dev` keeps using the local dev server; installed builds load the live web app, or the bundled
// copy when the server can't be reached.
let url = if cfg!(debug_assertions) || !server_reachable(APP_URL) {
WebviewUrl::App("index.html".into())
} else {
WebviewUrl::External(APP_URL.parse().expect("PHOTOREPORT_APP_URL must be a URL"))
};
// `tauri dev` serves the dev server: nothing to update.
if !cfg!(debug_assertions) {
ui::watch(app.handle().clone());
}
// Always the interface on this computer (`tauri dev`: the dev server). No download to start, and it
// works without a network; new versions arrive in the background (see `ui`).
let url = WebviewUrl::App("index.html".into());
WebviewWindowBuilder::new(app, "main", url)
.initialization_script(init_script())
.title("PhotoReport")
.inner_size(1440.0, 900.0)
.min_inner_size(1024.0, 680.0)
@@ -119,9 +125,11 @@ pub fn run() {
catalog::catalog_status,
catalog::catalog_cancel,
updater::update_check,
updater::update_install
updater::update_install,
ui::ui_status,
ui::ui_check
])
.run(tauri::generate_context!());
.run(context);
if let Err(err) = result {
eprintln!("PhotoReport desktop failed to start: {err}");
std::process::exit(1);
+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;
+473
View File
@@ -0,0 +1,473 @@
//! The interface lives on this computer. The window always opens the web app from disk (no download to start, works
//! without a network); new versions of the interface are fetched in the background, only the files that changed, and
//! used from the next start (or when the photographer chooses to reload).
//!
//! Every web deploy publishes `ui-manifest.json` next to the app (path, size and SHA-256 of each file, when it was
//! built). In the background (`watch`, or now with `ui_check`) the app compares it with the version in use, copies
//! the files it already has (same hash, in the installer or the version in use), downloads only the others, checks
//! every hash, then switches and tells the window (`ui-ready`). The installer's own copy is the fallback, and wins
//! when it is newer (after a shell update).
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::borrow::Cow;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, RwLock};
use tauri::utils::assets::{AssetKey, AssetsIter, CspHash};
use tauri::{App, Assets, Manager, Runtime};
const MANIFEST: &str = "ui-manifest.json";
const CURRENT: &str = "current";
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ManifestFile {
pub path: String,
pub size: u64,
pub sha256: String,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
pub version: String,
/// ISO 8601; compares as text.
pub built_at: String,
pub files: Vec<ManifestFile>,
}
/// Shared by the asset provider (which serves the files) and the commands (which install new versions).
#[derive(Default)]
pub struct UiShared {
/// `<app data>/ui`: one folder per version, and `current` naming the one in use.
root: RwLock<Option<PathBuf>>,
/// The downloaded version in use, when it is newer than the installer's.
active: RwLock<Option<(Manifest, PathBuf)>>,
/// The installer's own copy.
embedded: RwLock<Option<Manifest>>,
}
pub type Ui = Arc<UiShared>;
/// A path from the manifest or the webview, made safe to join under a folder: no `..`, no absolute paths.
fn safe(rel: &str) -> Option<PathBuf> {
let rel = rel.trim_start_matches('/');
let p = Path::new(rel);
if rel.is_empty() || p.components().any(|c| !matches!(c, Component::Normal(_))) {
return None;
}
Some(p.to_path_buf())
}
fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn read_manifest(dir: &Path) -> Option<Manifest> {
serde_json::from_slice(&std::fs::read(dir.join(MANIFEST)).ok()?).ok()
}
impl UiShared {
/// Picks the version to serve: the downloaded one named in `current` if it is complete and newer than the
/// installer's copy.
fn choose(&self, root: &Path) {
let embedded_at = self
.embedded
.read()
.unwrap()
.as_ref()
.map(|m| m.built_at.clone())
.unwrap_or_default();
let chosen = std::fs::read_to_string(root.join(CURRENT))
.ok()
.and_then(|name| safe(name.trim()))
.map(|name| root.join(name))
.and_then(|dir| read_manifest(&dir).map(|m| (m, dir)))
.filter(|(m, dir)| m.built_at > embedded_at && dir.join("index.html").is_file());
*self.active.write().unwrap() = chosen;
}
fn status(&self) -> UiStatus {
if let Some((m, _)) = self.active.read().unwrap().as_ref() {
return UiStatus {
version: m.version.clone(),
built_at: m.built_at.clone(),
downloaded: true,
};
}
let e = self.embedded.read().unwrap();
UiStatus {
version: e.as_ref().map(|m| m.version.clone()).unwrap_or_default(),
built_at: e.as_ref().map(|m| m.built_at.clone()).unwrap_or_default(),
downloaded: false,
}
}
fn root(&self) -> Result<PathBuf, String> {
self.root
.read()
.unwrap()
.clone()
.ok_or_else(|| "ui_not_ready".into())
}
}
/// Serves the interface: the downloaded version in use when there is one, else (and for anything it lacks) the
/// copy built into the installer. The window's origin stays the app's own, so nothing else changes.
pub struct UiAssets<R: Runtime> {
pub embedded: Box<dyn Assets<R>>,
pub shared: Ui,
}
impl<R: Runtime> Assets<R> for UiAssets<R> {
fn setup(&self, app: &App<R>) {
self.embedded.setup(app);
let embedded: Option<Manifest> = self
.embedded
.get(&AssetKey::from(MANIFEST))
.and_then(|b| serde_json::from_slice(&b).ok());
*self.shared.embedded.write().unwrap() = embedded;
if let Ok(dir) = app.path().app_data_dir() {
let root = dir.join("ui");
let _ = std::fs::create_dir_all(&root);
self.shared.choose(&root);
*self.shared.root.write().unwrap() = Some(root);
}
}
fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {
if let Some((_, dir)) = self.shared.active.read().unwrap().as_ref()
&& let Some(rel) = safe(key.as_ref())
&& let Ok(bytes) = std::fs::read(dir.join(rel))
{
return Some(Cow::Owned(bytes));
}
self.embedded.get(key)
}
fn iter(&self) -> Box<AssetsIter<'_>> {
self.embedded.iter()
}
fn csp_hashes(&self, html_path: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
self.embedded.csp_hashes(html_path)
}
}
/// An empty provider, only to take the generated one out of the context.
pub struct NoAssets;
impl<R: Runtime> Assets<R> for NoAssets {
fn get(&self, _: &AssetKey) -> Option<Cow<'_, [u8]>> {
None
}
fn iter(&self) -> Box<AssetsIter<'_>> {
Box::new(std::iter::empty())
}
fn csp_hashes(&self, _: &AssetKey) -> Box<dyn Iterator<Item = CspHash<'_>> + '_> {
Box::new(std::iter::empty())
}
}
#[derive(Clone, Debug, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct UiStatus {
pub version: String,
pub built_at: String,
/// False: the installer's copy.
pub downloaded: bool,
}
/// The interface version in use.
#[tauri::command]
pub fn ui_status(ui: tauri::State<'_, Ui>) -> UiStatus {
ui.status()
}
/// Looks for a newer interface now (it is also done in the background): true when one was installed, to use on reload.
#[tauri::command]
pub async fn ui_check(app: tauri::AppHandle) -> Result<bool, String> {
check(&app).await
}
/// How often the background check runs, and how long after start the first one waits (the window comes first).
const EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60);
const FIRST: std::time::Duration = std::time::Duration::from_secs(20);
/// Checks for new interface versions while the app runs; tells the window when one is ready (`ui-ready`).
pub fn watch(app: tauri::AppHandle) {
tauri::async_runtime::spawn(async move {
tokio::time::sleep(FIRST).await;
loop {
match check(&app).await {
Ok(true) => {
use tauri::Emitter;
let _ = app.emit("ui-ready", app.state::<Ui>().status());
}
Ok(false) => {}
// No network, server down: nothing to do, the interface on disk keeps working.
Err(err) => eprintln!("interface update: {err}"),
}
tokio::time::sleep(EVERY).await;
}
});
}
fn client() -> Result<reqwest::Client, String> {
if rustls::crypto::CryptoProvider::get_default().is_none() {
let _ = rustls::crypto::ring::default_provider().install_default();
}
reqwest::Client::builder()
.user_agent(concat!("PhotoReport-desktop/", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(120))
.build()
.map_err(|e| e.to_string())
}
/// One check: the published manifest (a few KB), and only if it is newer than what is in use, the files that changed.
async fn check(app: &tauri::AppHandle) -> Result<bool, String> {
let ui = app.state::<Ui>().inner().clone();
let base = crate::APP_URL.trim_end_matches('/');
let http = client()?;
let res = http
.get(format!("{base}/{MANIFEST}"))
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("manifest: {}", res.status()));
}
let manifest: Manifest = res.json().await.map_err(|e| e.to_string())?;
let current = ui.status();
if manifest.version == current.version || manifest.built_at <= current.built_at {
return Ok(false);
}
let root = ui.root()?;
let missing = prepare(&ui, &root, &manifest, |path| {
app.asset_resolver().get(path.to_string()).map(|a| a.bytes)
})?;
for path in missing {
let file = manifest
.files
.iter()
.find(|f| f.path == path)
.ok_or("bad_manifest")?;
let res = http
.get(format!("{base}/{path}"))
.send()
.await
.map_err(|e| e.to_string())?;
if !res.status().is_success() {
return Err(format!("{path}: {}", res.status()));
}
let bytes = res.bytes().await.map_err(|e| e.to_string())?;
if sha256_hex(&bytes) != file.sha256 {
return Err(format!("{path}: hash_mismatch"));
}
write(
&staging(&root, &manifest.version)?.join(safe(&path).ok_or("bad_path")?),
&bytes,
)?;
}
activate(&ui, &root, &manifest)?;
Ok(true)
}
fn staging(root: &Path, version: &str) -> Result<PathBuf, String> {
let name = safe(version)
.filter(|p| p.components().count() == 1)
.ok_or("bad_version")?;
Ok(root.join(format!("{}.part", name.display())))
}
/// Starts installing `manifest`: copies into a staging folder every file this computer already has (same hash, in the
/// version in use or the installer's copy) and returns the paths still to download.
fn prepare(
ui: &UiShared,
root: &Path,
manifest: &Manifest,
embedded: impl Fn(&str) -> Option<Vec<u8>>,
) -> Result<Vec<String>, String> {
let stage = staging(root, &manifest.version)?;
std::fs::create_dir_all(&stage).map_err(|e| e.to_string())?;
let active = ui.active.read().unwrap().as_ref().map(|(_, d)| d.clone());
let mut missing = Vec::new();
for f in &manifest.files {
let rel = safe(&f.path).ok_or("bad_path")?;
let target = stage.join(&rel);
let ok = |b: &[u8]| sha256_hex(b) == f.sha256;
if std::fs::read(&target).is_ok_and(|b| ok(&b)) {
continue;
}
let local = active
.as_ref()
.and_then(|d| std::fs::read(d.join(&rel)).ok())
.filter(|b| ok(b))
.or_else(|| embedded(&f.path).filter(|b| ok(b)));
match local {
Some(bytes) => write(&target, &bytes)?,
None => missing.push(f.path.clone()),
}
}
Ok(missing)
}
fn write(target: &Path, bytes: &[u8]) -> Result<(), String> {
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
std::fs::write(target, bytes).map_err(|e| e.to_string())
}
/// Switches to `manifest` once every file is in place and checks out; the version it replaces is kept as a fallback,
/// older ones removed. Served from the next start, or now if the window reloads.
fn activate(ui: &UiShared, root: &Path, manifest: &Manifest) -> Result<(), String> {
let stage = staging(root, &manifest.version)?;
for f in &manifest.files {
let bytes = std::fs::read(stage.join(safe(&f.path).ok_or("bad_path")?))
.map_err(|_| format!("missing:{}", f.path))?;
if sha256_hex(&bytes) != f.sha256 {
return Err(format!("hash_mismatch:{}", f.path));
}
}
if !manifest.files.iter().any(|f| f.path == "index.html") {
return Err("no_index".into());
}
write(
&stage.join(MANIFEST),
&serde_json::to_vec(manifest).map_err(|e| e.to_string())?,
)?;
let dir = root.join(&manifest.version);
let previous = ui.active.read().unwrap().as_ref().map(|(_, d)| d.clone());
if Some(&dir) != previous.as_ref() {
let _ = std::fs::remove_dir_all(&dir);
}
std::fs::rename(&stage, &dir).map_err(|e| e.to_string())?;
write(&root.join(CURRENT), manifest.version.as_bytes())?;
ui.choose(root);
if let Ok(entries) = std::fs::read_dir(root) {
for e in entries.flatten() {
let p = e.path();
if p.is_dir() && p != dir && Some(&p) != previous.as_ref() {
let _ = std::fs::remove_dir_all(p);
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn paths_stay_inside_the_folder() {
assert_eq!(
safe("/assets/index-abc.js"),
Some(PathBuf::from("assets/index-abc.js"))
);
assert_eq!(safe("index.html"), Some(PathBuf::from("index.html")));
assert_eq!(safe("../etc/passwd"), None);
assert_eq!(safe("assets/../../x"), None);
assert_eq!(safe(""), None);
assert!(staging(Path::new("/r"), "a/b").is_err());
assert!(staging(Path::new("/r"), "..").is_err());
}
#[test]
fn installs_only_what_changed_and_checks_every_file() {
let root = std::env::temp_dir().join(format!("pr-ui-install-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
let file = |path: &str, body: &str| ManifestFile {
path: path.into(),
size: body.len() as u64,
sha256: sha256_hex(body.as_bytes()),
};
let ui = UiShared::default();
*ui.embedded.write().unwrap() = Some(Manifest {
version: "v1".into(),
built_at: "2026-10-12T10:00:00Z".into(),
files: vec![],
});
let embedded = |p: &str| match p {
"index.html" => Some(b"<html>v1</html>".to_vec()),
"engine.wasm" => Some(b"wasm".to_vec()),
_ => None,
};
let v2 = Manifest {
version: "v2".into(),
built_at: "2026-10-13T16:00:00Z".into(),
files: vec![
file("index.html", "<html>v2</html>"),
file("engine.wasm", "wasm"),
file("assets/app-2.js", "js2"),
],
};
// The engine didn't change: copied from the installer, not downloaded.
assert_eq!(
prepare(&ui, &root, &v2, embedded).unwrap(),
vec!["index.html", "assets/app-2.js"]
);
// Not everything there yet: refused.
assert!(activate(&ui, &root, &v2).is_err());
let stage = staging(&root, "v2").unwrap();
write(&stage.join("index.html"), b"<html>v2</html>").unwrap();
write(&stage.join("assets/app-2.js"), b"tampered").unwrap();
assert!(
activate(&ui, &root, &v2)
.unwrap_err()
.starts_with("hash_mismatch")
);
write(&stage.join("assets/app-2.js"), b"js2").unwrap();
activate(&ui, &root, &v2).unwrap();
assert_eq!(ui.status().version, "v2");
assert!(ui.status().downloaded);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn serves_the_downloaded_version_only_when_newer_than_the_installer() {
let root = std::env::temp_dir().join(format!("pr-ui-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
let dir = root.join("v2");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("index.html"), "<html>v2</html>").unwrap();
let m = Manifest {
version: "v2".into(),
built_at: "2026-10-13T16:00:00Z".into(),
files: vec![],
};
std::fs::write(dir.join(MANIFEST), serde_json::to_vec(&m).unwrap()).unwrap();
std::fs::write(root.join(CURRENT), "v2").unwrap();
let ui = UiShared::default();
*ui.embedded.write().unwrap() = Some(Manifest {
version: "v1".into(),
built_at: "2026-10-12T10:00:00Z".into(),
files: vec![],
});
ui.choose(&root);
assert_eq!(
ui.status(),
UiStatus {
version: "v2".into(),
built_at: "2026-10-13T16:00:00Z".into(),
downloaded: true
}
);
// A newer installer (the shell was updated): its own copy wins.
*ui.embedded.write().unwrap() = Some(Manifest {
version: "v3".into(),
built_at: "2026-10-20T10:00:00Z".into(),
files: vec![],
});
ui.choose(&root);
assert!(!ui.status().downloaded);
let _ = std::fs::remove_dir_all(&root);
}
}
+3 -2
View File
@@ -1,5 +1,6 @@
//! Updates of the native shell. The web app inside the window already updates with every web deploy; only the
//! shell itself (local FTP, catalogue, keychain) needs an installer, and this keeps it current too.
//! Updates of the native shell. The interface inside the window updates itself from every web deploy (see `ui`:
//! downloaded in the background, only what changed); only the shell itself (local FTP, catalogue, keychain) needs an
//! installer, and this keeps it current too.
//!
//! The app asks the API (`/v1/desktop/update/{target}/{arch}/{version}`), which reads the latest `desktop-v*`
//! release. Installers are signed at build time with the release key; the matching public key is compiled in
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.3",
"version": "0.3.7",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
@@ -0,0 +1,37 @@
//! The web app is loaded from the server (a remote origin), so every command it calls must be listed in build.rs
//! (to get an ACL permission) and allowed in capabilities/default.json. A command registered in lib.rs but missing
//! from either is refused at runtime and looks like "this desktop app is too old" in the web app.
use std::path::Path;
fn read(rel: &str) -> String {
std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join(rel)).unwrap()
}
#[test]
fn every_registered_command_is_allowed_for_the_web_app() {
let lib = read("src/lib.rs");
let start =
lib.find("generate_handler![").expect("generate_handler") + "generate_handler![".len();
let end = start + lib[start..].find(']').unwrap();
let commands: Vec<String> = lib[start..end]
.split(',')
.map(|c| c.trim().rsplit("::").next().unwrap_or("").to_string())
.filter(|c| !c.is_empty())
.collect();
assert!(commands.len() > 10, "{commands:?}");
let build = read("build.rs");
let capabilities = read("capabilities/default.json");
for c in &commands {
assert!(
build.contains(&format!("\"{c}\"")),
"{c} is not listed in build.rs"
);
let permission = format!("\"allow-{}\"", c.replace('_', "-"));
assert!(
capabilities.contains(&permission),
"{permission} is missing from capabilities/default.json"
);
}
}
+22
View File
@@ -71,6 +71,11 @@ bodies, each switchable off. "Testar ligação" (`ftp_check`, run after every st
like a camera and reads the greeting, and on macOS reads the application firewall (`socketfilterfw`: block all, or
PhotoReport blocked) to tell the photographer what to change. Another FTP server on the same port takes the
connections, so the panel says to close it.
Photos from the local FTP count as camera ingest (`source` DESKTOP), previews and full originals alike (the
resumable start says `desktop: true` for an original), so the event's autopilot edits them; only hand uploads are
left as sent. Faces and the autopilot work per event: photos with no event (the inbox) are analysed for faces but
not grouped or edited. The face worker also queues, every minute, photos left at "no analysis" in organizations
with biometrics on.
Uploads from the browser or desktop (`POST /v1/orgs/:orgId/uploads`, one photo per request) go through the
same pipeline; an upload can target an open event directly. Still to come: resumable uploads (tus, preview
@@ -234,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
+10
View File
@@ -98,6 +98,16 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
Not deployed by webhook. A tag `desktop-v*` / `agent-v*` triggers Gitea Actions to build installers per OS and
publish a Gitea release; the Tauri updater and the agent's updater read from it.
The desktop app keeps the interface on disk and never needs the server to open. Each web deploy writes
`ui-manifest.json` (every file of the build with its SHA-256); the app checks it 20 s after start and every 30 minutes,
downloads only the files that changed, checks each hash and uses the new version from the next start (or when the
photographer reloads). The installer's own copy is the fallback, and wins when it is newer.
macOS builds on a Mac registered once as a runner (`bash infra/desktop/macos-runner.sh`, with a registration token
from Gitea → Actions → Runners; label `macos`, a launchd service of that user). Its builds carry the updater key, so
apps installed from a release update themselves; an app compiled by hand without the key never does. A release made
while the Mac is off waits for it.
## Importing the old app.photoreport.pt
`apps/api/scripts/import-legacy.ts` reads the old MySQL database, read-only. It brings over accounts, squads, events,
+6 -1
View File
@@ -30,6 +30,9 @@ Following the AP and NPPA codes:
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
background people don't count.
- **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.
- **Vertical placement:** the upper body (chest, faces) a little above the middle of the crop, never the knees.
Little or no empty pitch or floor under the feet: when the crop is taller than the subject, the spare height
goes above them (crowd, stands), not below.
- **Distractions:** prefer the crop that leaves out half-bodies, empty floor and bright clutter at the edges,
as long as nothing that matters goes with them.
- **Resolution:** never crop below what the delivery needs. Default: the crop keeps at least 2400 px on its long
@@ -57,7 +60,9 @@ Per event (and an organisation default), off unless switched on. When on, every
the local FTP of the desktop app or auto-ingest is, in order:
1. analysed (people, ball, focus);
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop;
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop.
The level reads the advertising boards, stands, posts and railings, never the pitch markings (lines on grass),
which perspective tilts; when those lines disagree the photo is left as it is;
3. scored within its burst; when the burst ends, its best frames are flagged as picks;
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target.
+188
View File
@@ -0,0 +1,188 @@
//! Levelling for sports photos. Lightroom's Level (LightCraft's `level_degrees`) reads every long line, and in a
//! stadium the longest lines are the pitch markings, which perspective tilts by 10 to 30 degrees: they outvote
//! the advertising boards and the stands, so the photo is left crooked (or levelled to a touchline). Here the
//! markings are left out (lines with grass on both sides), only lines within a few degrees of level or plumb
//! count (a crooked camera is a few degrees off; more is perspective or a creative tilt), and the boards,
//! stands, posts and railings that remain have to agree.
use lightcraft_pipeline::upright::{Segment, detect_segments};
use lightcraft_raster::resample::{Filter, fit};
use lightcraft_raster::{Plane, Rgb32f};
/// Analysis size (long edge), as LightCraft's Upright.
const LONG: usize = 1024;
/// Lines further than this from level (or plumb) are perspective, not a crooked camera.
const MAX_DEV: f64 = 8.0;
/// Lines within this much of each other agree.
const AGREE: f64 = 0.75;
/// Shortest line that counts, as a fraction of the long edge.
const MIN_LEN: f64 = 0.06;
/// The crop angle (degrees, LightCraft's sign) that levels a sports photo, or None when its lines don't agree.
pub fn sports_level(image: &Rgb32f) -> Option<f64> {
let img = if image.width.max(image.height) > LONG {
fit(image, LONG, LONG, Filter::Mitchell)
} else {
image.clone()
};
let (w, h) = (img.width, img.height);
if w < 32 || h < 32 {
return None;
}
let segs = detect_segments(&lightness(&img));
let half = w.max(h) as f64 / 2.0;
let to_px = |x: f64, y: f64| (x * half + w as f64 / 2.0, y * half + h as f64 / 2.0);
let mut devs: Vec<(f64, f64)> = Vec::new();
for s in &segs {
let len = s.len() / 2.0; // fraction of the long edge
if len < MIN_LEN {
continue;
}
let Some(d) = deviation(s) else { continue };
let (ax, ay) = to_px(s.a.x, s.a.y);
let (bx, by) = to_px(s.b.x, s.b.y);
if on_grass(&img, ax, ay, bx, by) {
continue;
}
devs.push((d, len));
}
let total: f64 = devs.iter().map(|d| d.1).sum();
// Too little structure to trust (close-ups, crowds): left alone.
if total < 0.35 {
return None;
}
// The angle most of the line length agrees on (the mode, not the median: people, flags and the odd
// perspective line scatter around, while the boards and the stands agree with each other).
let support = |c: f64| {
devs.iter()
.filter(|(d, _)| (d - c).abs() <= AGREE)
.map(|x| x.1)
.sum::<f64>()
};
let (best, weight) = devs
.iter()
.map(|(d, _)| (*d, support(*d)))
.max_by(|a, b| a.1.total_cmp(&b.1))?;
// Another, different angle almost as supported: the scene is ambiguous, better left alone.
let rival = devs
.iter()
.filter(|(d, _)| (d - best).abs() > 2.0 * AGREE)
.map(|(d, _)| support(*d))
.fold(0.0, f64::max);
if weight < 0.3 || weight < 0.35 * total || rival > 0.7 * weight {
return None;
}
let inliers: Vec<&(f64, f64)> = devs
.iter()
.filter(|(d, _)| (d - best).abs() <= AGREE)
.collect();
let mean = inliers.iter().map(|(d, l)| d * l).sum::<f64>()
/ inliers.iter().map(|(_, l)| l).sum::<f64>();
Some(((-mean) * 100.0).round() / 100.0)
}
/// Signed deviation (degrees) of a near-level or near-plumb line, in the sign of LightCraft's `level_angle`.
fn deviation(s: &Segment) -> Option<f64> {
let (dx, dy) = (s.b.x - s.a.x, s.b.y - s.a.y);
let fold = |a: f64| {
if a > 90.0 {
a - 180.0
} else if a < -90.0 {
a + 180.0
} else {
a
}
};
let horizontal = fold(dy.atan2(dx).to_degrees());
if horizontal.abs() <= MAX_DEV {
return Some(horizontal);
}
let vertical = -fold(dx.atan2(dy).to_degrees());
(vertical.abs() <= MAX_DEV).then_some(vertical)
}
/// Perceptual lightness normalised to the bright end, as LightCraft's analysis does.
fn lightness(img: &Rgb32f) -> Plane {
let lum = img.luminance();
let mut v: Vec<f32> = lum.data.iter().copied().filter(|x| x.is_finite()).collect();
v.sort_by(f32::total_cmp);
let white = v.get(v.len() * 99 / 100).copied().unwrap_or(1.0).max(1e-4);
lum.map(|x| (x.max(0.0) / white).min(1.5).powf(1.0 / 2.4))
}
fn green(p: [f32; 3]) -> bool {
let [r, g, b] = p;
g > 0.004 && g > r * 1.15 && g > b * 1.15
}
/// A pitch marking (or the pitch's edge): grass on both sides along most of the line.
fn on_grass(img: &Rgb32f, ax: f64, ay: f64, bx: f64, by: f64) -> bool {
let (dx, dy) = (bx - ax, by - ay);
let len = dx.hypot(dy).max(1e-9);
let (nx, ny) = (-dy / len * 5.0, dx / len * 5.0);
let at = |x: f64, y: f64| {
let (xi, yi) = (x.round(), y.round());
if xi < 0.0 || yi < 0.0 || xi >= img.width as f64 || yi >= img.height as f64 {
return None;
}
Some(img.data[yi as usize * img.width + xi as usize])
};
let (mut grass, mut n) = (0, 0);
for i in 1..10 {
let t = i as f64 / 10.0;
let (x, y) = (ax + dx * t, ay + dy * t);
// A line on grass has grass on both sides; the board above the pitch has it on one side at most.
let (Some(p), Some(q)) = (at(x + nx, y + ny), at(x - nx, y - ny)) else {
continue;
};
n += 1;
if green(p) && green(q) {
grass += 1;
}
}
n > 0 && grass * 10 >= n * 5
}
#[cfg(test)]
mod tests {
use super::*;
/// A stadium-like scene: a board along the top (its lower edge tilted by `tilt` degrees), grass below with a
/// touchline drawn in perspective at `line` degrees.
fn stadium(tilt: f64, line: f64) -> Rgb32f {
let (w, h) = (900usize, 600usize);
let (t, l) = (tilt.to_radians().tan(), line.to_radians().tan());
Rgb32f::from_fn(w, h, |x, y| {
let xc = x as f64 - w as f64 / 2.0;
let board = 200.0 + xc * t;
let touch = 420.0 + xc * l;
let y = y as f64;
if y < board - 120.0 {
[0.05, 0.05, 0.06] // stands
} else if y < board {
[0.6, 0.08, 0.06] // red board
} else if (y - touch).abs() < 3.0 {
[0.8, 0.8, 0.8] // the white line
} else {
[0.05, 0.25, 0.04] // grass
}
})
}
#[test]
fn levels_by_the_boards_not_the_pitch_markings() {
// Board 2.5 degrees off, touchline at 18 degrees in perspective: the board decides.
let d = sports_level(&stadium(2.5, 18.0)).expect("level found");
assert!((d + 2.5).abs() < 0.6, "{d}");
// A level board stays level, whatever the touchline does.
let d = sports_level(&stadium(0.0, -14.0)).expect("level found");
assert!(d.abs() < 0.4, "{d}");
}
#[test]
fn leaves_alone_what_has_no_lines() {
let flat = Rgb32f::from_fn(400, 300, |_, _| [0.1, 0.3, 0.05]);
assert_eq!(sports_level(&flat), None);
}
}
+1
View File
@@ -4,6 +4,7 @@
//! small JSON edit commands addressed by LightCraft control ids (`light.exposure`, `effects.clarity`, ...).
//! Updating LightCraft should only ever require changes in this crate.
pub mod level;
pub mod render;
pub use lightcraft_develop::DevelopSettings;
+6
View File
@@ -82,6 +82,12 @@ impl Source {
.map(|d| (d.clamp(-45.0, 45.0) * 100.0).round() / 100.0)
}
/// Auto straighten for sports and press photos: levels by the boards, stands, posts and railings, never by the
/// pitch markings (which perspective tilts). `None` when those lines don't agree.
pub fn auto_level_scene(&self) -> Option<f64> {
crate::level::sports_level(&self.image)
}
/// Automatic white balance (grey world on mid-tone, low-chroma pixels): `wb.temp` and `wb.tint`.
pub fn auto_wb(&self) -> Vec<(&'static str, f64)> {
let (temp, tint) = lightcraft_pipeline::auto::auto_wb(&self.image, &self.info);
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Turns a Mac into the macOS builder for desktop releases (run once, on the Mac that will build).
# bash ~/Projects/photoreport-build/infra/desktop/macos-runner.sh
#
# It installs Gitea's act_runner as a background service of this user (starts at login, restarts if it stops) with
# the label "macos". From then on every `desktop-v*` release also builds the signed .dmg and the macOS update, and the
# installed apps update themselves: nobody compiles by hand again. The Mac only has to be on (and logged in) when a
# release is made; a release made while it is off waits and builds when it comes back.
#
# The registration token comes from Gitea (BitReport.pt/photoreport → Definições → Actions → Runners → Criar
# runner). The script asks for it; it is used once and not saved.
set -Eeuo pipefail
VERSION="${ACT_RUNNER_VERSION:-0.2.11}"
INSTANCE="${GITEA_URL:-https://git.bitreport.pt}"
HOME_DIR="$HOME/.photoreport-runner"
PLIST="$HOME/Library/LaunchAgents/pt.photoreport.act-runner.plist"
step() { printf '\n\033[1;34m== %s\033[0m\n' "$*"; }
[[ "$(uname)" == Darwin ]] || { echo "Run this on a Mac." >&2; exit 1; }
xcode-select -p >/dev/null 2>&1 || { xcode-select --install; echo "Install the Xcode command line tools, then run this again." >&2; exit 1; }
command -v node >/dev/null || { echo "Node.js 22 is needed: brew install node@22" >&2; exit 1; }
step "Rust"
if ! command -v cargo >/dev/null; then curl -fsSL https://sh.rustup.rs | sh -s -- -y; fi
# shellcheck disable=SC1091
source "$HOME/.cargo/env"
rustup target add aarch64-apple-darwin x86_64-apple-darwin wasm32-unknown-unknown >/dev/null
step "pnpm"
command -v pnpm >/dev/null || corepack enable pnpm 2>/dev/null || npm install -g pnpm
step "act_runner $VERSION"
mkdir -p "$HOME_DIR"
cd "$HOME_DIR"
arch="$(uname -m)"; [[ "$arch" == "arm64" ]] || arch="amd64"
if [[ ! -x ./act_runner ]] || ! ./act_runner --version 2>/dev/null | grep -q "$VERSION"; then
curl -fsSL -o act_runner "https://dl.gitea.com/act_runner/${VERSION}/act_runner-${VERSION}-darwin-${arch}"
chmod +x act_runner
fi
if [[ ! -f .runner ]]; then
step "Register with $INSTANCE"
token="${GITEA_RUNNER_TOKEN:-}"
if [[ -z "$token" ]]; then read -rsp "Registration token (Gitea → Actions → Runners → Criar runner): " token; echo; fi
[[ -n "$token" ]] || { echo "No token." >&2; exit 1; }
./act_runner generate-config > config.yaml
# One build at a time; jobs run on this Mac directly (no containers on macOS).
sed -i '' 's/^ capacity: .*/ capacity: 1/' config.yaml
./act_runner register --no-interactive --config config.yaml --instance "$INSTANCE" --token "$token" \
--name "$(scutil --get ComputerName | tr ' ' '-')-macos" --labels "macos:host"
fi
step "Background service"
mkdir -p "$(dirname "$PLIST")"
cat > "$PLIST" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>pt.photoreport.act-runner</string>
<key>ProgramArguments</key><array><string>$HOME_DIR/act_runner</string><string>daemon</string><string>--config</string><string>$HOME_DIR/config.yaml</string></array>
<key>WorkingDirectory</key><string>$HOME_DIR</string>
<key>EnvironmentVariables</key><dict>
<key>PATH</key><string>$HOME/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
<key>HOME</key><string>$HOME</string>
</dict>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>$HOME_DIR/runner.log</string>
<key>StandardErrorPath</key><string>$HOME_DIR/runner.log</string>
</dict>
</plist>
PLIST
launchctl bootout "gui/$(id -u)" "$PLIST" 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
sleep 3
if launchctl print "gui/$(id -u)/pt.photoreport.act-runner" >/dev/null 2>&1; then
printf '\n\033[1;32mDone.\033[0m This Mac now builds the macOS version of every desktop release.\n'
printf 'Log: %s/runner.log Stop: launchctl bootout gui/%s %s\n' "$HOME_DIR" "$(id -u)" "$PLIST"
else
echo "The service did not start; see $HOME_DIR/runner.log" >&2
exit 1
fi
+13
View File
@@ -52,6 +52,15 @@ export const PhotoBatchPatch = z.object({
});
export type PhotoBatchPatch = z.infer<typeof PhotoBatchPatch>;
export type PhotoDelivery = "NONE" | "QUEUED" | "DONE" | "FAILED";
/** A photo's overall delivery state from the status of each of its deliveries. */
export function deliveryState(statuses: readonly string[]): PhotoDelivery {
if (statuses.includes("DONE")) return "DONE";
if (statuses.some((x) => x === "QUEUED" || x === "RUNNING")) return "QUEUED";
return statuses.length ? "FAILED" : "NONE";
}
export interface PhotoSummary {
id: string;
eventId: string | null;
@@ -63,6 +72,10 @@ export interface PhotoSummary {
/** False when only a preview is on the server and the original stays on the photographer's computer. */
originalStored: boolean;
status: "PROCESSING" | "READY" | "FAILED";
/** Why a FAILED photo could not be read (damaged or cut-off file, unsupported format). */
error?: string | null;
/** Where its deliveries stand: DONE once any destination has it, QUEUED while one is on its way, FAILED otherwise. */
delivery?: PhotoDelivery;
width: number | null;
height: number | null;
capturedAt: string | null;
+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}`;
}
/**
+2 -1
View File
@@ -85,7 +85,8 @@ fn auto(job: &AutoJob) -> Result<(serde_json::Value, Option<f64>), String> {
for (k, v) in wb.iter().chain(tone.iter()) {
values.insert((*k).to_string(), serde_json::json!(v));
}
let angle = source.auto_level(&settings);
// Stadium photos: the pitch markings must not decide the level (see photoreport_engine::level).
let angle = source.auto_level_scene();
Ok((serde_json::Value::Object(values), angle))
}