diff --git a/apps/api/prisma/migrations/20261013040000_rename_and_output/migration.sql b/apps/api/prisma/migrations/20261013040000_rename_and_output/migration.sql new file mode 100644 index 0000000..a2caaf3 --- /dev/null +++ b/apps/api/prisma/migrations/20261013040000_rename_and_output/migration.sql @@ -0,0 +1,14 @@ +-- Rename on arrival (organisation template, per FTP login override) and Photo Mechanic's uploader output options. +-- AlterTable +ALTER TABLE "delivery_targets" ADD COLUMN "dpi" INTEGER NOT NULL DEFAULT 300, +ADD COLUMN "keep_exif" BOOLEAN NOT NULL DEFAULT true, +ADD COLUMN "sharpen" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "srgb" BOOLEAN NOT NULL DEFAULT false; + +-- AlterTable +ALTER TABLE "ftp_accounts" ADD COLUMN "rename_template" TEXT; + +-- AlterTable +ALTER TABLE "photos" ADD COLUMN "file_name" TEXT; + +ALTER TABLE "organizations" ADD COLUMN "rename_template" TEXT; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 326a575..479c973 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -64,6 +64,9 @@ model Organization { /// Player-code generator settings (contracts CodeGeneratorSettings); null: defaults. codeGenerator Json? @map("code_generator") + /// File name given to photos as they arrive by FTP or the desktop app (e.g. PS_{event}_{timesort}); null: keep + /// the camera's. An FTP login can have its own. + renameTemplate String? @map("rename_template") memberships Membership[] events Event[] photos Photo[] @@ -260,6 +263,8 @@ model FtpAccount { /// Argon2 hash of the FTP password; SFTPGo asks the API to check it (external authentication hook). passwordHash String? @map("password_hash") lastLoginAt DateTime? @map("last_login_at") + /// This photographer's own rename template (overrides the organisation's; "" keeps the camera names). + renameTemplate String? @map("rename_template") createdAt DateTime @default(now()) @map("created_at") organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) @@ -276,6 +281,9 @@ model Photo { uploaderId String? @map("uploader_id") @db.Uuid source PhotoSource originalName String @map("original_name") + /// The name given on arrival by the rename template (Photo Mechanic's Live Ingest "Rename"), without the + /// extension; null keeps the camera's. Deliveries use it as {originalName}. + fileName String? @map("file_name") /// SHA-256 of the original as shot (also when only a preview was sent: the desktop app declares it). sha256 String byteSize Int @map("byte_size") @@ -418,6 +426,12 @@ model DeliveryTarget { fileNameTemplate String @map("file_name_template") longEdge Int @default(4000) @map("long_edge") jpegQuality Int @default(100) @map("jpeg_quality") + /// Output sharpening after resizing, pixels per inch, camera EXIF kept, conversion to sRGB (as in Photo + /// Mechanic's uploader). + sharpen Boolean @default(false) + dpi Int @default(300) + keepExif Boolean @default(true) @map("keep_exif") + srgb Boolean @default(false) createdAt DateTime @default(now()) @map("created_at") updatedAt DateTime @updatedAt @map("updated_at") disabledAt DateTime? @map("disabled_at") diff --git a/apps/api/src/delivery/render.ts b/apps/api/src/delivery/render.ts index 32efdb1..2ced20e 100644 --- a/apps/api/src/delivery/render.ts +++ b/apps/api/src/delivery/render.ts @@ -3,7 +3,7 @@ import { exiftool } from "exiftool-vendored"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import sharp from "sharp"; +import sharp, { type Sharp } from "sharp"; import type { RenderEngine, Settings } from "../develop/engine.js"; /** The photo was edited: render it with these develop settings. */ @@ -15,6 +15,14 @@ export interface DeliveryEdit { export interface RenderOptions { longEdge: number; quality: number; + /** Output sharpening after resizing (Photo Mechanic's "Sharpen"). */ + sharpen?: boolean; + /** Pixels per inch written in the file (newspapers still look at it). */ + dpi?: number; + /** Keep the camera EXIF (Photo Mechanic's "Preserve EXIF information"). */ + exif?: boolean; + /** Convert to sRGB (unedited photos keep their profile otherwise; edited ones are always sRGB). */ + srgb?: boolean; } /** @@ -24,25 +32,29 @@ export interface RenderOptions { export async function renderDelivery(original: string, iptc: IptcValues, opts: RenderOptions, created?: CreatedStamp, edit?: DeliveryEdit): Promise { const dir = await mkdtemp(path.join(tmpdir(), "pr-render-")); const file = path.join(dir, "out.jpg"); + const exif = opts.exif !== false; + const finish = (img: Sharp) => { + if (opts.sharpen) img = img.sharpen({ sigma: 0.6, m1: 0.5, m2: 2 }); + img = opts.srgb || edit ? img.withIccProfile("srgb") : img.keepIccProfile(); + return img.jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false }).toBuffer(); + }; + const dpi = opts.dpi ? [`-XResolution=${opts.dpi}`, `-YResolution=${opts.dpi}`, "-ResolutionUnit=inches", `-JFIF:XResolution=${opts.dpi}`, `-JFIF:YResolution=${opts.dpi}`, "-JFIF:ResolutionUnit=inches"] : []; try { if (edit) { - // Edited: the develop engine renders the original (crop and all) straight to the delivered size and quality, - // in sRGB. The camera EXIF is copied back, without the orientation (the pixels are already upright). - await edit.engine.render({ input: original, output: file, settings: edit.settings, maxEdge: opts.longEdge, quality: opts.quality }); - await exiftool.write(file, {}, { - writeArgs: ["-overwrite_original", "-TagsFromFile", original, "-EXIF:all", "--Orientation", "--ThumbnailImage", "--PreviewImage", "-Orientation#=1", ...toExiftoolArgs(iptc, created)], - }); + // Edited: the develop engine renders the original (crop and all) straight to the delivered size, in sRGB, + // losslessly enough (quality 100) for the last pass to sharpen and encode at the delivered quality. + const rendered = path.join(dir, "edited.jpg"); + await edit.engine.render({ input: original, output: rendered, settings: edit.settings, maxEdge: opts.longEdge, quality: opts.sharpen || opts.quality < 100 ? 100 : opts.quality }); + await writeFile(file, opts.sharpen || opts.quality < 100 ? await finish(sharp(rendered)) : await readFile(rendered)); + // The camera EXIF is copied back, without the orientation (the pixels are already upright). + const copyExif = exif ? ["-TagsFromFile", original, "-EXIF:all", "--Orientation", "--ThumbnailImage", "--PreviewImage", "-Orientation#=1"] : []; + await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...copyExif, ...dpi, ...toExiftoolArgs(iptc, created)] }); return await readFile(file); } - const image = await sharp(original) - .rotate() - .resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true }) - .keepExif() - .keepIccProfile() - .jpeg({ quality: opts.quality, chromaSubsampling: "4:4:4", mozjpeg: false }) - .toBuffer(); - await writeFile(file, image); - await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created)] }); + let img = sharp(original).rotate().resize({ width: opts.longEdge, height: opts.longEdge, fit: "inside", withoutEnlargement: true }); + if (exif) img = img.keepExif(); + await writeFile(file, await finish(img)); + await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...dpi, ...toExiftoolArgs(iptc, created)] }); return await readFile(file); } finally { await rm(dir, { recursive: true, force: true }); diff --git a/apps/api/src/delivery/routes.ts b/apps/api/src/delivery/routes.ts index 1de630d..19e0d47 100644 --- a/apps/api/src/delivery/routes.ts +++ b/apps/api/src/delivery/routes.ts @@ -36,14 +36,26 @@ const TargetBase = z.object({ folderTemplate: z.string().trim().min(1).max(400), fileNameTemplate: z.string().trim().min(1).max(200), longEdge: z.number().int().min(800).max(12000), - jpegQuality: z.number().int().min(60).max(100), + jpegQuality: z.number().int().min(40).max(100), + sharpen: z.boolean(), + dpi: z.number().int().min(72).max(1200), + keepExif: z.boolean(), + srgb: z.boolean(), }); 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}`); if (kind !== "DROPBOX" && !username) throw badRequest("username_required"); }; // Defaults only when creating: an update that leaves a field out keeps what is saved. -const TargetFields = TargetBase.extend({ kind: KIND.default("NEXTCLOUD"), longEdge: TargetBase.shape.longEdge.default(4000), jpegQuality: TargetBase.shape.jpegQuality.default(100) }); +const TargetFields = TargetBase.extend({ + kind: KIND.default("NEXTCLOUD"), + longEdge: TargetBase.shape.longEdge.default(4000), + jpegQuality: TargetBase.shape.jpegQuality.default(100), + sharpen: TargetBase.shape.sharpen.default(false), + dpi: TargetBase.shape.dpi.default(300), + keepExif: TargetBase.shape.keepExif.default(true), + srgb: TargetBase.shape.srgb.default(false), +}); const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() }); const ListQuery = z.object({ targetId: z.uuid().optional(), @@ -135,6 +147,21 @@ export async function registerDeliveryRoutes( return { ...publicTarget(target), example }; }); + /** A copy with another name (and folder): same server and credentials, e.g. one account with several folders. */ + app.post("/v1/orgs/:orgId/delivery-targets/:targetId/duplicate", { preHandler: authenticate }, async (req, reply) => { + const { orgId, targetId } = TargetParams.parse(req.params); + const body = z.object({ name: TargetBase.shape.name, folderTemplate: TargetBase.shape.folderTemplate.optional() }).parse(req.body); + await requireMembership(db, req, orgId, "ADMIN"); + const source = await db.deliveryTarget.findFirst({ where: { id: targetId, organizationId: orgId } }); + if (!source) throw notFound("target_not_found"); + 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 } }); + return reply.code(201).send({ ...publicTarget(target), example }); + }); + /** Connects with the saved settings (and remembers an SFTP server's host key the first time). */ app.post("/v1/orgs/:orgId/delivery-targets/:targetId/test", { preHandler: authenticate, config: { rateLimit: { max: 10, timeWindow: "1 minute" } } }, async (req) => { const { orgId, targetId } = TargetParams.parse(req.params); diff --git a/apps/api/src/delivery/service.ts b/apps/api/src/delivery/service.ts index 0d03c3d..a8fc94b 100644 --- a/apps/api/src/delivery/service.ts +++ b/apps/api/src/delivery/service.ts @@ -36,6 +36,13 @@ export function toItemSummary(item: DeliveryItem): DeliveryItemSummary { }; } +/** The file name a delivery starts from: the arrival rename if there was one (with the camera file's extension). */ +export function deliveredName(photo: { originalName: string; fileName: string | null }): string { + if (!photo.fileName) return photo.originalName; + const dot = photo.originalName.lastIndexOf("."); + return photo.fileName + (dot > 0 ? photo.originalName.slice(dot) : ""); +} + export class DeliveryRejected extends Error { constructor(readonly code: string) { super(code); @@ -200,12 +207,17 @@ export class DeliveryService { const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } }); let update: Partial; try { - const vars = buildVars(eventInfoOf(item.event), { capturedAt: item.photo.capturedAt ?? undefined, players: item.photo.players, sequence: item.sequence }, item.photo.uploader?.name); + const vars = buildVars( + eventInfoOf(item.event), + { capturedAt: item.photo.capturedAt ?? undefined, players: item.photo.players, sequence: item.sequence, cameraModel: item.photo.cameraModel ?? undefined, cameraSerial: item.photo.cameraSerial ?? undefined }, + item.photo.uploader?.name, + ); const folder = renderFolder(item.target.folderTemplate, vars); - const fileName = renderFileName(item.target.fileNameTemplate, vars, item.photo.originalName); + // {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file). + const fileName = renderFileName(item.target.fileNameTemplate, vars, deliveredName(item.photo)); const iptc = await iptcForPhoto(db, item.photoId); const edit = await this.editFor(item.photoId, item.photo.developSeq); - const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit); + const data = await renderDelivery(storage.resolve(item.photo.storageKey), 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 }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit); const client = this.client(item.target); await client.ensureFolder(folder); await client.upload(folder + fileName, data); diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 5852bc3..7ba781d 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -1,3 +1,4 @@ +import { applyRename } from "../library/rename.js"; import { mkdir, rename, rm, stat } from "node:fs/promises"; import path from "node:path"; import sharp from "sharp"; @@ -187,6 +188,8 @@ export class IngestService { where: { id: photo.id }, data: { status: "READY", width, height, facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", ...(autopilot && { autopilotStatus: "PENDING" }) }, }); + // Photo Mechanic's "Rename as" on Live Ingest: the arrival name (camera name kept in originalName). + if (origin.source !== "UPLOAD") await applyRename(db, photo.id).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: rename failed")); outcome = { status: "ingested", photoId: photo.id, eventId }; log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready"); } catch (err) { diff --git a/apps/api/src/library/ftp.ts b/apps/api/src/library/ftp.ts index b1b1fe7..adad095 100644 --- a/apps/api/src/library/ftp.ts +++ b/apps/api/src/library/ftp.ts @@ -1,3 +1,6 @@ +import { buildVars, variablesIn } from "@photoreport/metadata"; +import { compact } from "../lib/compact.js"; +import { nameFromTemplate } from "./rename.js"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; import { requireAuth, requireMembership } from "../auth/guard.js"; @@ -12,7 +15,28 @@ const AccountParams = OrgParams.extend({ accountId: z.uuid() }); /** Same rules SFTPGo uses for user names, kept strict so a login is always a safe folder name. */ const Login = z.string().trim().toLowerCase().regex(/^[a-z0-9][a-z0-9._-]{2,40}$/, "3-41 characters: a-z, 0-9, dot, dash, underscore"); const CreateBody = z.object({ userId: z.uuid(), login: Login, clockOffsetSec: z.number().int().min(-86400).max(86400).default(0) }); -const UpdateBody = z.object({ clockOffsetSec: z.number().int().min(-86400).max(86400) }); +const Template = z.string().trim().max(200); +const UpdateBody = z.object({ + clockOffsetSec: z.number().int().min(-86400).max(86400).optional(), + /** This photographer's rename template; null: the organisation's; "": keep the camera names. */ + renameTemplate: Template.nullable().optional(), +}); + +/** Renders a rename template against a sample photo; unknown variables are refused when saved, not at ingest. */ +export function renameExample(template: string): string { + const event = { id: "", organizationId: "", home: "ABC Braga", away: "CDE Gil Eanes", homeShort: "ABC", awayShort: "CDE", venue: "Pavilhão Flávio Sá Leite", city: "Braga", sport: "andebol", competition: "Campeonato Betclic", competitionCode: "PO01", round: "8", matchNumber: "169", startsAt: new Date("2026-10-11T17:00:00Z") }; + const known = new Set(Object.keys(buildVars(event, { capturedAt: new Date(), cameraModel: "X", cameraSerial: "1" }, "Peter Spark")).concat("originalName")); + const unknown = variablesIn(template).filter((v) => !known.has(v)); + if (unknown.length) throw badRequest("invalid_template", `unknown variables: ${unknown.join(", ")}`); + const name = nameFromTemplate( + template, + { originalName: "IMG_1234.JPG", capturedAt: new Date("2026-10-11T18:31:07.456Z"), createdAt: new Date(), cameraModel: "Canon EOS R3", cameraSerial: "123" }, + event as never, + "Peter Spark", + ); + if (!name) throw badRequest("invalid_template", "the template gives an empty name"); + return `${name}.jpg`; +} /** Passwords cameras can take: no symbols some bodies' keyboards lack, no look-alike characters. */ export function ftpPassword(length = 14): string { @@ -29,6 +53,31 @@ export async function registerFtpRoutes(app: FastifyInstance, deps: { db: Db; se const { db } = deps; const authenticate = requireAuth(deps.sessions); + /** Photo Mechanic's Live Ingest "Rename as", for the whole organisation (FTP logins can have their own). */ + app.get("/v1/orgs/:orgId/rename-template", { preHandler: authenticate }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + await requireMembership(db, req, orgId, "INGESTER"); + const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { renameTemplate: true } }); + return { template: org.renameTemplate, example: org.renameTemplate ? renameExample(org.renameTemplate) : null }; + }); + + app.put("/v1/orgs/:orgId/rename-template", { preHandler: authenticate }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + const { template } = z.object({ template: Template.nullable() }).parse(req.body); + await requireMembership(db, req, orgId, "ADMIN"); + const value = template?.trim() || null; + const example = value ? renameExample(value) : null; + await db.organization.update({ where: { id: orgId }, data: { renameTemplate: value } }); + return { template: value, example }; + }); + + app.post("/v1/orgs/:orgId/rename-template/preview", { preHandler: authenticate }, async (req) => { + const { orgId } = OrgParams.parse(req.params); + const { template } = z.object({ template: Template.min(1) }).parse(req.body); + await requireMembership(db, req, orgId, "INGESTER"); + return { example: renameExample(template) }; + }); + app.get("/v1/orgs/:orgId/ftp-accounts", { preHandler: authenticate }, async (req) => { const { orgId } = OrgParams.parse(req.params); await requireMembership(db, req, orgId, "ADMIN"); @@ -57,7 +106,8 @@ export async function registerFtpRoutes(app: FastifyInstance, deps: { db: Db; se const { orgId, accountId } = AccountParams.parse(req.params); const body = UpdateBody.parse(req.body); await requireMembership(db, req, orgId, "ADMIN"); - const result = await db.ftpAccount.updateMany({ where: { id: accountId, organizationId: orgId }, data: body }); + if (body.renameTemplate) renameExample(body.renameTemplate); + const result = await db.ftpAccount.updateMany({ where: { id: accountId, organizationId: orgId }, data: compact(body) }); if (!result.count) throw notFound("ftp_account_not_found"); const { passwordHash, ...account } = await db.ftpAccount.findUniqueOrThrow({ where: { id: accountId } }); return { ...account, hasPassword: !!passwordHash }; diff --git a/apps/api/src/library/photos.ts b/apps/api/src/library/photos.ts index eb798d2..d49283c 100644 --- a/apps/api/src/library/photos.ts +++ b/apps/api/src/library/photos.ts @@ -1,3 +1,4 @@ +import { applyRename } from "./rename.js"; import { createReadStream } from "node:fs"; import { PhotoBatchPatch } from "@photoreport/contracts"; import { expandCodes, IptcTemplate, parseCodeList } from "@photoreport/metadata"; @@ -94,6 +95,8 @@ export async function registerPhotoRoutes( if (patch.eventId !== undefined) data.eventId = patch.eventId; const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data }); if (result.count !== ids.length) throw notFound("photo_not_found"); + // Moved to another event: arrival names that use the event follow it. + if (patch.eventId) for (const id of ids) await applyRename(db, id); broadcaster.library(orgId, { type: "photo.updated", ids, patch }); return { updated: result.count }; }); diff --git a/apps/api/src/library/rename.ts b/apps/api/src/library/rename.ts new file mode 100644 index 0000000..169df60 --- /dev/null +++ b/apps/api/src/library/rename.ts @@ -0,0 +1,61 @@ +import { buildVars, PathTemplateError, renderFileName } from "@photoreport/metadata"; +import type { Db } from "../db.js"; +import { eventInfoOf } from "./event-info.js"; + +/** + * Rename on arrival, like Photo Mechanic's Live Ingest "Rename as" (Peter: `PS_{event}_{timesort}`). The template + * is the photographer's FTP login's, else the organisation's; `""` on the login means "keep the camera names". + * Only photos that arrive by FTP or the desktop app are renamed (hand uploads keep their names). The camera's name + * stays in `originalName`; the new one is `fileName` and becomes `{originalName}` in deliveries. + */ +export async function renameTemplateFor(db: Db, organizationId: string, userId: string | null): Promise { + if (userId) { + const login = await db.ftpAccount.findFirst({ where: { organizationId, userId }, select: { renameTemplate: true }, orderBy: { createdAt: "asc" } }); + if (login && login.renameTemplate !== null) return login.renameTemplate.trim() || null; + } + const org = await db.organization.findUnique({ where: { id: organizationId }, select: { renameTemplate: true } }); + return org?.renameTemplate?.trim() || null; +} + +/** The name a template gives a photo (without extension), or null while variables are missing (no event yet). */ +export function nameFromTemplate( + template: string, + photo: { originalName: string; capturedAt: Date | null; createdAt: Date; cameraModel: string | null; cameraSerial: string | null }, + event: Parameters[0] | null, + photographer: string | undefined, +): string | null { + const info = event ? eventInfoOf(event) : { home: "", away: "", startsAt: photo.capturedAt ?? photo.createdAt }; + const vars = buildVars(info, { capturedAt: photo.capturedAt ?? undefined, cameraModel: photo.cameraModel ?? undefined, cameraSerial: photo.cameraSerial ?? undefined }, photographer); + // Without an event, {event} would be " x ": wait for the event instead. + const usable = event ? vars : Object.fromEntries(Object.entries(vars).filter(([k]) => !["home", "away", "event", "homeShort", "awayShort"].includes(k))); + try { + const name = renderFileName(template, usable, photo.originalName); + return name.replace(/\.[a-z0-9]{2,4}$/i, ""); + } catch (err) { + if (err instanceof PathTemplateError) return null; + throw err; + } +} + +/** Gives the photo its arrival name (unique within its event: `_2`, `_3`... on a clash). Returns the new name. */ +export async function applyRename(db: Db, photoId: string): Promise { + const photo = await db.photo.findUnique({ where: { id: photoId }, include: { event: true, uploader: { select: { name: true } } } }); + if (!photo || photo.source === "UPLOAD") return null; + const template = await renameTemplateFor(db, photo.organizationId, photo.uploaderId); + if (!template) return null; + const base = nameFromTemplate(template, photo, photo.event, photo.uploader?.name); + if (!base) return null; + if (photo.fileName === base) return base; + const taken = new Set( + ( + await db.photo.findMany({ + where: { organizationId: photo.organizationId, eventId: photo.eventId, id: { not: photo.id }, fileName: { startsWith: base } }, + select: { fileName: true }, + }) + ).map((p) => p.fileName), + ); + let name = base; + for (let n = 2; taken.has(name); n++) name = `${base}_${n}`; + await db.photo.update({ where: { id: photo.id }, data: { fileName: name } }); + return name; +} diff --git a/apps/api/src/library/serialize.ts b/apps/api/src/library/serialize.ts index 5586595..5739de6 100644 --- a/apps/api/src/library/serialize.ts +++ b/apps/api/src/library/serialize.ts @@ -1,6 +1,7 @@ import type { PhotoSummary } from "@photoreport/contracts"; import type { Photo } from "../generated/prisma/client.js"; import type { UrlSigner } from "../storage/storage.js"; +import { deliveredName } from "../delivery/service.js"; export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null }; @@ -11,6 +12,7 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum id: photo.id, eventId: photo.eventId, originalName: photo.originalName, + name: deliveredName(photo), sha256: photo.sha256, originalStored: photo.originalStored, status: photo.status, diff --git a/apps/api/test/rename.test.ts b/apps/api/test/rename.test.ts new file mode 100644 index 0000000..df2740e --- /dev/null +++ b/apps/api/test/rename.test.ts @@ -0,0 +1,86 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import sharp from "sharp"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { deliveredName } 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"; +import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; + +const quiet = { info: () => {}, warn: () => {} }; + +describe("rename on arrival", () => { + let ctx: TestContext; + let dir: string; + let ingestRoot: string; + let ingest: IngestService; + + beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "pr-rename-")); + ingestRoot = path.join(dir, "ingest"); + ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }); + ingest = new IngestService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), signer: new UrlSigner(ctx.config.JWT_SECRET, 3600), broadcaster: new MemoryBroadcaster(), ingestRoot, log: quiet }); + }); + afterAll(async () => { + await ctx.app.close(); + await ctx.db.$disconnect(); + await rm(dir, { recursive: true, force: true }); + }); + beforeEach(() => resetDb(ctx.db)); + + let shade = 0; + async function arrive(name: string, taken: string) { + const file = path.join(ingestRoot, "peter", name); + await mkdir(path.dirname(file), { recursive: true }); + const data = await sharp({ create: { width: 64, height: 48, channels: 3, background: { r: ++shade, g: 10, b: 10 } } }) + .jpeg() + .withExif({ IFD0: { Make: "Canon", Model: "Canon EOS R3" }, IFD2: { DateTimeOriginal: taken } }) + .toBuffer(); + await writeFile(file, data); + const out = await ingest.ingestFile(file); + if (out.status !== "ingested") throw new Error(JSON.stringify(out)); + return ctx.db.photo.findUniqueOrThrow({ where: { id: out.photoId } }); + } + + it("names photos with the organisation's template, a login's own, or keeps the camera name", async () => { + const { org, user } = await seedUser(ctx.db, "peter@photoreport.pt", { org: "pr", role: "ADMIN" }); + await ctx.db.user.update({ where: { id: user.id }, data: { name: "Peter Spark" } }); + const account = await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "peter" } }); + const token = (await login(ctx.app, user.email)).body.accessToken; + + const bad = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${org!.id}/rename-template`, headers: bearer(token), payload: { template: "PS_{evento}" } }); + expect(bad.json()).toMatchObject({ error: "invalid_template" }); + const ok = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${org!.id}/rename-template`, headers: bearer(token), payload: { template: "{initials}_{datesort}_{timesort}" } }); + expect(ok.json()).toEqual({ template: "{initials}_{datesort}_{timesort}", example: "PS_20261011_19310745.jpg" }); + + const a = await arrive("IMG_0001.JPG", "2026:10:11 19:31:07"); + const b = await arrive("IMG_0002.JPG", "2026:10:11 19:31:07"); // same second, no sub-seconds: the second gets _2 + expect([a.fileName, b.fileName]).toEqual(["PS_20261011_19310700", "PS_20261011_19310700_2"]); + expect(deliveredName(a)).toBe("PS_20261011_19310700.JPG"); + const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${org!.id}/photos`, headers: bearer(token) })).json(); + expect(list.photos.map((p: { name: string; originalName: string }) => `${p.originalName}>${p.name}`).sort()).toEqual([ + "IMG_0001.JPG>PS_20261011_19310700.JPG", + "IMG_0002.JPG>PS_20261011_19310700_2.JPG", + ]); + + // The login's own template wins; "" keeps the camera names. + await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${org!.id}/ftp-accounts/${account.id}`, headers: bearer(token), payload: { renameTemplate: "" } }); + expect((await arrive("IMG_0003.JPG", "2026:10:11 19:40:00")).fileName).toBeNull(); + }); + + it("waits for the event when the template uses it, and follows the photo to another event", async () => { + const { org, user } = await seedUser(ctx.db, "peter@photoreport.pt", { org: "pr", role: "ADMIN" }); + await ctx.db.ftpAccount.create({ data: { organizationId: org!.id, userId: user.id, login: "peter", renameTemplate: "PS_{event}_{timesort}" } }); + const token = (await login(ctx.app, user.email)).body.accessToken; + const photo = await arrive("IMG_0001.JPG", "2026:10:11 19:31:07"); + expect(photo.eventId).toBeNull(); + expect(photo.fileName).toBeNull(); + const event = await ctx.db.event.create({ + data: { organizationId: org!.id, home: "ABC Braga", away: "CDE Gil Eanes", startsAt: new Date("2026-10-11T17:00:00Z"), ingestFrom: new Date("2026-10-11T15:00:00Z"), ingestUntil: new Date("2026-10-11T21:00:00Z"), iptcTemplate: {} }, + }); + await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${org!.id}/photos`, headers: bearer(token), payload: { ids: [photo.id], patch: { eventId: event.id } } }); + expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } })).fileName).toBe("PS_ABC Braga x CDE Gil Eanes_19310700"); + }); +}); diff --git a/apps/api/test/render-options.test.ts b/apps/api/test/render-options.test.ts new file mode 100644 index 0000000..4b75b48 --- /dev/null +++ b/apps/api/test/render-options.test.ts @@ -0,0 +1,32 @@ +import { exiftool } from "exiftool-vendored"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import sharp from "sharp"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { renderDelivery } from "../src/delivery/render.js"; + +describe("delivery output options (Photo Mechanic's uploader)", () => { + let dir: string; + let original: string; + beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "pr-out-")); + original = path.join(dir, "in.jpg"); + await writeFile(original, await sharp({ create: { width: 5000, height: 3000, channels: 3, background: "#808080" } }).jpeg().withExif({ IFD0: { Make: "Canon", Model: "Canon EOS R3" } }).toBuffer()); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + await exiftool.end(); + }); + + it("fits the box, writes 300 ppi, and keeps or drops the camera EXIF", async () => { + const keep = path.join(dir, "keep.jpg"); + await writeFile(keep, await renderDelivery(original, { headline: "Golo" }, { longEdge: 3500, quality: 80, sharpen: true, dpi: 300, exif: true })); + const k = await exiftool.read(keep); + expect([k.ImageWidth, k.ImageHeight, k.XResolution, k.Model, k.Headline]).toEqual([3500, 2100, 300, "Canon EOS R3", "Golo"]); + const drop = path.join(dir, "drop.jpg"); + await writeFile(drop, await renderDelivery(original, { headline: "Golo" }, { longEdge: 3500, quality: 80, dpi: 200, exif: false })); + const d = await exiftool.read(drop); + expect([d.XResolution, d.Model, d.Headline]).toEqual([200, undefined, "Golo"]); + }); +}); diff --git a/apps/app/src/library/FtpLogins.tsx b/apps/app/src/library/FtpLogins.tsx index 0330099..ce5d7c1 100644 --- a/apps/app/src/library/FtpLogins.tsx +++ b/apps/app/src/library/FtpLogins.tsx @@ -1,6 +1,7 @@ import { ApiError, type ApiClient, type FtpAccount, type Member } from "@photoreport/sdk"; import { useCallback, useEffect, useState } from "react"; import { t } from "../i18n.js"; +import { RenameSettings } from "./RenameSettings.js"; /** * FTP logins: each SFTPGo account (home folder /) belongs to one member. Photos sent with it @@ -19,6 +20,7 @@ export function FtpLogins({ api, orgId, members }: { api: ApiClient; orgId: stri const input = "h-8 border border-black bg-[#161617] px-2 text-[13px] text-ink focus:border-accent focus:outline-none"; return ( + <>
Logins FTP @@ -93,5 +95,7 @@ export function FtpLogins({ api, orgId, members }: { api: ApiClient; orgId: stri {error &&

{error}

}
+ void load()} /> + ); } diff --git a/apps/app/src/library/Grid.tsx b/apps/app/src/library/Grid.tsx index e3fc4de..8fef705 100644 --- a/apps/app/src/library/Grid.tsx +++ b/apps/app/src/library/Grid.tsx @@ -34,7 +34,7 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick, onClick={(e) => onPick(photo.id, e)} onDoubleClick={() => onOpen(photo.id)} aria-pressed={selected} - aria-label={`${photo.originalName}${photo.flag === "PICK" ? ", escolhida" : photo.flag === "REJECT" ? ", rejeitada" : ""}${photo.rating ? `, ${photo.rating} estrelas` : ""}`} + aria-label={`${photo.name}${photo.flag === "PICK" ? ", escolhida" : photo.flag === "REJECT" ? ", rejeitada" : ""}${photo.rating ? `, ${photo.rating} estrelas` : ""}`} className={`relative flex aspect-square flex-col items-center justify-between gap-1 border px-2 pb-1 pt-4 ${ selected ? "border-[#9a9a9a] bg-cell-on" : "border-[#151516] bg-cell hover:bg-[#444445]" } ${focused ? "outline outline-1 outline-offset-[-3px] outline-white/60" : ""} ${photo.flag === "REJECT" ? "opacity-40" : ""}`} @@ -105,7 +105,7 @@ export function Loupe({ photo, src, index, total, faces = [] }: { photo: PhotoSu return (
- {photo.originalName} + {photo.name} {faces.map((f) => (

- {photo.originalName} · {index + 1}/{total} + {photo.name} · {index + 1}/{total}

); diff --git a/apps/app/src/library/InfoPanel.tsx b/apps/app/src/library/InfoPanel.tsx index 3bcdac4..b199611 100644 --- a/apps/app/src/library/InfoPanel.tsx +++ b/apps/app/src/library/InfoPanel.tsx @@ -89,7 +89,7 @@ export function InfoPanel(props: { {focus ? (
Ficheiro
-
{focus.originalName}
+
{focus.name}
{t.camera}
{focus.cameraModel ?? "—"}
{t.exposure}
diff --git a/apps/app/src/library/RenameSettings.tsx b/apps/app/src/library/RenameSettings.tsx new file mode 100644 index 0000000..a641b69 --- /dev/null +++ b/apps/app/src/library/RenameSettings.tsx @@ -0,0 +1,141 @@ +import { ApiError, type ApiClient, type FtpAccount } from "@photoreport/sdk"; +import { useEffect, useState } from "react"; + +/** The variables most used in names, as in Photo Mechanic (clicking one adds it to the template). */ +export const RENAME_VARIABLES = [ + ["{event}", "Casa x Fora"], + ["{home}", "Casa"], + ["{away}", "Fora"], + ["{timesort}", "hhmmss + centésimos"], + ["{datesort}", "aaaammdd"], + ["{iptcyear4}", "ano"], + ["{iptcmonth0}", "mês"], + ["{iptcday0}", "dia"], + ["{initials}", "iniciais do fotógrafo"], + ["{photographer}", "fotógrafo"], + ["{competitionCode}", "PO01"], + ["{round}", "jornada"], + ["{originalName}", "nome da câmara"], +] as const; + +const input = "h-8 w-full border border-black bg-[#161617] px-2 font-mono text-[12px] text-ink focus:border-accent focus:outline-none"; + +/** A template field with a live example from the server (which also refuses unknown variables). */ +export function TemplateField({ api, orgId, value, onChange, placeholder }: { api: ApiClient; orgId: string; value: string; onChange: (v: string) => void; placeholder?: string }) { + const [example, setExample] = useState(null); + const [error, setError] = useState(null); + useEffect(() => { + if (!value.trim()) { + setExample(null); + setError(null); + return; + } + const timer = setTimeout(() => { + api.previewRename(orgId, value).then( + (r) => { + setExample(r.example); + setError(null); + }, + (err) => { + setExample(null); + setError(err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : "erro"); + }, + ); + }, 300); + return () => clearTimeout(timer); + }, [api, orgId, value]); + return ( +
+ onChange(e.target.value)} /> +

{error ?? (example ? `ex.: ${example}` : " ")}

+
+ ); +} + +/** + * Rename on arrival (Photo Mechanic's Live Ingest "Rename as"): photos that arrive by FTP or the desktop app get a + * name from the template; the camera's name is kept for reference. Each FTP login can have its own. + */ +export function RenameSettings({ api, orgId, accounts, onAccounts }: { api: ApiClient; orgId: string; accounts: FtpAccount[]; onAccounts: () => void }) { + const [template, setTemplate] = useState(""); + const [saved, setSaved] = useState(null); + const [status, setStatus] = useState(null); + const [editing, setEditing] = useState<{ id: string; value: string } | null>(null); + + useEffect(() => { + api.renameTemplate(orgId).then((r) => { + setTemplate(r.template ?? ""); + setSaved(r.template); + }, () => {}); + }, [api, orgId]); + + const fail = (err: unknown) => setStatus(err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : "erro"); + + return ( +
+
+ Nome dos ficheiros à chegada +
+
+

+ Como o “Rename as” do Live Ingest do Photo Mechanic: as fotos que chegam por FTP ou pela app ganham este nome (o da câmara fica guardado). As entregas usam-no no + lugar de {"{originalName}"}. Vazio mantém o nome da câmara. +

+ +
+ {RENAME_VARIABLES.map(([v, label]) => ( + + ))} +
+
+ + {status && {status}} +
+ {accounts.length > 0 && ( + + + + {accounts.map((a) => ( + + + + + ))} + +
Por login (sobrepõe-se ao da organização)
{a.login} + {editing?.id === a.id ? ( +
+
+ setEditing({ id: a.id, value })} placeholder="vazio: nomes da câmara" /> +
+ + +
+ ) : ( + + )} +
+ )} +
+
+ ); +} diff --git a/apps/app/src/library/TargetForm.tsx b/apps/app/src/library/TargetForm.tsx index 0f427cf..e8667ad 100644 --- a/apps/app/src/library/TargetForm.tsx +++ b/apps/app/src/library/TargetForm.tsx @@ -3,6 +3,8 @@ import { ApiError, type ApiClient, type DeliveryKind, type DeliveryTarget } from import { useState } from "react"; import { t } from "../i18n.js"; +const SIZES = [12000, 6000, 4000, 3500, 3000, 2000]; + /** Where each kind connects, and what its user and secret fields mean. */ const KINDS: Record = { NEXTCLOUD: { @@ -41,22 +43,40 @@ const KINDS: Record void; onCreated: (t: DeliveryTarget) => void }) { +/** + * New (or edited) delivery destination, with Photo Mechanic's uploader options. Secrets are write-only: encrypted + * on the server and never shown again (leave the field empty when editing to keep the saved one). + */ +export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: ApiClient; orgId: string; target?: DeliveryTarget; onClose: () => void; onCreated: (t: DeliveryTarget) => void }) { const [v, setV] = useState({ - name: "", - kind: "NEXTCLOUD" as DeliveryKind, - baseUrl: "https://cloud.photoreport.pt", - username: "", + name: target?.name ?? "", + kind: (target?.kind ?? "NEXTCLOUD") as DeliveryKind, + baseUrl: target?.baseUrl ?? "https://cloud.photoreport.pt", + username: target?.username ?? "", password: "", - folderTemplate: PRESETS.fpa.folder as string, - fileNameTemplate: PRESETS.fpa.fileName as string, - longEdge: 4000, + folderTemplate: target?.folderTemplate ?? (PRESETS.fpa.folder as string), + fileNameTemplate: target?.fileNameTemplate ?? (PRESETS.fpa.fileName as string), + longEdge: target?.longEdge ?? 4000, + jpegQuality: target?.jpegQuality ?? 100, + sharpen: target?.sharpen ?? false, + dpi: target?.dpi ?? 300, + keepExif: target?.keepExif ?? true, + srgb: target?.srgb ?? false, }); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); @@ -83,7 +103,8 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient; e.preventDefault(); setBusy(true); setError(null); - api.createDeliveryTarget(orgId, v).then( + const { password, ...rest } = v; + (target ? api.updateDeliveryTarget(orgId, target.id, password ? v : rest) : api.createDeliveryTarget(orgId, v)).then( (target) => onCreated(target), (err) => { setBusy(false); @@ -93,7 +114,7 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient; }} >
- Novo destino + {target ? `Editar ${target.name}` : "Novo destino"}
@@ -102,7 +123,17 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient; key={id} type="button" onClick={() => - setV({ ...v, kind: p.kind, baseUrl: v.kind === p.kind && v.baseUrl ? v.baseUrl : p.baseUrl, folderTemplate: p.folder, fileNameTemplate: p.fileName, longEdge: p.longEdge, name: v.name || p.label.replace(/ \(.*\)$/, "") }) + setV({ + ...v, + kind: p.kind, + baseUrl: v.kind === p.kind && v.baseUrl && v.baseUrl !== "ftp://" ? v.baseUrl : p.baseUrl, + folderTemplate: p.folder, + fileNameTemplate: p.fileName, + longEdge: p.longEdge, + jpegQuality: "jpegQuality" in p ? p.jpegQuality : 100, + sharpen: "sharpen" in p ? p.sharpen : false, + name: v.name || p.label.replace(/ \(.*\)$/, ""), + }) } className="h-7 border border-black bg-cell px-2.5 text-[12px] text-muted hover:text-ink" > @@ -136,10 +167,11 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient;