From 4029263d0e4d6f0d8867f9fb469cb0aae9102782 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 10:56:50 +0000 Subject: [PATCH 1/4] Autopilot: a second client gets every other pick, never the gallery's photos "Only the best" can now send to two clients at once: the main destination (e.g. a newspaper's FTP) gets the short gallery, each moment as the second pick of its burst, and a second destination (e.g. the federation's cloud) gets every other picked photo once its 5-minute window is decided. A photo never reaches both. New setting restTargetId ("As outras escolhidas para"). Also updates the autopilot test to the current rule: hand uploads are edited, only archive re-imports (CLOUD) stay as sent. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RL6fqg8fuk1vKF4H6Zrh9V --- apps/api/src/autopilot/best.ts | 8 ++++--- apps/api/src/autopilot/service.ts | 22 +++++++++++++++++- apps/api/test/autopilot.test.ts | 37 +++++++++++++++++++++++++++--- apps/app/src/i18n.ts | 3 +++ apps/app/src/library/Autopilot.tsx | 21 +++++++++++++++++ packages/contracts/src/library.ts | 6 +++++ 6 files changed, 90 insertions(+), 7 deletions(-) diff --git a/apps/api/src/autopilot/best.ts b/apps/api/src/autopilot/best.ts index 23959e6..bc7f63b 100644 --- a/apps/api/src/autopilot/best.ts +++ b/apps/api/src/autopilot/best.ts @@ -19,9 +19,10 @@ export const CANDIDATE_SELECT = { id: true, capturedAt: true, createdAt: true, c /** * One candidate per burst (its best frame), from the autopilot's analysis. Photos it never saw (autopilot off) are - * ranked by the photographer's own marks instead: stars, and picks. + * ranked by the photographer's own marks instead: stars, and picks. `frame: "second"` puts each burst forward by + * its second best frame instead (the best stays for another client), or its best when the burst has no usable second. */ -export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided: boolean): Candidate[] { +export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided: boolean, frame: "best" | "second" = "best"): Candidate[] { const frames = photos.map((p) => { const rec = p.autopilot as AutopilotRecord | null; const own = p.rating + (p.flag === "PICK" ? 1 : 0); @@ -30,7 +31,8 @@ export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided const out: Candidate[] = []; groupBursts(frames, burstGapMs).forEach((burst, i) => { if (onlyDecided && !burst.every((f) => f.rec?.decided)) return; - const best = bestOf(burst, 1)[0]; + const [first, second] = bestOf(burst, 2); + const best = frame === "second" && second && second.flag !== "REJECT" ? second : first; if (!best) return; const rec = best.rec; out.push({ diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index 385247c..cd8dccd 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -238,7 +238,10 @@ export class AutopilotService { const decided = photos .filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.curated) .map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen })); - const candidates = candidatesOf(photos, settings.burstGapSec * 1000, true); + // A second client: the gallery takes each moment's second pick, the rest of the picks go to the second client. + const restTarget = settings.restTargetId && settings.restTargetId !== settings.deliverTargetId ? settings.restTargetId : null; + const flags = new Map(photos.map((p) => [p.id, p.flag])); + const candidates = candidatesOf(photos, settings.burstGapSec * 1000, true, restTarget && settings.deliverTargetId ? "second" : "best"); const decisions = curate(candidates, decided, { count: settings.bestCount, start: event.startsAt.getTime(), durationMs: matchMinutes(event.sport) * 60_000, now: now.getTime() }); const records = new Map(photos.map((p) => [p.id, p.autopilot as unknown as AutopilotRecord | null])); // Frames that were not their burst's candidate are decided with it. @@ -253,10 +256,19 @@ export class AutopilotService { for (const d of decisions) { const chosen = new Set(d.chosen); const ids = new Set(d.ids.flatMap((id) => burstOf.get(id) ?? [id])); + const nowCurated: string[] = []; for (const id of ids) { const rec = records.get(id); if (!rec || rec.curated) continue; await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id) } as object } }); + nowCurated.push(id); + } + // Everything else picked in this window goes to the second client: never a photo the gallery got. + const rest = restOf(nowCurated, chosen, flags); + if (restTarget && rest.length && this.deps.deliveries && event.createdById) { + await this.deps.deliveries + .enqueue({ organizationId: event.organizationId, targetId: restTarget, photoIds: rest, again: false, requestedById: event.createdById }) + .catch((err: unknown) => log.warn({ err }, "autopilot: delivery to the second client not queued")); } chosenCount += chosen.size; if (chosen.size && settings.deliverTargetId && this.deps.deliveries && event.createdById) { @@ -270,6 +282,14 @@ export class AutopilotService { } } +/** + * The photos of a decided window that go to the second client: the picked ones (by the autopilot or a person) the + * gallery did not take. Never a chosen one, so no photo reaches both clients. + */ +export function restOf(ids: readonly string[], chosen: ReadonlySet, flags: ReadonlyMap): string[] { + return ids.filter((id) => !chosen.has(id) && flags.get(id) === "PICK"); +} + /** Polls the autopilot queue and settles bursts. */ export class AutopilotWorker { private timer: ReturnType | undefined; diff --git a/apps/api/test/autopilot.test.ts b/apps/api/test/autopilot.test.ts index 4565a39..31a20dd 100644 --- a/apps/api/test/autopilot.test.ts +++ b/apps/api/test/autopilot.test.ts @@ -11,6 +11,7 @@ import type { Detections } from "../src/composition/compose.js"; import type { SubjectDetector } from "../src/composition/detect.js"; import type { RenderEngine, RenderJob, Settings } from "../src/develop/engine.js"; import { DevelopService } from "../src/develop/service.js"; +import type { DeliveryService } from "../src/delivery/service.js"; import { IngestService } from "../src/ingest/service.js"; import { MemoryBroadcaster } from "../src/realtime.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; @@ -163,7 +164,7 @@ describe("autopilot", () => { }); let n = 0; - async function shot(orgId: string, userId: string, eventId: string, at: number, focus: number, source: "FTP" | "UPLOAD" = "FTP") { + async function shot(orgId: string, userId: string, eventId: string, at: number, focus: number, source: "FTP" | "UPLOAD" | "CLOUD" = "FTP") { n++; const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: (n * 31) % 256, g: 90, b: 120 } } }).jpeg().toBuffer(); const { createHash } = await import("node:crypto"); @@ -196,10 +197,10 @@ describe("autopilot", () => { for (let ids = await autopilot.claim(10); ids.length; ids = await autopilot.claim(10)) for (const id of ids) await autopilot.process(id); } - it("edits what arrives by FTP: measured tone, level, a crop around the subject; hand uploads stay as sent", async () => { + it("edits what arrives by FTP or by hand: measured tone, level, a crop around the subject; archive re-imports stay as sent", async () => { const { orgId, userId, eventId } = await setup(); const ftp = await shot(orgId, userId, eventId, 0, 300); - const hand = await shot(orgId, userId, eventId, 60_000, 300, "UPLOAD"); + const hand = await shot(orgId, userId, eventId, 60_000, 300, "CLOUD"); await runQueue(); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: ftp }, orderBy: { seq: "asc" } }); expect(edits.map((e) => (e.command as { command: string }).command)).toEqual(["develop.set", "crop.set"]); @@ -256,6 +257,36 @@ describe("autopilot", () => { expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK"); }); + it("two clients: the gallery takes each moment's second pick, every other pick goes to the second client, never both", async () => { + const { eventId, orgId, userId } = await setup(); + const start = new Date(1_800_000_000_000); + const record = "11111111-1111-4111-8111-111111111111"; + const fap = "22222222-2222-4222-8222-222222222222"; + await ctx.db.event.update({ + where: { id: eventId }, + data: { startsAt: start, sport: "andebol", createdById: userId, autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 16, deliverTargetId: record, restTargetId: fap } }, + }); + const sent: { targetId: string; photoIds: string[] }[] = []; + const deliveries = { enqueue: async (r: { targetId: string; photoIds: string[] }) => void sent.push({ targetId: r.targetId, photoIds: [...r.photoIds] }) }; + const service = new AutopilotService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, develop, engine: new FakeEngine(), detector: () => Promise.resolve(detector as unknown as SubjectDetector), deliveries: deliveries as unknown as DeliveryService }); + // Window 0 (one photo for the gallery): a strong burst and a weaker one. + const a1 = await shot(orgId, userId, eventId, 60_000, 900); + const a2 = await shot(orgId, userId, eventId, 60_100, 600); + const b1 = await shot(orgId, userId, eventId, 120_000, 300); + const b2 = await shot(orgId, userId, eventId, 120_100, 200); + for (let ids = await service.claim(10); ids.length; ids = await service.claim(10)) for (const id of ids) await service.process(id); + await service.decideBursts(new Date(start.getTime() + 7 * 60_000)); + const to = (target: string) => sent.filter((x) => x.targetId === target).flatMap((x) => x.photoIds); + // The newspaper gets the strong moment as its second frame; the federation gets every other pick. + expect(to(record)).toEqual([a2]); + expect(to(fap).sort()).toEqual([a1, b1, b2].sort()); + expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]); + // Decided once: nothing is sent again. + await service.decideBursts(new Date(start.getTime() + 8 * 60_000)); + expect(to(record)).toEqual([a2]); + expect(to(fap)).toHaveLength(3); + }); + it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => { const { orgId, userId, eventId } = await setup(); const photoId = await shot(orgId, userId, eventId, 0, 300); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 1834d21..62e447d 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -306,6 +306,9 @@ export const t = { selectionBest: "Só as melhores do jogo", bestCount: "Fotos na galeria (aprox.)", bestHelp: "Uma galeria curta de momentos de jogo: bola em jogo, duelos e festejos, jogadores grandes e nítidos no enquadramento, espalhados pelo jogo (a cada 5 minutos entram as melhores desse período). Aquecimento e intervalo ficam de fora; as fotos com estrelas têm prioridade e as rejeitadas nunca vão.", + restTarget: "As outras escolhidas para", + restHelp: + "Cada foto vai só para um cliente. A galeria acima leva a segunda melhor de cada sequência escolhida; todas as outras escolhidas seguem para aqui quando fecha cada período de 5 minutos.", learnt: "Aprendido com as tuas correções", learntHelp: (n: number, venue: string | null) => `${n} ${n === 1 ? "foto corrigida" : "fotos corrigidas"}${venue ? " neste recinto" : ""}. Aplica-se às próximas fotos que chegarem.`, learning: (n: number) => `A aprender: ${n} ${n === 1 ? "correção" : "correções"} até agora (a partir de 5 que concordem, as próximas fotos já chegam assim).`, diff --git a/apps/app/src/library/Autopilot.tsx b/apps/app/src/library/Autopilot.tsx index 52eb654..a9f3fe4 100644 --- a/apps/app/src/library/Autopilot.tsx +++ b/apps/app/src/library/Autopilot.tsx @@ -112,6 +112,27 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta )} {s.selection === "best" &&

{L.bestHelp}

} + {s.selection === "best" && ( + + )} + {s.selection === "best" && s.restTargetId &&

{L.restHelp}

} {s.deliverTargetId && props.targets.find((x) => x.id === s.deliverTargetId)?.kind === "ZEROZERO" && ( )} diff --git a/packages/contracts/src/library.ts b/packages/contracts/src/library.ts index cf5e2b9..8dfef73 100644 --- a/packages/contracts/src/library.ts +++ b/packages/contracts/src/library.ts @@ -49,6 +49,12 @@ export const AutopilotSettings = z.object({ */ selection: z.enum(["bursts", "best"]).default("bursts"), bestCount: z.number().int().min(5).max(300).default(30), + /** + * "Only the best" with a second client: every other picked photo goes here (e.g. the federation's cloud) once its + * window of the match is decided, while `deliverTargetId` gets the short gallery (e.g. a newspaper's FTP), each + * moment as the second pick of its burst. A photo never goes to both (null: no second client). + */ + restTargetId: z.string().uuid().nullable().default(null), }); export type AutopilotSettings = z.infer; -- 2.47.3 From d331ea15fdb46a0973f01645b8c4516b1db05143 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 11:01:43 +0000 Subject: [PATCH 2/4] Delivery: a client's own IPTC fields, and players left to right Each delivery target can now carry IPTC fields that replace the event's for that client only (e.g. Creator "Peter Spark / Movephoto" for a newspaper while the federation keeps PhotoReport.pt), with the event's variables. Applied after the event template and the photo's own changes. Edited in the target form ("IPTC deste cliente"). New column delivery_targets.iptc_overrides. {players} (Title, Persons shown...) now lists the players from left to right as they appear in the photo, by where their face is; names typed by hand without a face keep their order, after the others. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RL6fqg8fuk1vKF4H6Zrh9V --- .../migration.sql | 2 + apps/api/prisma/schema.prisma | 3 + apps/api/src/delivery/routes.ts | 23 +++-- apps/api/src/delivery/service.ts | 3 +- apps/api/src/library/iptc.ts | 35 +++++++- apps/api/test/delivery.test.ts | 35 ++++++++ apps/app/src/library/TargetForm.tsx | 87 ++++++++++++++++++- apps/app/src/library/targetOverrides.test.ts | 17 ++++ packages/sdk/src/types.ts | 4 + 9 files changed, 193 insertions(+), 16 deletions(-) create mode 100644 apps/api/prisma/migrations/20261018120000_target_iptc_overrides/migration.sql create mode 100644 apps/app/src/library/targetOverrides.test.ts diff --git a/apps/api/prisma/migrations/20261018120000_target_iptc_overrides/migration.sql b/apps/api/prisma/migrations/20261018120000_target_iptc_overrides/migration.sql new file mode 100644 index 0000000..0d4f226 --- /dev/null +++ b/apps/api/prisma/migrations/20261018120000_target_iptc_overrides/migration.sql @@ -0,0 +1,2 @@ +-- IPTC fields a delivery target gets instead of the event template's. +ALTER TABLE "delivery_targets" ADD COLUMN "iptc_overrides" JSONB; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 66c34ad..c5eb188 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -558,6 +558,9 @@ model DeliveryTarget { arrivalLogins String[] @default([]) @map("arrival_logins") @db.Uuid /// With `originals`: the file exactly as it arrived (no metadata written), for a local Live Ingest to take. untouched Boolean @default(false) + /// IPTC fields this client gets instead of the event's (packages/metadata IptcTemplate, partial; variables allowed): + /// e.g. the agency a photographer works for at this client in Creator, or `{players}` in Title. Applied last. + iptcOverrides Json? @map("iptc_overrides") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") disabledAt DateTime? @map("disabled_at") diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index ff34654..bf2ae8b 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -1,13 +1,13 @@ import { createReadStream } from "node:fs"; import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts"; import { bestOfEvent } from "../autopilot/best.js"; -import { PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata"; +import { IptcTemplate, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; -import type { DeliveryTarget } from "../generated/prisma/client.js"; +import { type DeliveryTarget, Prisma } from "../generated/prisma/client.js"; import { compact } from "../lib/compact.js"; import { AppError, badRequest, conflict, notFound } from "../lib/errors.js"; import { DeliveryRejected, type DeliveryService, toItemSummary } from "./service.js"; @@ -54,6 +54,8 @@ const TargetBase = z.object({ arrivalLogins: z.array(z.uuid()).max(100), /** With originals: the file exactly as it arrived, no metadata written. */ untouched: z.boolean(), + /** IPTC fields this client gets instead of the event's (variables allowed); null: none. */ + iptcOverrides: IptcTemplate.partial().nullable(), }); const checkAddress = (kind: z.infer, baseUrl: string, username: string) => { if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`); @@ -72,6 +74,7 @@ const TargetFields = TargetBase.extend({ onArrival: TargetBase.shape.onArrival.default(false), arrivalLogins: TargetBase.shape.arrivalLogins.default([]), untouched: TargetBase.shape.untouched.default(false), + iptcOverrides: TargetBase.shape.iptcOverrides.default(null), }); const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() }); const ListQuery = z.object({ @@ -85,6 +88,11 @@ const GameQuery = z.object({ eventId: z.uuid() }); /** A link or an id from fotos.zerozero.pt; null: forget the choice (and look it up again). */ const GameBody = z.object({ eventId: z.uuid(), game: z.string().trim().min(1).max(300).nullable() }); +/** A target's own IPTC fields as stored: none when empty (a JSON column takes DbNull, not null). */ +function overridesValue(o: unknown): Prisma.InputJsonValue | typeof Prisma.DbNull { + return o && typeof o === "object" && Object.keys(o).length ? (o as Prisma.InputJsonValue) : Prisma.DbNull; +} + function publicTarget(t: DeliveryTarget) { const { secretEnc: _secret, ...rest } = t; return { ...rest, shareLinks: t.kind === "NEXTCLOUD" || t.kind === "DROPBOX" }; @@ -143,10 +151,10 @@ export async function registerDeliveryRoutes( checkAddress(body.kind, body.baseUrl, body.username); const example = checkTemplates(body.folderTemplate, body.fileNameTemplate); if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken"); - const { password, ...fields } = body; + const { password, iptcOverrides, ...fields } = body; if (!password && body.kind !== "LOCAL") throw badRequest("password_required"); await checkLogins(orgId, body.arrivalLogins); - const target = await db.deliveryTarget.create({ data: { ...fields, organizationId: orgId, secretEnc: seal(password ?? "") } }); + const target = await db.deliveryTarget.create({ data: { ...fields, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } }); return reply.code(201).send({ ...publicTarget(target), example }); }); @@ -162,12 +170,13 @@ export async function registerDeliveryRoutes( checkAddress(kind, baseUrl, body.username ?? current.username); // Another server, another key: a changed address forgets the remembered one. const forgetKey = body.resetHostKey === true || kind !== current.kind || baseUrl !== current.baseUrl; - const { password, disabled, resetHostKey: _reset, ...fields } = body; + const { password, disabled, resetHostKey: _reset, iptcOverrides, ...fields } = body; if (fields.arrivalLogins) await checkLogins(orgId, fields.arrivalLogins); const target = await db.deliveryTarget.update({ where: { id: targetId }, data: { ...compact(fields), + ...(iptcOverrides !== undefined && { iptcOverrides: overridesValue(iptcOverrides) }), ...(password !== undefined && { secretEnc: seal(password) }), ...(forgetKey && { hostFingerprint: null }), ...(disabled !== undefined && { disabledAt: disabled ? (current.disabledAt ?? new Date()) : null }), @@ -186,8 +195,8 @@ export async function registerDeliveryRoutes( if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken"); const folderTemplate = body.folderTemplate ?? source.folderTemplate; const example = checkTemplates(folderTemplate, source.fileNameTemplate); - const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, ...copy } = source; - const target = await db.deliveryTarget.create({ data: { ...copy, name: body.name, folderTemplate } }); + const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, ...copy } = source; + const target = await db.deliveryTarget.create({ data: { ...copy, iptcOverrides: overridesValue(iptcOverrides), name: body.name, folderTemplate } }); return reply.code(201).send({ ...publicTarget(target), example }); }); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 357a9a6..05b2334 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -344,7 +344,8 @@ export class DeliveryService { } try { // The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad. - const iptc = await iptcForPhoto(db, item.photoId); + // With this client's own fields on top (another agency in Creator, players left to right in Title...). + const iptc = await iptcForPhoto(db, item.photoId, 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. const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null)); diff --git a/apps/api/src/library/iptc.ts b/apps/api/src/library/iptc.ts index 3112a0e..9462771 100644 --- a/apps/api/src/library/iptc.ts +++ b/apps/api/src/library/iptc.ts @@ -11,11 +11,35 @@ export const DEFAULT_CODE_LIST = "default"; * the photographer's name, with the organization's code list expanded. Used by the preview and by deliveries, * so what an editor sees is what the client receives. */ -export async function iptcForPhoto(db: Db, photoId: string): Promise<(ApplyResult & { organizationId: string }) | undefined> { - const photo = await db.photo.findUnique({ where: { id: photoId }, include: { event: true, uploader: { select: { name: true } } } }); +export async function iptcForPhoto(db: Db, photoId: string, targetOverrides?: unknown): Promise<(ApplyResult & { organizationId: string }) | undefined> { + const photo = await db.photo.findUnique({ + where: { id: photoId }, + include: { event: true, uploader: { select: { name: true } }, faces: { select: { x0: true, x1: true, group: { select: { person: { select: { name: true } } } } } } }, + }); if (!photo) return undefined; if (!photo.event) return { organizationId: photo.organizationId, values: {}, issues: [] }; - return { organizationId: photo.organizationId, ...iptcOf(photo, photo.event, photo.uploader?.name, await codeListOf(db, photo.organizationId)) }; + const players = leftToRight(photo.players, photo.faces.map((f) => ({ x0: f.x0, x1: f.x1, name: f.group?.person?.name }))); + return { organizationId: photo.organizationId, ...iptcOf({ ...photo, players }, photo.event, photo.uploader?.name, await codeListOf(db, photo.organizationId), targetOverrides) }; +} + +/** + * The players as they appear in the photo, from left to right (the newsroom convention for Title and captions): + * by where their face is. Names without a face in the photo (typed by hand) keep their order, after the others. + */ +export function leftToRight(players: readonly string[], faces: readonly { x0: number; x1: number; name: string | null | undefined }[]): string[] { + const at = (player: string) => { + let best: number | undefined; + for (const f of faces) { + if (!f.name || !(player === f.name || player.startsWith(`${f.name} (`))) continue; + const centre = (f.x0 + f.x1) / 2; + if (best === undefined || centre < best) best = centre; + } + return best; + }; + const placed = players.map((p, i) => ({ p, i, x: at(p) })); + return placed + .sort((a, b) => (a.x === undefined ? (b.x === undefined ? a.i - b.i : 1) : b.x === undefined ? -1 : a.x - b.x || a.i - b.i)) + .map((x) => x.p); } /** The organization's code list, parsed (undefined when it has none). */ @@ -30,8 +54,11 @@ export function iptcOf( event: Event, photographer: string | null | undefined, codes: CodeList | undefined, + targetOverrides?: unknown, ): ApplyResult { - const template = { ...IptcTemplate.parse(event.iptcTemplate), ...IptcTemplate.partial().parse(photo.iptcOverrides ?? {}) }; + // The event's pad, the photo's own changes, then what this client always gets (its Creator, its Title...). + const target = IptcTemplate.partial().safeParse(targetOverrides ?? {}); + const template = { ...IptcTemplate.parse(event.iptcTemplate), ...IptcTemplate.partial().parse(photo.iptcOverrides ?? {}), ...(target.success ? target.data : {}) }; // Photo Mechanic's IPTC variables ({caption}, {headline}...) in the pad are the photo's own, as it arrived. const embedded = photo.embeddedIptc && typeof photo.embeddedIptc === "object" ? (photo.embeddedIptc as Record) : {}; const vars = buildVars(eventInfoOf(event), photoInfoOf(photo), photographer ?? undefined, { iptc: embedded }); diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index 6b9ecb1..5c2c8f5 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -318,6 +318,41 @@ describe("delivery", () => { expect((resend.json() as { queued: { sequence: number }[] }).queued[0]?.sequence).toBe(3); // numbers are never reused }); + it("a client's own IPTC: its agency in Creator, and the players in Title from left to right", async () => { + const { orgId, token, target, eventId } = await setup(); + const saved = await ctx.app.inject({ + method: "PATCH", + url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, + headers: bearer(token), + payload: { iptcOverrides: { creator: "Peter Spark / Movephoto", title: "{players}" } }, + }); + expect(saved.statusCode).toBe(200); + expect((saved.json() as { iptcOverrides: unknown }).iptcOverrides).toEqual({ creator: "Peter Spark / Movephoto", title: "{players}" }); + const id = await photo("a.jpg", "2026:09:23 21:10:00"); + // Identified right one first: the photo lists them in that order; on the photo, Rui is on the left. + await ctx.db.photo.update({ where: { id }, data: { players: ["Miguel Silva (VSC)", "Rui Costa (AAAS)"] } }); + for (const [name, x0] of [ + ["Miguel Silva", 0.7], + ["Rui Costa", 0.1], + ] as const) { + const person = await ctx.db.person.create({ data: { organizationId: orgId, name } }); + const group = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, personId: person.id, model: "test" } }); + await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: group.id, x0, y0: 0.2, x1: x0 + 0.1, y1: 0.4, score: 0.9, model: "test" } }); + } + await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } }); + await drain(); + const out = path.join(dir, "client.jpg"); + await writeFile(out, [...nc.files.values()][0]!); + const tags = (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record; + expect(tags["IPTC:By-line"]).toBe("Peter Spark / Movephoto"); + expect(tags["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)"); + // The rest is the event's, as before. + expect(tags["IPTC:Caption-Abstract"]).toBe("VSC x AAAS, em Guimarães, no Pavilhão"); + // Cleared: back to the event's photographer. + const cleared = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, headers: bearer(token), payload: { iptcOverrides: null } }); + expect((cleared.json() as { iptcOverrides: unknown }).iptcOverrides).toBeNull(); + }); + it("ZeroZero: signs in, finds the event's game, and uploads with the photographer as author", async () => { const { orgId, token } = await setup(); const event = ( diff --git a/apps/app/src/library/TargetForm.tsx b/apps/app/src/library/TargetForm.tsx index b28687b..1bc8b1c 100644 --- a/apps/app/src/library/TargetForm.tsx +++ b/apps/app/src/library/TargetForm.tsx @@ -1,4 +1,4 @@ -import { DESTINATION_EXAMPLES } from "@photoreport/metadata"; +import { DESTINATION_EXAMPLES, IPTC_FIELDS } from "@photoreport/metadata"; import { ApiError, type ApiClient, @@ -13,6 +13,28 @@ import { isDesktop } from "../platform.js"; const SIZES = [12000, 6000, 4000, 3500, 3000, 2000]; +type OverrideRow = { key: string; value: string }; +const listField = (key: string) => IPTC_FIELDS.find((f) => f.key === key)?.list ?? false; +/** The target's own IPTC fields as editable rows (lists as comma-separated text). */ +function overrideRows(o: Record | null | undefined): OverrideRow[] { + return Object.entries(o ?? {}).map(([key, v]) => ({ key, value: Array.isArray(v) ? v.join(", ") : v })); +} +/** Back to the API's shape: empty rows dropped, lists split on commas; null when nothing is left. */ +export function overridesOf(rows: readonly OverrideRow[]): Record | null { + const out: Record = {}; + for (const { key, value } of rows) { + const v = value.trim(); + if (!key || !v) continue; + out[key] = listField(key) + ? v + .split(",") + .map((x) => x.trim()) + .filter(Boolean) + : v; + } + return Object.keys(out).length ? out : null; +} + /** Where each kind connects, and what its user and secret fields mean. */ const KINDS: Record< DeliveryKind, @@ -158,6 +180,8 @@ export function TargetForm({ arrivalLogins: target?.arrivalLogins ?? ([] as string[]), untouched: target?.untouched ?? false, }); + // IPTC fields this client always gets instead of the event's (e.g. another agency in Creator). + const [overrides, setOverrides] = useState(() => overrideRows(target?.iptcOverrides)); // The FTP logins whose arrivals this destination can take (a relay to one's computer). const [logins, setLogins] = useState([]); useEffect(() => { @@ -202,15 +226,19 @@ export function TargetForm({ e.preventDefault(); setBusy(true); setError(null); - const { password, ...rest } = v; + const { password: _pw, ...base } = v; + const iptcOverrides = overridesOf(overrides); + const password = v.password; + const rest = { ...base, iptcOverrides }; + const all = { ...v, iptcOverrides }; if (v.kind === "LOCAL" && !v.baseUrl) { setBusy(false); setError("Escolhe a pasta."); return; } (target - ? api.updateDeliveryTarget(orgId, target.id, password ? v : rest) - : api.createDeliveryTarget(orgId, v.kind === "LOCAL" ? rest : v) + ? api.updateDeliveryTarget(orgId, target.id, password ? all : rest) + : api.createDeliveryTarget(orgId, v.kind === "LOCAL" ? rest : all) ).then( (target) => onCreated(target), (err) => { @@ -475,6 +503,57 @@ export function TargetForm({ )} + {!(v.originals && v.untouched) && ( +
+ + IPTC deste cliente (substitui o do evento) + +

+ Por exemplo Creator/Photographer com a agência para quem trabalhas neste cliente. Aceita as variáveis + do evento: {"{players}"} dá os jogadores da esquerda para a direita + na foto. Nas listas (Keywords…) separa por vírgulas. +

+ {overrides.map((row, i) => ( +
+ + setOverrides(overrides.map((r, j) => (j === i ? { ...r, value: e.target.value } : r)))} + /> + +
+ ))} + +
+ )} {!v.originals && (
diff --git a/apps/app/src/library/targetOverrides.test.ts b/apps/app/src/library/targetOverrides.test.ts new file mode 100644 index 0000000..2588ccf --- /dev/null +++ b/apps/app/src/library/targetOverrides.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; +import { overridesOf } from "./TargetForm.js"; + +describe("a client's own IPTC fields", () => { + it("keeps filled rows, splits lists on commas, and is null when nothing is left", () => { + expect( + overridesOf([ + { key: "creator", value: " Peter Spark / Movephoto " }, + { key: "title", value: "{players}" }, + { key: "keywords", value: "ANDEBOL, PO01 ,," }, + { key: "credit", value: " " }, + { key: "", value: "sem campo" }, + ]), + ).toEqual({ creator: "Peter Spark / Movephoto", title: "{players}", keywords: ["ANDEBOL", "PO01"] }); + expect(overridesOf([{ key: "creator", value: "" }])).toBeNull(); + }); +}); diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 01dcd19..98a2e1d 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -249,6 +249,8 @@ export interface DeliveryTarget { arrivalLogins?: string[]; /** With originals: the file exactly as it arrived (no metadata written, the camera's name). */ untouched?: boolean; + /** IPTC fields this client gets instead of the event's (variables allowed); null: none. */ + iptcOverrides?: Record | null; username: string; folderTemplate: string; fileNameTemplate: string; @@ -312,6 +314,8 @@ export interface DeliveryTargetInput { onArrival?: boolean; arrivalLogins?: string[]; untouched?: boolean; + /** IPTC fields this client gets instead of the event's; null: none. */ + iptcOverrides?: Record | null; } export interface PersonSummary { -- 2.47.3 From 7faf2dc1efb56ec3fbdb74658b6de7028c113a4d Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 10:44:58 +0000 Subject: [PATCH 3/4] Develop: X swaps the crop's width and height, like Lightroom The second X turned the biggest portrait back into the whole frame, which looked like the crop was gone. X now swaps the crop's width and height in pixels about the same centre (moved in, then shrunk keeping its shape, only when the turned crop would leave the photo): R, X gives 2667x4000 on a 6000x4000 photo, the next X 4000x2667, and further presses swap between the two. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RL6fqg8fuk1vKF4H6Zrh9V --- apps/app/src/develop/crop.test.ts | 29 +++++++++++++++++++++++------ apps/app/src/develop/crop.ts | 10 +++++----- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/apps/app/src/develop/crop.test.ts b/apps/app/src/develop/crop.test.ts index 7dcf826..28a9b34 100644 --- a/apps/app/src/develop/crop.test.ts +++ b/apps/app/src/develop/crop.test.ts @@ -142,18 +142,35 @@ describe("dragging a crop handle (LightCraft's drag_crop)", () => { }); describe("X: swapping portrait and landscape", () => { - it("the whole 3:2 frame becomes the biggest 2:3, and back to the whole frame", () => { + it("R, X, X, X: the whole 3:2 frame becomes the biggest 2:3, then swaps with a 3:2 of the same size, back and forth", () => { + const px = (r: Rect) => [Math.round((r.x1 - r.x0) * W * 1000), Math.round((r.y1 - r.y0) * H * 1000)]; const full = { x0: 0, y0: 0, x1: 1, y1: 1 }; const tall = rotateAspect(full, 0, W, H); close(pxRatio(tall), 2 / 3); close(tall.y0, 0); close(tall.y1, 1); close((tall.x0 + tall.x1) / 2, 0.5); - const back = rotateAspect(tall, 0, W, H); - close(back.x0, 0); - close(back.x1, 1); - close(back.y0, 0); - close(back.y1, 1); + // The second X keeps that size, turned: not the whole frame again (which looked like the crop was gone). + const wide = rotateAspect(tall, 0, W, H); + expect(px(wide)).toEqual([px(tall)[1], px(tall)[0]]); + close((wide.x0 + wide.x1) / 2, 0.5); + close((wide.y0 + wide.y1) / 2, 0.5); + expect(wide.x1 - wide.x0).toBeLessThan(1); + // Further presses only swap between the two. + for (let i = 0; i < 4; i++) { + expect(px(rotateAspect(wide, 0, W, H))).toEqual(px(tall)); + expect(px(rotateAspect(tall, 0, W, H))).toEqual(px(wide)); + } + }); + + it("a crop that would not fit turned is moved in, then shrunk keeping its shape", () => { + // A landscape crop at the left edge: turned, it is taller than the photo allows there. + const r = { x0: 0, y0: 0.1, x1: 0.8, y1: 0.9 }; + const t = rotateAspect(r, 0, W, H); + expect(t.x0).toBeGreaterThanOrEqual(0); + expect(t.y0).toBeGreaterThanOrEqual(0); + expect(t.y1).toBeLessThanOrEqual(1); + close(pxRatio(t), 1 / pxRatio(r)); }); it("a small crop turns in place, keeping its centre", () => { diff --git a/apps/app/src/develop/crop.ts b/apps/app/src/develop/crop.ts index 3c2dc59..3d2a425 100644 --- a/apps/app/src/develop/crop.ts +++ b/apps/app/src/develop/crop.ts @@ -244,15 +244,15 @@ function lockedDrag(sr: Rect, hd: Handle, dx: number, dy: number, a: number, w: } /** - * Lightroom's X: the crop turns between landscape and portrait, keeping its centre and its size relative to the - * biggest crop of its shape (a full-frame 3:2 becomes the biggest 2:3 and back), kept on the photo. + * Lightroom's X: the crop turns between landscape and portrait, swapping its width and height in pixels about the + * same centre. Only when the turned crop would leave the photo is it moved in and, if still needed, shrunk keeping + * its shape. So R, X turns the whole 6000x4000 frame into the biggest 2667x4000 portrait, the next X gives a + * 4000x2667 landscape of the same size (not the whole frame again), and further presses swap between those two. */ export function rotateAspect(r: Rect, angle: number, w: number, h: number): Rect { const [pw, ph] = [width(r) * w, height(r) * h]; if (!(pw > 0 && ph > 0)) return r; - const k = Math.min(1, 1 / maxInscribedScale(w, h, angle, pw, ph)); - const s = maxInscribedScale(w, h, angle, ph, pw) * k; - const next = fromCentre(centre(r), (ph * s) / w, (pw * s) / h); + const next = fromCentre(centre(r), ph / w, pw / h); return clampUnit(constrainRotated(next, angle, w, h)); } -- 2.47.3 From a824c7bef695b4bb942ff141351d47570eaa16b1 Mon Sep 17 00:00:00 2001 From: spark Date: Sun, 18 Oct 2026 11:13:27 +0000 Subject: [PATCH 4/4] Delivery: names from the best guess, a local copy of a client's delivery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - {players} names every face: the confirmed player, or for a face nobody has confirmed yet the group's suggestion (face and shirt number). Put right later by confirming the right player. - A delivery waits up to 3 minutes for the photo's faces to be read (organizations with face recognition), so the names leave with it; waiting is not an attempt. - A target can copy everything it gets to another target ("Copiar também para", usually a folder on the computer). The copy is written with the first target's IPTC, so it is the same file the client got. New columns delivery_targets.copy_target_id and delivery_items.via_target_id. Also updates the resumable upload test to the current rule (hand uploads are edited by the autopilot too). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RL6fqg8fuk1vKF4H6Zrh9V --- .../migration.sql | 4 ++ apps/api/prisma/schema.prisma | 5 ++ apps/api/src/delivery/routes.ts | 11 +++ apps/api/src/delivery/service.ts | 38 ++++++++++- apps/api/src/library/iptc.ts | 23 ++++++- apps/api/test/delivery.test.ts | 68 +++++++++++++++++++ apps/api/test/resumable.test.ts | 4 +- apps/app/src/library/TargetForm.tsx | 29 ++++++++ packages/sdk/src/types.ts | 3 + 9 files changed, 178 insertions(+), 7 deletions(-) create mode 100644 apps/api/prisma/migrations/20261018130000_delivery_local_copy/migration.sql diff --git a/apps/api/prisma/migrations/20261018130000_delivery_local_copy/migration.sql b/apps/api/prisma/migrations/20261018130000_delivery_local_copy/migration.sql new file mode 100644 index 0000000..87159b0 --- /dev/null +++ b/apps/api/prisma/migrations/20261018130000_delivery_local_copy/migration.sql @@ -0,0 +1,4 @@ +-- A target can send a copy of everything it gets to another target (a folder on a computer). +ALTER TABLE "delivery_targets" ADD COLUMN "copy_target_id" UUID; +-- The copy's item remembers which target it copies (its IPTC is that target's). +ALTER TABLE "delivery_items" ADD COLUMN "via_target_id" UUID; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index c5eb188..0695de4 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -561,6 +561,9 @@ model DeliveryTarget { /// IPTC fields this client gets instead of the event's (packages/metadata IptcTemplate, partial; variables allowed): /// e.g. the agency a photographer works for at this client in Creator, or `{players}` in Title. Applied last. iptcOverrides Json? @map("iptc_overrides") + /// Everything sent here is also sent to this target (usually a folder on a computer), with this target's IPTC: + /// a local copy of what a client got. Same organization; null: none. + copyTargetId String? @map("copy_target_id") @db.Uuid createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") disabledAt DateTime? @map("disabled_at") @@ -581,6 +584,8 @@ model DeliveryItem { eventId String @map("event_id") @db.Uuid /// Position in this event's delivery to this target: the {n} in file names. Never reused. sequence Int + /// A copy of a delivery to that target (its `copyTargetId`): written with that target's IPTC, so it is the same file. + viaTargetId String? @map("via_target_id") @db.Uuid status DeliveryStatus @default(QUEUED) attempts Int @default(0) lastError String? @map("last_error") diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index bf2ae8b..b166d7e 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -56,6 +56,8 @@ const TargetBase = z.object({ untouched: z.boolean(), /** IPTC fields this client gets instead of the event's (variables allowed); null: none. */ iptcOverrides: IptcTemplate.partial().nullable(), + /** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC; null: none. */ + copyTargetId: z.uuid().nullable(), }); const checkAddress = (kind: z.infer, baseUrl: string, username: string) => { if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`); @@ -75,6 +77,7 @@ const TargetFields = TargetBase.extend({ arrivalLogins: TargetBase.shape.arrivalLogins.default([]), untouched: TargetBase.shape.untouched.default(false), iptcOverrides: TargetBase.shape.iptcOverrides.default(null), + copyTargetId: TargetBase.shape.copyTargetId.default(null), }); const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() }); const ListQuery = z.object({ @@ -125,6 +128,12 @@ export async function registerDeliveryRoutes( const found = await db.ftpAccount.count({ where: { organizationId: orgId, id: { in: ids } } }); if (found !== new Set(ids).size) throw badRequest("unknown_ftp_login"); }; + /** A copy goes to another of the organisation's targets, never back to itself. */ + const checkCopy = async (orgId: string, selfId: string | null, copyId: string | null | undefined) => { + if (!copyId) return; + if (copyId === selfId) throw badRequest("copy_to_itself"); + if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId } }))) throw badRequest("unknown_copy_target"); + }; const seal = (password: string) => { if (!secrets) throw new AppError(503, "delivery_not_configured", "DELIVERY_SECRET_KEY is not set"); return secrets.seal(password); @@ -154,6 +163,7 @@ export async function registerDeliveryRoutes( const { password, iptcOverrides, ...fields } = body; if (!password && body.kind !== "LOCAL") throw badRequest("password_required"); await checkLogins(orgId, body.arrivalLogins); + await checkCopy(orgId, null, body.copyTargetId); const target = await db.deliveryTarget.create({ data: { ...fields, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } }); return reply.code(201).send({ ...publicTarget(target), example }); }); @@ -172,6 +182,7 @@ export async function registerDeliveryRoutes( const forgetKey = body.resetHostKey === true || kind !== current.kind || baseUrl !== current.baseUrl; const { password, disabled, resetHostKey: _reset, iptcOverrides, ...fields } = body; if (fields.arrivalLogins) await checkLogins(orgId, fields.arrivalLogins); + if (fields.copyTargetId !== undefined) await checkCopy(orgId, targetId, fields.copyTargetId); const target = await db.deliveryTarget.update({ where: { id: targetId }, data: { diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 05b2334..ad2a2f9 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -23,6 +23,9 @@ 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. */ +export const FACES_WAIT_MS = 3 * 60_000; +export const FACES_ASK_MS = 20_000; /** 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. */ @@ -137,7 +140,15 @@ export class DeliveryService { } } - async enqueue(input: { organizationId: string; targetId: string; photoIds: string[]; again: boolean; requestedById: string | null }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> { + async enqueue(input: { + organizationId: string; + targetId: string; + photoIds: string[]; + again: boolean; + requestedById: string | null; + /** Set when this is the local copy of a delivery to that target. */ + via?: string; + }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> { const { db } = this.deps; const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } }); if (!target) throw new DeliveryRejected("target_not_found"); @@ -179,7 +190,7 @@ export class DeliveryService { for (const photo of group) { created.push( await tx.deliveryItem.create({ - data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence: next++, requestedById: input.requestedById }, + data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence: next++, requestedById: input.requestedById, viaTargetId: input.via ?? null }, }), ); } @@ -188,6 +199,12 @@ export class DeliveryService { queued.push(...items); } for (const item of queued) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) }); + // A copy of what this client gets, e.g. in a folder on the photographer's computer (one level: a copy is not copied). + if (target.copyTargetId && target.copyTargetId !== target.id && !input.via && queued.length) { + await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds: queued.map((q) => q.photoId), via: target.id }).catch((err: unknown) => + this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: local copy not queued"), + ); + } return { queued, skipped }; } @@ -322,6 +339,19 @@ export class DeliveryService { return saved; } let update: Partial; + // 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")) { + const org = await db.organization.findUnique({ where: { id: item.organizationId }, select: { biometricsEnabled: true } }); + if (org?.biometricsEnabled) { + const saved = await db.deliveryItem.update({ + where: { id: itemId }, + data: { status: "QUEUED", attempts: Math.max(0, item.attempts - 1), lastError: "waiting_for_faces", nextAttemptAt: new Date(Date.now() + FACES_ASK_MS) }, + }); + this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) }); + return saved; + } + } // An archive photo: its original is read from the cloud it lives on. let cloud: { file: string; done: () => Promise } | null = null; if (!item.photo.originalStored && this.deps.originals) { @@ -345,7 +375,9 @@ export class DeliveryService { try { // The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad. // With this client's own fields on top (another agency in Creator, players left to right in Title...). - const iptc = await iptcForPhoto(db, item.photoId, item.target.iptcOverrides); + // A local copy of another client's delivery is written with that client's IPTC: the same file it got. + const via = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId }, select: { iptcOverrides: true } }) : null; + const iptc = await iptcForPhoto(db, item.photoId, via ? via.iptcOverrides : 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. const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null)); diff --git a/apps/api/src/library/iptc.ts b/apps/api/src/library/iptc.ts index 9462771..53d4b1b 100644 --- a/apps/api/src/library/iptc.ts +++ b/apps/api/src/library/iptc.ts @@ -14,14 +14,33 @@ export const DEFAULT_CODE_LIST = "default"; export async function iptcForPhoto(db: Db, photoId: string, targetOverrides?: unknown): Promise<(ApplyResult & { organizationId: string }) | undefined> { const photo = await db.photo.findUnique({ where: { id: photoId }, - include: { event: true, uploader: { select: { name: true } }, faces: { select: { x0: true, x1: true, group: { select: { person: { select: { name: true } } } } } } }, + include: { + event: true, + uploader: { select: { name: true } }, + faces: { select: { x0: true, x1: true, group: { select: { ignoredAt: true, person: { select: { name: true } }, suggested: { select: { name: true } } } } } }, + }, }); if (!photo) return undefined; if (!photo.event) return { organizationId: photo.organizationId, values: {}, issues: [] }; - const players = leftToRight(photo.players, photo.faces.map((f) => ({ x0: f.x0, x1: f.x1, name: f.group?.person?.name }))); + const faces = photo.faces.map((f) => ({ x0: f.x0, x1: f.x1, name: f.group && !f.group.ignoredAt ? (f.group.person?.name ?? f.group.suggested?.name) : undefined })); + const players = leftToRight(withSuggested(photo.players, faces), faces); return { organizationId: photo.organizationId, ...iptcOf({ ...photo, players }, photo.event, photo.uploader?.name, await codeListOf(db, photo.organizationId), targetOverrides) }; } +/** + * The players named on the photo (confirmed, or typed by hand) plus the best guess for each face nobody has + * confirmed yet (face and shirt number: the group's suggestion). Sent as is; a wrong guess is put right later by + * confirming the right player. + */ +export function withSuggested(players: readonly string[], faces: readonly { name: string | null | undefined }[]): string[] { + const out = [...players]; + for (const f of faces) { + if (!f.name || out.some((p) => p === f.name || p.startsWith(`${f.name} (`))) continue; + out.push(f.name); + } + return out; +} + /** * The players as they appear in the photo, from left to right (the newsroom convention for Title and captions): * by where their face is. Names without a face in the photo (typed by hand) keep their order, after the others. diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index 5c2c8f5..b77bde1 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -353,6 +353,74 @@ describe("delivery", () => { expect((cleared.json() as { iptcOverrides: unknown }).iptcOverrides).toBeNull(); }); + it("names the best guess (face and shirt) without waiting for anyone to confirm, and keeps a copy on the computer", async () => { + const { orgId, token, target, eventId } = await setup(); + const local = ( + await ctx.app.inject({ + method: "POST", + url: `/v1/orgs/${orgId}/delivery-targets`, + headers: bearer(token), + payload: { name: "Cópia Record", kind: "LOCAL", baseUrl: "/Users/peter/Record", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" }, + }) + ).json() as { id: string }; + expect( + (await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, headers: bearer(token), payload: { copyTargetId: target.id } })).json(), + ).toMatchObject({ error: "copy_to_itself" }); + const saved = await ctx.app.inject({ + method: "PATCH", + url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, + headers: bearer(token), + payload: { copyTargetId: local.id, iptcOverrides: { creator: "Peter Spark / Movephoto", title: "{players}" } }, + }); + expect((saved.json() as { copyTargetId: string }).copyTargetId).toBe(local.id); + + const id = await photo("guess.jpg", "2026:09:23 21:10:00"); + // Nobody confirmed: one face is only suggested (face and shirt agree), the other was confirmed earlier. + const guessed = await ctx.db.person.create({ data: { organizationId: orgId, name: "Rui Costa (AAAS)" } }); + const known = await ctx.db.person.create({ data: { organizationId: orgId, name: "Miguel Silva (VSC)" } }); + const g1 = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, suggestedPersonId: guessed.id, suggestionScore: 0.9, model: "test" } }); + const g2 = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, personId: known.id, model: "test" } }); + await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: g2.id, x0: 0.6, y0: 0.2, x1: 0.7, y1: 0.4, score: 0.9, model: "test" } }); + await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: g1.id, x0: 0.1, y0: 0.2, x1: 0.2, y1: 0.4, score: 0.9, model: "test" } }); + await ctx.db.photo.update({ where: { id }, data: { players: ["Miguel Silva (VSC)"] } }); + + await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } }); + await drain(); + const read = async (data: Buffer, name: string) => { + const out = path.join(dir, name); + await writeFile(out, data); + return (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record; + }; + const sent = await read([...nc.files.values()][0]!, "record.jpg"); + expect(sent["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)"); + expect(sent["IPTC:By-line"]).toBe("Peter Spark / Movephoto"); + + // The copy on the computer is the same file the client got (its IPTC, not the event's). + const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId: local.id } }); + expect([copy.status, copy.viaTargetId]).toEqual(["WAITING", target.id]); + const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${copy.id}/local-file`, headers: bearer(token) }); + const copied = await read(file.rawPayload, "copy.jpg"); + expect(copied["IPTC:By-line"]).toBe("Peter Spark / Movephoto"); + expect(copied["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)"); + }); + + it("waits a little for the faces to be read before sending, so the names go with the photo", 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"); + 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] } }); + 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("ZeroZero: signs in, finds the event's game, and uploads with the photographer as author", async () => { const { orgId, token } = await setup(); const event = ( diff --git a/apps/api/test/resumable.test.ts b/apps/api/test/resumable.test.ts index 3a85dcc..e7cfd8f 100644 --- a/apps/api/test/resumable.test.ts +++ b/apps/api/test/resumable.test.ts @@ -107,7 +107,7 @@ describe("resumable uploads", () => { expect((await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) })).statusCode).toBe(200); }); - it("counts a full original from the desktop app's FTP as camera ingest (the autopilot edits it), not a hand upload", async () => { + it("counts a full original from the desktop app's FTP as camera ingest; the autopilot edits hand uploads too", async () => { const { org } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); const token = (await login(ctx.app, "foto@fpa.pt")).body.accessToken; const t = new Date("2026-10-13T15:00:00Z"); @@ -119,7 +119,7 @@ describe("resumable uploads", () => { return ctx.db.photo.findUniqueOrThrow({ where: { id: (done.json() as { photo: { id: string } }).photo.id } }); }; expect(await send("FTP_0001.JPG", { desktop: true })).toMatchObject({ source: "DESKTOP", autopilotStatus: "PENDING" }); - expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "NONE" }); + expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "PENDING" }); }); it("a photo that failed (a damaged file) is replaced when it is sent again", async () => { diff --git a/apps/app/src/library/TargetForm.tsx b/apps/app/src/library/TargetForm.tsx index 1bc8b1c..fc67d25 100644 --- a/apps/app/src/library/TargetForm.tsx +++ b/apps/app/src/library/TargetForm.tsx @@ -179,7 +179,16 @@ export function TargetForm({ onArrival: target?.onArrival ?? false, arrivalLogins: target?.arrivalLogins ?? ([] as string[]), untouched: target?.untouched ?? false, + copyTargetId: target?.copyTargetId ?? null, }); + // The other destinations a copy can go to (a folder on this computer, usually). + const [others, setOthers] = useState([]); + useEffect(() => { + api.listDeliveryTargets(orgId).then( + (r) => setOthers(r.targets.filter((x) => x.id !== target?.id && !x.disabledAt)), + () => setOthers([]), + ); + }, [api, orgId, target?.id]); // IPTC fields this client always gets instead of the event's (e.g. another agency in Creator). const [overrides, setOverrides] = useState(() => overrideRows(target?.iptcOverrides)); // The FTP logins whose arrivals this destination can take (a relay to one's computer). @@ -503,6 +512,26 @@ export function TargetForm({
)} + {others.length > 0 && ( + + )} {!(v.originals && v.untouched) && (
diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 98a2e1d..f0ae188 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -251,6 +251,8 @@ export interface DeliveryTarget { untouched?: boolean; /** IPTC fields this client gets instead of the event's (variables allowed); null: none. */ iptcOverrides?: Record | null; + /** Everything sent here also goes to this target (a folder on a computer), with this target's IPTC. */ + copyTargetId?: string | null; username: string; folderTemplate: string; fileNameTemplate: string; @@ -316,6 +318,7 @@ export interface DeliveryTargetInput { untouched?: boolean; /** IPTC fields this client gets instead of the event's; null: none. */ iptcOverrides?: Record | null; + copyTargetId?: string | null; } export interface PersonSummary { -- 2.47.3