diff --git a/apps/api/prisma/migrations/20261103140000_delivery_force_originals_wait_faces/migration.sql b/apps/api/prisma/migrations/20261103140000_delivery_force_originals_wait_faces/migration.sql new file mode 100644 index 0000000..32f100a --- /dev/null +++ b/apps/api/prisma/migrations/20261103140000_delivery_force_originals_wait_faces/migration.sql @@ -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; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 57817b0..35342e1 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -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") diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 9c18c6a..a54b102 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -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(); diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index 19e780b..9df36ae 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -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); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 6c3b47c..9ada3e2 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -112,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, @@ -210,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. */ @@ -260,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), + }, }), ); } @@ -273,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) { @@ -485,12 +502,12 @@ export class DeliveryService { return saved; } let update: Partial; - // Only automatic every-arrival deliveries wait for faces, and only while a read is in flight and the pad - // needs `{players}`. A manual send (Melhores… / Enviar) must not sit on waiting_for_faces — NONE never - // becomes DONE by waiting, and many destinations do not put names on the file. + // 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.onArrival && + item.target.waitForFaces && facesInFlight && !(item.target.originals && item.target.untouched) && Date.now() - item.createdAt.getTime() < FACES_WAIT_MS && @@ -537,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. @@ -547,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); diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index e721207..440c59d 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -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; }, ) {} @@ -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(); + 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. */ diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 12609c7..37a4720 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -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, { diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index 1737126..a347563 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -467,7 +467,7 @@ describe("delivery", () => { expect(item.lastError).not.toBe("waiting_for_faces"); }); - it("an every-arrival destination waits while faces are being read when the pad needs player names", async () => { + 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({ @@ -482,15 +482,14 @@ describe("delivery", () => { password: "app-password-123", folderTemplate: "/Backup/{event}/", fileNameTemplate: "{originalName}", - onArrival: true, + 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 } }); - const photoRow = await ctx.db.photo.findUniqueOrThrow({ where: { id } }); - await delivery.queueArrival({ id, organizationId: orgId, uploaderId: photoRow.uploaderId }); + 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]); @@ -501,7 +500,7 @@ describe("delivery", () => { expect(nc.files.size).toBe(1); }); - it("does not wait for faces that were never started (NONE)", async () => { + 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({ @@ -516,20 +515,38 @@ describe("delivery", () => { password: "app-password-123", folderTemplate: "/Backup/{event}/", fileNameTemplate: "{originalName}", - onArrival: true, + 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 } }); - const photoRow = await ctx.db.photo.findUniqueOrThrow({ where: { id } }); - await delivery.queueArrival({ id, organizationId: orgId, uploaderId: photoRow.uploaderId }); + 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"); diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 7d8c4ae..1707a23 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -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", diff --git a/apps/app/src/library/SendButton.tsx b/apps/app/src/library/SendButton.tsx index 4b62107..5a90033 100644 --- a/apps/app/src/library/SendButton.tsx +++ b/apps/app/src/library/SendButton.tsx @@ -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(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>[] = []; - 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>[] = []; - 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>[] = []; 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); @@ -259,6 +261,10 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph )} )} +