diff --git a/apps/api/prisma/migrations/20261018180000_delivery_local_folder/migration.sql b/apps/api/prisma/migrations/20261018180000_delivery_local_folder/migration.sql new file mode 100644 index 0000000..76f40fa --- /dev/null +++ b/apps/api/prisma/migrations/20261018180000_delivery_local_folder/migration.sql @@ -0,0 +1,10 @@ +-- A non-local export can also keep a copy in a folder on one computer. +ALTER TABLE "delivery_targets" ADD COLUMN "local_folder" TEXT; +ALTER TABLE "delivery_targets" ADD COLUMN "local_machine" TEXT; +ALTER TABLE "delivery_targets" ADD COLUMN "local_folder_template" TEXT; +-- The hidden LOCAL target that receives those copies. +ALTER TABLE "delivery_targets" ADD COLUMN "mirror_of_id" UUID; + +CREATE UNIQUE INDEX "delivery_targets_mirror_of_id_key" ON "delivery_targets"("mirror_of_id"); + +ALTER TABLE "delivery_targets" ADD CONSTRAINT "delivery_targets_mirror_of_id_fkey" FOREIGN KEY ("mirror_of_id") REFERENCES "delivery_targets"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 0695de4..2afce18 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -564,12 +564,23 @@ model DeliveryTarget { /// 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 + /// A folder on one computer that also receives every file this destination exports (FTP and the rest stay as + /// they are). Not for a LOCAL target. The desktop app of `localMachine` writes under this path. + localFolder String? @map("local_folder") + /// That computer's id (`delivery_machine`). + localMachine String? @map("local_machine") + /// Subfolders under `localFolder`. `{destination}` is this target's name. + 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 createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") disabledAt DateTime? @map("disabled_at") - organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) + organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) items DeliveryItem[] + mirrorOf DeliveryTarget? @relation("LocalMirror", fields: [mirrorOfId], references: [id], onDelete: Cascade) + localMirror DeliveryTarget? @relation("LocalMirror") @@unique([organizationId, name]) @@map("delivery_targets") diff --git a/apps/api/src/archive/match.ts b/apps/api/src/archive/match.ts index 808e2ef..0eb013e 100644 --- a/apps/api/src/archive/match.ts +++ b/apps/api/src/archive/match.ts @@ -1,4 +1,5 @@ import { sameTeam } from "../delivery/zerozero.js"; +import { officialSigla } from "../sports/fpa-siglas.js"; /** * What a gallery folder's place and name say about its game. The archives are organised by season, competition @@ -377,6 +378,10 @@ export function isTeam(name: string, team: { name: string; abbreviation: string if (team.abbreviation && fold(team.abbreviation) === n) return true; if (fold(team.slug) === n || fold(team.name) === n) return true; if (sameTeam(name, team.name)) return true; + // The delivery writes the federation's short code ("AAAS"). That is not the initials of the sponsor name + // ("Águas Santas Milaneza" is A, S, M), and these teams have no abbreviation of their own. + const sigla = officialSigla(team.name); + if (sigla && fold(sigla) === n) return true; return name.trim().length <= 6 && !/\s/.test(name.trim()) && isInitials(name, team.name); } diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 20035fa..5283889 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -321,7 +321,12 @@ export async function registerArchiveViewerRoutes( ...(query.player && { photo: { players: { has: query.player } } }), ...(query.person && { photo: { faces: { some: { group: { personId: query.person, ignoredAt: null } } } } }), }; - const [total, files, named, sharpest] = await Promise.all([ + // People named anywhere in this game (every part the viewer may see), not only in this folder. + const rosterScope = + visible === "all" + ? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE'` + : Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[])`; + const [total, files, named, sharpest, roster] = await Promise.all([ db.cloudFile.count({ where }), db.cloudFile.findMany({ where, @@ -344,6 +349,19 @@ export async function registerArchiveViewerRoutes( JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE' ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`, + folder.eventId + ? db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; here: number; in_game: number }[]>` + SELECT p.id, p.name, p.club, p.number, + count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ${folderId}::uuid)::int AS here, + count(DISTINCT cf.photo_id)::int AS in_game + FROM faces f + JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL + JOIN people p ON p.id = g.person_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${rosterScope} + JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${folder.eventId}::uuid + GROUP BY p.id, p.name, p.club, p.number + ORDER BY p.name` + : Promise.resolve([]), ]); const facePhotos = await db.photo.findMany({ where: { id: { in: sharpest.map((f) => f.photo_id) } }, @@ -368,6 +386,8 @@ export async function registerArchiveViewerRoutes( cloudUrl: `${base}/f/${folder.fileId}`, total, people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), + /** Everyone named in this game, so a gallery can offer them even when this part has only some. */ + roster: roster.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, here: Number(p.here), inGame: Number(p.in_game) })), photos: files.map((f) => ({ id: f.photo!.id, name: f.path.split("/").pop(), diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index 8f76d4d..19e780b 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -1,7 +1,7 @@ import { createReadStream, existsSync } from "node:fs"; import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts"; import { bestOfEvent } from "../autopilot/best.js"; -import { IptcTemplate, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata"; +import { IptcTemplate, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js"; @@ -10,7 +10,7 @@ import type { Db } from "../db.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"; +import { DeliveryRejected, syncLocalMirror, type DeliveryService, toItemSummary } from "./service.js"; import { NextcloudError } from "./nextcloud.js"; import { TransportError } from "./transports.js"; import type { SecretBox } from "./secrets.js"; @@ -59,6 +59,12 @@ const TargetBase = z.object({ 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(), + /** Also save each exported file under this folder on one computer. Null: the export only. Not for LOCAL. */ + localFolder: z.string().trim().min(1).max(300).nullable(), + /** That computer's id. Required when `localFolder` is set. */ + 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(), }); 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}`); @@ -79,6 +85,9 @@ const TargetFields = TargetBase.extend({ untouched: TargetBase.shape.untouched.default(false), iptcOverrides: TargetBase.shape.iptcOverrides.default(null), copyTargetId: TargetBase.shape.copyTargetId.default(null), + localFolder: TargetBase.shape.localFolder.default(null), + localMachine: TargetBase.shape.localMachine.default(null), + localFolderTemplate: TargetBase.shape.localFolderTemplate.default(null), }); const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() }); const ListQuery = z.object({ @@ -100,17 +109,35 @@ function overridesValue(o: unknown): Prisma.InputJsonValue | typeof Prisma.DbNul } function publicTarget(t: DeliveryTarget) { - const { secretEnc: _secret, ...rest } = t; + const { secretEnc: _secret, mirrorOfId: _mirror, ...rest } = t; return { ...rest, shareLinks: t.kind === "NEXTCLOUD" || t.kind === "DROPBOX" }; } +/** The local copy of an export: a real folder on a computer. A destination that is already a folder has none. */ +function localCopyOf( + kind: z.infer, + fields: { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null }, +): { localFolder: string | null; localMachine: string | null; localFolderTemplate: string | null } { + if (kind === "LOCAL" || !fields.localFolder) { + return { localFolder: null, localMachine: null, localFolderTemplate: null }; + } + if (!ADDRESS.LOCAL.test(fields.localFolder)) throw badRequest("invalid_address", "the local folder must be an absolute path"); + if (!fields.localMachine) throw badRequest("username_required"); + const localFolderTemplate = fields.localFolderTemplate || LOCAL_COPY_FOLDER; + checkTemplates(localFolderTemplate, "{originalName}", { destination: "Cliente" }); + return { localFolder: fields.localFolder, localMachine: fields.localMachine, localFolderTemplate }; +} + /** Renders the templates against a sample event so a broken template is refused when saved, not at delivery. */ -function checkTemplates(folderTemplate: string, fileNameTemplate: string) { - const sample = buildVars( - { home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") }, - { capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 }, - "Fotógrafo", - ); +function checkTemplates(folderTemplate: string, fileNameTemplate: string, extra: Record = {}) { + const sample = { + ...buildVars( + { home: "Casa", away: "Fora", venue: "Pavilhão", city: "Cidade", sport: "andebol", competition: "Competição", competitionCode: "C01", round: "1", matchNumber: "1", startsAt: new Date("2026-09-23T19:00:00Z") }, + { capturedAt: new Date("2026-09-23T19:30:00Z"), players: ["Jogador"], sequence: 1 }, + "Fotógrafo", + ), + ...extra, + }; try { return { folder: renderFolder(folderTemplate, sample), fileName: renderFileName(fileNameTemplate, sample, "IMG_0001.JPG") }; } catch (err) { @@ -135,7 +162,7 @@ export async function registerDeliveryRoutes( 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"); + if (!(await db.deliveryTarget.count({ where: { id: copyId, organizationId: orgId, mirrorOfId: null } }))) throw badRequest("unknown_copy_target"); }; const seal = (password: string) => { if (!secrets) throw new AppError(503, "delivery_not_configured", "DELIVERY_SECRET_KEY is not set"); @@ -152,7 +179,7 @@ export async function registerDeliveryRoutes( app.get("/v1/orgs/:orgId/delivery-targets", { preHandler: authenticate }, async (req) => { const { orgId } = OrgParams.parse(req.params); await requireMembership(db, req, orgId, "INGESTER"); - const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId }, orderBy: { name: "asc" } }); + const targets = await db.deliveryTarget.findMany({ where: { organizationId: orgId, mirrorOfId: null }, orderBy: { name: "asc" } }); return { targets: targets.map(publicTarget) }; }); @@ -163,11 +190,13 @@ 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, iptcOverrides, ...fields } = body; + const { password, iptcOverrides, localFolder: _lf, localMachine: _lm, localFolderTemplate: _lt, ...fields } = body; + const local = localCopyOf(body.kind, body); if (!password && body.kind !== "LOCAL") throw badRequest("password_required"); await checkLogins(orgId, body.arrivalLogins); await checkCopy(orgId, null, body.copyTargetId); - const target = await db.deliveryTarget.create({ data: { ...fields, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } }); + const target = await db.deliveryTarget.create({ data: { ...fields, ...local, iptcOverrides: overridesValue(iptcOverrides), organizationId: orgId, secretEnc: seal(password ?? "") } }); + await syncLocalMirror(db, secrets, target).catch(fail); return reply.code(201).send({ ...publicTarget(target), example }); }); @@ -184,18 +213,25 @@ export async function registerDeliveryRoutes( // 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, iptcOverrides, ...fields } = body; + const local = localCopyOf(kind, { + localFolder: fields.localFolder !== undefined ? fields.localFolder : current.localFolder, + localMachine: fields.localMachine !== undefined ? fields.localMachine : current.localMachine, + localFolderTemplate: fields.localFolderTemplate !== undefined ? fields.localFolderTemplate : current.localFolderTemplate, + }); 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), + ...local, ...(iptcOverrides !== undefined && { iptcOverrides: overridesValue(iptcOverrides) }), ...(password !== undefined && { secretEnc: seal(password) }), ...(forgetKey && { hostFingerprint: null }), ...(disabled !== undefined && { disabledAt: disabled ? (current.disabledAt ?? new Date()) : null }), }, }); + await syncLocalMirror(db, secrets, target).catch(fail); return { ...publicTarget(target), example }; }); @@ -209,8 +245,9 @@ 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, iptcOverrides, ...copy } = source; + const { id: _id, createdAt: _c, updatedAt: _u, disabledAt: _d, iptcOverrides, mirrorOfId: _mirror, ...copy } = source; const target = await db.deliveryTarget.create({ data: { ...copy, iptcOverrides: overridesValue(iptcOverrides), name: body.name, folderTemplate } }); + await syncLocalMirror(db, secrets, target).catch(fail); return reply.code(201).send({ ...publicTarget(target), example }); }); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index dcea70e..2dc2cf9 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -1,7 +1,7 @@ import type { DeliveryItemSummary } from "@photoreport/contracts"; -import { buildVars, createdStamp, eventName, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata"; +import { buildVars, createdStamp, eventName, LOCAL_COPY_FOLDER, PathTemplateError, renderFileName, renderFolder } from "@photoreport/metadata"; import type { Db } from "../db.js"; -import type { DeliveryItem } from "../generated/prisma/client.js"; +import type { DeliveryItem, DeliveryTarget } from "../generated/prisma/client.js"; import type { IngestLogger } from "../ingest/service.js"; import { waitUntil } from "../lib/idle.js"; import { eventInfoOf } from "../library/event-info.js"; @@ -61,6 +61,45 @@ export function deliveredName(photo: { originalName: string; fileName: string | /** Where a file rendered for a computer's folder waits on the server. */ export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`; +/** + * Keeps the hidden LOCAL target that receives one export's local copies in step with that export (same file name + * and output). Turning the folder off disables it; the export itself is unchanged. + */ +export async function syncLocalMirror(db: Db, secrets: { seal(plain: string): string } | undefined, target: DeliveryTarget): Promise { + const existing = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id } }); + const off = target.kind === "LOCAL" || !target.localFolder || !target.localMachine; + if (off) { + if (existing && !existing.disabledAt) await db.deliveryTarget.update({ where: { id: existing.id }, data: { disabledAt: new Date() } }); + return; + } + const data = { + name: `local-copy:${target.id}`, + kind: "LOCAL" as const, + baseUrl: target.localFolder!, + username: target.localMachine!, + folderTemplate: target.localFolderTemplate || LOCAL_COPY_FOLDER, + fileNameTemplate: target.fileNameTemplate, + longEdge: target.longEdge, + jpegQuality: target.jpegQuality, + sharpen: target.sharpen, + dpi: target.dpi, + keepExif: target.keepExif, + srgb: target.srgb, + originals: target.originals, + untouched: target.untouched, + onArrival: false, + arrivalLogins: [] as string[], + disabledAt: null, + organizationId: target.organizationId, + }; + if (existing) { + await db.deliveryTarget.update({ where: { id: existing.id }, data }); + return; + } + if (!secrets) throw new DeliveryRejected("delivery_secret_key_missing"); + await db.deliveryTarget.create({ data: { ...data, mirrorOfId: target.id, secretEnc: secrets.seal("") } }); +} + /** * Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination * (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED): @@ -148,6 +187,8 @@ export class DeliveryService { requestedById: string | null; /** Set when this is the local copy of a delivery to that target. */ via?: string; + /** Photo id → sequence of the export this copies, so `{n}` in the file name matches the file that was sent. */ + sequences?: ReadonlyMap; }): 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 } }); @@ -188,9 +229,13 @@ export class DeliveryService { let next = (last._max.sequence ?? 0) + 1; const created: DeliveryItem[] = []; for (const photo of group) { + // A local copy of an export keeps that export's number, so the file name is the one that was sent. + const fixed = input.sequences?.get(photo.id); + const sequence = fixed ?? next; + if (fixed === undefined || fixed >= next) next = sequence + 1; created.push( await tx.deliveryItem.create({ - data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence: next++, requestedById: input.requestedById, viaTargetId: input.via ?? null }, + data: { organizationId: input.organizationId, targetId: target.id, photoId: photo.id, eventId, sequence, requestedById: input.requestedById, viaTargetId: input.via ?? null }, }), ); } @@ -199,11 +244,30 @@ 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"), - ); + // Copies are not copied again. The export itself is unchanged; these are extra files. + if (!input.via && queued.length) { + const photoIds = queued.map((q) => q.photoId); + if (target.copyTargetId && target.copyTargetId !== target.id) { + await this.enqueue({ ...input, targetId: target.copyTargetId, photoIds, via: target.id }).catch((err: unknown) => + this.deps.log.warn({ err, targetId: target.id, copyTargetId: target.copyTargetId }, "delivery: copy not queued"), + ); + } + // The same export, also saved under the computer folder (date, game, destination name). + if (target.kind !== "LOCAL" && target.localFolder && target.localMachine) { + const mirror = await db.deliveryTarget.findFirst({ where: { mirrorOfId: target.id, disabledAt: null } }); + if (!mirror) this.deps.log.warn({ targetId: target.id }, "delivery: local folder set but its copy target is missing"); + else { + await this.enqueue({ + organizationId: input.organizationId, + targetId: mirror.id, + photoIds, + again: input.again, + requestedById: input.requestedById, + via: target.id, + sequences: new Map(queued.map((q) => [q.photoId, q.sequence])), + }).catch((err: unknown) => this.deps.log.warn({ err, targetId: target.id }, "delivery: local copy not queued")); + } + } } return { queued, skipped }; } @@ -397,25 +461,29 @@ export class DeliveryService { try { // The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad. // With this client's own fields on top (another agency in Creator, players left to right in Title...). - // 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); + // A copy of another client's delivery is written with that client's IPTC. The local folder of an export is + // the same file that client got (its size, name and IPTC), filed by day, game and destination. + const viaTarget = item.viaTargetId ? await db.deliveryTarget.findUnique({ where: { id: item.viaTargetId } }) : null; + const sameExport = Boolean(item.target.mirrorOfId && viaTarget); + const recipe = sameExport && viaTarget ? viaTarget : item.target; + const iptc = await iptcForPhoto(db, item.photoId, (viaTarget ?? item.target).iptcOverrides); const source = cloud?.file ?? storage.resolve(item.photo.storageKey); // Photos from before the camera details were kept: read them from the file being sent. const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null)); const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values }); - let folder = renderFolder(item.target.folderTemplate, vars); - if (item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`; + const named = sameExport && viaTarget ? { ...vars, destination: viaTarget.name } : vars; + let folder = renderFolder(sameExport && viaTarget ? viaTarget.localFolderTemplate || LOCAL_COPY_FOLDER : item.target.folderTemplate, named); + if (!sameExport && item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`; // {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file). // Untouched: the camera's own name, as a local FTP would have received it. - const fileName = renderFileName(item.target.fileNameTemplate, vars, item.target.originals && item.target.untouched ? item.photo.originalName : deliveredName(item.photo)); + const fileName = renderFileName(recipe.fileNameTemplate, named, recipe.originals && recipe.untouched ? item.photo.originalName : deliveredName(item.photo)); const edit = await this.editFor(item.photoId, item.photo.developSeq); const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined; - const rendered = item.target.originals - ? item.target.untouched + const rendered = recipe.originals + ? recipe.untouched ? await readFile(source) : await originalWithMetadata(source, iptc?.values ?? {}, created) - : await renderDelivery(source, iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, created, edit); + : await renderDelivery(source, iptc?.values ?? {}, { longEdge: recipe.longEdge, quality: recipe.jpegQuality, sharpen: recipe.sharpen, dpi: recipe.dpi, exif: recipe.keepExif, srgb: recipe.srgb }, created, edit); const data = rendered; if (item.target.kind === "LOCAL") { // Kept here until the computer's desktop app takes it (localClaim → localFile → localResult). diff --git a/apps/api/src/faces/service.ts b/apps/api/src/faces/service.ts index 62d57e8..afa7513 100644 --- a/apps/api/src/faces/service.ts +++ b/apps/api/src/faces/service.ts @@ -266,6 +266,9 @@ export class FaceService { const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport); // Numbers as worn in this event's season and competition (another season, a cup, the national team: another). const ctx = await numberContext(db, eventId); + // A game linked to its two clubs: only those squads. Another club's player who looks alike is not a guess. + const squadIds = ctx?.teamIds.length ? await playerIdsOnSquads(db, ctx.teamIds, ctx.season) : null; + const candidates = squadIds ? people.filter((p) => p.sportsPlayerId !== null && squadIds.has(p.sportsPlayerId)) : people; const worn = new Map(); const numberOf = async (ids: string[]): Promise> => { const missing = ids.filter((id) => !worn.has(id)); @@ -277,7 +280,7 @@ export class FaceService { }; for (const g of groups) { const { match, margin } = this.thresholds(g.model); - const ranked = people + const ranked = candidates .filter((p) => p.model === g.model) .map((p) => ({ p, s: cosine(p.centroid, g.centroid) })) .sort((a, b) => b.s - a.s); @@ -577,6 +580,31 @@ export function normSport(s: string | null | undefined): string | null { return v; } +/** + * Squad entries of these teams this season, plus the same player written under another season (the federation id, + * or the same name at the same club). Null when this season's squad is not here yet: then a face may still be + * matched more widely. An empty set means the squad is known and nobody outside it is a candidate. + */ +async function playerIdsOnSquads(db: Db, teamIds: string[], season: string): Promise | null> { + const squad = await db.sportsPlayer.findMany({ + where: { teamId: { in: teamIds }, season }, + select: { id: true, teamId: true, name: true, externalId: true }, + }); + if (!squad.length) return null; + const externalIds = [...new Set(squad.map((s) => s.externalId).filter((x): x is string => !!x))]; + const same = await db.sportsPlayer.findMany({ + where: { + OR: [ + { id: { in: squad.map((s) => s.id) } }, + ...squad.map((s) => ({ teamId: s.teamId, name: s.name })), + ...(externalIds.length ? [{ externalId: { in: externalIds } }] : []), + ], + }, + select: { id: true }, + }); + return new Set(same.map((s) => s.id)); +} + /** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */ export async function eventSport(db: Db, eventId: string): Promise { const rows = await db.$queryRaw<{ sport: string | null }[]>` diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index c378266..2ce81c1 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -169,6 +169,22 @@ describe("archive folder names", () => { expect(isTeam("ABC", { name: "ABC de Braga / Uminho", abbreviation: null, slug: "abc-braga" })).toBe(true); expect(isTeam("SLB", { name: "Sport Lisboa e Benfica", abbreviation: null, slug: "benfica" })).toBe(true); expect(isTeam("SLB", { name: "Sporting Clube de Portugal", abbreviation: null, slug: "sporting" })).toBe(false); + // The program writes the federation code. "AAAS" is not the initials of the sponsor name. + const aguas = { name: "Águas Santas Milaneza", abbreviation: null, slug: "aguas-santas-milaneza" }; + const sporting = { name: "Sporting CP", abbreviation: null, slug: "sporting-cp" }; + expect(isTeam("AAAS", aguas)).toBe(true); + expect(isTeam("SCP", sporting)).toBe(true); + expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-aguas-santas-b" })).toBe(false); + const today: FixtureCandidate = { + id: "hoje", + startsAt: new Date("2026-10-18T13:00:00Z"), + season: "20262027", + round: null, + competition: { externalId: "PO01" }, + homeTeam: aguas, + awayTeam: sporting, + }; + expect(pickFixture(parseFolder("/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20261018 - AAAS x SCP")!, [today])?.id).toBe("hoje"); }); it("takes a game only when both sides are recognised, never with one guessed", () => { @@ -686,6 +702,7 @@ describe("archive from a Nextcloud", () => { expect(res.json().total).toBe(2); expect(res.json().photos[0].faces).toBeUndefined(); expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]); + expect(res.json().roster).toEqual([expect.objectContaining({ name: "Martim Costa", here: 2, inGame: 2 })]); res = await get(owner, `/v1/archive/photos/${p2.id}`); expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort()); diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index b5ecd85..9bb1f6f 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -404,6 +404,56 @@ describe("delivery", () => { expect(copied["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)"); }); + it("saves the same export into a computer folder named by the day, the game and the destination", async () => { + const { orgId, token, target } = await setup(); + const saved = await ctx.app.inject({ + method: "PATCH", + url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, + headers: bearer(token), + payload: { localFolder: "/Users/cyclop/Desktop/2026", localMachine: "desktop-0000000000000001", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" }, + }); + expect(saved.statusCode).toBe(200); + expect(saved.json()).toMatchObject({ baseUrl: "https://cloud.test", localFolder: "/Users/cyclop/Desktop/2026", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" }); + const listed = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token) })).json() as { targets: { name: string }[] }; + expect(listed.targets.map((t) => t.name)).toEqual(["FPA"]); + + const id = await photo("a.jpg", "2026:09:23 21:10:00"); + await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } }); + await drain(); + + const sentPath = [...nc.files.keys()][0]!; + expect(sentPath.endsWith("/PS_VSC x AAAS_1.jpg")).toBe(true); + const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { viaTargetId: target.id } }); + expect([copy.status, copy.sequence, copy.remotePath]).toEqual(["WAITING", 1, "20260923 - VSC x AAAS - FPA/PS_VSC x AAAS_1.jpg"]); + const mirror = await ctx.db.deliveryTarget.findFirstOrThrow({ where: { mirrorOfId: target.id } }); + expect(mirror).toMatchObject({ kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", disabledAt: null }); + + const cleared = await ctx.app.inject({ + method: "PATCH", + url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, + headers: bearer(token), + payload: { localFolder: null }, + }); + expect(cleared.statusCode).toBe(200); + expect((cleared.json() as { localFolder: null }).localFolder).toBeNull(); + expect((await ctx.db.deliveryTarget.findFirstOrThrow({ where: { id: mirror.id } })).disabledAt).not.toBeNull(); + + const later = await photo("b.jpg", "2026:09:23 21:20:00"); + await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [later] } }); + await drain(); + expect(await ctx.db.deliveryItem.count({ where: { viaTargetId: target.id } })).toBe(1); + + // A destination that is already a folder does not grow a second copy of itself. + const localOnly = await ctx.app.inject({ + method: "POST", + url: `/v1/orgs/${orgId}/delivery-targets`, + headers: bearer(token), + payload: { name: "Pasta", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", localFolder: "/tmp/outra", localMachine: "desktop-0000000000000001" }, + }); + expect(localOnly.statusCode).toBe(201); + expect((localOnly.json() as { localFolder: null }).localFolder).toBeNull(); + }); + it("waits a little for the faces to be read before sending, so the names go with the photo", async () => { const { orgId, token, target } = await setup(); await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } }); diff --git a/apps/app/src/library/TargetForm.tsx b/apps/app/src/library/TargetForm.tsx index 3a8b929..87437f6 100644 --- a/apps/app/src/library/TargetForm.tsx +++ b/apps/app/src/library/TargetForm.tsx @@ -1,4 +1,4 @@ -import { DESTINATION_EXAMPLES, IPTC_FIELDS } from "@photoreport/metadata"; +import { DESTINATION_EXAMPLES, IPTC_FIELDS, LOCAL_COPY_FOLDER } from "@photoreport/metadata"; import { ApiError, type ApiClient, @@ -180,6 +180,9 @@ export function TargetForm({ arrivalLogins: target?.arrivalLogins ?? ([] as string[]), untouched: target?.untouched ?? false, copyTargetId: target?.copyTargetId ?? null, + localFolder: target?.localFolder ?? null, + localMachine: target?.localMachine ?? null, + localFolderTemplate: target?.localFolderTemplate || LOCAL_COPY_FOLDER, }); // The other destinations a copy can go to (a folder on this computer, usually). const [others, setOthers] = useState([]); @@ -239,8 +242,12 @@ export function TargetForm({ const { password: _pw, ...base } = v; const iptcOverrides = overridesOf(overrides); const password = v.password; - const rest = { ...base, iptcOverrides }; - const all = { ...v, iptcOverrides }; + const local = + v.kind === "LOCAL" || !v.localFolder + ? { localFolder: null, localMachine: null, localFolderTemplate: null } + : { localFolder: v.localFolder, localMachine: v.localMachine, localFolderTemplate: v.localFolderTemplate || LOCAL_COPY_FOLDER }; + const rest = { ...base, ...local, iptcOverrides }; + const all = { ...v, ...local, iptcOverrides }; if (v.kind === "LOCAL" && !v.baseUrl) { setBusy(false); setError("Escolhe a pasta."); @@ -513,6 +520,75 @@ export function TargetForm({ )} + {v.kind !== "LOCAL" && ( +
+ Cópia neste computador +

+ O envio (FTP, cloud, …) fica como está. Cada ficheiro enviado é gravado também numa pasta, para se ver + depois o que foi para onde. A app de computador tem de estar aberta nessa máquina. +

+ + {v.localFolder && ( + <> +
+ {v.localFolder} + {isDesktop() && ( + + )} +
+ +

+ {v.localFolder.replace(/\/$/, "")}/20261018 - Águas Santas Milaneza x Sporting CP - {v.name || "Record"}/ +

+ + )} +
+ )} {others.length > 0 && (