Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fcf62f8be | ||
|
|
1ed6d144d3 | ||
|
|
2a839d8305 | ||
|
|
f20dea883e | ||
|
|
a9ae5ce6ad | ||
|
|
42912453e2 | ||
|
|
3fd6a6f1cc | ||
|
|
4d3a9dfc07 | ||
|
|
a781be6d9e | ||
|
|
df741d8268 | ||
|
|
3f8e36f6e3 | ||
|
|
7173c88e08 | ||
|
|
176f15a5a0 | ||
|
|
4e88244a8b | ||
|
|
549def64f7 | ||
|
|
bf2d8b4b6a | ||
|
|
7080a1d7fe | ||
|
|
2c8adede4c | ||
|
|
22c1d0530b | ||
|
|
1279294e8d | ||
|
|
341c41b617 | ||
|
|
140bdc2d68 | ||
|
|
cc759dda4f | ||
|
|
f7570f8706 | ||
|
|
c089868d59 | ||
|
|
9c5463f337 | ||
|
|
fbdc728ae7 | ||
|
|
dc977fdb6b | ||
|
|
097ee18572 | ||
|
|
a1a8c74a70 |
No files matched your search
+6
@@ -0,0 +1,6 @@
|
||||
-- Per-send override: photographer asked for the camera original on this item.
|
||||
ALTER TABLE "delivery_items" ADD COLUMN "force_originals" BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- Optional on a destination: wait a little for faces when the pad needs {players}.
|
||||
-- Off by default — a send the photographer asked for must leave at once; names can resend later.
|
||||
ALTER TABLE "delivery_targets" ADD COLUMN "wait_for_faces" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -559,6 +559,9 @@ model DeliveryTarget {
|
||||
/// The original as it arrived (no resizing, no recompression), with the metadata written into it and renamed:
|
||||
/// a copy for one's own backup, like Photo Mechanic's Live Ingest destination.
|
||||
originals Boolean @default(false)
|
||||
/// Wait a little for faces when the pad/path needs `{players}` (automatic every-arrival or when opted in).
|
||||
/// Off by default: a send the photographer asked for leaves at once; names can update the file later.
|
||||
waitForFaces Boolean @default(false) @map("wait_for_faces")
|
||||
/// Every photo that arrives (FTP, the desktop app, uploads) is sent here on its own, as soon as it is in an event.
|
||||
onArrival Boolean @default(false) @map("on_arrival")
|
||||
/// With `onArrival`: only the photos of these FTP logins (ids; empty: everyone's). The central FTP then works as
|
||||
@@ -615,6 +618,8 @@ model DeliveryItem {
|
||||
replacesPath String? @map("replaces_path")
|
||||
/// Queued to be taken back from the destination (the photo was rejected or un-picked): the worker removes it.
|
||||
retract Boolean @default(false)
|
||||
/// This send asked for the camera original (overrides the destination's resize recipe for this item only).
|
||||
forceOriginals Boolean @default(false) @map("force_originals")
|
||||
byteSize Int? @map("byte_size")
|
||||
requestedById String? @map("requested_by_id") @db.Uuid
|
||||
nextAttemptAt DateTime @default(now()) @map("next_attempt_at")
|
||||
|
||||
+1
-1
@@ -145,7 +145,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
|
||||
await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster, archive, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) });
|
||||
await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 });
|
||||
// The API never runs the face engine: it confirms and merges groups; the worker detects and groups.
|
||||
const faces = new FaceService({ db, storage, broadcaster, log: app.log });
|
||||
const faces = new FaceService({ db, storage, broadcaster, log: app.log, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) });
|
||||
// Search by photo (library, archive editors, "Encontra-te"): the API's own face engine, started on demand.
|
||||
const facePaths = faceEnginePaths(config);
|
||||
const slots = scanSlots();
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { NEWSROOM_TEMPLATE, GENERAL_TEMPLATE } from "@photoreport/metadata";
|
||||
import { deliveryWantsPlayerNames } from "./service.js";
|
||||
|
||||
describe("deliveryWantsPlayerNames", () => {
|
||||
const plain = { folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", iptcOverrides: null };
|
||||
|
||||
it("is true when the event IPTC pad uses {players}", () => {
|
||||
expect(deliveryWantsPlayerNames(plain, NEWSROOM_TEMPLATE)).toBe(true);
|
||||
});
|
||||
|
||||
it("is true when the destination folder template uses {players}", () => {
|
||||
expect(deliveryWantsPlayerNames({ ...plain, folderTemplate: "/{players}/" }, {})).toBe(true);
|
||||
});
|
||||
|
||||
it("is false when neither path nor IPTC asks for player names", () => {
|
||||
const noPlayers = { ...GENERAL_TEMPLATE, title: "{event}", personsShown: undefined };
|
||||
expect(deliveryWantsPlayerNames(plain, noPlayers)).toBe(false);
|
||||
});
|
||||
|
||||
it("respects destination IPTC overrides that drop {players}", () => {
|
||||
expect(
|
||||
deliveryWantsPlayerNames(
|
||||
{ ...plain, iptcOverrides: { title: "{event}", personsShown: [] } },
|
||||
NEWSROOM_TEMPLATE,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,8 @@ const TargetBase = z.object({
|
||||
srgb: z.boolean(),
|
||||
/** The original as it arrived, metadata written in, renamed (no resizing or recompression). */
|
||||
originals: z.boolean(),
|
||||
/** Wait a little for faces when the pad needs `{players}` (off by default). */
|
||||
waitForFaces: z.boolean(),
|
||||
/** Everything that arrives is sent here on its own. */
|
||||
onArrival: z.boolean(),
|
||||
/** With onArrival: only these FTP logins' photos (empty: everyone's). */
|
||||
@@ -80,6 +82,7 @@ const TargetFields = TargetBase.extend({
|
||||
keepExif: TargetBase.shape.keepExif.default(true),
|
||||
srgb: TargetBase.shape.srgb.default(false),
|
||||
originals: TargetBase.shape.originals.default(false),
|
||||
waitForFaces: TargetBase.shape.waitForFaces.default(false),
|
||||
onArrival: TargetBase.shape.onArrival.default(false),
|
||||
arrivalLogins: TargetBase.shape.arrivalLogins.default([]),
|
||||
untouched: TargetBase.shape.untouched.default(false),
|
||||
@@ -267,7 +270,14 @@ export async function registerDeliveryRoutes(
|
||||
const body = DeliveryRequest.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: body.photoIds, again: body.again, requestedById: currentUserId(req) });
|
||||
const result = await delivery.enqueue({
|
||||
organizationId: orgId,
|
||||
targetId: body.targetId,
|
||||
photoIds: body.photoIds,
|
||||
again: body.again,
|
||||
originals: body.originals,
|
||||
requestedById: currentUserId(req),
|
||||
});
|
||||
return reply.code(202).send({ queued: result.queued.map(toItemSummary), skipped: result.skipped });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
@@ -297,7 +307,14 @@ export async function registerDeliveryRoutes(
|
||||
);
|
||||
if (body.dryRun || !chosen.length) return { chosen, rest, queued: [], skipped: [] };
|
||||
try {
|
||||
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: chosen, again: body.again, requestedById: currentUserId(req) });
|
||||
const result = await delivery.enqueue({
|
||||
organizationId: orgId,
|
||||
targetId: body.targetId,
|
||||
photoIds: chosen,
|
||||
again: body.again,
|
||||
originals: body.originals,
|
||||
requestedById: currentUserId(req),
|
||||
});
|
||||
return reply.code(202).send({ chosen, rest, queued: result.queued.map(toItemSummary), skipped: result.skipped });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { DeliveryItemSummary } from "@photoreport/contracts";
|
||||
import { buildVars, createdStamp, eventName, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata";
|
||||
import {
|
||||
buildVars,
|
||||
createdStamp,
|
||||
eventName,
|
||||
IptcTemplate,
|
||||
LOCAL_COPY_FOLDER,
|
||||
PathTemplateError,
|
||||
renderFileName,
|
||||
renderFolder,
|
||||
} from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
@@ -23,9 +32,25 @@ export const MAX_ATTEMPTS = 5;
|
||||
export const ORIGINAL_WAIT_MS = 72 * 3600_000;
|
||||
/** How often it asks that computer again while waiting. */
|
||||
export const ORIGINAL_ASK_MS = 60_000;
|
||||
/** How long a delivery waits for the photo's faces to be read (the players' names), checking this often. */
|
||||
/**
|
||||
* Automatic "every arrival" deliveries may wait this long for faces when the pad needs `{players}`.
|
||||
* A send the photographer asked for never waits — the cloud copy must leave at once.
|
||||
*/
|
||||
export const FACES_WAIT_MS = 3 * 60_000;
|
||||
export const FACES_ASK_MS = 20_000;
|
||||
|
||||
const PLAYER_VARS = /\{players\}|\{persons\}|\{prsn\}/i;
|
||||
|
||||
/** True when this delivery's folder, file name or IPTC pad will put player names on the file. */
|
||||
export function deliveryWantsPlayerNames(
|
||||
target: { folderTemplate: string; fileNameTemplate: string; iptcOverrides: unknown },
|
||||
eventIptc: unknown,
|
||||
): boolean {
|
||||
if (PLAYER_VARS.test(target.folderTemplate) || PLAYER_VARS.test(target.fileNameTemplate)) return true;
|
||||
const overrides = IptcTemplate.partial().safeParse(target.iptcOverrides ?? {});
|
||||
const template = { ...IptcTemplate.parse(eventIptc ?? {}), ...(overrides.success ? overrides.data : {}) };
|
||||
return PLAYER_VARS.test(JSON.stringify(template));
|
||||
}
|
||||
/** Running items older than this belonged to a worker that died; they go back in the queue. */
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** A delivered photo edited again is sent again once its edits have paused this long. */
|
||||
@@ -87,6 +112,7 @@ export async function syncLocalMirror(db: Db, secrets: { seal(plain: string): st
|
||||
srgb: target.srgb,
|
||||
originals: target.originals,
|
||||
untouched: target.untouched,
|
||||
waitForFaces: false,
|
||||
onArrival: false,
|
||||
arrivalLogins: [] as string[],
|
||||
disabledAt: null,
|
||||
@@ -185,6 +211,8 @@ export class DeliveryService {
|
||||
photoIds: string[];
|
||||
again: boolean;
|
||||
requestedById: string | null;
|
||||
/** Camera original for this batch (overrides the destination's resize recipe). */
|
||||
originals?: boolean;
|
||||
/** Set when this is the local copy of a delivery to that target. */
|
||||
via?: string;
|
||||
/** Photo id → sequence of the export this copies, so `{n}` in the file name matches the file that was sent. */
|
||||
@@ -235,7 +263,17 @@ export class DeliveryService {
|
||||
if (fixed === undefined || fixed >= next) next = sequence + 1;
|
||||
created.push(
|
||||
await tx.deliveryItem.create({
|
||||
data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence, requestedById: input.requestedById, viaTargetId: input.via ?? null },
|
||||
data: {
|
||||
organizationId: input.organizationId,
|
||||
targetId: target.id,
|
||||
photoId: photo.id,
|
||||
eventId,
|
||||
sequence,
|
||||
requestedById: input.requestedById,
|
||||
viaTargetId: input.via ?? null,
|
||||
// Per-send "Enviar originais" (destination may still resize by default).
|
||||
forceOriginals: Boolean(input.originals),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -248,9 +286,13 @@ export class DeliveryService {
|
||||
if (!input.via && queued.length) {
|
||||
const photoIds = queued.map((q) => q.photoId);
|
||||
if (target.copyTargetId && target.copyTargetId !== target.id) {
|
||||
await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds, via: target.id }).catch((err: unknown) =>
|
||||
this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"),
|
||||
);
|
||||
await this.enqueue({
|
||||
...input,
|
||||
targetId: target.copyTargetId,
|
||||
photoIds,
|
||||
via: target.id,
|
||||
...(input.originals !== undefined ? { originals: input.originals } : {}),
|
||||
}).catch((err: unknown) => this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"));
|
||||
}
|
||||
// The same export, also saved under the computer folder (date, game, destination name).
|
||||
if (target.kind !== "LOCAL" && target.localFolder && target.localMachine) {
|
||||
@@ -460,9 +502,17 @@ export class DeliveryService {
|
||||
return saved;
|
||||
}
|
||||
let update: Partial<DeliveryItem>;
|
||||
// The players' names come from the faces (who is where, face and shirt number): give their reading a moment,
|
||||
// so a photo does not leave without names. Waiting does not count as an attempt.
|
||||
if (!(item.target.originals && item.target.untouched) && Date.now() - item.createdAt.getTime() < FACES_WAIT_MS && (item.photo.facesStatus === "NONE" || item.photo.facesStatus === "PENDING")) {
|
||||
// Waiting for faces is opt-in per destination (`waitForFaces`). A send the photographer asked for must
|
||||
// leave at once; when names appear later the file is rewritten (resendPhotos). NONE never becomes DONE
|
||||
// by waiting, so it never blocks.
|
||||
const facesInFlight = item.photo.facesStatus === "PENDING" || item.photo.facesStatus === "RUNNING";
|
||||
if (
|
||||
item.target.waitForFaces &&
|
||||
facesInFlight &&
|
||||
!(item.target.originals && item.target.untouched) &&
|
||||
Date.now() - item.createdAt.getTime() < FACES_WAIT_MS &&
|
||||
deliveryWantsPlayerNames(item.target, item.event?.iptcTemplate)
|
||||
) {
|
||||
const org = await db.organization.findUnique({ where: { id: item.organizationId }, select: { biometricsEnabled: true } });
|
||||
if (org?.biometricsEnabled) {
|
||||
const saved = await db.deliveryItem.update({
|
||||
@@ -504,6 +554,9 @@ export class DeliveryService {
|
||||
const viaTarget = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId } }) : null;
|
||||
const sameExport = Boolean(item.target.mirrorOfId && viaTarget);
|
||||
const recipe = sameExport && viaTarget ? viaTarget : item.target;
|
||||
// Per-send "Enviar originais" beats the destination's resize; untouched only applies when the destination says so.
|
||||
const sendOriginals = recipe.originals || item.forceOriginals;
|
||||
const untouched = recipe.originals && recipe.untouched;
|
||||
const iptc = await iptcForPhoto(db, item.photoId, (viaTarget ?? item.target).iptcOverrides);
|
||||
const source = cloud?.file ?? storage.resolve(item.photo.storageKey);
|
||||
// Photos from before the camera details were kept: read them from the file being sent.
|
||||
@@ -514,11 +567,11 @@ export class DeliveryService {
|
||||
if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
|
||||
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
|
||||
// Untouched: the camera's own name, as a local FTP would have received it.
|
||||
const fileName = renderFileName(recipe.fileNameTemplate, named, recipe.originals && recipe.untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
const edit = await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const fileName = renderFileName(recipe.fileNameTemplate, named, sendOriginals && untouched ? item.photo.originalName : deliveredName(item.photo));
|
||||
const edit = sendOriginals ? undefined : await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
|
||||
const rendered = recipe.originals
|
||||
? recipe.untouched
|
||||
const rendered = sendOriginals
|
||||
? untouched
|
||||
? await readFile(source)
|
||||
: await originalWithMetadata(source, iptc?.values ?? {}, created)
|
||||
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit);
|
||||
|
||||
@@ -85,6 +85,8 @@ export class FaceService {
|
||||
videoTools?: VideoTools | undefined;
|
||||
/** Frames per second looked at in a video. */
|
||||
videoFps?: number | undefined;
|
||||
/** When player names land on a photo already delivered, rewrite the file at each destination (IPTC). */
|
||||
resend?: (organizationId: string, photoIds: readonly string[]) => Promise<number>;
|
||||
},
|
||||
) {}
|
||||
|
||||
@@ -902,6 +904,14 @@ export class FaceService {
|
||||
for (const photo of pending) {
|
||||
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players: photo.players } });
|
||||
}
|
||||
// A send that left without names gets the updated IPTC: same path, file replaced (like the Info window).
|
||||
const byOrg = new Map<string, string[]>();
|
||||
for (const photo of pending) {
|
||||
byOrg.set(photo.organizationId, [...(byOrg.get(photo.organizationId) ?? []), photo.id]);
|
||||
}
|
||||
for (const [organizationId, photoIds] of byOrg) {
|
||||
await this.deps.resend?.(organizationId, photoIds).catch((err) => this.deps.log.warn({ err, organizationId, n: photoIds.length }, "faces: delivered photos not resent after names"));
|
||||
}
|
||||
}
|
||||
|
||||
/** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { exiftool } from "exiftool-vendored";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { cullFromCameraRating, ratingFromTags, readCameraInfo, withCameraRatingChecked } from "./exif.js";
|
||||
|
||||
describe("on-camera star ratings", () => {
|
||||
it("maps EXIF Rating and RatingPercent tags", () => {
|
||||
expect(ratingFromTags({})).toBeUndefined();
|
||||
expect(ratingFromTags({ Rating: 0 })).toBeUndefined();
|
||||
expect(ratingFromTags({ Rating: 3 })).toBe(3);
|
||||
expect(ratingFromTags({ Rating: "5" })).toBe(5);
|
||||
expect(ratingFromTags({ Rating: 9 })).toBe(5);
|
||||
expect(ratingFromTags({ RatingPercent: 0 })).toBeUndefined();
|
||||
expect(ratingFromTags({ RatingPercent: 1 })).toBe(1);
|
||||
expect(ratingFromTags({ RatingPercent: 75 })).toBe(4);
|
||||
expect(ratingFromTags({ RatingPercent: 99 })).toBe(5);
|
||||
});
|
||||
|
||||
it("turns any star into a library pick", () => {
|
||||
expect(cullFromCameraRating(undefined)).toEqual({});
|
||||
expect(cullFromCameraRating(0)).toEqual({});
|
||||
expect(cullFromCameraRating(1)).toEqual({ rating: 1, flag: "PICK" });
|
||||
expect(cullFromCameraRating(4)).toEqual({ rating: 4, flag: "PICK" });
|
||||
});
|
||||
|
||||
it("marks exif so the backfill does not re-read the same file", () => {
|
||||
expect(withCameraRatingChecked(undefined)).toEqual({ cameraRatingChecked: true });
|
||||
expect(withCameraRatingChecked({ owner: "PS" })).toEqual({ owner: "PS", cameraRatingChecked: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe("readCameraInfo rating from files", () => {
|
||||
let dir: string;
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-rating-"));
|
||||
});
|
||||
afterAll(async () => {
|
||||
await exiftool.end();
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function file(name: string, args: string[]): Promise<string> {
|
||||
const p = path.join(dir, name);
|
||||
await writeFile(p, await sharp({ create: { width: 64, height: 48, channels: 3, background: "#456" } }).jpeg().toBuffer());
|
||||
await exiftool.write(p, {}, { writeArgs: ["-overwrite_original", ...args] });
|
||||
return p;
|
||||
}
|
||||
|
||||
it("reads EXIF Rating and XMP xmp:Rating", async () => {
|
||||
expect((await readCameraInfo(await file("rated-exif.jpg", ["-EXIF:Rating=4"]))).rating).toBe(4);
|
||||
expect((await readCameraInfo(await file("rated-xmp.jpg", ["-XMP-xmp:Rating=2"]))).rating).toBe(2);
|
||||
const bare = path.join(dir, "bare.jpg");
|
||||
await writeFile(bare, await sharp({ create: { width: 8, height: 8, channels: 3, background: "#000" } }).jpeg().toBuffer());
|
||||
expect((await readCameraInfo(bare)).rating).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -54,9 +54,45 @@ export interface CameraInfo {
|
||||
aperture?: number | undefined;
|
||||
exposureTime?: number | undefined;
|
||||
iso?: number | undefined;
|
||||
/** 1–5 when the photographer set stars on the body (EXIF/XMP Rating). Absent or 0 = unrated. */
|
||||
rating?: number | undefined;
|
||||
extra?: CameraExtra | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stars written on the camera (or in Photo Mechanic before upload). EXIF `Rating` (0–5) and Microsoft
|
||||
* `RatingPercent` (0 / 1 / 25 / 50 / 75 / 99). Zero or missing means unrated — not a deliberate 0-star mark.
|
||||
*/
|
||||
export function ratingFromTags(tags: Record<string, unknown>): number | undefined {
|
||||
const percent = num(tags.RatingPercent);
|
||||
if (percent !== undefined) {
|
||||
if (percent <= 0) return undefined;
|
||||
if (percent <= 12) return 1;
|
||||
if (percent <= 37) return 2;
|
||||
if (percent <= 62) return 3;
|
||||
if (percent <= 87) return 4;
|
||||
return 5;
|
||||
}
|
||||
const raw = tags.Rating ?? tags.rating;
|
||||
const r = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : num(raw);
|
||||
if (r === undefined || !Number.isFinite(r) || r <= 0) return undefined;
|
||||
return Math.max(1, Math.min(5, Math.round(r)));
|
||||
}
|
||||
|
||||
/** Library cull from on-camera stars: keep the rating and mark as a pick (Escolhida) when there is at least one. */
|
||||
export function cullFromCameraRating(rating: number | undefined): { rating: number; flag: "PICK" } | Record<string, never> {
|
||||
if (rating === undefined || rating <= 0) return {};
|
||||
return { rating, flag: "PICK" };
|
||||
}
|
||||
|
||||
/** Marker in `photos.exif` so the worker does not re-read files that already had no stars. */
|
||||
export const CAMERA_RATING_CHECKED = "cameraRatingChecked";
|
||||
|
||||
export function withCameraRatingChecked(exif: unknown): Record<string, unknown> {
|
||||
const base = exif && typeof exif === "object" && !Array.isArray(exif) ? { ...(exif as Record<string, unknown>) } : {};
|
||||
return { ...base, [CAMERA_RATING_CHECKED]: true };
|
||||
}
|
||||
|
||||
const TIME_ZONE = "Europe/Lisbon";
|
||||
|
||||
/** Offset of a time zone at a given UTC instant, in minutes (Lisbon: 0 in winter, 60 in summer). */
|
||||
@@ -171,12 +207,13 @@ export async function readFocusPoint(file: string | Buffer): Promise<FocusHint |
|
||||
}
|
||||
|
||||
export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo> {
|
||||
// XMP on: bodies and Photo Mechanic often put stars only in xmp:Rating.
|
||||
const tags = (await exifr.parse(file, {
|
||||
tiff: true,
|
||||
exif: true,
|
||||
gps: true,
|
||||
iptc: false,
|
||||
xmp: false,
|
||||
xmp: true,
|
||||
icc: false,
|
||||
reviveValues: false,
|
||||
translateValues: false,
|
||||
@@ -205,6 +242,7 @@ export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo>
|
||||
aperture: num(tags.FNumber),
|
||||
exposureTime: num(tags.ExposureTime),
|
||||
iso,
|
||||
rating: ratingFromTags(tags),
|
||||
extra: Object.keys(extra).length ? extra : undefined,
|
||||
};
|
||||
}
|
||||
+126
-21
@@ -9,11 +9,23 @@ import { stripNulBytes } from "../lib/sanitize.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import { LocalStorage, sha256File, UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
|
||||
import { readEmbeddedIptc } from "./embedded.js";
|
||||
import { readCameraInfo } from "./exif.js";
|
||||
import { cullFromCameraRating, readCameraInfo, withCameraRatingChecked } from "./exif.js";
|
||||
import { jpegFileComplete } from "./jpeg.js";
|
||||
|
||||
export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]);
|
||||
|
||||
/**
|
||||
* Open events (treino, long ingest windows without a hard match end) must not keep swallowing photos after the
|
||||
* photographer has stopped for more than this: a later burst is another session (inbox or another event).
|
||||
*/
|
||||
export const INGEST_SESSION_GAP_MS = 60 * 60 * 1000;
|
||||
|
||||
/** True when this capture still belongs to the same shooting session as `lastCapturedAt` (or there is no prior photo). */
|
||||
export function withinIngestSession(at: Date, lastCapturedAt: Date | null | undefined): boolean {
|
||||
if (!lastCapturedAt) return true;
|
||||
return at.getTime() - lastCapturedAt.getTime() <= INGEST_SESSION_GAP_MS;
|
||||
}
|
||||
|
||||
export type IngestOutcome =
|
||||
| { status: "ingested"; photoId: string; eventId: string | null }
|
||||
| { status: "duplicate"; photoId: string }
|
||||
@@ -97,8 +109,8 @@ export class IngestService {
|
||||
return { status: "skipped", reason: "unknown_login" };
|
||||
}
|
||||
|
||||
// "Receber FTP aqui": the login sends everything to the event chosen in the library, whatever the camera's
|
||||
// clock says, until the time set; then (or with that event put away) by the time again.
|
||||
// "Receber FTP aqui": pin is a preferred event for captures that still sit in its ingest window (and session).
|
||||
// Outside that window the clock routes — a leftover pin on the afternoon training must not take the morning studio.
|
||||
const target =
|
||||
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
|
||||
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
|
||||
@@ -161,16 +173,19 @@ export class IngestService {
|
||||
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
|
||||
const embedded = await readEmbeddedIptc(file);
|
||||
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
|
||||
const at = capturedAt ?? new Date();
|
||||
// Archive imports name their own event. A file with no camera time, or a time outside that event's window,
|
||||
// must not fall through onto whatever is live today.
|
||||
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
|
||||
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
|
||||
// ingest window; otherwise the clock (closest start when windows overlap) decides.
|
||||
const requestedEventId = origin.inbox
|
||||
? null
|
||||
: origin.held && origin.eventId
|
||||
? origin.eventId
|
||||
: origin.source === "CLOUD"
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
|
||||
: !capturedAt
|
||||
? await this.namedEvent(orgId, origin.eventId)
|
||||
: (await this.requestedEvent(orgId, origin.userId, origin.eventId, capturedAt)) ??
|
||||
(await this.routeToEvent(orgId, origin.userId, capturedAt));
|
||||
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
await storage.adopt(file, storageKey);
|
||||
@@ -196,8 +211,11 @@ export class IngestService {
|
||||
aperture: camera.aperture ?? null,
|
||||
exposureTime: camera.exposureTime ?? null,
|
||||
iso: camera.iso ?? null,
|
||||
...(camera.extra && Object.keys(camera.extra).length && { exif: camera.extra }),
|
||||
// Always mark that stars were read, so the worker backfill skips this file.
|
||||
exif: withCameraRatingChecked(camera.extra && Object.keys(camera.extra).length ? camera.extra : undefined) as Prisma.InputJsonValue,
|
||||
...(Object.keys(embedded).length && { embeddedIptc: embedded }),
|
||||
// Stars set on the body (or in Photo Mechanic): rating + Escolhida so filters and live picks see them.
|
||||
...cullFromCameraRating(camera.rating),
|
||||
});
|
||||
try {
|
||||
photo = await db.photo.create({ data });
|
||||
@@ -326,7 +344,7 @@ export class IngestService {
|
||||
}
|
||||
|
||||
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
|
||||
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string; rating?: number }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
const { db, storage, log } = this.deps;
|
||||
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
@@ -335,9 +353,21 @@ export class IngestService {
|
||||
// Previews (thumb/preview) stay: they already show this photo. Only the stored file changes.
|
||||
// Faces and shirt numbers were read from the 2048 px preview: read them again from the full photo.
|
||||
const org = await db.organization.findUnique({ where: { id: photo.organizationId }, select: { biometricsEnabled: true } });
|
||||
// Preview JPEGs often lack the body's star rating; apply it from the original when still unrated.
|
||||
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, exif: true } });
|
||||
const camera = (existing?.rating ?? photo.rating ?? 0) > 0 ? null : await readCameraInfo(file).catch(() => null);
|
||||
const cull = cullFromCameraRating(camera?.rating);
|
||||
const updated = await db.photo.update({
|
||||
where: { id: photo.id },
|
||||
data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) },
|
||||
data: {
|
||||
storageKey: key,
|
||||
byteSize: size,
|
||||
originalStored: true,
|
||||
...(org?.biometricsEnabled && { facesStatus: "PENDING" }),
|
||||
...("rating" in cull ? { rating: cull.rating } : {}),
|
||||
...("flag" in cull && existing?.flag === "NONE" ? { flag: cull.flag } : {}),
|
||||
...(camera ? { exif: withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue } : {}),
|
||||
},
|
||||
});
|
||||
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
|
||||
// Deliveries waiting for it go now.
|
||||
@@ -357,27 +387,35 @@ export class IngestService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The event asked for on the upload (the one open in the library, or the desktop's pinned FTP target).
|
||||
* Kept, unless it is a game already put away and this photo was taken outside that game's window: then the
|
||||
* clock decides, so a pin left on yesterday's match does not take today's event.
|
||||
* The event asked for on the upload (open library / desktop pin). Kept only while the capture sits in that
|
||||
* event's ingest window and the photographer has not paused more than {@link INGEST_SESSION_GAP_MS} since
|
||||
* their last photo there — otherwise the clock (or inbox) decides.
|
||||
*/
|
||||
private async requestedEvent(organizationId: string, requested: string | undefined, at: Date): Promise<string | undefined> {
|
||||
private async requestedEvent(
|
||||
organizationId: string,
|
||||
userId: string,
|
||||
requested: string | undefined,
|
||||
at: Date,
|
||||
): Promise<string | undefined> {
|
||||
if (!requested) return undefined;
|
||||
const event = await this.deps.db.event.findFirst({
|
||||
where: { id: requested, organizationId },
|
||||
select: { archivedAt: true, ingestFrom: true, ingestUntil: true },
|
||||
select: { ingestFrom: true, ingestUntil: true },
|
||||
});
|
||||
if (!event) return undefined;
|
||||
if (event.archivedAt && (at < event.ingestFrom || at > event.ingestUntil)) return undefined;
|
||||
if (at < event.ingestFrom || at > event.ingestUntil) return undefined;
|
||||
if (!(await this.sameSession(requested, userId, at))) return undefined;
|
||||
return requested;
|
||||
}
|
||||
|
||||
/**
|
||||
* The event this photo belongs to: one the photographer is assigned to (or an event with no assignments,
|
||||
* open to everyone) whose ingest window contains the capture time. The latest-starting one wins.
|
||||
* open to everyone) whose ingest window contains the capture time, without a >1 h shooting gap. When two
|
||||
* windows overlap (studio at 14:00 and training at 16:30), the start closest to the capture wins — not the
|
||||
* latest event on the calendar.
|
||||
*/
|
||||
async routeToEvent(organizationId: string, userId: string, at: Date): Promise<string | null> {
|
||||
const event = await this.deps.db.event.findFirst({
|
||||
const events = await this.deps.db.event.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
archivedAt: null,
|
||||
@@ -385,10 +423,77 @@ export class IngestService {
|
||||
ingestUntil: { gte: at },
|
||||
OR: [{ assignments: { some: { userId } } }, { assignments: { none: {} } }],
|
||||
},
|
||||
orderBy: { startsAt: "desc" },
|
||||
select: { id: true },
|
||||
take: 20,
|
||||
select: { id: true, startsAt: true },
|
||||
});
|
||||
return event?.id ?? null;
|
||||
events.sort((a, b) => Math.abs(a.startsAt.getTime() - at.getTime()) - Math.abs(b.startsAt.getTime() - at.getTime()));
|
||||
for (const event of events) {
|
||||
if (await this.sameSession(event.id, userId, at)) return event.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Last capture by this photographer in the event; none yet → new session may start. */
|
||||
private async sameSession(eventId: string, userId: string, at: Date): Promise<boolean> {
|
||||
const last = await this.deps.db.photo.findFirst({
|
||||
where: {
|
||||
eventId,
|
||||
uploaderId: userId,
|
||||
capturedAt: { not: null, lt: at },
|
||||
},
|
||||
orderBy: { capturedAt: "desc" },
|
||||
select: { capturedAt: true },
|
||||
});
|
||||
return withinIngestSession(at, last?.capturedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos ingested before on-camera stars were read: re-open the original in storage, apply Rating, and mark
|
||||
* the row so it is not scanned again. Newest first; the worker calls this in small batches.
|
||||
* Does not touch photos the photographer already rated, or a REJECT flag.
|
||||
*/
|
||||
async backfillCameraRatings(limit = 25): Promise<number> {
|
||||
const { db, storage, log, broadcaster } = this.deps;
|
||||
const rows = await db.$queryRaw<
|
||||
Array<{ id: string; organization_id: string; storage_key: string; flag: "NONE" | "PICK" | "REJECT"; exif: unknown }>
|
||||
>`
|
||||
SELECT id, organization_id, storage_key, flag, exif
|
||||
FROM photos
|
||||
WHERE rating = 0
|
||||
AND original_stored
|
||||
AND status = 'READY'
|
||||
AND (
|
||||
exif IS NULL
|
||||
OR jsonb_typeof(exif::jsonb) <> 'object'
|
||||
OR COALESCE((exif::jsonb->>'cameraRatingChecked')::boolean, false) IS NOT TRUE
|
||||
)
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ${limit}
|
||||
`;
|
||||
let applied = 0;
|
||||
for (const row of rows) {
|
||||
const file = storage.resolve(row.storage_key);
|
||||
const camera = await readCameraInfo(file).catch(() => null);
|
||||
const cull = cullFromCameraRating(camera?.rating);
|
||||
const data: Prisma.PhotoUpdateInput = {
|
||||
exif: withCameraRatingChecked(row.exif) as Prisma.InputJsonValue,
|
||||
};
|
||||
if ("rating" in cull) {
|
||||
data.rating = cull.rating;
|
||||
if (row.flag === "NONE") data.flag = "PICK";
|
||||
applied++;
|
||||
}
|
||||
await db.photo.update({ where: { id: row.id }, data });
|
||||
if ("rating" in cull) {
|
||||
broadcaster.library(row.organization_id, {
|
||||
type: "photo.updated",
|
||||
ids: [row.id],
|
||||
patch: { rating: cull.rating, ...(row.flag === "NONE" ? { flag: "PICK" as const } : {}) },
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rows.length) log.info({ scanned: rows.length, applied }, "ingest: camera rating backfill");
|
||||
return applied;
|
||||
}
|
||||
|
||||
private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { INGEST_SESSION_GAP_MS, withinIngestSession } from "./service.js";
|
||||
|
||||
describe("withinIngestSession", () => {
|
||||
const at = new Date("2026-11-03T16:00:00Z");
|
||||
|
||||
it("allows the first photo of an event", () => {
|
||||
expect(withinIngestSession(at, null)).toBe(true);
|
||||
expect(withinIngestSession(at, undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps photos inside a one-hour pause", () => {
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - INGEST_SESSION_GAP_MS))).toBe(true);
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - 30 * 60_000))).toBe(true);
|
||||
});
|
||||
|
||||
it("ends the session after more than one hour without shots", () => {
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - INGEST_SESSION_GAP_MS - 1))).toBe(false);
|
||||
expect(withinIngestSession(at, new Date(at.getTime() - 2 * 60 * 60_000))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -25,11 +25,13 @@ export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promi
|
||||
/**
|
||||
* 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.
|
||||
* When another open event's window also covers the capture and starts closer to it, leave the photo in the inbox
|
||||
* (or for that other event) — otherwise creating a 16:30 training steals a 14:00 studio card from the overlap.
|
||||
*/
|
||||
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 } } },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, startsAt: true, assignments: { select: { userId: true } } },
|
||||
});
|
||||
if (!event || event.archivedAt) return [];
|
||||
const photos = await db.photo.findMany({
|
||||
@@ -39,14 +41,35 @@ export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
|
||||
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
|
||||
},
|
||||
select: { id: true },
|
||||
select: { id: true, capturedAt: true },
|
||||
take: 20_000,
|
||||
});
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (!photos.length) return [];
|
||||
const rivals = await db.event.findMany({
|
||||
where: {
|
||||
organizationId: event.organizationId,
|
||||
archivedAt: null,
|
||||
id: { not: eventId },
|
||||
ingestFrom: { lte: event.ingestUntil },
|
||||
ingestUntil: { gte: event.ingestFrom },
|
||||
},
|
||||
select: { id: true, startsAt: true, ingestFrom: true, ingestUntil: true },
|
||||
});
|
||||
const ids = photos
|
||||
.filter((p) => {
|
||||
if (!p.capturedAt) return true;
|
||||
const t = p.capturedAt.getTime();
|
||||
const better = rivals.some((r) => {
|
||||
if (t < r.ingestFrom.getTime() || t > r.ingestUntil.getTime()) return false;
|
||||
return Math.abs(r.startsAt.getTime() - t) < Math.abs(event.startsAt.getTime() - t);
|
||||
});
|
||||
return !better;
|
||||
})
|
||||
.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;
|
||||
}
|
||||
}
|
||||
+17
-1
@@ -134,7 +134,17 @@ const faceEngine =
|
||||
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
|
||||
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
|
||||
const faceService = faceEngine
|
||||
? new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS })
|
||||
? new FaceService({
|
||||
db,
|
||||
storage,
|
||||
broadcaster,
|
||||
log,
|
||||
engine: faceEngine,
|
||||
jersey,
|
||||
videoTools,
|
||||
videoFps: config.ARCHIVE_VIDEO_FACE_FPS,
|
||||
resend: (orgId, ids) => deliveryService.resendPhotos(orgId, ids),
|
||||
})
|
||||
: undefined;
|
||||
const faces = faceService
|
||||
? new FaceWorker(faceService, {
|
||||
@@ -171,6 +181,11 @@ faces?.start();
|
||||
renders?.start();
|
||||
fulfilment.start();
|
||||
invoices.start();
|
||||
// Photos that arrived before on-camera stars were read: apply Rating from the original in storage.
|
||||
const ratingBackfill = setInterval(() => {
|
||||
void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed"));
|
||||
}, 60_000);
|
||||
void ingest.backfillCameraRatings(25).catch((err) => log.warn({ err }, "ingest: camera rating backfill failed"));
|
||||
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
|
||||
|
||||
/** Drain in-flight jobs before ending the Prisma/pg pool (BIT-31189). Leave headroom under PM2 kill_timeout. */
|
||||
@@ -181,6 +196,7 @@ const shutdown = async (signal: string) => {
|
||||
shuttingDown = true;
|
||||
log.info({ signal }, "worker stopping");
|
||||
// Stop claiming first, then wait for ticks/in-flight work so `$disconnect` does not race Prisma queries.
|
||||
clearInterval(ratingBackfill);
|
||||
await Promise.all([
|
||||
scanner.stop(DRAIN_MS),
|
||||
archive.stop(DRAIN_MS),
|
||||
|
||||
@@ -455,23 +455,98 @@ describe("delivery", () => {
|
||||
expect((localOnly.json() as { localFolder: null }).localFolder).toBeNull();
|
||||
});
|
||||
|
||||
it("waits a little for the faces to be read before sending, so the names go with the photo", async () => {
|
||||
it("a send the photographer asked for does not wait for faces", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const id = await photo("faces.jpg", "2026:09:23 21:10:00");
|
||||
const id = await photo("faces-manual.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "PENDING" } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
|
||||
await drain();
|
||||
expect(nc.files.size).toBe(1);
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } });
|
||||
expect(item.lastError).not.toBe("waiting_for_faces");
|
||||
});
|
||||
|
||||
it("a destination with waitForFaces waits while faces are being read when the pad needs player names", async () => {
|
||||
const { orgId, token, eventId } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: {
|
||||
name: "Backup faces",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.test",
|
||||
username: "photoreport",
|
||||
password: "app-password-123",
|
||||
folderTemplate: "/Backup/{event}/",
|
||||
fileNameTemplate: "{originalName}",
|
||||
waitForFaces: true,
|
||||
},
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const id = await photo("faces-arrival.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "PENDING", eventId } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [id] } });
|
||||
const [itemId] = await delivery.claim(10);
|
||||
const waiting = await delivery.process(itemId!);
|
||||
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_faces", 0]);
|
||||
expect(nc.files.size).toBe(0);
|
||||
// Read: it goes.
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "DONE" } });
|
||||
await ctx.db.deliveryItem.update({ where: { id: itemId! }, data: { nextAttemptAt: new Date() } });
|
||||
await drain();
|
||||
expect(nc.files.size).toBe(1);
|
||||
});
|
||||
|
||||
it("does not wait for faces that were never started (NONE), even with waitForFaces", async () => {
|
||||
const { orgId, token, eventId } = await setup();
|
||||
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: {
|
||||
name: "Backup none",
|
||||
kind: "NEXTCLOUD",
|
||||
baseUrl: "https://cloud.test",
|
||||
username: "photoreport",
|
||||
password: "app-password-123",
|
||||
folderTemplate: "/Backup/{event}/",
|
||||
fileNameTemplate: "{originalName}",
|
||||
waitForFaces: true,
|
||||
},
|
||||
});
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const id = await photo("faces-none.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE", eventId } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [id] } });
|
||||
await drain();
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId } });
|
||||
expect(item.lastError).not.toBe("waiting_for_faces");
|
||||
expect(nc.files.size).toBe(1);
|
||||
});
|
||||
|
||||
it("Enviar originais forces the camera file even when the destination resizes", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("orig.jpg", "2026:09:23 21:10:00", { width: 1200, height: 800 });
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/deliveries`,
|
||||
headers: bearer(token),
|
||||
payload: { targetId: target.id, photoIds: [id], originals: true },
|
||||
});
|
||||
await drain();
|
||||
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { photoId: id, targetId: target.id } });
|
||||
expect(item.forceOriginals).toBe(true);
|
||||
expect(item.status).toBe("DONE");
|
||||
const [buf] = [...nc.files.values()];
|
||||
const meta = await sharp(buf!).metadata();
|
||||
expect(meta.width).toBe(1200);
|
||||
expect(meta.height).toBe(800);
|
||||
});
|
||||
|
||||
it("an IPTC change in the Info window sends the photo again where it went, replacing the old file", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("info.jpg", "2026:09:23 21:10:00");
|
||||
|
||||
@@ -160,10 +160,10 @@ describe("library", () => {
|
||||
expect(forged.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
|
||||
it("FTP pin keeps shots inside its window; shots from another event's time still follow the clock", async () => {
|
||||
const { orgId, admin, foto, other, event } = await setup();
|
||||
const until = new Date(Date.now() + 3600_000).toISOString();
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
|
||||
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: "2026-10-14T10:00:00Z", photographerIds: [] } })).json() as { id: string };
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
|
||||
// The photographer sees only their own login; the editor sees all.
|
||||
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
|
||||
@@ -178,8 +178,10 @@ describe("library", () => {
|
||||
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
|
||||
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
|
||||
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
|
||||
// Taken during the game, but sent while the login points at the press conference: it goes there.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the press (pin window): press gets it.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456", taken: "2026:10:14 10:15:00" })))).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
// Taken during the game, pin still on press: clock wins — pin must not swallow another session.
|
||||
expect(await service.ingestFile(await drop("foto.r1", "game.jpg", await jpeg({ color: "#abcdef" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
|
||||
// Switched off: by the time again.
|
||||
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
|
||||
@@ -189,6 +191,41 @@ describe("library", () => {
|
||||
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", async () => {
|
||||
const { orgId, admin, photographer } = await setup();
|
||||
const miguel = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Miguel em estúdio", startsAt: "2026-11-03T14:00:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
const sub21 = (
|
||||
await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "Treino Sub-21", startsAt: "2026-11-03T16:30:00Z", photographerIds: [photographer.id] },
|
||||
})
|
||||
).json() as { id: string };
|
||||
// Widen windows so they overlap (default is −2h/+4h: Miguel until 18:00, Sub-21 from 14:30).
|
||||
await ctx.db.event.update({ where: { id: miguel.id }, data: { ingestFrom: new Date("2026-11-03T12:00:00Z"), ingestUntil: new Date("2026-11-03T18:00:00Z") } });
|
||||
await ctx.db.event.update({ where: { id: sub21.id }, data: { ingestFrom: new Date("2026-11-03T14:30:00Z"), ingestUntil: new Date("2026-11-03T20:30:00Z") } });
|
||||
|
||||
const send = async (name: string, taken: string, pin?: string) => {
|
||||
const file = path.join(dir, name);
|
||||
await writeFile(file, await jpeg({ color: "#778899", taken }));
|
||||
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: pin });
|
||||
};
|
||||
// 14:20: only Miguel — Sub-21 pin must not take it.
|
||||
expect(await send("studio.jpg", "2026:11:03 14:20:00", sub21.id)).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 15:00 overlap, no pin: closest start is Miguel.
|
||||
expect(await send("overlap.jpg", "2026:11:03 15:00:00")).toMatchObject({ status: "ingested", eventId: miguel.id });
|
||||
// 16:40: Sub-21.
|
||||
expect(await send("treino.jpg", "2026:11:03 16:40:00")).toMatchObject({ status: "ingested", eventId: sub21.id });
|
||||
});
|
||||
|
||||
it("a pin left on a game already put away does not take photos shot for the next event", async () => {
|
||||
const { orgId, admin, photographer, event } = await setup();
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-10-19T10:40:00Z") } });
|
||||
@@ -210,6 +247,21 @@ describe("library", () => {
|
||||
expect(await send("today.jpg", "2026:10:19 12:05:00")).toMatchObject({ status: "ingested", eventId: press.id });
|
||||
});
|
||||
|
||||
it("a pin does not keep photos after a one-hour shooting pause (open ingest window)", async () => {
|
||||
const { orgId, photographer, event } = await setup();
|
||||
// Window still open for both bursts — only the gap must end the session.
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { ingestUntil: new Date("2026-09-24T06:00:00Z") } });
|
||||
const send = async (name: string, taken: string) => {
|
||||
const file = path.join(dir, name);
|
||||
await writeFile(file, await jpeg({ color: "#445566", taken }));
|
||||
return service.ingest(file, { organizationId: orgId, userId: photographer.id, source: "DESKTOP", originalName: name, eventId: event.id });
|
||||
};
|
||||
expect(await send("a.jpg", "2026:09:23 20:00:00")).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
expect(await send("b.jpg", "2026:09:23 20:45:00")).toMatchObject({ status: "ingested", eventId: event.id });
|
||||
// >1 h after the last shot: not the same session → Sem evento (no other event fits).
|
||||
expect(await send("c.jpg", "2026:09:23 22:00:00")).toMatchObject({ status: "ingested", eventId: null });
|
||||
});
|
||||
|
||||
it("an archive import stays in its put-away event when the photo was taken outside that window", async () => {
|
||||
const { orgId, admin, photographer, event } = await setup();
|
||||
await ctx.db.event.update({ where: { id: event.id }, data: { archivedAt: new Date("2026-09-24T00:00:00Z") } });
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { API_URL } from "../api.js";
|
||||
import { desktopInvoke, type Invoke, isDesktop, openExternal } from "../platform.js";
|
||||
@@ -16,35 +16,55 @@ 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).
|
||||
* Desktop only: a newer interface was downloaded onto this computer (`ui.rs`). This is a local app — switch into
|
||||
* it at once (reload). Edits wait in the offline queue; nothing is lost. Also asks `ui_check` on open so a
|
||||
* deploy that landed while the app was closed is applied without waiting for the background timer.
|
||||
*/
|
||||
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);
|
||||
export function UiReadyNotice({
|
||||
listen = tauriListen,
|
||||
invoke = desktopInvoke,
|
||||
enabled = isDesktop(),
|
||||
reload = () => window.location.reload(),
|
||||
}: {
|
||||
listen?: Listen;
|
||||
invoke?: Invoke;
|
||||
enabled?: boolean;
|
||||
reload?: () => void;
|
||||
}) {
|
||||
const [applying, setApplying] = useState(false);
|
||||
const applied = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let stop: (() => void) | undefined;
|
||||
let alive = true;
|
||||
listen("ui-ready", () => setReady(true)).then(
|
||||
const apply = () => {
|
||||
if (!alive || applied.current) return;
|
||||
applied.current = true;
|
||||
setApplying(true);
|
||||
// Let the asset provider finish switching folders before the webview asks for index.html again.
|
||||
window.setTimeout(() => reload(), 150);
|
||||
};
|
||||
listen("ui-ready", apply).then(
|
||||
(unlisten) => (alive ? (stop = unlisten) : unlisten()),
|
||||
() => {},
|
||||
);
|
||||
// Launch: pull the published interface now if this copy is behind (app-first, not "refresh the browser").
|
||||
invoke<boolean>("ui_check")
|
||||
.then((updated) => {
|
||||
if (alive && updated) apply();
|
||||
})
|
||||
.catch(() => {});
|
||||
return () => {
|
||||
alive = false;
|
||||
stop?.();
|
||||
};
|
||||
}, [enabled, listen]);
|
||||
if (!ready || dismissed) return null;
|
||||
}, [enabled, listen, invoke, reload]);
|
||||
|
||||
if (!applying) 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>
|
||||
<span>{t.update.uiApplying}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -38,18 +38,28 @@ describe("local catalogue", () => {
|
||||
});
|
||||
|
||||
describe("interface update notice", () => {
|
||||
it("says when a newer interface is ready and reloads into it", async () => {
|
||||
it("reloads into a newer interface as soon as it is ready (local app, not a browser tab)", async () => {
|
||||
let fire: () => void = () => {};
|
||||
const listen = vi.fn(async (_event: string, handler: () => void) => {
|
||||
fire = handler;
|
||||
return () => {};
|
||||
});
|
||||
const invoke = vi.fn(async () => false) as unknown as Invoke;
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} enabled reload={reload} />);
|
||||
render(<UiReadyNotice listen={listen} invoke={invoke} 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();
|
||||
expect(await screen.findByText("A actualizar a interface da app…")).toBeTruthy();
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 });
|
||||
});
|
||||
|
||||
it("checks for a newer interface on launch and reloads when one was downloaded", async () => {
|
||||
const listen = vi.fn(async () => () => {});
|
||||
const invoke = vi.fn(async (cmd: string) => (cmd === "ui_check" ? true : null)) as unknown as Invoke;
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} invoke={invoke} enabled reload={reload} />);
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledWith("ui_check"));
|
||||
await waitFor(() => expect(reload).toHaveBeenCalled(), { timeout: 1000 });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -108,6 +108,11 @@ interface ViewerProps {
|
||||
/** Eyedropper on: a click reports where (0..1 in the shown frame). */
|
||||
picking?: boolean;
|
||||
onPick?: (u: number, v: number) => void;
|
||||
/** Remove / heal tool: a click reports where (0..1 in the shown frame). */
|
||||
spotting?: boolean;
|
||||
onSpot?: (u: number, v: number) => void;
|
||||
/** Spot pins to draw over the loupe (normalized in the shown / cropped frame). */
|
||||
spotMarks?: { u: number; v: number; size: number }[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -224,7 +229,7 @@ export function Viewer(props: ViewerProps) {
|
||||
|
||||
// 1:1: click and drag moves the photo (the hand tool), like Lightroom.
|
||||
const pan = useRef<{ x: number; y: number; left: number; top: number; id: number } | null>(null);
|
||||
const panning = !!props.actualPixels && !props.picking && !cropping;
|
||||
const panning = !!props.actualPixels && !props.picking && !props.spotting && !cropping;
|
||||
const panHandlers = panning
|
||||
? {
|
||||
onPointerDown: (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
@@ -265,14 +270,34 @@ export function Viewer(props: ViewerProps) {
|
||||
// While cropping the photo turns under an upright crop, as in Lightroom: the engine renders it unturned
|
||||
// (the whole frame), and the straighten angle is shown here so a drag follows the pointer at once.
|
||||
style={cropping && props.crop.angle ? { transform: `rotate(${props.crop.angle}deg)` } : undefined}
|
||||
className={`block h-full w-full shadow-[0_2px_12px_rgba(0,0,0,0.7)] ${props.picking ? "cursor-crosshair" : ""}`}
|
||||
className={`block h-full w-full shadow-[0_2px_12px_rgba(0,0,0,0.7)] ${props.picking || props.spotting ? "cursor-crosshair" : ""}`}
|
||||
aria-label="Foto em revelação"
|
||||
onClick={(e) => {
|
||||
if (!props.picking) return;
|
||||
if (!props.picking && !props.spotting) return;
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
callbacks.current.onPick?.((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height);
|
||||
const u = (e.clientX - r.left) / r.width;
|
||||
const v = (e.clientY - r.top) / r.height;
|
||||
if (props.picking) callbacks.current.onPick?.(u, v);
|
||||
else callbacks.current.onSpot?.(u, v);
|
||||
}}
|
||||
/>
|
||||
{props.spotMarks && props.spotMarks.length > 0 && (
|
||||
<div className="pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{props.spotMarks.map((m, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="absolute rounded-full border border-white/90 bg-black/30"
|
||||
style={{
|
||||
left: `${m.u * 100}%`,
|
||||
top: `${m.v * 100}%`,
|
||||
width: `${Math.max(8, m.size * 100)}%`,
|
||||
height: `${Math.max(8, m.size * 100)}%`,
|
||||
transform: "translate(-50%, -50%)",
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{cropping && frame && (
|
||||
<CropFrame
|
||||
crop={props.crop}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { addSpot, removeSpotAt, spotsOf, spotsPartial } from "./spots.js";
|
||||
|
||||
describe("spots", () => {
|
||||
it("adds a fill spot and round-trips through merge partial", () => {
|
||||
const settings = "{}";
|
||||
const next = addSpot(settings, { mode: "fill", x: 0.4, y: 0.6, size: 0.03, feather: 40, opacity: 100 });
|
||||
expect(next).toHaveLength(1);
|
||||
expect(next[0]?.mode).toBe("fill");
|
||||
expect(next[0]?.points[0]).toEqual({ x: 0.4, y: 0.6 });
|
||||
const merged = JSON.stringify({ ...JSON.parse(settings), ...spotsPartial(next) });
|
||||
expect(spotsOf(merged)).toEqual(next);
|
||||
});
|
||||
|
||||
it("removes by index", () => {
|
||||
let spots = addSpot("{}", { mode: "remove", x: 0.1, y: 0.1, size: 0.02, feather: 50, opacity: 100 });
|
||||
spots = addSpot(JSON.stringify({ spots }), { mode: "heal", x: 0.2, y: 0.2, size: 0.02, feather: 50, opacity: 100 });
|
||||
expect(removeSpotAt(JSON.stringify({ spots }), 0)).toHaveLength(1);
|
||||
expect(removeSpotAt(JSON.stringify({ spots }), 0)[0]?.mode).toBe("heal");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/** Spot / heal / clone / content-aware fill — LightCraft `DevelopSettings.spots` (snake_case JSON). */
|
||||
|
||||
export type SpotMode = "remove" | "heal" | "clone" | "fill";
|
||||
|
||||
export interface SpotPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface Spot {
|
||||
mode: SpotMode;
|
||||
points: SpotPoint[];
|
||||
/** Radius as a fraction of the long edge (LightCraft default ~0.02). */
|
||||
size: number;
|
||||
feather: number;
|
||||
opacity: number;
|
||||
source_offset?: SpotPoint | null;
|
||||
}
|
||||
|
||||
export const SPOT_MODES: { id: SpotMode; labelKey: "spotRemove" | "spotHeal" | "spotClone" | "spotFill" }[] = [
|
||||
{ id: "remove", labelKey: "spotRemove" },
|
||||
{ id: "heal", labelKey: "spotHeal" },
|
||||
{ id: "clone", labelKey: "spotClone" },
|
||||
{ id: "fill", labelKey: "spotFill" },
|
||||
];
|
||||
|
||||
export const DEFAULT_SPOT_SIZE = 0.025;
|
||||
export const DEFAULT_SPOT_FEATHER = 50;
|
||||
export const DEFAULT_SPOT_OPACITY = 100;
|
||||
|
||||
export function spotsOf(settings: string): Spot[] {
|
||||
try {
|
||||
const s = JSON.parse(settings) as { spots?: Spot[] };
|
||||
return Array.isArray(s.spots) ? s.spots : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Partial for `develop.merge`: replace the spots list. */
|
||||
export function spotsPartial(spots: Spot[]): Record<string, unknown> {
|
||||
return { spots };
|
||||
}
|
||||
|
||||
export function addSpot(
|
||||
settings: string,
|
||||
spot: {
|
||||
mode: SpotMode;
|
||||
x: number;
|
||||
y: number;
|
||||
size: number;
|
||||
feather: number;
|
||||
opacity: number;
|
||||
sourceOffset?: SpotPoint | null;
|
||||
},
|
||||
): Spot[] {
|
||||
const next: Spot = {
|
||||
mode: spot.mode,
|
||||
points: [{ x: clamp01(spot.x), y: clamp01(spot.y) }],
|
||||
size: clamp(spot.size, 0.002, 0.25),
|
||||
feather: clamp(spot.feather, 0, 100),
|
||||
opacity: clamp(spot.opacity, 0, 100),
|
||||
source_offset: spot.sourceOffset ?? null,
|
||||
};
|
||||
return [...spotsOf(settings), next];
|
||||
}
|
||||
|
||||
export function removeSpotAt(settings: string, index: number): Spot[] {
|
||||
return spotsOf(settings).filter((_, i) => i !== index);
|
||||
}
|
||||
|
||||
function clamp01(v: number): number {
|
||||
return Math.min(1, Math.max(0, v));
|
||||
}
|
||||
|
||||
function clamp(v: number, lo: number, hi: number): number {
|
||||
return Math.min(hi, Math.max(lo, v));
|
||||
}
|
||||
+33
-3
@@ -98,6 +98,10 @@ export const t = {
|
||||
clearFilter: "Limpar filtro",
|
||||
clearPlayers: "Limpar jogadores",
|
||||
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
|
||||
sendOriginals: "Enviar originais",
|
||||
sendOriginalsHelp: "O ficheiro da câmara (sem redimensionar), com IPTC e o nome do destino. Para casos como as fotos do Francisco Tavares.",
|
||||
waitForFaces: "Esperar pelas caras",
|
||||
waitForFacesHelp: "Só neste destino: se o pad usa nomes de jogadores, espera um pouco pelas caras antes de enviar. Por defeito envia já; quando os nomes chegarem, o ficheiro é actualizado e reenviado.",
|
||||
outputSelection: "As selecionadas",
|
||||
outputBest: "As melhores",
|
||||
outputRest: "O resto",
|
||||
@@ -193,14 +197,14 @@ export const t = {
|
||||
usbCamera: {
|
||||
button: "USB",
|
||||
title: "Câmara por USB",
|
||||
help: "Com a câmara ligada por cabo, vês o cartão e cada foto nova. Nada sobe sozinho: escolhes o que descarregar para o evento abaixo.",
|
||||
help: "Carrega em «Ligar cabo» com a câmara ligada. A app lê o cartão em pulsos curtos e larga a sessão PTP para poderes disparar (sem ecrã «computador»). A primeira leitura dum cartão cheio demora; depois só entram disparos novos. Nada sobe sozinho: escolhes o que descarregar, ou marca «Puxar automaticamente».",
|
||||
none: "Nenhuma câmara ligada por cabo.",
|
||||
tetherOn: "Cabo ligado",
|
||||
tetherOff: "Cabo desligado",
|
||||
turnOn: "Ligar cabo",
|
||||
turnOff: "Desligar cabo",
|
||||
opening: "A ligar à câmara…",
|
||||
tethered: "Câmara pronta — escolhe o que descarregar",
|
||||
tethered: "Câmara livre para disparar — a app lê o cartão em segundo plano",
|
||||
busy: "A câmara está ocupada por outra app (o EOS Utility, por exemplo). Fecha-a: o cabo só pode estar com uma de cada vez. A tentar outra vez sozinho.",
|
||||
idle: "Cabo desligado",
|
||||
listing: "A ler o cartão…",
|
||||
@@ -219,11 +223,17 @@ export const t = {
|
||||
newShot: "nova",
|
||||
imported: "já puxada",
|
||||
selectNew: "Seleccionar novas",
|
||||
selectEvent: "Do evento",
|
||||
selectAll: "Todas",
|
||||
selectNone: "Nenhuma",
|
||||
refresh: "Actualizar lista",
|
||||
download: (n: number) => (n === 1 ? "Descarregar 1" : `Descarregar ${n}`),
|
||||
emptyCard: "O cartão ainda não tem fotos listadas.",
|
||||
outsideEvent: "fora do evento",
|
||||
windowHint: (inWin: number, total: number) => `${inWin} de ${total} na janela do evento`,
|
||||
autoIngest: "Puxar automaticamente (só na janela do evento)",
|
||||
autoIngestHelp: "Só fotos novas cuja hora da câmara cai entre o início e o fim de ingestão do evento. O resto do cartão fica por escolher.",
|
||||
autoNeedsEvent: "Escolhe um evento com janela de ingestão para o automático.",
|
||||
},
|
||||
squad: {
|
||||
title: "Pessoas",
|
||||
@@ -413,6 +423,7 @@ export const t = {
|
||||
},
|
||||
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
|
||||
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
|
||||
sendingOriginals: (n: number) => (n === 1 ? "A enviar 1 original desta máquina" : `A enviar ${n} originais desta máquina`),
|
||||
uploadFailed: (n: number) => `${n} com erro`,
|
||||
dismiss: "Fechar",
|
||||
useEmbeddedTitle: "Usar o Title como jogadores",
|
||||
@@ -595,6 +606,7 @@ export const t = {
|
||||
copied: "Copiado",
|
||||
deliveryErrors: {
|
||||
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
|
||||
waiting_for_original_here: "A pedir o original desta máquina…",
|
||||
original_not_here: "O original nunca chegou do computador do fotógrafo",
|
||||
},
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou", RETRACTED: "Retirada" },
|
||||
@@ -842,6 +854,12 @@ export const t = {
|
||||
download: "Descarregar instalador",
|
||||
later: "Mais tarde",
|
||||
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
|
||||
uiApplying: "A actualizar a interface da app…",
|
||||
uiSection: "Interface da app",
|
||||
uiSectionHelp: "A PhotoReport é uma app neste computador. Novas funções descarregam-se sozinhas; podes forçar a verificação aqui.",
|
||||
uiCheckNow: "Actualizar interface agora",
|
||||
uiChecking: "A verificar…",
|
||||
uiCurrent: "Já tens a interface mais recente.",
|
||||
reload: "Recarregar agora",
|
||||
},
|
||||
editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.",
|
||||
@@ -1227,6 +1245,18 @@ export const t = {
|
||||
saved: "Guardado",
|
||||
crop: "Recortar",
|
||||
cropDone: "Concluir",
|
||||
spot: "Apagar",
|
||||
spotDone: "Concluir",
|
||||
spotHelp: "Clica na zona a limpar (softbox, cabo, pó). Q liga a ferramenta.",
|
||||
spotNow: "Clica na foto onde queres apagar. Esc cancela.",
|
||||
spotRemove: "Remover",
|
||||
spotHeal: "Corrigir",
|
||||
spotClone: "Clonar",
|
||||
spotFill: "Preencher",
|
||||
spotSize: "Tamanho",
|
||||
spotFeather: "Suavizar",
|
||||
spotOpacity: "Opacidade",
|
||||
spotDelete: "Tirar",
|
||||
aspect: "Proporção",
|
||||
aspectFree: "Livre",
|
||||
aspectOriginal: "Original",
|
||||
@@ -1260,7 +1290,7 @@ export const t = {
|
||||
syncApply: "Aplicar",
|
||||
synced: (n: number) => `Ajustes sincronizados em ${n} ${n === 1 ? "foto" : "fotos"}`,
|
||||
noAccess: "Só podes revelar fotos que enviaste.",
|
||||
shortcuts: "← → foto · Ctrl/Cmd+A todas · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular",
|
||||
shortcuts: "← → foto · Ctrl/Cmd+A todas · P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · G grelha · I informação · Shift+A automático · \\ antes/depois · R recortar · Q apagar · W conta-gotas · Z 1:1 (arrastar move) · E lupa · Ctrl+Alt+1 biblioteca · Ctrl+Z anular",
|
||||
groups: { wb: "Equilíbrio de brancos", tone: "Tom", presence: "Presença", profile: "Perfil" },
|
||||
labels: {
|
||||
"profile.amount": "Intensidade",
|
||||
|
||||
@@ -81,6 +81,7 @@ describe("local FTP feed", () => {
|
||||
// Each shows as soon as it arrives. The one the server has leaves; the failed one stays so it can be edited.
|
||||
await waitFor(() => expect(localPhotos.list().map((p) => p.name)).toEqual(["B.JPG"]));
|
||||
// Working locally (the default): previews go up, each with the fingerprint of its original.
|
||||
// Stub previews have no EXIF: the open pin still names the event (same as the server).
|
||||
expect(added).toEqual([
|
||||
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
{ name: "B.JPG", eventId: "ev1", size: "preview of /x/FTP/B.JPG".length, sha: "sha-/x/FTP/B.JPG" },
|
||||
|
||||
@@ -47,6 +47,9 @@ export interface FtpTarget {
|
||||
id: string;
|
||||
title: string;
|
||||
date: string;
|
||||
/** Event ingest window (ISO). USB auto-ingest only pulls shots inside this range. */
|
||||
ingestFrom?: string;
|
||||
ingestUntil?: string;
|
||||
}
|
||||
|
||||
export type Invoke = <T>(cmd: string, args?: Record<string, unknown>) => Promise<T>;
|
||||
@@ -59,7 +62,7 @@ const IN_FLIGHT = 6;
|
||||
* Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access
|
||||
* token expires, and the server answers 401. Two leaves room for the upload to leave.
|
||||
*/
|
||||
const IN_FLIGHT_ORIGINALS = 2;
|
||||
const IN_FLIGHT_ORIGINALS = 3;
|
||||
/**
|
||||
* Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in
|
||||
* ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left,
|
||||
@@ -120,7 +123,15 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
originalsRef.current = !!status?.settings.uploadOriginals;
|
||||
|
||||
const setTarget = useCallback((e: EventSummary | null) => {
|
||||
const next = e ? { id: e.id, title: eventLabel(e), date: e.startsAt.slice(0, 10) } : null;
|
||||
const next = e
|
||||
? {
|
||||
id: e.id,
|
||||
title: eventLabel(e),
|
||||
date: e.startsAt.slice(0, 10),
|
||||
ingestFrom: e.ingestFrom,
|
||||
ingestUntil: e.ingestUntil,
|
||||
}
|
||||
: null;
|
||||
setTargetState(next);
|
||||
prefs.set("ftp.target", JSON.stringify(next));
|
||||
}, []);
|
||||
@@ -154,9 +165,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
const cached = orgId ? await cache.events(orgId) : null;
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(preview));
|
||||
// A pin on a game already put away, or left over from the previous match, does not take the next photos.
|
||||
const pinnedId = to && (!cached || events.some((e) => e.id === to.id && !e.archivedAt)) ? to.id : null;
|
||||
const eventId = eventForArrival(pinnedId, events, capturedAt);
|
||||
// Open FTP target always; eventForArrival drops an archived leftover and keeps shots inside the window.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
if (!localPhotos.bySha(info.sha256)) {
|
||||
let url = "";
|
||||
|
||||
@@ -66,6 +66,8 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
const [pickOpen, setPickOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
/** Camera original for this send (overrides the destination's resize). */
|
||||
const [sendOriginals, setSendOriginals] = useState(false);
|
||||
|
||||
/** Remember the chosen destinations across tabs and restarts (persisted on every change, not only on send). */
|
||||
const remember = (ids: string[]) => {
|
||||
@@ -122,7 +124,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
try {
|
||||
// Without a network (or photos still uploading) each request waits on this computer and goes when it can.
|
||||
const results: Awaited<ReturnType<typeof deliver>>[] = [];
|
||||
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again));
|
||||
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again, sendOriginals));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
const waiting = results.some((r) => r.waiting);
|
||||
@@ -142,7 +144,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
setBusy(true);
|
||||
try {
|
||||
const results: Awaited<ReturnType<ApiClient["deliverBest"]>>[] = [];
|
||||
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain }));
|
||||
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain, originals: sendOriginals }));
|
||||
prefs.set(BEST_COUNT, String(bestCount));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
@@ -184,7 +186,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
const results: Awaited<ReturnType<typeof deliver>>[] = [];
|
||||
for (const batch of idsByTarget(choices, photos.map((p) => p.id), bestByCount, [...restIds])) {
|
||||
for (let i = 0; i < batch.ids.length; i += DELIVER_CHUNK) {
|
||||
results.push(await deliver(api, orgId, batch.targetId, batch.ids.slice(i, i + DELIVER_CHUNK)));
|
||||
results.push(await deliver(api, orgId, batch.targetId, batch.ids.slice(i, i + DELIVER_CHUNK), false, sendOriginals));
|
||||
}
|
||||
}
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
@@ -255,10 +257,25 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
);
|
||||
})}
|
||||
{planned && <p className="text-faint">{t.outputRestHelp}</p>}
|
||||
<label className="flex items-start gap-2 border-t border-line pt-2 text-ink" title={t.sendOriginalsHelp}>
|
||||
<input type="checkbox" className="mt-0.5" checked={sendOriginals} onChange={(e) => setSendOriginals(e.target.checked)} disabled={busy} />
|
||||
<span>
|
||||
<span className="font-semibold">{t.sendOriginals}</span>
|
||||
<span className="block text-[11px] text-faint">{t.sendOriginalsHelp}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{/* Always visible next to Enviar — desktop may still be on a cached UI until reload. */}
|
||||
<label
|
||||
className={`flex h-6 shrink-0 items-center gap-1 border px-2 text-[11px] ${sendOriginals ? "border-accent bg-accent/20 text-ink" : "border-black bg-cell text-ink"}`}
|
||||
title={t.sendOriginalsHelp}
|
||||
>
|
||||
<input type="checkbox" checked={sendOriginals} onChange={(e) => setSendOriginals(e.target.checked)} disabled={busy} />
|
||||
{t.sendOriginals}
|
||||
</label>
|
||||
<button
|
||||
onClick={() => void (planned ? sendSplit() : send())}
|
||||
disabled={busy || !selected.length || (!planned && !photos.length)}
|
||||
|
||||
@@ -176,6 +176,7 @@ export function TargetForm({
|
||||
keepExif: target?.keepExif ?? true,
|
||||
srgb: target?.srgb ?? false,
|
||||
originals: target?.originals ?? false,
|
||||
waitForFaces: target?.waitForFaces ?? false,
|
||||
onArrival: target?.onArrival ?? false,
|
||||
arrivalLogins: target?.arrivalLogins ?? ([] as string[]),
|
||||
untouched: target?.untouched ?? false,
|
||||
@@ -481,6 +482,17 @@ export function TargetForm({
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5"
|
||||
checked={v.waitForFaces}
|
||||
onChange={(e) => setV({ ...v, waitForFaces: e.target.checked })}
|
||||
/>
|
||||
<span>
|
||||
<span className="text-ink">{t.waitForFaces}</span> — {t.waitForFacesHelp}
|
||||
</span>
|
||||
</label>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { useIngest } from "./ingest.js";
|
||||
|
||||
/**
|
||||
* Thin transfer strip (Photo Mechanic–style): always at the bottom of the workspace while JPEGs or
|
||||
* originals are leaving this computer — not only on the library page.
|
||||
*/
|
||||
export function TransferBar() {
|
||||
const { uploads, originals } = useIngest();
|
||||
const originalFlight = useSyncExternalStore(
|
||||
(fn) => originals?.subscribe(fn) ?? (() => {}),
|
||||
() => originals?.inFlight.size ?? 0,
|
||||
() => 0,
|
||||
);
|
||||
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
|
||||
const failed = uploads.items.filter((i) => i.status === "failed");
|
||||
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
|
||||
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
|
||||
const busy = sending.length > 0 || originalFlight > 0;
|
||||
if (!busy && uploads.items.length === 0) return null;
|
||||
|
||||
const label = (() => {
|
||||
if (sending.length) return t.uploading(sentCount, uploads.items.length);
|
||||
if (originalFlight > 0) return t.sendingOriginals(originalFlight);
|
||||
return t.uploaded(sentCount);
|
||||
})();
|
||||
|
||||
const pct = sending.length || uploads.items.length ? Math.round(overall * 100) : originalFlight > 0 ? 50 : 100;
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1 text-[11px]" role="status" aria-live="polite">
|
||||
<span className="font-mono text-faint">
|
||||
{label}
|
||||
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
|
||||
{originalFlight > 0 && sending.length > 0 && <span className="text-faint"> · {t.sendingOriginals(originalFlight)}</span>}
|
||||
</span>
|
||||
<span className="h-1 min-w-[7rem] flex-1 bg-black" role="progressbar" aria-valuenow={pct} aria-valuemin={0} aria-valuemax={100}>
|
||||
<span className={`block h-full bg-accent transition-[width] ${originalFlight > 0 && !sending.length ? "animate-pulse" : ""}`} style={{ width: `${pct}%` }} />
|
||||
</span>
|
||||
{failed.length > 0 && (
|
||||
<span className="max-w-[14rem] truncate text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>
|
||||
{failed[0]?.name}: {failed[0]?.error}
|
||||
</span>
|
||||
)}
|
||||
{!sending.length && uploads.items.length > 0 && (
|
||||
<button type="button" onClick={uploads.clear} className="text-faint underline hover:text-muted">
|
||||
{t.dismiss}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,9 @@ import { render, renderHook, screen, waitFor } from "@testing-library/react";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Invoke } from "./LocalFtp.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import type { UploadStatus } from "./uploads.js";
|
||||
import { UsbCameraButton, type UsbStatus, useUsbCamera, withSidecars } from "./UsbCamera.js";
|
||||
import { UsbCameraButton, type UsbStatus, inEventWindow, useUsbCamera, withSidecars } from "./UsbCamera.js";
|
||||
|
||||
const camera: UsbStatus = {
|
||||
supported: true,
|
||||
@@ -14,12 +15,17 @@ const camera: UsbStatus = {
|
||||
{ name: "IMG_0001.CR3", size: 20, isNew: true, imported: false },
|
||||
{ name: "IMG_0002.JPG", size: 10, isNew: false, imported: false },
|
||||
],
|
||||
catalogGen: 1,
|
||||
};
|
||||
|
||||
function shell(files: { path: string; name: string; size: number; modifiedMs: number }[]) {
|
||||
const sent: unknown[] = [];
|
||||
const invoke = vi.fn(async (cmd: string, args?: Record<string, unknown>) => {
|
||||
if (cmd === "camera_status") return camera;
|
||||
if (cmd === "camera_status") {
|
||||
const since = args?.sinceGen;
|
||||
if (since === camera.catalogGen) return { ...camera, files: [] };
|
||||
return camera;
|
||||
}
|
||||
if (cmd === "camera_take") return files.splice(0);
|
||||
if (cmd === "ftp_preview") return [...new TextEncoder().encode(`preview of ${String(args?.path)}`)];
|
||||
if (cmd === "ftp_info") return { sha256: "sha", size: 5_000_000, width: 6000, height: 4000 };
|
||||
@@ -42,6 +48,8 @@ const usbStub = {
|
||||
syncClock: vi.fn(),
|
||||
importFiles: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
autoIngest: false,
|
||||
setAutoIngest: vi.fn(),
|
||||
};
|
||||
|
||||
describe("usb tether", () => {
|
||||
@@ -55,6 +63,7 @@ describe("usb tether", () => {
|
||||
}
|
||||
};
|
||||
renderHook(() => useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04" }, invoke));
|
||||
// Preview has no EXIF: keep the open pin (auto-pull already used the card clock for the window).
|
||||
await waitFor(() => expect(added).toEqual([{ name: "IMG_0001.JPG", eventId: "ev1" }]));
|
||||
await waitFor(() => expect(sent).toEqual([{ path: "/ingest/.usb/IMG_0001.JPG", event: "Portugal x Suíça", date: "2026-11-04" }]));
|
||||
});
|
||||
@@ -83,4 +92,37 @@ describe("usb tether", () => {
|
||||
expect(withSidecars(["IMG_0001.JPG"], camera.files).sort()).toEqual(["IMG_0001.CR3", "IMG_0001.JPG"]);
|
||||
expect(withSidecars(["IMG_0002.JPG"], camera.files)).toEqual(["IMG_0002.JPG"]);
|
||||
});
|
||||
|
||||
it("does not crash auto-ingest when the shell status omits files", async () => {
|
||||
vi.spyOn(prefs, "get").mockReturnValue("1");
|
||||
const invoke = vi.fn(async (cmd: string) => {
|
||||
if (cmd === "camera_status") return { supported: true, tether: true, devices: [] } as unknown as UsbStatus;
|
||||
if (cmd === "camera_take") return [];
|
||||
return null;
|
||||
}) as unknown as Invoke;
|
||||
const add = () => {};
|
||||
const { result } = renderHook(() =>
|
||||
useUsbCamera(add, true, { id: "ev1", title: "Portugal x Suíça", date: "2026-11-04", ingestFrom: "2026-11-04T18:00:00Z", ingestUntil: "2026-11-04T23:00:00Z" }, invoke),
|
||||
);
|
||||
await waitFor(() => expect(result.current.status?.tether).toBe(true));
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("only treats shots inside the event ingest window as auto-eligible", () => {
|
||||
const from = "2026-11-03T18:00:00.000Z";
|
||||
const until = "2026-11-03T23:00:00.000Z";
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, from, until)).toBe(true);
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-02T19:30:00Z") }, from, until)).toBe(false);
|
||||
expect(inEventWindow({ createdMs: null }, from, until)).toBe(false);
|
||||
expect(inEventWindow({ createdMs: Date.parse("2026-11-03T19:30:00Z") }, undefined, until)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the last file list when the shell omits files for an unchanged catalogGen", async () => {
|
||||
window.localStorage.removeItem("pr.usb.tether");
|
||||
const { invoke } = shell([]);
|
||||
const { result } = renderHook(() => useUsbCamera(() => {}, true, null, invoke));
|
||||
await waitFor(() => expect(result.current.status?.files).toHaveLength(3));
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalledWith("camera_status", { sinceGen: 1 }));
|
||||
await waitFor(() => expect(result.current.status?.files).toHaveLength(3));
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { asArrayBuffer } from "../platform.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
@@ -35,6 +37,8 @@ export interface UsbStatus {
|
||||
tether: boolean;
|
||||
devices: UsbCamera[];
|
||||
files: UsbFile[];
|
||||
/** Bumps when the shell's file list changes; poll with the last value to skip a repeat payload. */
|
||||
catalogGen?: number;
|
||||
}
|
||||
|
||||
const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args);
|
||||
@@ -48,14 +52,39 @@ type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, st
|
||||
* USB camera: the shell lists the card (and each new shot). Chosen files are downloaded into the
|
||||
* ingest folder; this hook then uploads them to the target event like local FTP.
|
||||
*/
|
||||
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke) {
|
||||
function savedTetherOn(): boolean {
|
||||
return prefs.get("usb.tether") === "1";
|
||||
}
|
||||
|
||||
export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | null, invoke: Invoke = tauriInvoke, orgId = "") {
|
||||
const [status, setStatus] = useState<UsbStatus | null>(null);
|
||||
const [outdated, setOutdated] = useState(false);
|
||||
const [counts, setCounts] = useState({ received: 0, sent: 0, failed: 0 });
|
||||
/** Auto-pull only new shots whose camera time sits inside the event's ingest window. */
|
||||
const [autoIngest, setAutoIngestState] = useState(savedAutoIngest);
|
||||
const backlog = useRef<IncomingFile[]>([]);
|
||||
const inFlight = useRef(0);
|
||||
const autoAsked = useRef<Set<string>>(new Set());
|
||||
const catalogGen = useRef(0);
|
||||
const filesRef = useRef<UsbFile[]>([]);
|
||||
const tetherRestored = useRef(false);
|
||||
const targetRef = useRef(target);
|
||||
targetRef.current = target;
|
||||
const orgIdRef = useRef(orgId);
|
||||
orgIdRef.current = orgId;
|
||||
const autoIngestRef = useRef(autoIngest);
|
||||
autoIngestRef.current = autoIngest;
|
||||
|
||||
const applyStatus = useCallback((s: UsbStatus) => {
|
||||
// Same generation → shell omitted `files` on purpose; keep the list we already have.
|
||||
if (typeof s.catalogGen === "number" && s.catalogGen === catalogGen.current) {
|
||||
setStatus({ ...s, files: filesRef.current });
|
||||
return;
|
||||
}
|
||||
if (typeof s.catalogGen === "number") catalogGen.current = s.catalogGen;
|
||||
filesRef.current = s.files;
|
||||
setStatus(s);
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (inFlight.current < IN_FLIGHT && backlog.current.length) {
|
||||
@@ -69,11 +98,21 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
invoke<PreviewOf>("ftp_info", { path: f.path }),
|
||||
]);
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], to?.id, (_file, result) => {
|
||||
const cached = orgIdRef.current ? await cache.events(orgIdRef.current) : null;
|
||||
const events = cached?.events ?? [];
|
||||
const capturedAt = lisbonInstant(exifDateTime(bytes));
|
||||
// Always the open USB target — never drop a live pull into Sem evento because the agenda cache is stale.
|
||||
const eventId = eventForArrival(to?.id ?? null, events, capturedAt);
|
||||
const filed = events.find((e) => e.id === eventId);
|
||||
add([file], eventId ?? undefined, (_file, result) => {
|
||||
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(() => {});
|
||||
invoke("ftp_sent", {
|
||||
path: f.path,
|
||||
event: filed ? eventLabel(filed) : (to?.title ?? ""),
|
||||
date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""),
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
@@ -93,9 +132,9 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
let alive = true;
|
||||
const tick = async () => {
|
||||
try {
|
||||
const s = await invoke<UsbStatus>("camera_status");
|
||||
const s = await invoke<UsbStatus>("camera_status", { sinceGen: catalogGen.current });
|
||||
if (!alive) return;
|
||||
setStatus(s);
|
||||
applyStatus(s);
|
||||
if (!s.supported || !s.tether) return;
|
||||
const files = await invoke<IncomingFile[]>("camera_take");
|
||||
if (!alive || !files.length) return;
|
||||
@@ -119,48 +158,78 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul
|
||||
alive = false;
|
||||
clearInterval(timer);
|
||||
};
|
||||
}, [enabled, invoke, pump]);
|
||||
}, [enabled, invoke, pump, applyStatus]);
|
||||
|
||||
const syncClock = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await invoke<UsbStatus>("camera_sync"));
|
||||
applyStatus(await invoke<UsbStatus>("camera_sync"));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
}, [invoke]);
|
||||
}, [invoke, applyStatus]);
|
||||
|
||||
const setTether = useCallback(
|
||||
async (on: boolean) => {
|
||||
prefs.set("usb.tether", on ? "1" : "0");
|
||||
try {
|
||||
setStatus(await invoke<UsbStatus>("camera_tether", { enabled: on }));
|
||||
// Full list after a tether change (gen may bump when clearing).
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_tether", { enabled: on }));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
},
|
||||
[invoke],
|
||||
[invoke, applyStatus],
|
||||
);
|
||||
|
||||
// Cable stays off at launch so a full card is not listed until asked; restore the last choice once.
|
||||
useEffect(() => {
|
||||
if (!enabled || tetherRestored.current || !savedTetherOn()) return;
|
||||
tetherRestored.current = true;
|
||||
void setTether(true);
|
||||
}, [enabled, setTether]);
|
||||
|
||||
const importFiles = useCallback(
|
||||
async (names: string[]) => {
|
||||
if (!names.length) return;
|
||||
try {
|
||||
setStatus(await invoke<UsbStatus>("camera_import", { names }));
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_import", { names }));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
},
|
||||
[invoke],
|
||||
[invoke, applyStatus],
|
||||
);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
setStatus(await invoke<UsbStatus>("camera_refresh"));
|
||||
catalogGen.current = 0;
|
||||
applyStatus(await invoke<UsbStatus>("camera_refresh"));
|
||||
} catch {
|
||||
setOutdated(true);
|
||||
}
|
||||
}, [invoke]);
|
||||
}, [invoke, applyStatus]);
|
||||
|
||||
return { status, outdated, counts, setTether, syncClock, importFiles, refresh };
|
||||
const setAutoIngest = useCallback((on: boolean) => {
|
||||
setAutoIngestState(on);
|
||||
prefs.set("usb.autoIngest", on ? "1" : "0");
|
||||
if (!on) autoAsked.current.clear();
|
||||
}, []);
|
||||
|
||||
// New tethered shots inside the event window only — never the rest of the card / other days.
|
||||
useEffect(() => {
|
||||
if (!autoIngest || !status?.tether || !target?.ingestFrom || !target.ingestUntil) return;
|
||||
const files = status.files ?? [];
|
||||
const due = files.filter(
|
||||
(f) => /\.jpe?g$/i.test(f.name) && f.isNew && !f.imported && inEventWindow(f, target.ingestFrom, target.ingestUntil) && !autoAsked.current.has(f.name),
|
||||
);
|
||||
if (!due.length) return;
|
||||
for (const f of due) autoAsked.current.add(f.name);
|
||||
void importFiles(withSidecars(due.map((f) => f.name), files));
|
||||
}, [autoIngest, status, target, importFiles]);
|
||||
|
||||
return { status, outdated, counts, setTether, syncClock, importFiles, refresh, autoIngest, setAutoIngest };
|
||||
}
|
||||
|
||||
export type UsbCameraState = ReturnType<typeof useUsbCamera>;
|
||||
@@ -177,6 +246,23 @@ export function withSidecars(selected: Iterable<string>, files: UsbFile[]): stri
|
||||
return files.filter((f) => want.has(stemOf(f.name))).map((f) => f.name);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the shot's camera time falls inside the event ingest window. No capture time → not auto-eligible
|
||||
* (a full card without dates must not flood the event; the photographer picks those by hand).
|
||||
*/
|
||||
export function inEventWindow(file: Pick<UsbFile, "createdMs">, fromIso: string | undefined, untilIso: string | undefined): boolean {
|
||||
if (!fromIso || !untilIso) return false;
|
||||
if (file.createdMs == null || !Number.isFinite(file.createdMs)) return false;
|
||||
const from = Date.parse(fromIso);
|
||||
const until = Date.parse(untilIso);
|
||||
if (!Number.isFinite(from) || !Number.isFinite(until)) return false;
|
||||
return file.createdMs >= from && file.createdMs <= until;
|
||||
}
|
||||
|
||||
function savedAutoIngest(): boolean {
|
||||
return prefs.get("usb.autoIngest") === "1";
|
||||
}
|
||||
|
||||
/** Button + panel in the Library toolbar. Hidden where the shell has no USB cameras (Windows, Linux). */
|
||||
export function UsbCameraButton({
|
||||
usb,
|
||||
@@ -191,7 +277,7 @@ export function UsbCameraButton({
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [picked, setPicked] = useState<Set<string>>(() => new Set());
|
||||
const { status, counts } = usb;
|
||||
const { status, counts, autoIngest, setAutoIngest } = usb;
|
||||
const L = t.usbCamera;
|
||||
const devices = status?.devices ?? [];
|
||||
const files = status?.files ?? [];
|
||||
@@ -199,6 +285,11 @@ export function UsbCameraButton({
|
||||
const on = connected.some((d) => d.state === "tethered" || d.state === "opening");
|
||||
const catalogReady = devices.some((d) => d.catalogReady);
|
||||
const jpegs = useMemo(() => files.filter((f) => /\.jpe?g$/i.test(f.name)), [files]);
|
||||
const inWindow = useMemo(
|
||||
() => jpegs.filter((f) => inEventWindow(f, target?.ingestFrom, target?.ingestUntil)),
|
||||
[jpegs, target?.ingestFrom, target?.ingestUntil],
|
||||
);
|
||||
const hasWindow = !!(target?.ingestFrom && target.ingestUntil);
|
||||
|
||||
useEffect(() => {
|
||||
if (connected.length && !target && openEvent) setTarget(openEvent);
|
||||
@@ -259,11 +350,24 @@ export function UsbCameraButton({
|
||||
<div className="mb-3">
|
||||
<div className="mb-1 text-[11px] uppercase tracking-wide text-faint">{t.localFtp.target}</div>
|
||||
<div className="text-ink">{target ? `${target.date} · ${target.title}` : t.localFtp.noTarget}</div>
|
||||
{hasWindow && (
|
||||
<div className="mt-1 font-mono text-[11px] text-muted">
|
||||
{L.windowHint(inWindow.length, jpegs.length)}
|
||||
</div>
|
||||
)}
|
||||
{openEvent && openEvent.id !== target?.id && (
|
||||
<button onClick={() => setTarget(openEvent)} className="mt-1 text-left text-accent underline">
|
||||
{t.localFtp.useOpen(eventLabel(openEvent))}
|
||||
</button>
|
||||
)}
|
||||
{on && hasWindow && (
|
||||
<label className="mt-2 flex cursor-pointer items-center gap-2 text-ink">
|
||||
<input type="checkbox" checked={autoIngest} onChange={(e) => setAutoIngest(e.target.checked)} className="accent-accent" />
|
||||
{L.autoIngest}
|
||||
</label>
|
||||
)}
|
||||
{autoIngest && !hasWindow && <p className="mt-1 text-[#f0a35a]">{L.autoNeedsEvent}</p>}
|
||||
{autoIngest && hasWindow && <p className="mt-1 text-[11px] text-faint">{L.autoIngestHelp}</p>}
|
||||
</div>
|
||||
{devices.length === 0 && <p className="text-faint">{L.none}</p>}
|
||||
{devices.map((d) => (
|
||||
@@ -297,6 +401,11 @@ export function UsbCameraButton({
|
||||
{jpegs.length > 0 && <span className="ml-2 font-mono normal-case text-muted">{L.files(jpegs.length)}</span>}
|
||||
</span>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{hasWindow && (
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(inWindow.filter((f) => !f.imported).map((f) => f.name)))}>
|
||||
{L.selectEvent}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" className="text-accent underline" onClick={() => setPicked(new Set(jpegs.filter((f) => f.isNew && !f.imported).map((f) => f.name)))}>
|
||||
{L.selectNew}
|
||||
</button>
|
||||
@@ -317,6 +426,7 @@ export function UsbCameraButton({
|
||||
<ul className="max-h-48 overflow-auto border border-line">
|
||||
{jpegs.map((f) => {
|
||||
const checked = picked.has(f.name);
|
||||
const matches = inEventWindow(f, target?.ingestFrom, target?.ingestUntil);
|
||||
return (
|
||||
<li key={f.name} className="flex items-center gap-2 border-b border-line px-2 py-1 last:border-b-0 hover:bg-cell">
|
||||
<input type="checkbox" checked={checked} disabled={!!f.imported} onChange={() => toggle(f.name)} className="accent-accent" />
|
||||
@@ -325,6 +435,7 @@ export function UsbCameraButton({
|
||||
</button>
|
||||
{f.isNew && !f.imported && <span className="text-[10px] uppercase text-[#4cc38a]">{L.newShot}</span>}
|
||||
{f.imported && <span className="text-[10px] uppercase text-faint">{L.imported}</span>}
|
||||
{hasWindow && !matches && !f.imported && <span className="text-[10px] uppercase text-[#f0a35a]">{L.outsideEvent}</span>}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react";
|
||||
import { createContext, type ReactNode, useContext, useEffect, useMemo } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js";
|
||||
import { isDesktop, localOriginal } from "../platform.js";
|
||||
import { useLocalFtp } from "./LocalFtp.js";
|
||||
import { OriginalSender } from "./originals.js";
|
||||
import { useLibraryLive } from "./realtime.js";
|
||||
import { useUploadQueue } from "./uploads.js";
|
||||
import { useOfflineSync } from "../offline/sync.js";
|
||||
@@ -14,6 +14,8 @@ type Ingest = {
|
||||
localFtp: ReturnType<typeof useLocalFtp>;
|
||||
usb: ReturnType<typeof useUsbCamera>;
|
||||
desktop: boolean;
|
||||
/** Desktop only: pushes full originals for delivery / 100% zoom, off the JPEG upload queue. */
|
||||
originals: OriginalSender | null;
|
||||
};
|
||||
|
||||
const IngestContext = createContext<Ingest | null>(null);
|
||||
@@ -35,90 +37,37 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
|
||||
const desktop = isDesktop();
|
||||
const uploads = useUploadQueue(api, orgId);
|
||||
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
|
||||
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target);
|
||||
const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target, undefined, orgId);
|
||||
const originals = useMemo(() => (desktop && orgId ? new OriginalSender(api) : null), [api, desktop, orgId]);
|
||||
useOfflineSync(api, orgId);
|
||||
return (
|
||||
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop }}>
|
||||
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
|
||||
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop, originals }}>
|
||||
{desktop && !!orgId && originals && <OriginalResponder api={api} orgId={orgId} sender={originals} />}
|
||||
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
|
||||
{children}
|
||||
</IngestContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */
|
||||
const ORIGINAL_IPC_MS = 45_000;
|
||||
/** A few at a time: one is slow, all of them freeze the bar. */
|
||||
const MAX_PARALLEL_ORIGINALS = 3;
|
||||
|
||||
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value: T | "timeout" | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish("timeout"), ms);
|
||||
work.then(
|
||||
(value) => finish(value),
|
||||
() => finish(null),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export
|
||||
* made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it.
|
||||
* Up to three at a time, so the webview stays responsive and the next ask can run.
|
||||
* Desktop: when delivery (or 100% zoom) needs a full original kept here, send it on its own track — never
|
||||
* through the JPEG upload queue, so new shots keep leaving and one stuck file does not block the rest.
|
||||
*/
|
||||
function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"]; add: ReturnType<typeof useUploadQueue>["add"] }) {
|
||||
const sending = useRef(new Set<string>());
|
||||
const queue = useRef<{ sha256: string; photoId: string }[]>([]);
|
||||
const active = useRef(0);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (active.current < MAX_PARALLEL_ORIGINALS) {
|
||||
const next = queue.current.shift();
|
||||
if (!next) return;
|
||||
active.current += 1;
|
||||
const release = () => {
|
||||
sending.current.delete(next.sha256);
|
||||
active.current -= 1;
|
||||
pump();
|
||||
};
|
||||
void (async () => {
|
||||
const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS);
|
||||
if (bytes && bytes !== "timeout") {
|
||||
add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release());
|
||||
return;
|
||||
}
|
||||
if (bytes !== "timeout") {
|
||||
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
|
||||
// photo's original, which the server checks is the same photo.
|
||||
try {
|
||||
const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS);
|
||||
if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`);
|
||||
} catch {
|
||||
/* not the same photo, or offline: asked again later */
|
||||
}
|
||||
}
|
||||
release();
|
||||
})();
|
||||
}
|
||||
}, [add, api]);
|
||||
|
||||
const onMessage = useCallback(
|
||||
(m: LibraryMessage) => {
|
||||
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
|
||||
sending.current.add(m.sha256);
|
||||
queue.current.push({ sha256: m.sha256, photoId: m.photoId });
|
||||
pump();
|
||||
},
|
||||
[pump],
|
||||
);
|
||||
useLibraryLive(api, onMessage);
|
||||
function OriginalResponder({
|
||||
api,
|
||||
orgId,
|
||||
sender,
|
||||
}: {
|
||||
api: ReturnType<typeof useAuth>["api"];
|
||||
orgId: string;
|
||||
sender: OriginalSender;
|
||||
}) {
|
||||
useLibraryLive(api, (m) => sender.onMessage(m));
|
||||
useEffect(() => {
|
||||
void sender.flushWaiting(orgId);
|
||||
const timer = setInterval(() => void sender.flushWaiting(orgId), 45_000);
|
||||
return () => clearInterval(timer);
|
||||
}, [sender, orgId]);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { showLocalJpeg } from "./localIngest.js";
|
||||
|
||||
describe("showLocalJpeg", () => {
|
||||
it("puts a desktop preview into the library before upload", async () => {
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
const bytes = new Uint8Array([0xff, 0xd8, 0xff, 0xd9]);
|
||||
const file = new File([bytes], "IMG_1.JPG", { type: "image/jpeg" });
|
||||
// createImageBitmap may be missing in jsdom — stub size via origin.
|
||||
const sha = await showLocalJpeg({
|
||||
file,
|
||||
eventId: "ev1",
|
||||
origin: { sha256: "abc123", size: 4, width: 100, height: 80 },
|
||||
});
|
||||
expect(sha?.sha256).toBe("abc123");
|
||||
expect(localPhotos.bySha("abc123")?.eventId).toBe("ev1");
|
||||
expect(localPhotos.bySha("abc123")?.originalName).toBe("IMG_1.JPG");
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
});
|
||||
|
||||
it("skips a second put for the same sha", async () => {
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
const file = new File([new Uint8Array([1, 2, 3])], "A.JPG", { type: "image/jpeg" });
|
||||
const origin = { sha256: "same", size: 3, width: 10, height: 10 };
|
||||
await showLocalJpeg({ file, origin });
|
||||
const spy = vi.spyOn(localPhotos, "put");
|
||||
await showLocalJpeg({ file, origin });
|
||||
expect(spy).not.toHaveBeenCalled();
|
||||
spy.mockRestore();
|
||||
for (const p of localPhotos.list()) localPhotos.remove(p.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { eventForArrival, exifDateTime, lisbonInstant, localPhoto, localPhotos } from "../offline/local.js";
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import type { DesktopOrigin } from "./uploads.js";
|
||||
|
||||
/** SHA-256 hex of the bytes (same fingerprint the desktop shell uses for the original). */
|
||||
export async function sha256Hex(bytes: ArrayBuffer): Promise<string> {
|
||||
const hash = await crypto.subtle.digest("SHA-256", bytes);
|
||||
return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
async function imageSize(blob: Blob): Promise<{ width: number; height: number }> {
|
||||
if (typeof createImageBitmap === "function") {
|
||||
const bmp = await createImageBitmap(blob);
|
||||
const size = { width: bmp.width, height: bmp.height };
|
||||
bmp.close();
|
||||
return size;
|
||||
}
|
||||
return await new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
const url = URL.createObjectURL(blob);
|
||||
img.onload = () => {
|
||||
resolve({ width: img.naturalWidth, height: img.naturalHeight });
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
img.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("decode"));
|
||||
};
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts a JPEG into the library at once from bytes already on this computer. Upload can finish later;
|
||||
* `photo.added` (same sha) replaces this row. Returns the sha (and the event chosen from EXIF) when on screen.
|
||||
*/
|
||||
export async function showLocalJpeg(args: {
|
||||
file: File;
|
||||
eventId?: string | undefined;
|
||||
origin?: DesktopOrigin | undefined;
|
||||
orgId?: string | undefined;
|
||||
events?: Pick<EventSummary, "id" | "startsAt" | "ingestFrom" | "ingestUntil" | "archivedAt">[] | undefined;
|
||||
}): Promise<{ sha256: string; eventId: string | null } | null> {
|
||||
const { file, origin, orgId, events } = args;
|
||||
try {
|
||||
let sha256: string;
|
||||
let width: number;
|
||||
let height: number;
|
||||
// Always read EXIF from the JPEG bytes when we can — desktop previews keep DateTimeOriginal, and that
|
||||
// clock (not the open event pin) decides which folder the photo appears in.
|
||||
const previewBytes = await file.arrayBuffer();
|
||||
if (origin && origin !== "original") {
|
||||
sha256 = origin.sha256;
|
||||
width = origin.width;
|
||||
height = origin.height;
|
||||
} else {
|
||||
sha256 = await sha256Hex(previewBytes);
|
||||
const size = await imageSize(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
width = size.width;
|
||||
height = size.height;
|
||||
}
|
||||
if (localPhotos.bySha(sha256)) return { sha256, eventId: localPhotos.bySha(sha256)?.eventId ?? null };
|
||||
let url = "";
|
||||
try {
|
||||
url = URL.createObjectURL(new Blob([previewBytes], { type: "image/jpeg" }));
|
||||
} catch {
|
||||
try {
|
||||
url = URL.createObjectURL(file);
|
||||
} catch {
|
||||
/* tests / no blob URLs */
|
||||
}
|
||||
}
|
||||
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
|
||||
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
|
||||
localPhotos.put(
|
||||
localPhoto({
|
||||
sha256,
|
||||
name: file.name,
|
||||
width,
|
||||
height,
|
||||
capturedAt,
|
||||
eventId,
|
||||
url,
|
||||
}),
|
||||
);
|
||||
if (orgId) {
|
||||
for (const op of offlineQueue(orgId).pending) {
|
||||
if (op.kind === "patch" && op.ids.includes(localId(sha256))) {
|
||||
localPhotos.patch(localId(sha256), op.patch as Partial<PhotoSummary>);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { sha256, eventId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** After the server has the photo: map offline edits and drop the local stand-in. */
|
||||
export function settleLocalUpload(orgId: string, sha256: string | null | undefined, photo: PhotoSummary | undefined): void {
|
||||
if (!sha256) return;
|
||||
if (photo) offlineQueue(orgId).uploaded(sha256, photo.id);
|
||||
localPhotos.remove(localId(sha256));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { OriginalSender } from "./originals.js";
|
||||
|
||||
describe("OriginalSender", () => {
|
||||
it("does not put the same sha on the queue twice", () => {
|
||||
const api = {
|
||||
sendOriginal: vi.fn(async () => ({ stored: true })),
|
||||
requestOriginal: vi.fn(async () => ({ stored: false })),
|
||||
listDeliveries: vi.fn(async () => ({ items: [] })),
|
||||
};
|
||||
const sender = new OriginalSender(api as never);
|
||||
sender.enqueue({ photoId: "p1", sha256: "abc" });
|
||||
sender.enqueue({ photoId: "p1", sha256: "abc" });
|
||||
expect(sender.inFlight.size).toBeLessThanOrEqual(1);
|
||||
});
|
||||
|
||||
it("asks the server for originals when a delivery is waiting", () => {
|
||||
const api = {
|
||||
sendOriginal: vi.fn(async () => ({ stored: true })),
|
||||
requestOriginal: vi.fn(async () => ({ stored: false })),
|
||||
listDeliveries: vi.fn(async () => ({ items: [] })),
|
||||
};
|
||||
const sender = new OriginalSender(api as never);
|
||||
sender.onMessage({
|
||||
type: "delivery.updated",
|
||||
item: {
|
||||
id: "i1",
|
||||
targetId: "t1",
|
||||
photoId: "p1",
|
||||
eventId: "e1",
|
||||
sequence: 1,
|
||||
status: "QUEUED",
|
||||
attempts: 0,
|
||||
lastError: "waiting_for_original",
|
||||
remotePath: null,
|
||||
byteSize: null,
|
||||
updatedAt: "",
|
||||
},
|
||||
});
|
||||
expect(api.requestOriginal).toHaveBeenCalledWith("p1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { localOriginal, localOriginalChanged, prefs } from "../platform.js";
|
||||
|
||||
/** Several megabytes through IPC. Dozens at once freeze the webview; one slow disk must not kill the rest. */
|
||||
const ORIGINAL_IPC_MS = 90_000;
|
||||
|
||||
const PREF_PARALLEL = "originals.parallel";
|
||||
|
||||
/** How many full originals leave this computer at once (delivery / 100% zoom). Default 4, clamp 2..8. */
|
||||
export function originalsParallel(): number {
|
||||
const n = Number(prefs.get(PREF_PARALLEL));
|
||||
if (Number.isFinite(n) && n >= 2 && n <= 8) return Math.floor(n);
|
||||
return 4;
|
||||
}
|
||||
|
||||
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (value: T | "timeout" | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish("timeout"), ms);
|
||||
work.then(
|
||||
(value) => finish(value),
|
||||
() => finish(null),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export type OriginalNeed = { photoId: string; sha256: string };
|
||||
|
||||
/**
|
||||
* Sends originals this computer still has, on their own path (`POST /original`), never through the JPEG
|
||||
* upload queue. New shots keep uploading in parallel; one stuck original does not block the others.
|
||||
*/
|
||||
export class OriginalSender {
|
||||
private readonly sending = new Set<string>();
|
||||
private readonly queue: OriginalNeed[] = [];
|
||||
private active = 0;
|
||||
/** photoIds this machine is currently pushing — Destinos shows "a enviar…" instead of "abre a app". */
|
||||
readonly inFlight = new Set<string>();
|
||||
private readonly listeners = new Set<() => void>();
|
||||
|
||||
constructor(private readonly api: ApiClient) {}
|
||||
|
||||
subscribe(fn: () => void): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
|
||||
/** From the live channel, or a Destinos row that is waiting for the file on this Mac. */
|
||||
enqueue(need: OriginalNeed): void {
|
||||
if (this.sending.has(need.sha256)) return;
|
||||
this.sending.add(need.sha256);
|
||||
this.queue.push(need);
|
||||
this.pump();
|
||||
}
|
||||
|
||||
onMessage(m: LibraryMessage): void {
|
||||
if (m.type === "original.requested") {
|
||||
this.enqueue({ photoId: m.photoId, sha256: m.sha256 });
|
||||
return;
|
||||
}
|
||||
// Delivery is blocked on the original we keep: push it at once (do not wait for the next 60 s ask).
|
||||
if (m.type === "delivery.updated" && m.item.lastError === "waiting_for_original") {
|
||||
void this.api.requestOriginal(m.item.photoId).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Destinos / start: every queued row still waiting for an original — ask the server (it broadcasts sha256)
|
||||
* so we send what we have without the photographer clicking Retry.
|
||||
*/
|
||||
async flushWaiting(orgId: string): Promise<void> {
|
||||
try {
|
||||
const { items } = await this.api.listDeliveries(orgId, { status: "QUEUED" });
|
||||
for (const item of items) {
|
||||
if (item.lastError !== "waiting_for_original") continue;
|
||||
void this.api.requestOriginal(item.photoId).catch(() => {});
|
||||
}
|
||||
} catch {
|
||||
/* offline: live channel will ask again */
|
||||
}
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
const room = originalsParallel();
|
||||
while (this.active < room) {
|
||||
const next = this.queue.shift();
|
||||
if (!next) return;
|
||||
this.active += 1;
|
||||
this.inFlight.add(next.photoId);
|
||||
this.changed();
|
||||
void this.sendOne(next).finally(() => {
|
||||
this.sending.delete(next.sha256);
|
||||
this.inFlight.delete(next.photoId);
|
||||
this.active -= 1;
|
||||
this.changed();
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async sendOne(need: OriginalNeed): Promise<void> {
|
||||
const exact = await withTimeout(localOriginal(need.sha256), ORIGINAL_IPC_MS);
|
||||
let bytes: ArrayBuffer | null = exact && exact !== "timeout" ? exact : null;
|
||||
if (!bytes) {
|
||||
const changed = await withTimeout(localOriginalChanged(need.sha256), ORIGINAL_IPC_MS);
|
||||
bytes = changed && changed !== "timeout" ? changed : null;
|
||||
}
|
||||
if (!bytes) return;
|
||||
try {
|
||||
await this.api.sendOriginal(need.photoId, new Blob([bytes], { type: "image/jpeg" }), `${need.sha256}.jpg`);
|
||||
} catch {
|
||||
/* offline / not the same photo: server asks again */
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { isNetworkError, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { prefs } from "../platform.js";
|
||||
import { settleLocalUpload, showLocalJpeg } from "./localIngest.js";
|
||||
|
||||
export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed";
|
||||
|
||||
@@ -14,7 +17,12 @@ export interface UploadItem {
|
||||
error?: string | undefined;
|
||||
}
|
||||
|
||||
const CONCURRENCY = 4;
|
||||
/** Parallel JPEG uploads. Pref `upload.concurrency` (3–8); default 4. One failure never holds the others. */
|
||||
function uploadConcurrency(): number {
|
||||
const n = Number(prefs.get("upload.concurrency"));
|
||||
if (Number.isFinite(n) && n >= 3 && n <= 8) return Math.floor(n);
|
||||
return 4;
|
||||
}
|
||||
const ACCEPTED = /\.jpe?g$/i;
|
||||
|
||||
const CHUNK = 4 * 1024 * 1024;
|
||||
@@ -146,12 +154,21 @@ export async function sendResumable(
|
||||
}
|
||||
|
||||
/**
|
||||
* Parallel upload queue (4 at a time). New photos show up in the grid through the live channel, so the queue
|
||||
* only tracks progress. Non-JPEG files are refused before sending.
|
||||
* Parallel upload queue (4 at a time). Each JPEG is shown in the library from a local preview at once;
|
||||
* the live channel replaces it when the server has the photo. Non-JPEG files are refused before sending.
|
||||
*/
|
||||
export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
const [items, setItems] = useState<UploadItem[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void }[]>([]);
|
||||
const queue = useRef<
|
||||
{
|
||||
item: UploadItem;
|
||||
file: File;
|
||||
eventId: string | undefined;
|
||||
original?: DesktopOrigin;
|
||||
sha256?: string | null;
|
||||
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);
|
||||
@@ -162,28 +179,29 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (!paused.current && running.current < CONCURRENCY && queue.current.length) {
|
||||
while (!paused.current && running.current < uploadConcurrency() && queue.current.length) {
|
||||
const next = queue.current.shift()!;
|
||||
running.current++;
|
||||
void (async () => {
|
||||
const { item, file, eventId, original, onSettled } = next;
|
||||
const { item, file, original, onSettled } = next;
|
||||
let final: UploadStatus = "failed";
|
||||
let filed: PhotoSummary | undefined;
|
||||
let waiting = false;
|
||||
update(item.id, { status: "uploading", error: undefined });
|
||||
try {
|
||||
let lastTick = 0;
|
||||
// Read eventId/sha at send time so a late EXIF route on `next` still wins if it finished first.
|
||||
const res = await sendResumable(
|
||||
api,
|
||||
orgId,
|
||||
file,
|
||||
eventId,
|
||||
next.eventId,
|
||||
(p) => {
|
||||
const now = Date.now();
|
||||
if (now - lastTick > 150 || p === 1) {
|
||||
lastTick = now;
|
||||
update(item.id, { progress: p });
|
||||
}
|
||||
const now = Date.now();
|
||||
if (now - lastTick > 150 || p === 1) {
|
||||
lastTick = now;
|
||||
update(item.id, { progress: p });
|
||||
}
|
||||
},
|
||||
original,
|
||||
);
|
||||
@@ -215,7 +233,13 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
}
|
||||
} else update(item.id, { status: "failed", error: (err as Error).message });
|
||||
} finally {
|
||||
if (!waiting) onSettled?.(final, filed);
|
||||
if (!waiting) {
|
||||
if (final === "done" || final === "duplicate") {
|
||||
settleLocalUpload(orgId, next.sha256, filed);
|
||||
void offlineQueue(orgId).flush(api);
|
||||
}
|
||||
onSettled?.(final, filed);
|
||||
}
|
||||
running.current--;
|
||||
pump();
|
||||
}
|
||||
@@ -227,6 +251,10 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
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, photo?: PhotoSummary) => void, original?: DesktopOrigin) => {
|
||||
// A previous offline pause must not leave new shots stuck on "queued" after the VPN is back.
|
||||
if (paused.current) {
|
||||
paused.current = false;
|
||||
}
|
||||
const added: UploadItem[] = [];
|
||||
for (const file of files) {
|
||||
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
|
||||
@@ -236,14 +264,53 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
continue;
|
||||
}
|
||||
added.push(item);
|
||||
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }) });
|
||||
// Preview / EXIF routing must not block the wire: a hung IndexedDB cache left the bar at "queued" forever.
|
||||
// Enqueue at once with the open pin; enrich sha + routed event while the queue runs (or before the first byte).
|
||||
const entry: {
|
||||
item: UploadItem;
|
||||
file: File;
|
||||
eventId: string | undefined;
|
||||
original?: DesktopOrigin;
|
||||
sha256?: string | null;
|
||||
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
|
||||
} = {
|
||||
item,
|
||||
file,
|
||||
eventId,
|
||||
...(original && { original }),
|
||||
sha256: null,
|
||||
...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }),
|
||||
};
|
||||
queue.current.push(entry);
|
||||
void (async () => {
|
||||
try {
|
||||
const cached = orgId
|
||||
? await Promise.race([
|
||||
cache.events(orgId),
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 800)),
|
||||
])
|
||||
: null;
|
||||
const shown = await showLocalJpeg({
|
||||
file,
|
||||
eventId,
|
||||
origin: original,
|
||||
orgId,
|
||||
events: cached?.events,
|
||||
});
|
||||
if (!shown) return;
|
||||
entry.sha256 = shown.sha256;
|
||||
// Prefer EXIF routing when it names an event; otherwise keep the open pin already on the entry.
|
||||
if (shown.eventId) entry.eventId = shown.eventId;
|
||||
} catch {
|
||||
/* preview optional — upload already queued */
|
||||
}
|
||||
})();
|
||||
}
|
||||
setItems((list) => [...list.filter((i) => i.status !== "done" && i.status !== "duplicate"), ...added]);
|
||||
setItems((list) => list.filter((i) => i.status !== "done" && i.status !== "duplicate").concat(added));
|
||||
pump();
|
||||
},
|
||||
[pump],
|
||||
[orgId, pump],
|
||||
);
|
||||
|
||||
const clear = useCallback(() => setItems((list) => list.filter((i) => i.status === "queued" || i.status === "uploading")), []);
|
||||
|
||||
return { items, add, clear };
|
||||
|
||||
@@ -75,29 +75,44 @@ export function lisbonInstant(exif: string | null): string | null {
|
||||
|
||||
type RoutedEvent = Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">;
|
||||
|
||||
/**
|
||||
* Among open events whose ingest window covers `at`, the one whose start is closest to the capture.
|
||||
* "Latest start wins" wrongly pulled a 14:00 studio session into a 16:30 training when windows overlapped.
|
||||
*/
|
||||
export function bestEventForCapture(events: RoutedEvent[], at: string): RoutedEvent | null {
|
||||
const t = Date.parse(at);
|
||||
if (!Number.isFinite(t)) return null;
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
if (!open.length) return null;
|
||||
open.sort((a, b) => Math.abs(Date.parse(a.startsAt) - t) - Math.abs(Date.parse(b.startsAt) - t));
|
||||
return open[0] ?? null;
|
||||
}
|
||||
|
||||
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
|
||||
export function routeLocally(events: RoutedEvent[], 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;
|
||||
return bestEventForCapture(events, at)?.id ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a local-FTP photo goes. The event the photographer pinned receives it only while the capture falls in that
|
||||
* event's window. Outside it (the pin left over from yesterday's match), the photo goes to the event of the time
|
||||
* it was taken. A pin whose window isn't in the list, or a photo with no capture time, keeps the pin.
|
||||
* Where a photo arrives on this computer. With a capture time, the pin (FTP target / open event) wins only
|
||||
* inside that event's window — leftover pins from the morning studio must not swallow the afternoon training.
|
||||
* Without a capture time, keep the pin (same as the server): USB auto-pull already filtered by the window via
|
||||
* the card clock, and inventing "now" is what we must not do.
|
||||
*/
|
||||
export function eventForArrival(pinnedId: string | null, events: RoutedEvent[], at: string | null): string | null {
|
||||
if (!at) return pinnedId;
|
||||
if (!pinnedId) return routeLocally(events, at);
|
||||
const pinned = events.find((e) => e.id === pinnedId);
|
||||
if (!pinned || !at) return pinnedId;
|
||||
if (!pinned) {
|
||||
// Agenda cache miss: keep the open pin so USB/FTP does not dump live shots into Sem evento.
|
||||
return pinnedId;
|
||||
}
|
||||
if (pinned.archivedAt) return routeLocally(events, at);
|
||||
const t = Date.parse(at);
|
||||
if (Date.parse(pinned.ingestFrom) <= t && t <= Date.parse(pinned.ingestUntil)) return pinnedId;
|
||||
return routeLocally(events, at);
|
||||
}
|
||||
|
||||
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),
|
||||
|
||||
@@ -123,8 +123,26 @@ describe("photos arriving on this computer", () => {
|
||||
// Yesterday's pin only holds photos taken inside it. The next morning goes to that morning's event.
|
||||
expect(eventForArrival("braga", events, at)).toBe("braga");
|
||||
expect(eventForArrival("braga", events, "2026-10-10T15:30:00Z")).toBe("other");
|
||||
// No capture time: keep the pin (USB already filtered by the card clock; server keeps the named folder too).
|
||||
expect(eventForArrival("braga", events, null)).toBe("braga");
|
||||
expect(eventForArrival(null, events, null)).toBeNull();
|
||||
// Cache miss for the pin id: keep it (do not dump into Sem evento); archived pins fall through to the clock.
|
||||
expect(eventForArrival("missing", events, "2026-10-10T15:30:00Z")).toBe("missing");
|
||||
expect(eventForArrival("braga", [{ ...events[0]!, archivedAt: "2026-10-10T00:00:00Z" }, events[1]!], "2026-10-10T15:30:00Z")).toBe("other");
|
||||
});
|
||||
|
||||
it("when two ingest windows overlap, files the photo in the event whose start is closest to the capture", () => {
|
||||
const events = [
|
||||
{ id: "miguel", startsAt: "2026-11-03T14:00:00Z", ingestFrom: "2026-11-03T12:00:00Z", ingestUntil: "2026-11-03T18:00:00Z", archivedAt: null },
|
||||
{ id: "sub21", startsAt: "2026-11-03T16:30:00Z", ingestFrom: "2026-11-03T14:30:00Z", ingestUntil: "2026-11-03T20:30:00Z", archivedAt: null },
|
||||
];
|
||||
// Studio at 14:20: only Miguel's window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T14:20:00Z")).toBe("miguel");
|
||||
// Overlap at 15:00 with Sub-21 pinned: pin wins while capture is inside its window.
|
||||
expect(eventForArrival("sub21", events, "2026-11-03T15:00:00Z")).toBe("sub21");
|
||||
// Overlap without a pin: closest start (Miguel at 14:00 beats Sub-21 at 16:30 for a 15:00 capture).
|
||||
expect(eventForArrival(null, events, "2026-11-03T15:00:00Z")).toBe("miguel");
|
||||
expect(eventForArrival(null, events, "2026-11-03T16:40:00Z")).toBe("sub21");
|
||||
});
|
||||
|
||||
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
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 };
|
||||
| { id: string; kind: "deliver"; targetId: string; ids: string[]; again: boolean; originals?: boolean };
|
||||
|
||||
export type NewOp = QueuedOp extends infer O ? (O extends QueuedOp ? Omit<O, "id"> : never) : never;
|
||||
|
||||
@@ -189,7 +189,7 @@ export class OfflineQueue {
|
||||
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);
|
||||
else await api.deliver(this.orgId, op.targetId, resolved, op.again, op.originals ?? false);
|
||||
} 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.
|
||||
|
||||
@@ -71,16 +71,16 @@ export function setIptc(api: ApiClient, orgId: string, ids: string[], set: Recor
|
||||
}
|
||||
|
||||
/** "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) {
|
||||
export async function deliver(api: ApiClient, orgId: string, targetId: string, ids: string[], again = false, originals = 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);
|
||||
answer = await api.deliver(orgId, targetId, x, again, originals);
|
||||
},
|
||||
() => queue.add({ kind: "deliver", targetId, ids, again }),
|
||||
() => queue.add({ kind: "deliver", targetId, ids, again, originals }),
|
||||
);
|
||||
return result === "sent" && answer ? { ...(answer as Awaited<ReturnType<ApiClient["deliver"]>>), waiting: false } : { queued: [], skipped: [], waiting: true };
|
||||
}
|
||||
@@ -122,7 +122,13 @@ export function DeliveryPage() {
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
|
||||
{i.remotePath ?? <span className="text-faint">—</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
|
||||
{i.lastError && (
|
||||
<span className="block text-[10px] text-[#f0a35a]">
|
||||
{i.lastError === "waiting_for_original" && isDesktop()
|
||||
? t.deliveryErrors.waiting_for_original_here
|
||||
: (t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError)}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
|
||||
{t.deliveryStatus[i.status]}
|
||||
|
||||
@@ -12,6 +12,17 @@ import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/sessi
|
||||
import { SyncSettingsButton } from "../develop/SyncSettings.js";
|
||||
import { commandsFrom, queueSync } from "../develop/copySettings.js";
|
||||
import { clampUnit, constrainRotated, fitAspect, GUIDES, type Guide, rotateAspect } from "../develop/crop.js";
|
||||
import {
|
||||
addSpot,
|
||||
DEFAULT_SPOT_FEATHER,
|
||||
DEFAULT_SPOT_OPACITY,
|
||||
DEFAULT_SPOT_SIZE,
|
||||
removeSpotAt,
|
||||
SPOT_MODES,
|
||||
spotsOf,
|
||||
spotsPartial,
|
||||
type SpotMode,
|
||||
} from "../develop/spots.js";
|
||||
import { engineAuto, Viewer } from "../develop/Viewer.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
|
||||
@@ -342,12 +353,21 @@ export function DevelopPage() {
|
||||
e.preventDefault();
|
||||
flagCurrent(patchForKey(e.key)!);
|
||||
}
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) setCropping((c) => !c);
|
||||
else if (e.key.toLowerCase() === "w" && canEdit) setPicking((p) => !p);
|
||||
else if (e.key.toLowerCase() === "z") setOneToOne((z) => !z);
|
||||
else if (e.key.toLowerCase() === "r" && canEdit) {
|
||||
setSpotting(false);
|
||||
setCropping((c) => !c);
|
||||
} else if (e.key.toLowerCase() === "q" && canEdit) {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting((s) => !s);
|
||||
} else if (e.key.toLowerCase() === "w" && canEdit) {
|
||||
setSpotting(false);
|
||||
setPicking((p) => !p);
|
||||
} else if (e.key.toLowerCase() === "z") setOneToOne((z) => !z);
|
||||
else if (e.key === "Escape") {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting(false);
|
||||
}
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
@@ -356,6 +376,7 @@ export function DevelopPage() {
|
||||
|
||||
const settings = session?.loaded ? session.settings : null;
|
||||
const crop = useMemo(() => (settings ? cropOf(settings) : { rect: { x0: 0, y0: 0, x1: 1, y1: 1 }, angle: 0, aspect: null }), [settings]);
|
||||
const spots = useMemo(() => (settings ? spotsOf(settings) : []), [settings]);
|
||||
const shown = settings && before && typeof engine === "object" ? engine.defaultSettings() : settings;
|
||||
|
||||
const setValue = useCallback(
|
||||
@@ -366,9 +387,57 @@ export function DevelopPage() {
|
||||
[session],
|
||||
);
|
||||
const [picking, setPicking] = useState(false);
|
||||
const [spotting, setSpotting] = useState(false);
|
||||
const [spotMode, setSpotMode] = useState<SpotMode>("remove");
|
||||
const [spotSize, setSpotSize] = useState(DEFAULT_SPOT_SIZE);
|
||||
const [spotFeather, setSpotFeather] = useState(DEFAULT_SPOT_FEATHER);
|
||||
const [spotOpacity, setSpotOpacity] = useState(DEFAULT_SPOT_OPACITY);
|
||||
|
||||
const placeSpot = useCallback(
|
||||
(u: number, v: number) => {
|
||||
if (!session?.loaded || !canEdit) return;
|
||||
const r = crop.rect;
|
||||
const x = r.x0 + u * (r.x1 - r.x0);
|
||||
const y = r.y0 + v * (r.y1 - r.y0);
|
||||
const next = addSpot(session.settings, {
|
||||
mode: spotMode,
|
||||
x,
|
||||
y,
|
||||
size: spotSize,
|
||||
feather: spotFeather,
|
||||
opacity: spotOpacity,
|
||||
});
|
||||
session.edit({ command: "develop.merge", params: { partial: spotsPartial(next) } });
|
||||
session.endGesture();
|
||||
},
|
||||
[session, canEdit, crop.rect, spotMode, spotSize, spotFeather, spotOpacity],
|
||||
);
|
||||
|
||||
const deleteSpot = useCallback(
|
||||
(index: number) => {
|
||||
if (!session?.loaded || !canEdit) return;
|
||||
session.edit({ command: "develop.merge", params: { partial: spotsPartial(removeSpotAt(session.settings, index)) } });
|
||||
session.endGesture();
|
||||
},
|
||||
[session, canEdit],
|
||||
);
|
||||
|
||||
const spotMarks = useMemo(() => {
|
||||
if (!spotting || !spots.length) return [];
|
||||
const r = crop.rect;
|
||||
const rw = r.x1 - r.x0 || 1;
|
||||
const rh = r.y1 - r.y0 || 1;
|
||||
return spots
|
||||
.map((s) => {
|
||||
const p = s.points[0];
|
||||
if (!p) return null;
|
||||
return { u: (p.x - r.x0) / rw, v: (p.y - r.y0) / rh, size: s.size / Math.max(rw, rh) };
|
||||
})
|
||||
.filter((m): m is { u: number; v: number; size: number } => !!m && m.u >= -0.05 && m.u <= 1.05 && m.v >= -0.05 && m.v <= 1.05);
|
||||
}, [spotting, spots, crop.rect]);
|
||||
|
||||
/** 1:1 view, and where its full-resolution original stands. */
|
||||
const [oneToOne, setOneToOne] = useState(false);
|
||||
const [fullState, setFullState] = useState<"idle" | "waiting" | "ready" | "missing">("idle");
|
||||
const [oneToOne, setOneToOne] = useState(false); const [fullState, setFullState] = useState<"idle" | "waiting" | "ready" | "missing">("idle");
|
||||
useEffect(() => {
|
||||
setOneToOne(false);
|
||||
setFullState("idle");
|
||||
@@ -625,13 +694,16 @@ export function DevelopPage() {
|
||||
{...(oneToOne || current.originalName.toLowerCase().endsWith(".dng") || current.name.toLowerCase().endsWith(".dng")
|
||||
? { localSource: fullSource }
|
||||
: isDesktop() && { localSource: () => localOriginalToView(current.sha256) })}
|
||||
picking={picking && !cropping && !before}
|
||||
picking={picking && !cropping && !spotting && !before}
|
||||
onPick={(u, v) => {
|
||||
setPicking(false);
|
||||
// The view shows the cropped frame: map back to the whole frame (straighten angle ignored).
|
||||
const r = crop.rect;
|
||||
void autoValues("pick", { x: r.x0 + u * (r.x1 - r.x0), y: r.y0 + v * (r.y1 - r.y0) });
|
||||
}}
|
||||
spotting={spotting && !cropping && !before}
|
||||
onSpot={placeSpot}
|
||||
spotMarks={spotMarks}
|
||||
onCrop={(rect, final) => {
|
||||
setDragging(!final);
|
||||
session?.edit({ command: "crop.set", params: { rect: clampUnit(rect), angle: crop.angle, aspect: crop.aspect } }, "crop");
|
||||
@@ -651,13 +723,103 @@ export function DevelopPage() {
|
||||
{oneToOne && fullState === "waiting" && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.fullWaiting}</p>}
|
||||
{oneToOne && fullState === "missing" && <p className="border-b border-line px-3 py-2 text-[12px] text-[#f0a35a]">{t.dev.fullMissing}</p>}
|
||||
{picking && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.pickWbNow}</p>}
|
||||
{spotting && <p className="border-b border-line bg-accent/20 px-3 py-2 text-[12px] text-ink">{t.dev.spotNow}</p>}
|
||||
{!canEdit && current && <p className="border-b border-line px-3 py-2 text-[12px] text-faint">{t.dev.noAccess}</p>}
|
||||
<Section title={t.dev.spot}>
|
||||
<div className="mb-2 flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
disabled={!canEdit}
|
||||
onClick={() => {
|
||||
setCropping(false);
|
||||
setPicking(false);
|
||||
setSpotting((s) => !s);
|
||||
}}
|
||||
aria-pressed={spotting}
|
||||
className={`h-7 border border-black px-3 text-[12px] disabled:opacity-40 ${spotting ? "bg-accent text-white" : "bg-cell"}`}
|
||||
>
|
||||
{spotting ? t.dev.spotDone : t.dev.spot}
|
||||
</button>
|
||||
<span className="text-[11px] text-faint">{t.dev.spotHelp}</span>
|
||||
</div>
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
{SPOT_MODES.map((m) => (
|
||||
<button
|
||||
key={m.id}
|
||||
disabled={!canEdit}
|
||||
onClick={() => setSpotMode(m.id)}
|
||||
aria-pressed={spotMode === m.id}
|
||||
className={`h-6 border border-black px-2 text-[11px] disabled:opacity-40 ${spotMode === m.id ? "bg-cell-on text-ink" : "bg-cell text-muted"}`}
|
||||
>
|
||||
{t.dev[m.labelKey]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotSize}
|
||||
<input
|
||||
type="range"
|
||||
min={0.005}
|
||||
max={0.12}
|
||||
step={0.001}
|
||||
value={spotSize}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotSize(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotFeather}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
value={spotFeather}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotFeather(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
<label className="mb-2 block text-[11px] text-faint">
|
||||
{t.dev.spotOpacity}
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
value={spotOpacity}
|
||||
disabled={!canEdit}
|
||||
onChange={(e) => setSpotOpacity(Number(e.target.value))}
|
||||
className="mt-1 w-full"
|
||||
/>
|
||||
</label>
|
||||
{spots.length > 0 && (
|
||||
<ul className="mt-1 max-h-28 space-y-1 overflow-y-auto text-[11px]">
|
||||
{spots.map((s, i) => {
|
||||
const label = SPOT_MODES.find((m) => m.id === s.mode);
|
||||
return (
|
||||
<li key={i} className="flex items-center justify-between gap-2 border border-line bg-cell px-2 py-1">
|
||||
<span className="truncate text-muted">
|
||||
{label ? t.dev[label.labelKey] : s.mode} · {i + 1}
|
||||
</span>
|
||||
<button type="button" disabled={!canEdit} className="text-ink underline disabled:opacity-40" onClick={() => deleteSpot(i)}>
|
||||
{t.dev.spotDelete}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</Section>
|
||||
{modules.includes("crop") && (
|
||||
<Section title={t.modules.crop}>
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<button
|
||||
disabled={!canEdit}
|
||||
onClick={() => setCropping(!cropping)}
|
||||
onClick={() => {
|
||||
setSpotting(false);
|
||||
setCropping(!cropping);
|
||||
}}
|
||||
aria-pressed={cropping}
|
||||
className={`h-7 border border-black px-3 text-[12px] disabled:opacity-40 ${cropping ? "bg-accent text-white" : "bg-cell"}`}
|
||||
>
|
||||
|
||||
@@ -321,11 +321,6 @@ export function LibraryPage() {
|
||||
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
|
||||
syncGames(games);
|
||||
}, [events, openEvent, syncGames]);
|
||||
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
|
||||
const failed = uploads.items.filter((i) => i.status === "failed");
|
||||
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
|
||||
const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0;
|
||||
|
||||
const playerIds = useMemo(() => photoIdsOf(players), [players]);
|
||||
const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]);
|
||||
const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]);
|
||||
@@ -774,23 +769,6 @@ export function LibraryPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{uploads.items.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-3 border-t border-line bg-panel px-3 py-1.5 text-[12px]" role="status">
|
||||
<span className="font-mono text-[11px]">
|
||||
{sending.length ? t.uploading(sentCount, uploads.items.length) : t.uploaded(sentCount)}
|
||||
{failed.length > 0 && <span className="text-[#f0a35a]"> · {t.uploadFailed(failed.length)}</span>}
|
||||
</span>
|
||||
<span className="h-1 min-w-24 flex-1 bg-black">
|
||||
<span className="block h-full bg-accent transition-[width]" style={{ width: `${Math.round(overall * 100)}%` }} />
|
||||
</span>
|
||||
{failed.length > 0 && <span className="truncate text-[11px] text-faint" title={failed.map((f) => `${f.name}: ${f.error}`).join("\n")}>{failed[0]?.name}: {failed[0]?.error}</span>}
|
||||
{!sending.length && (
|
||||
<button onClick={uploads.clear} className="text-[11px] text-faint underline hover:text-muted">
|
||||
{t.dismiss}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{desktop && <CardOverallStatus />}
|
||||
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useAuth } from "../auth.js";
|
||||
import { Alert } from "../components/ui.js";
|
||||
import { LocalCatalog } from "../desktop/LocalCatalog.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
// "advanced" is an internal bucket for controls a future engine version adds before we name a panel.
|
||||
@@ -14,6 +14,7 @@ export function PreferencesPage() {
|
||||
const { api, me, reload } = useAuth();
|
||||
const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]);
|
||||
const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");
|
||||
const [uiStatus, setUiStatus] = useState<"idle" | "checking" | "current" | "error">("idle");
|
||||
|
||||
const toggle = async (module: Module) => {
|
||||
const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module];
|
||||
@@ -52,6 +53,30 @@ export function PreferencesPage() {
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{isDesktop() && (
|
||||
<section className="max-w-2xl space-y-3 border-t border-line p-6">
|
||||
<h2 className="text-sm font-semibold">{t.update.uiSection}</h2>
|
||||
<p className="text-sm text-muted">{t.update.uiSectionHelp}</p>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uiStatus === "checking"}
|
||||
className="h-8 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-50"
|
||||
onClick={() => {
|
||||
setUiStatus("checking");
|
||||
desktopInvoke<boolean>("ui_check")
|
||||
.then((updated) => {
|
||||
if (updated) window.location.reload();
|
||||
else setUiStatus("current");
|
||||
})
|
||||
.catch(() => setUiStatus("error"));
|
||||
}}
|
||||
>
|
||||
{uiStatus === "checking" ? t.update.uiChecking : t.update.uiCheckNow}
|
||||
</button>
|
||||
{uiStatus === "current" && <p className="text-xs text-ok">{t.update.uiCurrent}</p>}
|
||||
{uiStatus === "error" && <Alert>{t.unexpectedError}</Alert>}
|
||||
</section>
|
||||
)}
|
||||
{isDesktop() && <LocalCatalog />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { LocalDeliveries } from "../desktop/localDeliveries.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { FolderScanProvider } from "../library/folderScan.js";
|
||||
import { IngestProvider } from "../library/ingest.js";
|
||||
import { TransferBar } from "../library/TransferBar.js";
|
||||
|
||||
const moduleClass = ({ isActive }: { isActive: boolean }) =>
|
||||
`px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide transition-colors ${
|
||||
@@ -141,13 +142,14 @@ export function Shell() {
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<LocalDeliveries />
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<IngestProvider>
|
||||
<IngestProvider>
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<FolderScanProvider>
|
||||
<Outlet />
|
||||
</FolderScanProvider>
|
||||
</IngestProvider>
|
||||
</main>
|
||||
</main>
|
||||
<TransferBar />
|
||||
</IngestProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -12,8 +12,9 @@ What the shell adds today:
|
||||
- Refresh token in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service).
|
||||
Without a keychain the session stays in memory and ends when the app closes.
|
||||
- Local FTP server for cameras (`src/ftp.rs`, Library → **FTP local**). See below.
|
||||
- USB tether (`src/camera.rs` + `camera_mac.m`, Library → **USB**): a PTP body on the cable sends new shots
|
||||
to the open event and syncs its clock to this Mac. EOS Utility must not hold the cable.
|
||||
- USB tether (`src/camera.rs` + `camera_mac.m`, Library → **USB**): pulses the PTP session so the body stays
|
||||
shootable (no permanent computer/busy screen), pulls new shots to the open event, syncs the clock. EOS Utility
|
||||
must not hold the cable.
|
||||
- Local catalogue (`src/catalog.rs`, Preferências → **Catálogo local**). See below.
|
||||
- Works without network: when the server can't be reached at start-up, the window opens the copy of the web app
|
||||
bundled in the installer (photo engine included), so the catalogue, local FTP and editing originals on disk go on;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.26",
|
||||
"version": "0.3.27",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.26"
|
||||
version = "0.3.27"
|
||||
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."
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! USB tether (macOS). A Canon (or any PTP body) does not show up as a disk; ImageCaptureCore
|
||||
//! (`camera_mac.m`) lists the card and each new shot. Nothing is copied until the photographer
|
||||
//! picks files (`camera_import`). Chosen files land in `<ingest>/.usb` and the web app polls
|
||||
//! `camera_take` to file them like a local-FTP photo. The dot folder is skipped by the FTP scan.
|
||||
//! (`camera_mac.m`) briefly opens a PTP session to list/download, then closes it so the body can
|
||||
//! shoot (a held session + `requestEnableTethering` put many cameras on the computer/busy screen).
|
||||
//! The session stays off until the photographer turns the cable on. Nothing is copied until they
|
||||
//! pick files (`camera_import`) or auto-ingest asks. Chosen files land in `<ingest>/.usb` and the
|
||||
//! web app polls `camera_take` to file them like a local-FTP photo.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
@@ -53,7 +55,10 @@ pub struct CameraStatus {
|
||||
pub supported: bool,
|
||||
pub tether: bool,
|
||||
pub devices: Vec<CameraDevice>,
|
||||
/// Empty when `catalog_gen` is unchanged since the client's `since_gen` (keep the last list).
|
||||
pub files: Vec<CameraFile>,
|
||||
/// Bumps when the file list changes. Poll with the last value to skip re-sending thousands of rows.
|
||||
pub catalog_gen: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -76,8 +81,10 @@ struct Inner {
|
||||
devices: Vec<CameraDevice>,
|
||||
files: Vec<CameraFile>,
|
||||
pending: Vec<IncomingFile>,
|
||||
/// Off by default: opening the PTP session lists the whole card. The UI turns it on (and remembers).
|
||||
tether: bool,
|
||||
dir: String,
|
||||
catalog_gen: u64,
|
||||
}
|
||||
|
||||
pub struct CameraState {
|
||||
@@ -91,8 +98,9 @@ impl Default for CameraState {
|
||||
devices: Vec::new(),
|
||||
files: Vec::new(),
|
||||
pending: Vec::new(),
|
||||
tether: true,
|
||||
tether: false,
|
||||
dir: String::new(),
|
||||
catalog_gen: 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -137,13 +145,33 @@ impl CameraState {
|
||||
}
|
||||
|
||||
pub fn status(&self) -> CameraStatus {
|
||||
self.status_since(None)
|
||||
}
|
||||
|
||||
/// When `since_gen` matches the current catalog generation, `files` is left empty so the 1 s poll
|
||||
/// does not clone and serialize the whole card again.
|
||||
pub fn status_since(&self, since_gen: Option<u64>) -> CameraStatus {
|
||||
self.drain();
|
||||
let inner = self.inner.lock().ok();
|
||||
let Ok(inner) = self.inner.lock() else {
|
||||
return CameraStatus {
|
||||
supported: supported(),
|
||||
tether: false,
|
||||
devices: Vec::new(),
|
||||
files: Vec::new(),
|
||||
catalog_gen: 0,
|
||||
};
|
||||
};
|
||||
let unchanged = since_gen == Some(inner.catalog_gen);
|
||||
CameraStatus {
|
||||
supported: supported(),
|
||||
tether: inner.as_ref().is_none_or(|i| i.tether),
|
||||
devices: inner.as_ref().map(|i| i.devices.clone()).unwrap_or_default(),
|
||||
files: inner.map(|i| i.files.clone()).unwrap_or_default(),
|
||||
tether: inner.tether,
|
||||
devices: inner.devices.clone(),
|
||||
files: if unchanged {
|
||||
Vec::new()
|
||||
} else {
|
||||
inner.files.clone()
|
||||
},
|
||||
catalog_gen: inner.catalog_gen,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,8 +186,9 @@ impl CameraState {
|
||||
pub fn set_tether(&self, on: bool) {
|
||||
if let Ok(mut inner) = self.inner.lock() {
|
||||
inner.tether = on;
|
||||
if !on {
|
||||
if !on && !inner.files.is_empty() {
|
||||
inner.files.clear();
|
||||
inner.catalog_gen = inner.catalog_gen.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
set_tether_native(on);
|
||||
@@ -182,7 +211,10 @@ fn apply_event(inner: &mut Inner, line: &str) {
|
||||
};
|
||||
match event {
|
||||
CameraEvent::Devices { devices } => inner.devices = devices,
|
||||
CameraEvent::Catalog { camera_id: _, files } => inner.files = files,
|
||||
CameraEvent::Catalog { camera_id: _, files } => {
|
||||
inner.files = files;
|
||||
inner.catalog_gen = inner.catalog_gen.wrapping_add(1);
|
||||
}
|
||||
CameraEvent::File { path, name, size } => {
|
||||
if size > 0 && (crate::ftp::is_jpeg_name(&name) || crate::ftp::is_raw_name(&name)) {
|
||||
inner.pending.push(IncomingFile::at(path, name, size));
|
||||
@@ -287,9 +319,13 @@ pub fn start(ftp: &FtpState) {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn camera_status(cam: tauri::State<'_, CameraState>, ftp: tauri::State<'_, FtpState>) -> CameraStatus {
|
||||
pub fn camera_status(
|
||||
cam: tauri::State<'_, CameraState>,
|
||||
ftp: tauri::State<'_, FtpState>,
|
||||
since_gen: Option<u64>,
|
||||
) -> CameraStatus {
|
||||
cam.sync_dir(&ftp.ingest_dir());
|
||||
cam.status()
|
||||
cam.status_since(since_gen)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -336,6 +372,7 @@ mod tests {
|
||||
pending: Vec::new(),
|
||||
tether: true,
|
||||
dir: String::new(),
|
||||
catalog_gen: 0,
|
||||
};
|
||||
apply_event(
|
||||
&mut inner,
|
||||
@@ -357,6 +394,7 @@ mod tests {
|
||||
assert!(inner.devices[0].catalog_ready);
|
||||
assert_eq!(inner.files.len(), 2);
|
||||
assert_eq!(inner.pending.len(), 2);
|
||||
assert_eq!(inner.catalog_gen, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -383,10 +421,32 @@ mod tests {
|
||||
pending: Vec::new(),
|
||||
tether: true,
|
||||
dir: String::new(),
|
||||
catalog_gen: 1,
|
||||
};
|
||||
apply_event(&mut inner, r#"{"kind":"devices","devices":[]}"#);
|
||||
apply_event(&mut inner, r#"{"kind":"catalog","cameraId":"abc","files":[]}"#);
|
||||
assert!(inner.devices.is_empty());
|
||||
assert!(inner.files.is_empty());
|
||||
assert_eq!(inner.catalog_gen, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_since_omits_files_when_the_catalog_did_not_change() {
|
||||
let state = CameraState::default();
|
||||
{
|
||||
let mut inner = state.inner.lock().unwrap();
|
||||
apply_event(
|
||||
&mut inner,
|
||||
r#"{"kind":"catalog","cameraId":"abc","files":[{"name":"a.jpg","size":1,"isNew":false,"imported":false}]}"#,
|
||||
);
|
||||
}
|
||||
let first = state.status_since(None);
|
||||
assert_eq!(first.files.len(), 1);
|
||||
assert_eq!(first.catalog_gen, 1);
|
||||
let again = state.status_since(Some(1));
|
||||
assert!(again.files.is_empty());
|
||||
assert_eq!(again.catalog_gen, 1);
|
||||
let refreshed = state.status_since(Some(0));
|
||||
assert_eq!(refreshed.files.len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// USB still cameras speak PTP, so macOS never mounts them as a disk. Image Capture (and this file)
|
||||
// talks to them through ImageCaptureCore: open a session, list what is on the card (and each new
|
||||
// shot as it appears), and download only the files the photographer picks. Nothing is copied on its
|
||||
// own — that is deliberate: a full card would flood the ingest folder.
|
||||
// talks to them through ImageCaptureCore: open a session briefly, list what is on the card, download
|
||||
// what the photographer picked (or auto-ingest asked for), then close the session so the body can
|
||||
// shoot again. Holding the session open (and especially requestEnableTethering) puts many Canons on
|
||||
// the "computer / busy" viewfinder screen and blocks the shutter — that is why we pulse.
|
||||
// One process can hold the PTP session; if EOS Utility has it, opening fails and we try again.
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
@@ -12,7 +13,14 @@ typedef void (*pr_camera_cb)(const char *json);
|
||||
|
||||
static pr_camera_cb g_callback = NULL;
|
||||
static NSString *g_dir = nil;
|
||||
static BOOL g_tether = YES;
|
||||
// Off until the photographer turns the cable on (or the web UI restores their last choice). Opening a
|
||||
// session lists the whole card over USB; doing that at every launch made big cards feel hung.
|
||||
static BOOL g_tether = NO;
|
||||
|
||||
/// How long the body stays free to shoot between card reads.
|
||||
static const NSTimeInterval kPollSeconds = 2.5;
|
||||
/// Close shortly after a catalog (or last download) so the viewfinder is not stuck on "computer".
|
||||
static const NSTimeInterval kCloseAfterIdleSeconds = 0.4;
|
||||
|
||||
static void emit(NSDictionary *obj) {
|
||||
if (!g_callback || !obj) return;
|
||||
@@ -47,6 +55,12 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
@property (retain) NSMutableSet<NSString *> *fetched;
|
||||
@property (retain) NSMutableSet<NSString *> *seenAtConnect;
|
||||
@property (retain) NSMutableDictionary<NSString *, ICCameraFile *> *filesByName;
|
||||
/// First full catalog of this tether-on cycle: names already on the card (not "new shots").
|
||||
@property (assign) BOOL baselineTaken;
|
||||
@property (assign) NSInteger pendingDownloads;
|
||||
@property (retain) NSMutableArray<NSString *> *pendingImport;
|
||||
/// Last file rows sent to the UI (kept when the session closes so the list does not vanish).
|
||||
@property (retain) NSArray<NSDictionary *> *lastCatalog;
|
||||
/// synced | unsupported. Nil until the session is ready.
|
||||
@property (copy) NSString *clock;
|
||||
@property (assign) double clockOffset;
|
||||
@@ -63,6 +77,7 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
@property (copy) NSString *dir;
|
||||
@property (assign) BOOL tether;
|
||||
@property (assign) BOOL retryScheduled;
|
||||
@property (assign) BOOL pollScheduled;
|
||||
@property (retain) NSArray<NSDictionary *> *locked;
|
||||
@end
|
||||
|
||||
@@ -144,14 +159,17 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
cam.fetched = [NSMutableSet set];
|
||||
cam.seenAtConnect = [NSMutableSet set];
|
||||
cam.filesByName = [NSMutableDictionary dictionary];
|
||||
cam.pendingImport = [NSMutableArray array];
|
||||
cam.lastCatalog = @[];
|
||||
cam.clockDone = NO;
|
||||
cam.openRequested = NO;
|
||||
cam.state = @"idle";
|
||||
self.cams[uuid] = cam;
|
||||
}
|
||||
cam.device = (ICCameraDevice *)device;
|
||||
cam.name = device.name ?: @"Câmara";
|
||||
cam.vendor = device.usbVendorID;
|
||||
cam.product = device.usbProductID;
|
||||
cam.vendor = (int)device.usbVendorID;
|
||||
cam.product = (int)device.usbProductID;
|
||||
return cam;
|
||||
}
|
||||
|
||||
@@ -168,7 +186,8 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
@"error": cam.errorText ?: [NSNull null],
|
||||
@"clock": cam.clock ?: [NSNull null],
|
||||
@"clockOffset": cam.clockOffsetKnown ? @(cam.clockOffset) : [NSNull null],
|
||||
@"catalogReady": @(cam.catalogReady),
|
||||
// Keep the last list usable while the session is closed between pulses.
|
||||
@"catalogReady": @(cam.catalogReady || cam.lastCatalog.count > 0),
|
||||
}];
|
||||
}
|
||||
if (self.locked) [list addObjectsFromArray:self.locked];
|
||||
@@ -177,27 +196,41 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
|
||||
- (void)publishCatalog:(PRCam *)cam {
|
||||
NSMutableArray *files = [NSMutableArray array];
|
||||
for (NSString *name in cam.filesByName) {
|
||||
ICCameraFile *file = cam.filesByName[name];
|
||||
BOOL isNew = ![cam.seenAtConnect containsObject:name];
|
||||
NSDate *created = file.creationDate;
|
||||
[files addObject:@{
|
||||
@"name": name,
|
||||
@"size": @(file.fileSize),
|
||||
@"createdMs": created ? @((long long)(created.timeIntervalSince1970 * 1000.0)) : [NSNull null],
|
||||
@"isNew": @(isNew),
|
||||
@"imported": @([cam.fetched containsObject:name]),
|
||||
}];
|
||||
}
|
||||
[files sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
|
||||
NSNumber *ca = a[@"createdMs"];
|
||||
NSNumber *cb = b[@"createdMs"];
|
||||
if ([ca isKindOfClass:[NSNumber class]] && [cb isKindOfClass:[NSNumber class]] && ![ca isEqual:[NSNull null]] && ![cb isEqual:[NSNull null]]) {
|
||||
NSComparisonResult byDate = [cb compare:ca];
|
||||
if (byDate != NSOrderedSame) return byDate;
|
||||
if (cam.device.hasOpenSession && cam.filesByName.count) {
|
||||
for (NSString *name in cam.filesByName) {
|
||||
ICCameraFile *file = cam.filesByName[name];
|
||||
BOOL isNew = ![cam.seenAtConnect containsObject:name];
|
||||
NSDate *created = file.creationDate;
|
||||
[files addObject:@{
|
||||
@"name": name,
|
||||
@"size": @(file.fileSize),
|
||||
@"createdMs": created ? @((long long)(created.timeIntervalSince1970 * 1000.0)) : [NSNull null],
|
||||
@"isNew": @(isNew),
|
||||
@"imported": @([cam.fetched containsObject:name]),
|
||||
}];
|
||||
}
|
||||
return [((NSString *)a[@"name"]) compare:b[@"name"]];
|
||||
}];
|
||||
[files sortUsingComparator:^NSComparisonResult(NSDictionary *a, NSDictionary *b) {
|
||||
NSNumber *ca = a[@"createdMs"];
|
||||
NSNumber *cb = b[@"createdMs"];
|
||||
if ([ca isKindOfClass:[NSNumber class]] && [cb isKindOfClass:[NSNumber class]] && ![ca isEqual:[NSNull null]] && ![cb isEqual:[NSNull null]]) {
|
||||
NSComparisonResult byDate = [cb compare:ca];
|
||||
if (byDate != NSOrderedSame) return byDate;
|
||||
}
|
||||
return [((NSString *)a[@"name"]) compare:b[@"name"]];
|
||||
}];
|
||||
cam.lastCatalog = files;
|
||||
} else if (cam.lastCatalog.count) {
|
||||
// Session closed: refresh only the imported flags on the last snapshot.
|
||||
NSMutableArray *refreshed = [NSMutableArray arrayWithCapacity:cam.lastCatalog.count];
|
||||
for (NSDictionary *row in cam.lastCatalog) {
|
||||
NSMutableDictionary *copy = [row mutableCopy];
|
||||
NSString *name = copy[@"name"];
|
||||
if (name) copy[@"imported"] = @([cam.fetched containsObject:name]);
|
||||
[refreshed addObject:copy];
|
||||
}
|
||||
files = refreshed;
|
||||
cam.lastCatalog = files;
|
||||
}
|
||||
emit(@{@"kind": @"catalog", @"cameraId": cam.uuid ?: @"", @"files": files});
|
||||
}
|
||||
|
||||
@@ -271,6 +304,56 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
});
|
||||
}
|
||||
|
||||
/// After the card is free again, wait a beat then reopen briefly to catch new shots.
|
||||
- (void)schedulePoll {
|
||||
if (self.pollScheduled || !self.tether) return;
|
||||
self.pollScheduled = YES;
|
||||
__weak PRCameraHub *weak = self;
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kPollSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
PRCameraHub *hub = weak;
|
||||
if (!hub) return;
|
||||
hub.pollScheduled = NO;
|
||||
if (!hub.tether) return;
|
||||
for (NSString *key in hub.cams.allKeys) {
|
||||
PRCam *cam = hub.cams[key];
|
||||
if (cam.pendingDownloads > 0) continue;
|
||||
cam.openRequested = NO;
|
||||
[hub requestOpenIfReady:cam];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Free the shutter: close PTP once catalog (and downloads) are done.
|
||||
- (void)closeWhenIdle:(PRCam *)cam {
|
||||
if (!self.tether) return;
|
||||
if (cam.pendingDownloads > 0 || cam.pendingImport.count > 0) return;
|
||||
if (!cam.device.hasOpenSession) {
|
||||
[self schedulePoll];
|
||||
return;
|
||||
}
|
||||
NSString *uuid = cam.uuid;
|
||||
__weak PRCameraHub *weak = self;
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kCloseAfterIdleSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||
PRCameraHub *hub = weak;
|
||||
if (!hub || !hub.tether) return;
|
||||
PRCam *still = hub.cams[uuid];
|
||||
if (!still || still.pendingDownloads > 0 || still.pendingImport.count > 0) return;
|
||||
if (still.device.hasOpenSession) [still.device requestCloseSession];
|
||||
});
|
||||
}
|
||||
|
||||
- (void)drainPendingImport:(PRCam *)cam {
|
||||
if (!cam.device.hasOpenSession || cam.pendingImport.count == 0) return;
|
||||
NSArray *names = [cam.pendingImport copy];
|
||||
[cam.pendingImport removeAllObjects];
|
||||
for (NSString *name in names) {
|
||||
ICCameraFile *file = cam.filesByName[name];
|
||||
if (file) [self download:file cam:cam];
|
||||
}
|
||||
[self publishCatalog:cam];
|
||||
if (cam.pendingDownloads == 0) [self closeWhenIdle:cam];
|
||||
}
|
||||
|
||||
- (NSString *)uniqueName:(NSString *)original {
|
||||
NSString *base = original.lastPathComponent ?: @"photo.JPG";
|
||||
NSString *stem = base.stringByDeletingPathExtension;
|
||||
@@ -295,6 +378,7 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
NSURL *url = [NSURL fileURLWithPath:self.dir isDirectory:YES];
|
||||
if (!url) return;
|
||||
[cam.fetched addObject:file.name];
|
||||
cam.pendingDownloads++;
|
||||
NSDictionary *options = @{
|
||||
ICDownloadsDirectoryURL: url,
|
||||
ICSaveAsFilename: save,
|
||||
@@ -315,12 +399,15 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
if (self.dir.length == 0 || names.count == 0) return;
|
||||
for (NSString *key in self.cams) {
|
||||
PRCam *cam = self.cams[key];
|
||||
if (!cam.device.hasOpenSession) continue;
|
||||
for (NSString *name in names) {
|
||||
ICCameraFile *file = cam.filesByName[name];
|
||||
if (file) [self download:file cam:cam];
|
||||
if (![cam.pendingImport containsObject:name]) [cam.pendingImport addObject:name];
|
||||
}
|
||||
if (cam.device.hasOpenSession && cam.catalogReady) {
|
||||
[self drainPendingImport:cam];
|
||||
} else {
|
||||
cam.openRequested = NO;
|
||||
[self requestOpenIfReady:cam];
|
||||
}
|
||||
[self publishCatalog:cam];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -362,10 +449,8 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
}
|
||||
cam.state = @"tethered";
|
||||
cam.errorText = nil;
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
[cam.device requestEnableTethering];
|
||||
#pragma clang diagnostic pop
|
||||
// Do NOT call requestEnableTethering: that puts many bodies on the computer/busy screen and
|
||||
// blocks the shutter. We only need a short PTP session to list and download files.
|
||||
[self syncClock:cam];
|
||||
[self publish];
|
||||
}
|
||||
@@ -376,13 +461,18 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
if (!cam) return;
|
||||
cam.openRequested = NO;
|
||||
cam.catalogReady = NO;
|
||||
[cam.filesByName removeAllObjects];
|
||||
if (self.tether) {
|
||||
cam.state = @"busy";
|
||||
[self scheduleRetry];
|
||||
// Session closed on purpose: body is free to shoot until the next poll.
|
||||
cam.state = @"tethered";
|
||||
cam.errorText = nil;
|
||||
[self publish];
|
||||
[self publishCatalog:cam];
|
||||
[self schedulePoll];
|
||||
} else {
|
||||
cam.state = @"idle";
|
||||
[self publish];
|
||||
}
|
||||
[self publish];
|
||||
}
|
||||
|
||||
- (void)didRemoveDevice:(ICDevice *)device {
|
||||
@@ -398,10 +488,13 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
|
||||
- (void)deviceDidBecomeReadyWithCompleteContentCatalog:(ICCameraDevice *)device {
|
||||
PRCam *cam = [self camFor:device];
|
||||
// Snapshot what was already on the card so the UI can mark later shots as "new".
|
||||
[cam.seenAtConnect removeAllObjects];
|
||||
for (ICCameraItem *item in cam.device.mediaFiles) {
|
||||
if (item.name && is_still(item)) [cam.seenAtConnect addObject:item.name];
|
||||
// Baseline once per tether-on cycle so each poll does not re-mark the whole card as "old".
|
||||
if (!cam.baselineTaken) {
|
||||
[cam.seenAtConnect removeAllObjects];
|
||||
for (ICCameraItem *item in cam.device.mediaFiles) {
|
||||
if (item.name && is_still(item)) [cam.seenAtConnect addObject:item.name];
|
||||
}
|
||||
cam.baselineTaken = YES;
|
||||
}
|
||||
cam.catalogReady = YES;
|
||||
if ([cam.state isEqualToString:@"opening"]) cam.state = @"tethered";
|
||||
@@ -409,13 +502,18 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
[self rebuildCatalog:cam];
|
||||
[self syncClock:cam];
|
||||
[self publish];
|
||||
[self drainPendingImport:cam];
|
||||
[self closeWhenIdle:cam];
|
||||
}
|
||||
|
||||
- (void)cameraDevice:(ICCameraDevice *)camera didAddItems:(NSArray<ICCameraItem *> *)items {
|
||||
PRCam *cam = [self camFor:camera];
|
||||
// List only — never auto-download. The photographer picks what to pull.
|
||||
// List only — never auto-download. The photographer picks what to pull (or auto-ingest via the UI).
|
||||
for (ICCameraItem *item in items) [self indexItem:item cam:cam];
|
||||
[self publishCatalog:cam];
|
||||
// During the first pass Image Capture calls this for every file on the card. Publishing each
|
||||
// time sorts and ships thousands of JSON rows to the UI. Wait for the complete catalog (or a
|
||||
// real tethered shot after catalogReady) before emitting.
|
||||
if (cam.catalogReady) [self publishCatalog:cam];
|
||||
}
|
||||
|
||||
- (void)cameraDevice:(ICCameraDevice *)camera didRemoveItems:(NSArray<ICCameraItem *> *)items {
|
||||
@@ -423,7 +521,7 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
for (ICCameraItem *item in items) {
|
||||
if (item.name) [cam.filesByName removeObjectForKey:item.name];
|
||||
}
|
||||
[self publishCatalog:cam];
|
||||
if (cam.catalogReady) [self publishCatalog:cam];
|
||||
}
|
||||
|
||||
- (void)cameraDevice:(ICCameraDevice *)camera didReceiveThumbnail:(CGImageRef)thumbnail forItem:(ICCameraItem *)item error:(NSError *)error {
|
||||
@@ -464,25 +562,33 @@ static BOOL is_still(ICCameraItem *item) {
|
||||
|
||||
- (void)didDownloadFile:(ICCameraFile *)file error:(NSError *)error options:(NSDictionary *)options contextInfo:(void *)contextInfo {
|
||||
NSString *camId = contextInfo ? CFBridgingRelease(contextInfo) : nil;
|
||||
PRCam *cam = camId ? self.cams[camId] : nil;
|
||||
if (cam && cam.pendingDownloads > 0) cam.pendingDownloads--;
|
||||
if (error || self.dir.length == 0) {
|
||||
if (camId && file.name) {
|
||||
PRCam *cam = self.cams[camId];
|
||||
if (cam && file.name) {
|
||||
[cam.fetched removeObject:file.name];
|
||||
[self publishCatalog:cam];
|
||||
}
|
||||
if (cam) [self closeWhenIdle:cam];
|
||||
return;
|
||||
}
|
||||
NSString *saved = options[ICSavedFilename];
|
||||
if (![saved isKindOfClass:[NSString class]] || saved.length == 0) saved = file.name;
|
||||
if (saved.length == 0) return;
|
||||
if (saved.length == 0) {
|
||||
if (cam) [self closeWhenIdle:cam];
|
||||
return;
|
||||
}
|
||||
NSString *path = [self.dir stringByAppendingPathComponent:saved];
|
||||
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
|
||||
unsigned long long size = [attrs fileSize];
|
||||
if (size == 0) return;
|
||||
if (size == 0) {
|
||||
if (cam) [self closeWhenIdle:cam];
|
||||
return;
|
||||
}
|
||||
emit(@{@"kind": @"file", @"path": path, @"name": saved, @"size": @(size)});
|
||||
if (camId) {
|
||||
PRCam *cam = self.cams[camId];
|
||||
if (cam) [self publishCatalog:cam];
|
||||
if (cam) {
|
||||
[self publishCatalog:cam];
|
||||
[self closeWhenIdle:cam];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -528,9 +634,11 @@ void pr_camera_set_tether(int on) {
|
||||
g_tether = on ? YES : NO;
|
||||
if (!g_hub) return;
|
||||
g_hub.tether = g_tether;
|
||||
g_hub.pollScheduled = NO;
|
||||
for (NSString *key in g_hub.cams.allKeys) {
|
||||
PRCam *cam = g_hub.cams[key];
|
||||
if (g_hub.tether) {
|
||||
cam.baselineTaken = NO;
|
||||
cam.openRequested = NO;
|
||||
[g_hub requestOpenIfReady:cam];
|
||||
} else if (cam.device.hasOpenSession) {
|
||||
@@ -562,7 +670,11 @@ void pr_camera_refresh_catalog(void) {
|
||||
if (!g_hub) return;
|
||||
for (NSString *key in g_hub.cams.allKeys) {
|
||||
PRCam *cam = g_hub.cams[key];
|
||||
if (cam.catalogReady) [g_hub rebuildCatalog:cam];
|
||||
if (cam.device.hasOpenSession && cam.catalogReady) [g_hub rebuildCatalog:cam];
|
||||
else if (g_hub.tether) {
|
||||
cam.openRequested = NO;
|
||||
[g_hub requestOpenIfReady:cam];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! 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).
|
||||
//! applied at once (the window reloads into them — this is a local app, not a browser tab waiting for a refresh).
|
||||
//!
|
||||
//! 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
|
||||
@@ -194,8 +194,9 @@ pub async fn ui_check(app: tauri::AppHandle) -> Result<bool, String> {
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// Short on purpose: a web deploy during a shoot must land in the local app within minutes, not half an hour.
|
||||
const EVERY: std::time::Duration = std::time::Duration::from_secs(2 * 60);
|
||||
const FIRST: std::time::Duration = std::time::Duration::from_secs(3);
|
||||
|
||||
/// Checks for new interface versions while the app runs; tells the window when one is ready (`ui-ready`).
|
||||
pub fn watch(app: tauri::AppHandle) {
|
||||
@@ -204,8 +205,12 @@ pub fn watch(app: tauri::AppHandle) {
|
||||
loop {
|
||||
match check(&app).await {
|
||||
Ok(true) => {
|
||||
use tauri::Emitter;
|
||||
use tauri::{Emitter, Manager};
|
||||
let _ = app.emit("ui-ready", app.state::<Ui>().status());
|
||||
// Local app: apply at once. Do not wait for a "refresh" click like a browser tab.
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
let _ = window.eval("window.location.reload()");
|
||||
}
|
||||
}
|
||||
Ok(false) => {}
|
||||
// No network, server down: nothing to do, the interface on disk keeps working.
|
||||
@@ -327,7 +332,7 @@ fn write(target: &Path, bytes: &[u8]) -> Result<(), 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.
|
||||
/// older ones removed. The window reloads into it as soon as `ui-ready` fires.
|
||||
fn activate(ui: &UiShared, root: &Path, manifest: &Manifest) -> Result<(), String> {
|
||||
let stage = staging(root, &manifest.version)?;
|
||||
for f in &manifest.files {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.26",
|
||||
"version": "0.3.27",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -142,6 +142,8 @@ export const DeliveryRequest = z.object({
|
||||
photoIds: z.array(z.string().uuid()).min(1).max(2000),
|
||||
/** Send again photos already delivered (or queued) to this target. */
|
||||
again: z.boolean().default(false),
|
||||
/** Camera original for this batch (overrides the destination's resize recipe). */
|
||||
originals: z.boolean().default(false),
|
||||
});
|
||||
export type DeliveryRequest = z.infer<typeof DeliveryRequest>;
|
||||
|
||||
@@ -154,6 +156,8 @@ export const DeliveryBestRequest = z.object({
|
||||
dryRun: z.boolean().default(false),
|
||||
/** Send again the ones this destination already has (a new export, a fixed file). */
|
||||
again: z.boolean().default(false),
|
||||
/** Camera original for this batch (overrides the destination's resize recipe). */
|
||||
originals: z.boolean().default(false),
|
||||
});
|
||||
export type DeliveryBestRequest = z.infer<typeof DeliveryBestRequest>;
|
||||
|
||||
|
||||
@@ -957,7 +957,7 @@ export class ApiClient {
|
||||
}
|
||||
|
||||
/** Only the best of an event (game moments spread over the match); `dryRun` only works out the choice. */
|
||||
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean; again?: boolean }) {
|
||||
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean; again?: boolean; originals?: boolean }) {
|
||||
return this.request<{ chosen: string[]; rest: string[]; queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries/best`, input);
|
||||
}
|
||||
|
||||
@@ -971,8 +971,8 @@ export class ApiClient {
|
||||
return this.request<{ game: ZerozeroGame | null; chosen: boolean }>("PUT", `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, { eventId, game });
|
||||
}
|
||||
|
||||
deliver(orgId: string, targetId: string, photoIds: string[], again = false) {
|
||||
return this.request<{ queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries`, { targetId, photoIds, again });
|
||||
deliver(orgId: string, targetId: string, photoIds: string[], again = false, originals = false) {
|
||||
return this.request<{ queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries`, { targetId, photoIds, again, originals });
|
||||
}
|
||||
|
||||
listDeliveries(orgId: string, query: { targetId?: string; eventId?: string; photoId?: string; status?: string } = {}) {
|
||||
|
||||
@@ -269,6 +269,8 @@ export interface DeliveryTarget {
|
||||
srgb?: boolean;
|
||||
/** The originals as they arrived (metadata written in, renamed), not resized JPEGs: one's own backup. */
|
||||
originals?: boolean;
|
||||
/** Wait a little for faces when the pad needs player names (off by default). */
|
||||
waitForFaces?: boolean;
|
||||
/** Everything that arrives is sent here on its own. */
|
||||
onArrival?: boolean;
|
||||
/** With onArrival: only these FTP logins' photos (ids; empty: everyone's). */
|
||||
@@ -345,6 +347,7 @@ export interface DeliveryTargetInput {
|
||||
keepExif?: boolean;
|
||||
srgb?: boolean;
|
||||
originals?: boolean;
|
||||
waitForFaces?: boolean;
|
||||
onArrival?: boolean;
|
||||
arrivalLogins?: string[];
|
||||
untouched?: boolean;
|
||||
|
||||
Reference in new issue
Block a user