diff --git a/apps/api/prisma/migrations/20261104110000_delivery_target_color/migration.sql b/apps/api/prisma/migrations/20261104110000_delivery_target_color/migration.sql new file mode 100644 index 0000000..2f14526 --- /dev/null +++ b/apps/api/prisma/migrations/20261104110000_delivery_target_color/migration.sql @@ -0,0 +1,8 @@ +-- Colour that routes a photo to this delivery (paint → send here). Null: no colour route. +ALTER TABLE "delivery_targets" ADD COLUMN "color_label" "ColorLabel"; + +-- One destination per colour per organisation (multiple NULLs remain allowed). +CREATE UNIQUE INDEX "delivery_targets_organization_id_color_label_key" ON "delivery_targets"("organization_id", "color_label"); + +-- Local FTP / desktop may attribute a resumable upload to another org member. +ALTER TABLE "pending_uploads" ADD COLUMN "uploader_user_id" UUID; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 35342e1..f872a72 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -584,6 +584,8 @@ model DeliveryTarget { localFolderTemplate String? @map("local_folder_template") /// Set only on the hidden LOCAL target that holds those copies; points at the export it mirrors. mirrorOfId String? @unique @map("mirror_of_id") @db.Uuid + /// Library colour that routes a photo to this delivery (paint → send here). Null: no colour route. + colorLabel ColorLabel? @map("color_label") createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") disabledAt DateTime? @map("disabled_at") @@ -594,6 +596,7 @@ model DeliveryTarget { localMirror DeliveryTarget? @relation("LocalMirror") @@unique([organizationId, name]) + @@unique([organizationId, colorLabel]) @@map("delivery_targets") } @@ -1189,6 +1192,8 @@ model PendingUpload { original Json? /// An original sent by the desktop app's ingest (its local FTP): edited by the event's autopilot like FTP photos. fromDesktop Boolean @default(false) @map("from_desktop") + /// Photo attributed to this org member (local FTP second photographer); null: `userId` (who uploaded). + uploaderUserId String? @map("uploader_user_id") @db.Uuid createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index a54b102..a30e309 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -142,7 +142,23 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerEventRoutes(app, { db, sessions, sports, broadcaster }); await registerSportsRoutes(app, { db, sessions, sports }); // Photos whose IPTC changes go again to where they went. - await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster, archive, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) }); + await registerPhotoRoutes(app, { + db, + sessions, + storage, + signer, + broadcaster, + archive, + resend: (orgId, ids) => delivery.resendPhotos(orgId, ids), + queueColor: async (orgId, ids, colorLabel) => { + const target = await db.deliveryTarget.findFirst({ + where: { organizationId: orgId, colorLabel: colorLabel as "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE", disabledAt: null, mirrorOfId: null }, + select: { id: true }, + }); + if (!target) return; + await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: ids, again: false, requestedById: null }); + }, + }); 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, resend: (orgId, ids) => delivery.resendPhotos(orgId, ids) }); diff --git a/apps/api/src/autopilot/best.ts b/apps/api/src/autopilot/best.ts index 50af84e..70442fe 100644 --- a/apps/api/src/autopilot/best.ts +++ b/apps/api/src/autopilot/best.ts @@ -100,7 +100,7 @@ export function restBeside( * then — only if still short — takes a second frame from bursts already used. The number the photographer asked * for is the target; under-filling to ~100 when they asked for 300 is a bug. */ -export function fillToCount(picked: readonly Candidate[], spare: readonly Candidate[], count: number, minGapMs = 8_000): Candidate[] { +export function fillToCount(picked: readonly Candidate[], spare: readonly Candidate[], count: number, minGapMs = 5_000): Candidate[] { const out: Candidate[] = [...picked]; const have = new Set(out.map((c) => c.id)); const usedBurst = new Set(out.map((c) => c.burst)); diff --git a/apps/api/src/autopilot/curate.ts b/apps/api/src/autopilot/curate.ts index 761c9be..9141069 100644 --- a/apps/api/src/autopilot/curate.ts +++ b/apps/api/src/autopilot/curate.ts @@ -71,7 +71,7 @@ const median = (xs: number[]) => { */ export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean }[], opts: CurateOptions): WindowDecision[] { const windowMs = opts.windowMs ?? 5 * 60_000; - const minGapMs = opts.minGapMs ?? 8_000; + const minGapMs = opts.minGapMs ?? 5_000; const settleMs = opts.settleMs ?? 60_000; const done = new Map(decided.map((d) => [d.id, d.chosen])); let chosenSoFar = [...done.values()].filter(Boolean).length; diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index f26f2fd..2657ad5 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -20,6 +20,7 @@ import { bestOf, FOCUS_SHARP, groupBursts, reportagePickCount } from "./bursts.j import { curate, matchMinutes } from "./curate.js"; import { type LearntStyle, learntStyle } from "./learning.js"; import { detailForCrop, lookValues } from "./look.js"; +import { exportTargets, MELHORES_GAP_MS, picksNeeded } from "./targets.js"; const STALE_RUNNING_MS = 10 * 60_000; /** A burst is decided once no new frame of it has arrived for this long. */ @@ -233,17 +234,21 @@ export class AutopilotService { if (Math.max(...burst.map((f) => f.createdAt.getTime())) > now.getTime() - BURST_SETTLE_MS) continue; const reportage = reportageEvent; const sharp = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP).length; - const asked = reportage ? reportagePickCount(sharp, settings.picksPerBurst) : settings.picksPerBurst; + const need = picksNeeded(settings); + const asked = reportage ? reportagePickCount(sharp, need) : need; const planKey = [null, "half", "threeQuarter"] as const; // Drop backs / blinks when the burst has a clearer face with open eyes (look weight already crushed). - const usable = burst.filter((f) => (look.get(f.id) ?? 1) >= 0.25); - const pool = usable.length ? usable : burst; + // Soft frames lose when the burst has a sharp sibling (FOCUS_SHARP). + const sharpEnough = burst.filter((f) => (f.rec?.focus ?? 0) >= FOCUS_SHARP); + const lookOk = (sharpEnough.length ? sharpEnough : burst).filter((f) => (look.get(f.id) ?? 1) >= 0.25); + const usable = lookOk.length ? lookOk : sharpEnough.length ? sharpEnough : burst; + const pool = usable; // Extra frames beyond the event's number are only kept when they can carry a different plan. // The plan stays with the frame: dropping one does not hand its crop to the next. const chosen = bestOf(pool, asked) .map((f, i) => ({ f, key: planKey[i] ?? null })) .filter(({ f, key }, i) => { - if (!reportage || i < settings.picksPerBurst) return true; + if (!reportage || i < need) return true; const planned = key ? f.rec?.plans?.[key] : null; return !!planned && !!f.rec?.crop && distinctPlan(f.rec.crop, planned); }); @@ -312,12 +317,17 @@ export class AutopilotService { await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } }); } // "Only the best" delivers per window of the match instead (below), not every burst's picks. - // A photo taken outside this event (yesterday's pin still receiving today's arrival) is not this client's. - const here = takenHere(toFlag, new Map(photos.map((p) => [p.id, p.capturedAt])), event); - if (settings.selection === "bursts" && settings.deliverTargetId && here.length && this.deps.deliveries && event.createdById) { - await this.deps.deliveries - .enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: here, again: false, requestedById: event.createdById }) - .catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued")); + // N exports → rank i of this burst to export i (same file never to two). + const targets = exportTargets(settings); + if (settings.selection === "bursts" && targets.length && best.length && this.deps.deliveries && event.createdById) { + const when = new Map(photos.map((p) => [p.id, p.capturedAt])); + for (let i = 0; i < targets.length && i < best.length; i++) { + const id = best[i]!.id; + if (!takenHere([id], when, event).length) continue; + await this.deps.deliveries + .enqueue({ organizationId: event.organizationId, targetId: targets[i]!, photoIds: [id], again: false, requestedById: event.createdById }) + .catch((err: unknown) => log.warn({ err, targetId: targets[i] }, "autopilot: delivery not queued")); + } } } if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now); @@ -350,11 +360,16 @@ 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 })); - // 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(ranked, 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 targets = exportTargets(settings); + // With 2+ exports, curate on the best frame; delivery below assigns best/2nd/… to each target. + const candidates = candidatesOf(ranked, settings.burstGapSec * 1000, true, "best"); + const decisions = curate(candidates, decided, { + count: settings.bestCount, + start: event.startsAt.getTime(), + durationMs: matchMinutes(event.sport) * 60_000, + now: now.getTime(), + minGapMs: MELHORES_GAP_MS, + }); 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. const burstOf = new Map(); @@ -375,20 +390,27 @@ export class AutopilotService { 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 when = new Map(photos.map((p) => [p.id, p.capturedAt])); - const rest = takenHere(restOf(nowCurated, chosen, flags), when, event); - 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")); - } - const gallery = takenHere([...chosen], when, event); chosenCount += chosen.size; - if (gallery.length && settings.deliverTargetId && this.deps.deliveries && event.createdById) { - await this.deps.deliveries - .enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: gallery, again: false, requestedById: event.createdById }) - .catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued")); + if (targets.length && this.deps.deliveries && event.createdById) { + // Per chosen moment (burst): rank i → export i. Same photo never to two destinations. + for (const momentId of chosen) { + const burstIds = burstOf.get(momentId) ?? [momentId]; + const burstPhotos = burstIds.map((id) => photos.find((p) => p.id === id)).filter(Boolean) as typeof photos; + const rankedBurst = burstPhotos + .map((p) => ({ ...p, score: ((p.autopilot as AutopilotRecord | null)?.score ?? 0) * (look.get(p.id) ?? 1) })) + .sort((a, b) => (b.score ?? 0) - (a.score ?? 0)); + for (let i = 0; i < targets.length && i < rankedBurst.length; i++) { + const photo = rankedBurst[i]!; + if (photo.flag === "REJECT") continue; + if (!takenHere([photo.id], when, event).length) continue; + await this.deps.deliveries + .enqueue({ organizationId: event.organizationId, targetId: targets[i]!, photoIds: [photo.id], again: false, requestedById: event.createdById }) + .catch((err: unknown) => log.warn({ err, targetId: targets[i] }, "autopilot: delivery not queued")); + } + } + } else if (targets.length === 0) { + /* no auto-export */ } if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window"); } diff --git a/apps/api/src/autopilot/targets.ts b/apps/api/src/autopilot/targets.ts new file mode 100644 index 0000000..bbf75dc --- /dev/null +++ b/apps/api/src/autopilot/targets.ts @@ -0,0 +1,33 @@ +import type { AutopilotSettings } from "@photoreport/contracts"; + +/** + * Ordered auto-export destinations for a burst: `deliverTargetIds` when set, else the legacy + * `deliverTargetId` then `restTargetId`. Same id never listed twice. + */ +export function exportTargets(settings: Pick): string[] { + const fromList = (settings.deliverTargetIds ?? []).filter(Boolean); + if (fromList.length) { + const seen = new Set(); + const out: string[] = []; + for (const id of fromList) { + if (seen.has(id)) continue; + seen.add(id); + out.push(id); + } + return out; + } + const out: string[] = []; + if (settings.deliverTargetId) out.push(settings.deliverTargetId); + if (settings.restTargetId && settings.restTargetId !== settings.deliverTargetId) out.push(settings.restTargetId); + return out; +} + +/** How many frames of a burst to keep: one per configured export, else `picksPerBurst`. */ +export function picksNeeded(settings: AutopilotSettings): number { + const n = exportTargets(settings).length; + if (n > 0) return Math.min(5, Math.max(1, n)); + return settings.picksPerBurst; +} + +/** Melhores spacing between two sends to the same destination (ms). */ +export const MELHORES_GAP_MS = 5_000; diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index 9df36ae..f575590 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -67,6 +67,8 @@ const TargetBase = z.object({ localMachine: z.string().trim().min(8).max(120).nullable(), /** Subfolders under `localFolder`. `{destination}` is this target's name. Null with a folder: the default. */ localFolderTemplate: z.string().trim().min(1).max(400).nullable(), + /** Library colour that routes photos to this delivery (null: no colour route). */ + colorLabel: z.enum(["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"]).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}`); @@ -91,6 +93,7 @@ const TargetFields = TargetBase.extend({ localFolder: TargetBase.shape.localFolder.default(null), localMachine: TargetBase.shape.localMachine.default(null), localFolderTemplate: TargetBase.shape.localFolderTemplate.default(null), + colorLabel: TargetBase.shape.colorLabel.default(null), }); const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() }); const ListQuery = z.object({ diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 244f103..52322ae 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -245,6 +245,7 @@ export class DeliveryService { if (photo.status !== "READY") skipped.push({ photoId: photo.id, reason: "not_ready" }); else if (!photo.eventId) skipped.push({ photoId: photo.id, reason: "not_in_event" }); else if (already.has(photo.id)) skipped.push({ photoId: photo.id, reason: "already_delivered" }); + else if (target.colorLabel && photo.colorLabel !== target.colorLabel) skipped.push({ photoId: photo.id, reason: "color_mismatch" }); else byEvent.set(photo.eventId, [...(byEvent.get(photo.eventId) ?? []), photo]); } diff --git a/apps/api/src/library/photos.ts b/apps/api/src/library/photos.ts index d8f59d6..955dead 100644 --- a/apps/api/src/library/photos.ts +++ b/apps/api/src/library/photos.ts @@ -53,6 +53,8 @@ export async function registerPhotoRoutes( archive?: { openOriginal(photoId: string): Promise } | undefined; /** Sends photos whose IPTC changed again to where they went (DeliveryService.resendPhotos). */ resend?: ((organizationId: string, photoIds: string[]) => Promise) | undefined; + /** Paint → colour-bound delivery: queue these photos to that target. */ + queueColor?: ((organizationId: string, photoIds: string[], colorLabel: string) => Promise) | undefined; }, ) { const { db, storage, signer, broadcaster } = deps; @@ -126,10 +128,30 @@ export async function registerPhotoRoutes( }) ).map((p) => p.id) : []; + // Colour change: take back from colour-bound destinations that no longer match (before the paint). + const colorRetract = + patch.colorLabel !== undefined + ? ( + await db.deliveryItem.findMany({ + where: { + organizationId: orgId, + photoId: { in: ids }, + status: { in: ["QUEUED", "WAITING", "DONE"] }, + retract: false, + target: { colorLabel: { not: null }, ...(patch.colorLabel === "NONE" ? {} : { NOT: { colorLabel: patch.colorLabel } }) }, + }, + select: { photoId: true }, + }) + ).map((i) => i.photoId) + : []; const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data }); if (result.count !== ids.length) throw notFound("photo_not_found"); if (retractIds.length) await retractPhotos(db, orgId, retractIds); if (leaving.length) await retractPhotos(db, orgId, leaving); + if (colorRetract.length) await retractPhotos(db, orgId, [...new Set(colorRetract)]); + if (patch.colorLabel && patch.colorLabel !== "NONE" && deps.queueColor) { + await deps.queueColor(orgId, ids, patch.colorLabel).catch(() => {}); + } // Moved to another event: arrival names, faces and the autopilot follow it. if (patch.eventId) await joinedEvent(db, patch.eventId, ids); broadcaster.library(orgId, { type: "photo.updated", ids, patch }); diff --git a/apps/api/src/library/uploads.ts b/apps/api/src/library/uploads.ts index b72e076..1ac8f73 100644 --- a/apps/api/src/library/uploads.ts +++ b/apps/api/src/library/uploads.ts @@ -7,7 +7,7 @@ import { pipeline } from "node:stream/promises"; import type { FastifyInstance } from "fastify"; import sharp from "sharp"; import { z } from "zod"; -import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; +import { ROLE_RANK, currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; import type { SessionService } from "../auth/sessions.js"; import type { Db } from "../db.js"; import { ACCEPTED_EXTENSIONS, type IngestService, type PreviewOf } from "../ingest/service.js"; @@ -16,7 +16,13 @@ import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { photoInclude, toSummary } from "./serialize.js"; const OrgParams = z.object({ orgId: z.uuid() }); -const UploadQuery = z.object({ eventId: z.uuid().optional(), silent: z.string().optional(), inbox: z.string().optional() }); +const UploadQuery = z.object({ + eventId: z.uuid().optional(), + silent: z.string().optional(), + inbox: z.string().optional(), + /** Attribute the photo to this org member (INGESTER+; local FTP second photographer). */ + uploaderUserId: z.uuid().optional(), +}); const LinearQuery = z.object({ capturedAt: z.string().optional(), width: z.coerce.number().int().positive().max(100_000), @@ -42,10 +48,20 @@ export async function registerUploadRoutes( const { orgId } = OrgParams.parse(req.params); const query = UploadQuery.parse(req.query); const { eventId } = query; - await requireMembership(db, req, orgId, "PHOTOGRAPHER"); + const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER"); if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) { throw badRequest("event_not_in_organization"); } + let uploaderId = currentUserId(req); + if (query.uploaderUserId && query.uploaderUserId !== uploaderId) { + if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden"); + const other = await db.membership.findUnique({ + where: { userId_organizationId: { userId: query.uploaderUserId, organizationId: orgId } }, + select: { userId: true }, + }); + if (!other) throw badRequest("uploader_not_in_organization"); + uploaderId = other.userId; + } const part = await req.file(); if (!part) throw badRequest("file_missing"); const name = path.basename(part.filename || "upload.jpg"); @@ -61,7 +77,7 @@ export async function registerUploadRoutes( if (part.file.truncated) throw new AppError(413, "file_too_large"); const outcome = await ingest.ingest(tmp, { organizationId: orgId, - userId: currentUserId(req), + userId: uploaderId, source: "UPLOAD", originalName: name, eventId, @@ -165,16 +181,28 @@ export async function registerUploadRoutes( .optional(), /** A full original from the desktop app's ingest (its local FTP), not a hand upload. */ desktop: z.boolean().optional(), + /** Attribute the photo to this org member (INGESTER+; local FTP second photographer). */ + uploaderUserId: z.uuid().optional(), }); app.post("/v1/orgs/:orgId/uploads/resumable", { preHandler: authenticate }, async (req, reply) => { const { orgId } = OrgParams.parse(req.params); const body = StartBody.parse(req.body); - await requireMembership(db, req, orgId, "PHOTOGRAPHER"); + const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER"); const name = path.basename(body.name); if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) throw new AppError(415, "unsupported_type", "JPEG only for now"); if (body.eventId && !(await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } }))) throw badRequest("event_not_in_organization"); const userId = currentUserId(req); + let uploaderUserId: string | null = null; + if (body.uploaderUserId && body.uploaderUserId !== userId) { + if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden"); + const other = await db.membership.findUnique({ + where: { userId_organizationId: { userId: body.uploaderUserId, organizationId: orgId } }, + select: { userId: true }, + }); + if (!other) throw badRequest("uploader_not_in_organization"); + uploaderUserId = other.userId; + } // Abandoned uploads of this user (older than two days) are cleared on the way. for (const old of await db.pendingUpload.findMany({ where: { userId, updatedAt: { lt: new Date(Date.now() - 2 * 86_400_000) } } })) { await rm(partPath(old.id), { force: true }); @@ -193,7 +221,17 @@ export async function registerUploadRoutes( if (known && known.status !== "FAILED") return reply.code(200).send({ status: "duplicate", photo: toSummary(known, signer) }); } const upload = await db.pendingUpload.create({ - data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }), ...(body.desktop && { fromDesktop: true }) }, + data: { + organizationId: orgId, + userId, + eventId: body.eventId ?? null, + fileName: name, + size: body.size, + fingerprint: body.fingerprint, + ...(body.original && { original: body.original }), + ...(body.desktop && { fromDesktop: true }), + ...(uploaderUserId && { uploaderUserId }), + }, }); return reply.code(201).send({ id: upload.id, offset: 0, size: upload.size }); }); @@ -238,7 +276,7 @@ export async function registerUploadRoutes( try { const outcome = await ingest.ingest(partPath(id), { organizationId: upload.organizationId, - userId: upload.userId, + userId: upload.uploaderUserId ?? upload.userId, source: upload.original || upload.fromDesktop ? "DESKTOP" : "UPLOAD", originalName: upload.fileName, eventId: upload.eventId ?? undefined, diff --git a/apps/api/test/autopilot.test.ts b/apps/api/test/autopilot.test.ts index 8a2bb82..35047b8 100644 --- a/apps/api/test/autopilot.test.ts +++ b/apps/api/test/autopilot.test.ts @@ -279,7 +279,7 @@ 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 () => { + it("two clients: best of each chosen moment to the first export, second best to the second, 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"; @@ -298,7 +298,7 @@ describe("autopilot", () => { 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. + // Window 0: 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); @@ -308,15 +308,17 @@ describe("autopilot", () => { 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()); + // First export gets the best of each chosen moment; second export gets the second best. Same file never both. + expect(to(record)).toEqual([a1]); + expect(to(fap)).toEqual([a2]); expect(to(record).filter((id) => to(fap).includes(id))).toEqual([]); expect([...to(record), ...to(fap)]).not.toContain(later); + expect([...to(record), ...to(fap)]).not.toContain(b1); + expect([...to(record), ...to(fap)]).not.toContain(b2); // 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); + expect(to(record)).toEqual([a1]); + expect(to(fap)).toEqual([a2]); }); it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => { @@ -330,7 +332,7 @@ describe("autopilot", () => { expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE"); }); - it("edits the agencies' way by default: neutral whites, fuller tone, the finishing look", async () => { + it("defaults to look none: white balance and tone only, no finishing look", async () => { const { orgId, userId, eventId } = await setup(); await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true } } }); const id = await shot(orgId, userId, eventId, 0, 300); @@ -339,11 +341,24 @@ describe("autopilot", () => { await autopilot.decideBursts(new Date(Date.now() + 20_000)); const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } }); const values = (edits[0]!.command as { params: { values: Record } }).params.values; - // Sharpen starts at 40 and is scaled when the crop does not keep the whole frame (detailForCrop). - expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 38.5, "detail.nrLuminance": 22 }); + expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15 }); + expect(values["color.vibrance"]).toBeUndefined(); + expect(values["detail.sharpenAmount"]).toBeUndefined(); expect(Object.keys(values).some((k) => k.startsWith("vignette."))).toBe(false); }); + it("applies the agency finishing look when asked", async () => { + const { orgId, userId, eventId } = await setup(); + await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true, look: "agency" } } }); + const id = await shot(orgId, userId, eventId, 0, 300); + await ctx.db.photo.update({ where: { id }, data: { iso: 6400 } }); + await runQueue(); + await autopilot.decideBursts(new Date(Date.now() + 20_000)); + const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } }); + const values = (edits[0]!.command as { params: { values: Record } }).params.values; + expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 38.5, "detail.nrLuminance": 22 }); + }); + it("leaves events without autopilot alone", async () => { const { orgId, userId, eventId } = await setup(false); await shot(orgId, userId, eventId, 0, 100); diff --git a/apps/api/test/targets.test.ts b/apps/api/test/targets.test.ts new file mode 100644 index 0000000..d44a193 --- /dev/null +++ b/apps/api/test/targets.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { AutopilotSettings } from "@photoreport/contracts"; +import { exportTargets, picksNeeded } from "../src/autopilot/targets.js"; + +const a = "11111111-1111-4111-8111-111111111111"; +const b = "22222222-2222-4222-8222-222222222222"; +const c = "33333333-3333-4333-8333-333333333333"; + +describe("exportTargets", () => { + it("prefers deliverTargetIds and dedupes", () => { + expect(exportTargets({ deliverTargetIds: [a, b, a], deliverTargetId: null, restTargetId: null })).toEqual([a, b]); + }); + + it("falls back to legacy deliver + rest", () => { + expect(exportTargets({ deliverTargetIds: [], deliverTargetId: a, restTargetId: b })).toEqual([a, b]); + expect(exportTargets({ deliverTargetIds: [], deliverTargetId: a, restTargetId: a })).toEqual([a]); + }); +}); + +describe("picksNeeded", () => { + it("matches the number of exports when set", () => { + const s = AutopilotSettings.parse({ enabled: true, deliverTargetIds: [a, b, c] }); + expect(picksNeeded(s)).toBe(3); + }); + + it("uses picksPerBurst when no exports", () => { + expect(picksNeeded(AutopilotSettings.parse({ enabled: true, picksPerBurst: 2 }))).toBe(2); + }); +}); diff --git a/apps/app/src/library/Autopilot.tsx b/apps/app/src/library/Autopilot.tsx index b1628be..48f6899 100644 --- a/apps/app/src/library/Autopilot.tsx +++ b/apps/app/src/library/Autopilot.tsx @@ -16,10 +16,13 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta useEffect(() => setS(AutopilotSettings.parse(props.event.autopilot ?? {})), [props.event]); const save = async (next: AutopilotSettings) => { - setS(next); + // Keep deliverTargetIds in sync with the two legacy slots (N exports = ordered list). + const ids = [next.deliverTargetId, next.restTargetId].filter((x): x is string => !!x); + const synced = { ...next, deliverTargetIds: ids.length ? ids : next.deliverTargetIds ?? [] }; + setS(synced); setState("saving"); try { - props.onSaved(await props.api.updateEvent(props.event.id, { autopilot: next })); + props.onSaved(await props.api.updateEvent(props.event.id, { autopilot: synced })); setState("idle"); } catch { setState("error"); diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 8ececd9..3fb2e82 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -15,7 +15,7 @@ import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js"; export interface FtpSettings { port: number; /** `enabled` missing (older desktop app): on. */ - users: { name: string; password: string; enabled?: boolean; label?: string }[]; + users: { name: string; password: string; enabled?: boolean; label?: string; memberUserId?: string }[]; ingest: string; workFolder: string; autoStart: boolean; @@ -40,6 +40,8 @@ export interface IncomingFile { name: string; size: number; modifiedMs: number; + /** FTP login that uploaded this file (camera body). */ + login?: string; } /** Where FTP photos go: the event, and what its work folder on disk is called. */ @@ -76,7 +78,13 @@ function isIncomplete(err: unknown): boolean { return err === "incomplete" || (err instanceof Error && err.message === "incomplete"); } -type Add = (files: Iterable, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => void; +type Add = ( + files: Iterable, + eventId?: string, + onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, + original?: DesktopOrigin, + uploaderUserId?: string, +) => void; export const eventLabel = (e: Pick) => e.title || [e.home, e.away].filter(Boolean).join(" x "); @@ -121,6 +129,8 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn targetRef.current = target; const originalsRef = useRef(false); originalsRef.current = !!status?.settings.uploadOriginals; + const settingsRef = useRef(status?.settings); + settingsRef.current = status?.settings; const setTarget = useCallback((e: EventSummary | null) => { const next = e @@ -229,9 +239,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn () => undefined, () => undefined, ); + const login = f.login ?? ""; + const photographer = settingsRef.current?.users.find((u) => u.name === login && u.memberUserId)?.memberUserId; if (!full) { const file = new File([preview], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); - add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info); + add([file], eventId ?? undefined, (_file, result, photo) => settle(_file, result, photo), info, photographer); return; } await takeOriginal(); @@ -244,10 +256,16 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn try { const bytes = await invoke("ftp_read", { path: f.path }).then(asArrayBuffer); const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs }); - add([file], eventId ?? undefined, (_file, result, photo) => { - drop(); - settle(_file, result, photo); - }, "original"); + add( + [file], + eventId ?? undefined, + (_file, result, photo) => { + drop(); + settle(_file, result, photo); + }, + "original", + photographer, + ); } catch (err) { drop(); if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 })); diff --git a/apps/app/src/library/uploads.ts b/apps/app/src/library/uploads.ts index f90ecd2..c6eb642 100644 --- a/apps/app/src/library/uploads.ts +++ b/apps/app/src/library/uploads.ts @@ -85,9 +85,17 @@ export async function sendResumable( eventId: string | undefined, onProgress: (p: number) => void, origin?: DesktopOrigin, + uploaderUserId?: string, ): Promise<{ status: number; body: unknown }> { const fingerprint = `${file.name}:${file.size}:${file.lastModified}`; - const beginBody = JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }); + const beginBody = JSON.stringify({ + name: file.name, + size: file.size, + fingerprint, + ...(eventId && { eventId }), + ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}), + ...(uploaderUserId && { uploaderUserId }), + }); let failures = 0; let begin: { status: number; body: unknown }; for (;;) { @@ -165,6 +173,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) { file: File; eventId: string | undefined; original?: DesktopOrigin; + uploaderUserId?: string; sha256?: string | null; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void; }[] @@ -204,6 +213,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) { } }, original, + next.uploaderUserId, ); // The server took the file but could not read it as a photo: not sent (FTP keeps the original in ingest). const photo = (res.body as { photo?: PhotoSummary } | null)?.photo; @@ -250,7 +260,7 @@ 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, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => { + (files: Iterable, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin, uploaderUserId?: string) => { // A previous offline pause must not leave new shots stuck on "queued" after the VPN is back. if (paused.current) { paused.current = false; @@ -271,6 +281,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) { file: File; eventId: string | undefined; original?: DesktopOrigin; + uploaderUserId?: string; sha256?: string | null; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void; } = { @@ -278,6 +289,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) { file, eventId, ...(original && { original }), + ...(uploaderUserId && { uploaderUserId }), sha256: null, ...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }), }; diff --git a/apps/desktop/src-tauri/src/ftp.rs b/apps/desktop/src-tauri/src/ftp.rs index 8ec966e..3d60533 100644 --- a/apps/desktop/src-tauri/src/ftp.rs +++ b/apps/desktop/src-tauri/src/ftp.rs @@ -33,6 +33,7 @@ const PASSIVE_PORTS: std::ops::RangeInclusive = 50000..=50100; const STABLE_MS: u64 = 2_000; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] pub struct FtpUser { pub name: String, pub password: String, @@ -42,6 +43,9 @@ pub struct FtpUser { /// What you call this body ("R3", "1DX"). Empty: the login name is the label. #[serde(default)] pub label: String, + /// PhotoReport org member who owns this camera login (second photographer on this Mac). Empty: signed-in user. + #[serde(default)] + pub member_user_id: String, } fn enabled_by_default() -> bool { @@ -73,6 +77,7 @@ impl Default for FtpSettings { password: new_password(), enabled: true, label: String::new(), + member_user_id: String::new(), }], ingest: "~/Desktop/ingest".into(), work_folder: "~/Desktop/{year}/{date} - {event}".into(), @@ -118,6 +123,9 @@ pub struct IncomingFile { name: String, size: u64, modified_ms: u64, + /// FTP login that uploaded this file (camera body); empty when unknown (older desktop). + #[serde(default)] + login: String, } impl IncomingFile { @@ -127,6 +135,7 @@ impl IncomingFile { name, size, modified_ms: now_ms(), + login: String::new(), } } } @@ -166,9 +175,8 @@ pub struct FtpState { settings: Mutex>, /// Overrides the settings file location (tests). config_path: Option, - /// (file name, bytes) of uploads the FTP session reported as finished. The session only gives the name - /// relative to its current folder, so the folder scan matches them up by name and size. - finished: Arc>>, + /// File name → (bytes, FTP login) of uploads the session reported finished. Matched by name and size on scan. + finished: Arc>>, /// Size and time of each file at the previous scan. Quiet is not enough; the end marker has to be there too. seen: Mutex>, /// Paths already handed to the web app (so the next scan does not send them twice). @@ -275,6 +283,7 @@ fn describe(path: &Path) -> Option { name: path.file_name()?.to_string_lossy().into_owned(), size: meta.len(), modified_ms, + login: String::new(), }) } @@ -468,15 +477,19 @@ impl Authenticator for Logins { #[derive(Debug)] struct Arrivals { - finished: Arc>>, + /// File name → (byte size, FTP login that uploaded it). + finished: Arc>>, } #[async_trait] impl DataListener for Arrivals { - async fn receive_data_event(&self, e: DataEvent, _m: EventMeta) { + async fn receive_data_event(&self, e: DataEvent, m: EventMeta) { if let DataEvent::Put { path, bytes } = e { let name = path.rsplit('/').next().unwrap_or(&path).to_string(); - self.finished.lock().unwrap().insert((name, bytes)); + self.finished + .lock() + .unwrap() + .insert(name, (bytes, m.username)); } } } @@ -665,15 +678,22 @@ impl FtpState { continue; } let quiet = now.saturating_sub(f.modified_ms); - let reported = finished.contains(&(f.name.clone(), f.size)); + let meta = finished.get(&f.name).cloned(); + let reported = meta.as_ref().is_some_and(|(bytes, _)| *bytes == f.size); + let login = meta + .filter(|(bytes, _)| *bytes == f.size) + .map(|(_, login)| login) + .unwrap_or_default(); let stable = quiet >= STABLE_MS && seen.get(&f.path) == Some(&(f.size, f.modified_ms)); let done = (reported || stable) && jpeg_complete(Path::new(&f.path)); if done { - let name = f.name.clone(); - finished.retain(|(n, _)| n != &name); + finished.remove(&f.name); seen.remove(&f.path); taken.insert(f.path.clone()); - ready.push(f); + ready.push(IncomingFile { + login, + ..f + }); } else { seen.insert(f.path.clone(), (f.size, f.modified_ms)); } @@ -1077,6 +1097,7 @@ mod tests { password: "1dx".into(), enabled: true, label: String::new(), + member_user_id: String::new(), }], ingest: dir.join("ingest").to_string_lossy().into_owned(), work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(), @@ -1122,12 +1143,14 @@ mod tests { password: "1dx".into(), enabled: true, label: String::new(), + member_user_id: String::new(), }, FtpUser { name: "R3".into(), password: "r3".into(), enabled: false, label: "R3".into(), + member_user_id: String::new(), }, ]; assert!(s.check().is_ok()); @@ -1172,12 +1195,14 @@ mod tests { password: "1dx".into(), enabled: true, label: String::new(), + member_user_id: String::new(), }, FtpUser { name: "R3".into(), password: "r3".into(), enabled: false, label: "R3".into(), + member_user_id: String::new(), }, ], ingest: dir.join("ingest").to_string_lossy().into_owned(), @@ -1295,6 +1320,7 @@ mod tests { password: "1dx".into(), enabled: true, label: String::new(), + member_user_id: String::new(), }], ingest: dir.join("ingest").to_string_lossy().into_owned(), work_folder: dir @@ -1309,7 +1335,7 @@ mod tests { .finished .lock() .unwrap() - .insert(("partial.jpg".into(), bytes.len() as u64)); + .insert("partial.jpg".into(), (bytes.len() as u64, "cam".into())); assert!(state.take().is_empty()); assert!(partial.exists()); assert_eq!( @@ -1325,7 +1351,7 @@ mod tests { .finished .lock() .unwrap() - .insert(("partial.jpg".into(), 4)); + .insert("partial.jpg".into(), (4, "cam".into())); let got = state.take(); assert_eq!(got.len(), 1); let moved = state.sent(&got[0].path, "Game", "2026-10-18").unwrap(); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 47e686c..3348e51 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -433,6 +433,13 @@ for Lightroom Classic ≥ 13.2 Attribute filters: `XMP-xmpDM:Pick` (1 / 0 / −1 watches local delivery folders; a Reject written back by Lightroom (XMP auto-write) sets the photo to REJECT and retracts any delivery of that file. +**Colour ↔ destination.** A delivery target may own one library colour. Painting that colour queues the photo +only there; enqueue skips `color_mismatch` otherwise. The library colour is how you see what went where. + +**Autopilot exports.** An ordered list of destinations (`deliverTargetIds`) takes rank 1…N of each burst (one +file per destination). Melhores keeps a 5 s gap only within the same destination. Local FTP logins may map to +an org member so a second photographer on this Mac is attributed correctly. + **Photo Mechanic compatibility (templates and IPTC).** Every template (IPTC pad, folders, file names, rename on arrival) takes every variable of Photo Mechanic's list, under its names and short names, in any case (`packages/metadata/src/pmvars.ts`), and its modifiers: substrings `{var:index,count}` (negative index from the diff --git a/docs/photo-editing-rules.md b/docs/photo-editing-rules.md index 317d606..8ada579 100644 --- a/docs/photo-editing-rules.md +++ b/docs/photo-editing-rules.md @@ -82,7 +82,7 @@ Following the AP and NPPA codes: A camera at 10–30 frames per second sends several photos of the same moment. -- **A burst** is a run of photos from the same camera with less than 1.5 s between frames (configurable). +- **A burst** is a run of photos from the same camera with less than 1 s between frames (configurable; was 1.5 s). - **Score** of each frame: sharpness of the subject (focus landed on them, no motion blur), subject size, ball in frame and near the subject, faces visible. Ties go to the earliest frame (usually the peak of the action). - **Facing and eyes:** inside one burst, a frame of a player from behind loses to a frame where the face is @@ -125,10 +125,10 @@ is, in order: **Look** (per event, `apps/api/src/autopilot/look.ts`): fixed values on top of the measured tone, the same for every photo of a match. They never go over a measured control. -- **"agency"** (default): kolektiff's punchy kits. Vibrance +18, saturation +4, clarity +8, texture +6, and +- **"none"** (default): white balance and tone only — no creative look ("no filters"). +- **"agency"**: kolektiff's punchy kits. Vibrance +18, saturation +4, clarity +8, texture +6, and shadows a touch blue-magenta. Every agency measured has that last trait: Getty, AFP and kolektiff all do it. - **"natural"**: Getty's more natural colour. -- **"none"**: no look. - **Both looks** add capture sharpening (40, radius 1, masking 35), colour noise reduction, and luminance noise reduction by ISO (from ISO 1600). Clarity, texture and sharpening are sized for the whole frame and applied with the tone, before the crop takes effect: a crop that keeps half the frame keeps half of that strength @@ -173,7 +173,8 @@ With autopilot "only the best", windows still shape the first pass (`apps/api/sr (×1.3), a duel or a celebration (several people in the subject), less when the subject is small (far away); the photographer's stars count (+20% each), a rejected frame never goes; - frames well below the match's typical frame (half the median) are left out even when the window has room, - and never two frames of the same moment (8 s); + and never two frames of the same moment on the **same** destination (5 s); with N configured exports, up to + N best frames of a burst leave together (one per destination); - warm-up and line-ups (more than 5 minutes before kick-off) are not candidates; - a window is decided a minute after it ends, so the gallery reaches the client with about 6 minutes' delay. diff --git a/packages/contracts/src/library.ts b/packages/contracts/src/library.ts index 91c124a..c159a66 100644 --- a/packages/contracts/src/library.ts +++ b/packages/contracts/src/library.ts @@ -40,17 +40,28 @@ export const AutopilotSettings = z.object({ * reportage and ignores this: whole hands and feet stay, and a sharp sequence can keep up to three plans. */ framing: z.enum(["tight", "full"]).default("tight"), - /** Finishing look (apps/api/src/autopilot/look.ts): "agency" punchy kits, "natural" Getty-like, "none". */ - look: z.enum(["agency", "natural", "none"]).default("agency"), + /** + * Finishing look (apps/api/src/autopilot/look.ts): "none" = WB/tone only (default); "agency" punchy kits; + * "natural" Getty-like. + */ + look: z.enum(["agency", "natural", "none"]).default("none"), /** Crop shape (width, height); null: the photo's own. */ aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null), /** The crop keeps at least this many pixels on its long edge of the original. */ minLongEdge: z.number().int().min(800).max(12000).default(2400), - /** Best frames flagged as picks per burst (0: don't pick). */ - picksPerBurst: z.number().int().min(0).max(5).default(2), + /** + * Best frames flagged as picks per burst when no export list is set (0: don't pick). With `deliverTargetIds` + * (or legacy deliver/rest), the autopilot keeps one frame per destination instead. + */ + picksPerBurst: z.number().int().min(0).max(5).default(1), /** Frames closer than this (seconds) belong to the same burst. */ - burstGapSec: z.number().min(0.2).max(10).default(1.5), - /** Deliver the picks to this target as they are chosen (null: don't). */ + burstGapSec: z.number().min(0.2).max(10).default(1), + /** + * Ordered auto-export destinations: rank 1 of each burst → first id, rank 2 → second, …. Prefer this over the + * legacy pair below. Empty: use `deliverTargetId` / `restTargetId` when set. + */ + deliverTargetIds: z.array(z.string().uuid()).max(10).default([]), + /** Legacy first export (null: don't). Kept for older clients; folded into `deliverTargetIds` when that is empty. */ deliverTargetId: z.string().uuid().nullable().default(null), /** * What is delivered: every burst's picks, or only the best of the match (a short gallery of game moments, spread @@ -59,9 +70,8 @@ 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). + * Legacy second export. With two destinations, each burst's best goes to `deliverTargetId` and the second best + * to this one when `deliverTargetIds` is empty. Prefer `deliverTargetIds`. */ restTargetId: z.string().uuid().nullable().default(null), });