Delivery: local copy, client IPTC, and the rest of the picks #25
No files matched your search
@@ -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;
|
||||
@@ -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;
|
||||
@@ -558,6 +558,12 @@ 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")
|
||||
/// 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")
|
||||
@@ -578,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")
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<string>, flags: ReadonlyMap<string, string>): 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<typeof setTimeout> | undefined;
|
||||
|
||||
@@ -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,10 @@ 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(),
|
||||
/** 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<typeof KIND>, baseUrl: string, username: string) => {
|
||||
if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`);
|
||||
@@ -72,6 +76,8 @@ 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),
|
||||
copyTargetId: TargetBase.shape.copyTargetId.default(null),
|
||||
});
|
||||
const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() });
|
||||
const ListQuery = z.object({
|
||||
@@ -85,6 +91,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" };
|
||||
@@ -117,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);
|
||||
@@ -143,10 +160,11 @@ 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 ?? "") } });
|
||||
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 });
|
||||
});
|
||||
|
||||
@@ -162,12 +180,14 @@ 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);
|
||||
if (fields.copyTargetId !== undefined) await checkCopy(orgId, targetId, fields.copyTargetId);
|
||||
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 +206,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 });
|
||||
});
|
||||
|
||||
|
||||
@@ -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<DeliveryItem>;
|
||||
// The players' names come from the faces (who is where, face and shirt number): give their reading a moment,
|
||||
// so a photo does not leave without names. Waiting does not count as an attempt.
|
||||
if (!(item.target.originals && item.target.untouched) && Date.now() - item.createdAt.getTime() < FACES_WAIT_MS && (item.photo.facesStatus === "NONE" || item.photo.facesStatus === "PENDING")) {
|
||||
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<void> } | null = null;
|
||||
if (!item.photo.originalStored && this.deps.originals) {
|
||||
@@ -344,7 +374,10 @@ 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...).
|
||||
// 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));
|
||||
|
||||
@@ -11,11 +11,54 @@ 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: { ignoredAt: true, person: { select: { name: true } }, suggested: { 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 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.
|
||||
*/
|
||||
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 +73,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<string, string | string[]>) : {};
|
||||
const vars = buildVars(eventInfoOf(event), photoInfoOf(photo), photographer ?? undefined, { iptc: embedded });
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -318,6 +318,109 @@ 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<string, unknown>;
|
||||
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("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<string, unknown>;
|
||||
};
|
||||
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 = (
|
||||
|
||||
@@ -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, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const t = new Date("2026-10-13T15:00:00Z");
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -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).`,
|
||||
|
||||
@@ -112,6 +112,27 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta
|
||||
</label>
|
||||
)}
|
||||
{s.selection === "best" && <p className="text-faint">{L.bestHelp}</p>}
|
||||
{s.selection === "best" && (
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.restTarget}</span>
|
||||
<select
|
||||
className="h-6 max-w-[180px] border border-black bg-cell px-1"
|
||||
disabled={!s.enabled || !props.canEdit}
|
||||
value={s.restTargetId ?? ""}
|
||||
onChange={(e) => void save({ ...s, restTargetId: e.target.value || null })}
|
||||
>
|
||||
<option value="">{L.noDelivery}</option>
|
||||
{props.targets
|
||||
.filter((x) => x.id !== s.deliverTargetId)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{s.selection === "best" && s.restTargetId && <p className="text-faint">{L.restHelp}</p>}
|
||||
{s.deliverTargetId && props.targets.find((x) => x.id === s.deliverTargetId)?.kind === "ZEROZERO" && (
|
||||
<ZerozeroGamePicker api={props.api} orgId={props.event.organizationId} targetId={s.deliverTargetId} eventId={props.event.id} />
|
||||
)}
|
||||
|
||||
@@ -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<string, string | string[]> | 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<string, string | string[]> | null {
|
||||
const out: Record<string, string | string[]> = {};
|
||||
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,
|
||||
@@ -157,7 +179,18 @@ 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<DeliveryTarget[]>([]);
|
||||
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<OverrideRow[]>(() => overrideRows(target?.iptcOverrides));
|
||||
// The FTP logins whose arrivals this destination can take (a relay to one's computer).
|
||||
const [logins, setLogins] = useState<FtpAccount[]>([]);
|
||||
useEffect(() => {
|
||||
@@ -202,15 +235,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 +512,77 @@ export function TargetForm({
|
||||
</fieldset>
|
||||
)}
|
||||
</div>
|
||||
{others.length > 0 && (
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">
|
||||
Copiar também para (o mesmo ficheiro, com o IPTC deste cliente)
|
||||
</span>
|
||||
<select
|
||||
className={input}
|
||||
value={v.copyTargetId ?? ""}
|
||||
onChange={(e) => setV({ ...v, copyTargetId: e.target.value || null })}
|
||||
>
|
||||
<option value="">Não copiar</option>
|
||||
{others.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
{x.kind === "LOCAL" ? " (pasta no computador)" : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{!(v.originals && v.untouched) && (
|
||||
<fieldset className="space-y-2 border border-line p-3 text-[12px]">
|
||||
<legend className="px-1 text-[11px] text-faint">
|
||||
IPTC deste cliente (substitui o do evento)
|
||||
</legend>
|
||||
<p className="text-faint">
|
||||
Por exemplo Creator/Photographer com a agência para quem trabalhas neste cliente. Aceita as variáveis
|
||||
do evento: <code className="font-mono">{"{players}"}</code> dá os jogadores da esquerda para a direita
|
||||
na foto. Nas listas (Keywords…) separa por vírgulas.
|
||||
</p>
|
||||
{overrides.map((row, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<select
|
||||
aria-label="Campo IPTC"
|
||||
className={`${input} w-48 shrink-0`}
|
||||
value={row.key}
|
||||
onChange={(e) => setOverrides(overrides.map((r, j) => (j === i ? { ...r, key: e.target.value } : r)))}
|
||||
>
|
||||
<option value="">Campo…</option>
|
||||
{IPTC_FIELDS.map((f) => (
|
||||
<option key={f.key} value={f.key} disabled={f.key !== row.key && overrides.some((r) => r.key === f.key)}>
|
||||
{f.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<input
|
||||
aria-label="Valor"
|
||||
className={`${input} min-w-0 flex-1`}
|
||||
value={row.value}
|
||||
placeholder={row.key === "title" ? "{players}" : row.key === "creator" ? "Peter Spark / Movephoto" : ""}
|
||||
onChange={(e) => setOverrides(overrides.map((r, j) => (j === i ? { ...r, value: e.target.value } : r)))}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Remover campo"
|
||||
className="h-8 shrink-0 border border-black bg-cell px-2 text-muted hover:text-ink"
|
||||
onClick={() => setOverrides(overrides.filter((_, j) => j !== i))}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="h-7 border border-black bg-cell px-3 text-ink hover:bg-cell-on"
|
||||
onClick={() => setOverrides([...overrides, { key: "", value: "" }])}
|
||||
>
|
||||
Adicionar campo
|
||||
</button>
|
||||
</fieldset>
|
||||
)}
|
||||
{!v.originals && (
|
||||
<fieldset className="grid grid-cols-2 gap-3 border border-line p-3 max-sm:grid-cols-1">
|
||||
<legend className="px-1 text-[11px] text-faint">
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<typeof AutopilotSettings>;
|
||||
|
||||
|
||||
@@ -249,6 +249,10 @@ 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<string, string | string[]> | 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;
|
||||
@@ -312,6 +316,9 @@ export interface DeliveryTargetInput {
|
||||
onArrival?: boolean;
|
||||
arrivalLogins?: string[];
|
||||
untouched?: boolean;
|
||||
/** IPTC fields this client gets instead of the event's; null: none. */
|
||||
iptcOverrides?: Record<string, string | string[]> | null;
|
||||
copyTargetId?: string | null;
|
||||
}
|
||||
|
||||
export interface PersonSummary {
|
||||
|
||||
Reference in new issue
Block a user