Photo Mechanic parity: rename on arrival, uploader output options, PM variables
Photos arriving by FTP or the desktop app get a name from a template (Live Ingest "Rename as", e.g.
PS_{event}_{timesort}); the organisation sets one, an FTP login can have its own or keep camera names.
Names are unique per event and follow the photo to another event; deliveries use them as {originalName}.
Delivery targets get Photo Mechanic's uploader options (size, quality, sharpen, ppi, EXIF, sRGB), can be
edited and duplicated, and a Cofina preset. Templates accept PM's {iptcyear4} {iptcmonth0} {iptcday0}
{datesort} {timesort} and {initials}.
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
1 parent
35901215d0
commit
3c94dabcf1
26 files changed
+734
-56
No files matched your search
@@ -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;
|
||||
@@ -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")
|
||||
|
||||
@@ -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<Buffer> {
|
||||
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 });
|
||||
|
||||
@@ -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<typeof KIND>, 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);
|
||||
|
||||
@@ -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<DeliveryItem>;
|
||||
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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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 };
|
||||
});
|
||||
|
||||
@@ -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<string | null> {
|
||||
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<typeof eventInfoOf>[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<string | null> {
|
||||
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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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, "[email protected]", { 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, "[email protected]", { 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");
|
||||
});
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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 <ingest>/<login>) 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 (
|
||||
<>
|
||||
<section className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<span>Logins FTP</span>
|
||||
@@ -93,5 +95,7 @@ export function FtpLogins({ api, orgId, members }: { api: ApiClient; orgId: stri
|
||||
{error && <p className="w-full text-[12px] text-danger">{error}</p>}
|
||||
</form>
|
||||
</section>
|
||||
<RenameSettings api={api} orgId={orgId} accounts={accounts} onAccounts={() => void load()} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<section aria-label="Lupa" className="relative flex h-full min-h-[420px] items-center justify-center bg-[#121213] p-6">
|
||||
<span className="relative inline-block max-h-full max-w-full">
|
||||
<img src={src} alt={photo.originalName} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
|
||||
<img src={src} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
|
||||
{faces.map((f) => (
|
||||
<span
|
||||
key={f.id}
|
||||
@@ -121,7 +121,7 @@ export function Loupe({ photo, src, index, total, faces = [] }: { photo: PhotoSu
|
||||
))}
|
||||
</span>
|
||||
<p className="absolute bottom-2 left-3 font-mono text-[11px] text-faint">
|
||||
{photo.originalName} · {index + 1}/{total}
|
||||
{photo.name} · {index + 1}/{total}
|
||||
</p>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -89,7 +89,7 @@ export function InfoPanel(props: {
|
||||
{focus ? (
|
||||
<dl className="grid grid-cols-[76px_1fr] gap-x-2.5 gap-y-1.5 border-b border-line px-3 py-3 text-[12px]">
|
||||
<dt className="text-right text-faint">Ficheiro</dt>
|
||||
<dd className="truncate font-mono text-[11px]">{focus.originalName}</dd>
|
||||
<dd className="truncate font-mono text-[11px]" title={focus.name !== focus.originalName ? `câmara: ${focus.originalName}` : undefined}>{focus.name}</dd>
|
||||
<dt className="text-right text-faint">{t.camera}</dt>
|
||||
<dd>{focus.cameraModel ?? "—"}</dd>
|
||||
<dt className="text-right text-faint">{t.exposure}</dt>
|
||||
|
||||
@@ -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<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<div>
|
||||
<input className={input} value={value} placeholder={placeholder} spellCheck={false} onChange={(e) => onChange(e.target.value)} />
|
||||
<p className={`mt-1 font-mono text-[11px] ${error ? "text-danger" : "text-faint"}`}>{error ?? (example ? `ex.: ${example}` : " ")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string | null>(null);
|
||||
const [status, setStatus] = useState<string | null>(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 (
|
||||
<section className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<span>Nome dos ficheiros à chegada</span>
|
||||
</div>
|
||||
<div className="space-y-3 p-4 text-[13px]">
|
||||
<p className="text-muted">
|
||||
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 <span className="font-mono">{"{originalName}"}</span>. Vazio mantém o nome da câmara.
|
||||
</p>
|
||||
<TemplateField api={api} orgId={orgId} value={template} onChange={setTemplate} placeholder="PS_{event}_{timesort}" />
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{RENAME_VARIABLES.map(([v, label]) => (
|
||||
<button key={v} type="button" title={label} onClick={() => setTemplate(template + v)} className="h-6 border border-black bg-cell px-2 font-mono text-[11px] text-muted hover:text-ink">
|
||||
{v}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
disabled={(template.trim() || null) === saved}
|
||||
onClick={() =>
|
||||
api.setRenameTemplate(orgId, template.trim() || null).then((r) => {
|
||||
setSaved(r.template);
|
||||
setStatus("Guardado");
|
||||
}, fail)
|
||||
}
|
||||
className="h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-40"
|
||||
>
|
||||
Guardar
|
||||
</button>
|
||||
{status && <span className="text-[12px] text-muted">{status}</span>}
|
||||
</div>
|
||||
{accounts.length > 0 && (
|
||||
<table className="w-full text-[12px]">
|
||||
<caption className="pb-1 text-left text-[11px] text-faint">Por login (sobrepõe-se ao da organização)</caption>
|
||||
<tbody>
|
||||
{accounts.map((a) => (
|
||||
<tr key={a.id} className="border-t border-line">
|
||||
<td className="w-32 py-1.5 font-mono">{a.login}</td>
|
||||
<td className="py-1.5">
|
||||
{editing?.id === a.id ? (
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="flex-1">
|
||||
<TemplateField api={api} orgId={orgId} value={editing.value} onChange={(value) => setEditing({ id: a.id, value })} placeholder="vazio: nomes da câmara" />
|
||||
</div>
|
||||
<button className="h-8 border border-black bg-cell px-3 hover:bg-cell-on" onClick={() => api.updateFtpAccount(orgId, a.id, { renameTemplate: editing.value.trim() }).then(() => (setEditing(null), onAccounts()), fail)}>
|
||||
OK
|
||||
</button>
|
||||
<button className="h-8 px-2 text-faint hover:text-ink" onClick={() => api.updateFtpAccount(orgId, a.id, { renameTemplate: null }).then(() => (setEditing(null), onAccounts()), fail)}>
|
||||
Usar o da organização
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="w-full text-left font-mono text-muted hover:text-ink" onClick={() => setEditing({ id: a.id, value: a.renameTemplate ?? "" })}>
|
||||
{a.renameTemplate === null || a.renameTemplate === undefined ? <span className="text-faint">o da organização</span> : a.renameTemplate || <span className="text-faint">nome da câmara</span>}
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -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<DeliveryKind, { label: string; address: string; placeholder: string; user: string; secret: string; help: string; multiline?: boolean }> = {
|
||||
NEXTCLOUD: {
|
||||
@@ -41,22 +43,40 @@ const KINDS: Record<DeliveryKind, { label: string; address: string; placeholder:
|
||||
};
|
||||
|
||||
const PRESETS = {
|
||||
cofina: {
|
||||
label: "Cofina Arquivo (FTP)",
|
||||
kind: "FTP",
|
||||
baseUrl: "ftp://",
|
||||
longEdge: 3500,
|
||||
folder: "/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}/",
|
||||
fileName: "{originalName}",
|
||||
jpegQuality: 80,
|
||||
sharpen: true,
|
||||
},
|
||||
abola: { label: "A Bola (SFTP)", kind: "SFTP", baseUrl: "sftp://transfer.ringier.ch", longEdge: 12000, ...DESTINATION_EXAMPLES.abola },
|
||||
fpa: { label: "Estrutura FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.fpa },
|
||||
liga: { label: "Estrutura Liga", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.liga },
|
||||
} as const;
|
||||
|
||||
/** New delivery destination. Secrets are write-only: encrypted on the server and never shown again. */
|
||||
export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient; orgId: string; onClose: () => 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<string | null>(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;
|
||||
}}
|
||||
>
|
||||
<div className="panel-head">
|
||||
<span>Novo destino</span>
|
||||
<span>{target ? `Editar ${target.name}` : "Novo destino"}</span>
|
||||
</div>
|
||||
<div className="space-y-3 p-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
@@ -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;
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">{k.secret}</span>
|
||||
{k.multiline && v.password.includes("\n") ? (
|
||||
<textarea required rows={4} className={`${input} h-auto font-mono text-[11px]`} value={v.password} onChange={(e) => setV({ ...v, password: e.target.value })} spellCheck={false} />
|
||||
<textarea required={!target} rows={4} className={`${input} h-auto font-mono text-[11px]`} value={v.password} onChange={(e) => setV({ ...v, password: e.target.value })} spellCheck={false} />
|
||||
) : (
|
||||
<input
|
||||
required
|
||||
required={!target}
|
||||
placeholder={target ? "(manter a guardada)" : undefined}
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
className={input}
|
||||
@@ -160,16 +192,42 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
|
||||
<p className="text-[11px] leading-snug text-faint">{k.help} Fica guardada encriptada e nunca volta a ser mostrada.</p>
|
||||
{field("folderTemplate", "Pasta ({event} = Casa x Fora)")}
|
||||
{field("fileNameTemplate", "Nome do ficheiro ({originalName} mantém o da câmara, {n:pad3} numera 001, 002…)")}
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Tamanho (lado maior)</span>
|
||||
<select className={input} value={v.longEdge} onChange={(e) => setV({ ...v, longEdge: Number(e.target.value) })}>
|
||||
<option value={12000}>Original (sem redimensionar)</option>
|
||||
<option value={6000}>6000 px</option>
|
||||
<option value={4000}>4000 px</option>
|
||||
<option value={3000}>3000 px</option>
|
||||
<option value={2000}>2000 px</option>
|
||||
</select>
|
||||
</label>
|
||||
<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">Saída (como no uploader do Photo Mechanic)</legend>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Tamanho (lado maior)</span>
|
||||
<select className={input} value={SIZES.includes(v.longEdge) ? v.longEdge : "custom"} onChange={(e) => e.target.value !== "custom" && setV({ ...v, longEdge: Number(e.target.value) })}>
|
||||
{SIZES.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{s >= 12000 ? "Original (sem redimensionar)" : `${s} px`}
|
||||
</option>
|
||||
))}
|
||||
<option value="custom">Outro…</option>
|
||||
</select>
|
||||
{!SIZES.includes(v.longEdge) && (
|
||||
<input type="number" min={800} max={12000} className={`${input} mt-1`} value={v.longEdge} onChange={(e) => setV({ ...v, longEdge: Number(e.target.value) })} />
|
||||
)}
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Qualidade JPEG: {v.jpegQuality}</span>
|
||||
<input type="range" min={40} max={100} className="w-full accent-[var(--color-accent,#e5484d)]" value={v.jpegQuality} onChange={(e) => setV({ ...v, jpegQuality: Number(e.target.value) })} />
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Resolução (ppi)</span>
|
||||
<input type="number" min={72} max={1200} className={input} value={v.dpi} onChange={(e) => setV({ ...v, dpi: Number(e.target.value) })} />
|
||||
</label>
|
||||
<div className="space-y-1 pt-4 text-[12px] text-muted">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={v.sharpen} onChange={(e) => setV({ ...v, sharpen: e.target.checked })} /> Nitidez (sharpen)
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={v.keepExif} onChange={(e) => setV({ ...v, keepExif: e.target.checked })} /> Manter EXIF da câmara
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={v.srgb} onChange={(e) => setV({ ...v, srgb: e.target.checked })} /> Converter para sRGB
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
{error && <p className="px-4 pb-2 text-[12px] text-danger">{error}</p>}
|
||||
<div className="flex justify-end gap-2 border-t border-line px-4 py-3">
|
||||
@@ -177,7 +235,7 @@ export function TargetForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
|
||||
{t.cancel}
|
||||
</button>
|
||||
<button disabled={busy} className="h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50">
|
||||
{t.create}
|
||||
{target ? t.save : t.create}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -6,6 +6,7 @@ const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}
|
||||
id,
|
||||
eventId: "e1",
|
||||
originalName: `${id}.jpg`,
|
||||
name: `${id}.jpg`,
|
||||
sha256: `sha-${id}`,
|
||||
originalStored: true,
|
||||
status: "READY",
|
||||
|
||||
@@ -19,6 +19,8 @@ export function DeliveryPage() {
|
||||
const { api, organization, role } = useAuth();
|
||||
const isAdmin = role !== null && hasRole(role, "ADMIN");
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [editing, setEditing] = useState<DeliveryTarget | null>(null);
|
||||
const [copyName, setCopyName] = useState<string | null>(null);
|
||||
const orgId = organization?.id ?? "";
|
||||
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
|
||||
const [targetId, setTargetId] = useState("");
|
||||
@@ -169,7 +171,37 @@ export function DeliveryPage() {
|
||||
>
|
||||
Testar ligação
|
||||
</button>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" onClick={() => setEditing(target)}>
|
||||
Editar
|
||||
</button>
|
||||
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on" title="Mesmo servidor e credenciais, outro nome e pasta" onClick={() => setCopyName(`${target.name} (cópia)`)}>
|
||||
Duplicar
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{copyName !== null && (
|
||||
<form
|
||||
className="flex gap-2 px-3 pb-3"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
api.duplicateDeliveryTarget(orgId, target.id, { name: copyName.trim() }).then(
|
||||
(copy) => {
|
||||
setCopyName(null);
|
||||
setTargets((list) => [...list, copy]);
|
||||
setTargetId(copy.id);
|
||||
setEditing(copy);
|
||||
},
|
||||
(err) => setNote(err instanceof ApiError ? err.code : t.unexpectedError),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<input autoFocus aria-label="Nome da cópia" className="h-7 flex-1 border border-black bg-[#161617] px-2 text-[12px]" value={copyName} onChange={(e) => setCopyName(e.target.value)} />
|
||||
<button className="h-7 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on">OK</button>
|
||||
</form>
|
||||
)}
|
||||
{target.shareLinks === false ? (
|
||||
<div className="space-y-2 border-t border-line px-3 py-3">{note && <p className="text-[12px] text-muted">{note}</p>}</div>
|
||||
) : (
|
||||
@@ -212,6 +244,18 @@ export function DeliveryPage() {
|
||||
</aside>
|
||||
)}
|
||||
</div>
|
||||
{editing && (
|
||||
<TargetForm
|
||||
api={api}
|
||||
orgId={orgId}
|
||||
target={editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onCreated={(saved) => {
|
||||
setEditing(null);
|
||||
setTargets((list) => list.map((x) => (x.id === saved.id ? saved : x)));
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{adding && (
|
||||
<TargetForm
|
||||
api={api}
|
||||
|
||||
@@ -369,7 +369,7 @@ export function DevelopPage() {
|
||||
<div className="flex min-h-0 flex-1 flex-col lg:flex-row">
|
||||
<div className="flex min-h-[60vh] min-w-0 flex-1 flex-col bg-[#121213] lg:min-h-0">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<span className="truncate font-mono text-[11px] text-faint">{current ? `${current.originalName} · ${index + 1}/${photos.length}` : ""}</span>
|
||||
<span className="truncate font-mono text-[11px] text-faint">{current ? `${current.name} · ${index + 1}/${photos.length}` : ""}</span>
|
||||
{current && (
|
||||
<span className="text-[12px] text-ink" aria-label={t.dev.flagState}>
|
||||
{current.flag === "PICK" ? "⚑ " : current.flag === "REJECT" ? "✕ " : ""}
|
||||
@@ -554,7 +554,7 @@ export function DevelopPage() {
|
||||
aria-current={p.id === current?.id}
|
||||
onClick={() => navigate(`/develop/${p.id}`)}
|
||||
className={`relative h-full shrink-0 border ${p.id === current?.id ? "border-[#cfcfcf]" : "border-transparent opacity-70 hover:opacity-100"} ${p.flag === "REJECT" ? "grayscale" : ""}`}
|
||||
title={p.originalName}
|
||||
title={p.name}
|
||||
>
|
||||
<img src={api.absolute(p.urls.thumb)} alt="" loading="lazy" className="h-full w-auto" draggable={false} />
|
||||
{p.developSeq > 0 && <span className="absolute bottom-0.5 right-0.5 bg-black/70 px-1 font-mono text-[9px] text-white">±</span>}
|
||||
|
||||
@@ -176,6 +176,18 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
|
||||
- **FTP:** `ftps://` for explicit TLS.
|
||||
- **Dropbox:** app key plus refresh token, or a long-lived access token.
|
||||
|
||||
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
|
||||
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Templates accept Photo Mechanic's variable
|
||||
names (`{iptcyear4}`, `{iptcmonth0}`, `{iptcday0}`, `{datesort}`, `{timesort}`, `{event}`), so a Cofina path such
|
||||
as `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}` works as typed there. Targets can be duplicated
|
||||
(same server and credentials, another name and folder).
|
||||
|
||||
Rename on arrival (Live Ingest "Rename as"): photos arriving by FTP or the desktop app get a name from a
|
||||
template. The template is the organisation's, or the FTP login's own (`""` keeps camera names). Names are made
|
||||
unique within the event (`_2`), and are redone when the photo moves to another event (a template that uses the
|
||||
event waits for one). The camera name is kept in `originalName`; deliveries use the new name as
|
||||
`{originalName}`.
|
||||
|
||||
Files with the same name are replaced (as in Photo Mechanic). Public links exist only for Nextcloud and
|
||||
Dropbox. The old app also mirrored raw uploads to Dropbox/FTP; here every delivery is the edited, captioned
|
||||
JPEG.
|
||||
|
||||
@@ -56,6 +56,8 @@ export interface PhotoSummary {
|
||||
id: string;
|
||||
eventId: string | null;
|
||||
originalName: string;
|
||||
/** The name shown and delivered: the arrival rename (with extension) or the camera's. */
|
||||
name: string;
|
||||
/** SHA-256 of the original file: lets the desktop app find its own copy on disk and edit without downloading. */
|
||||
sha256: string;
|
||||
/** False when only a preview is on the server and the original stays on the photographer's computer. */
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderFileName, renderFolder } from "./paths.js";
|
||||
import { buildVars } from "./vars.js";
|
||||
|
||||
describe("Photo Mechanic variables", () => {
|
||||
const event = { home: "ABC Braga", away: "CDE Gil Eanes", startsAt: new Date("2026-10-11T17:00:00Z") };
|
||||
const vars = buildVars(event, { capturedAt: new Date("2026-10-11T18:31:07.456Z"), cameraModel: "Canon EOS R3" }, "Peter Spark");
|
||||
|
||||
it("builds the COFINA folder and Live Ingest names as typed in Photo Mechanic", () => {
|
||||
expect(renderFolder("/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}", vars)).toBe("/fotografia/2026.10.11 ABC Braga x CDE Gil Eanes/");
|
||||
expect(renderFileName("PS_{event}_{timesort}", vars, "IMG_1234.JPG")).toBe("PS_ABC Braga x CDE Gil Eanes_19310745.jpg");
|
||||
expect(renderFileName("{initials}_{datesort}_{originalName}", vars, "IMG_1234.JPG")).toBe("PS_20261011_IMG_1234.jpg");
|
||||
});
|
||||
|
||||
it("falls back to the event day without a capture time", () => {
|
||||
const v = buildVars(event, {});
|
||||
expect(v.datesort).toBe("20261011");
|
||||
expect(v.timesort).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -22,11 +22,13 @@ export interface PhotoInfo {
|
||||
players?: readonly string[] | undefined;
|
||||
/** Position in the delivery, starting at 1. */
|
||||
sequence?: number | undefined;
|
||||
cameraModel?: string | undefined;
|
||||
cameraSerial?: string | undefined;
|
||||
}
|
||||
|
||||
const TIME_ZONE = "Europe/Lisbon";
|
||||
|
||||
function parts(date: Date): { y: string; m: string; d: string; hh: string; mm: string; ss: string } {
|
||||
function parts(date: Date): { y: string; m: string; d: string; hh: string; mm: string; ss: string; cs: string } {
|
||||
const fmt = new Intl.DateTimeFormat("en-GB", {
|
||||
timeZone: TIME_ZONE,
|
||||
year: "numeric",
|
||||
@@ -38,7 +40,9 @@ function parts(date: Date): { y: string; m: string; d: string; hh: string; mm: s
|
||||
hourCycle: "h23",
|
||||
});
|
||||
const get = (type: string) => fmt.formatToParts(date).find((p) => p.type === type)?.value ?? "";
|
||||
return { y: get("year"), m: get("month"), d: get("day"), hh: get("hour"), mm: get("minute"), ss: get("second") };
|
||||
// Hundredths of a second (bursts shoot 10-30 frames a second; EXIF SubSecTimeOriginal lands in the milliseconds).
|
||||
const cs = String(Math.floor(date.getUTCMilliseconds() / 10)).padStart(2, "0");
|
||||
return { y: get("year"), m: get("month"), d: get("day"), hh: get("hour"), mm: get("minute"), ss: get("second"), cs };
|
||||
}
|
||||
|
||||
/** Sports seasons run July to June: September 2026 is season 2026/2027. */
|
||||
@@ -78,6 +82,10 @@ export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?
|
||||
players: photo.players && photo.players.length ? photo.players : undefined,
|
||||
n: photo.sequence,
|
||||
photographer,
|
||||
initials: photographer ? initialsOf(photographer) : undefined,
|
||||
camera: photo.cameraModel,
|
||||
serial: photo.cameraSerial,
|
||||
...photoMechanicDates(photo.capturedAt ?? event.startsAt, photo.capturedAt),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -91,3 +99,43 @@ export function createdStamp(at: Date): { date: string; time: string; iso: strin
|
||||
const offset = `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;
|
||||
return { date: `${p.y}:${p.m}:${p.d}`, time: `${p.hh}:${p.mm}:${p.ss}${offset}`, iso: `${p.y}-${p.m}-${p.d}T${p.hh}:${p.mm}:${p.ss}${offset}` };
|
||||
}
|
||||
|
||||
const initialsOf = (name: string) =>
|
||||
name
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.map((w) => w[0]!.toUpperCase())
|
||||
.join("");
|
||||
|
||||
/**
|
||||
* Photo Mechanic's names for the capture date and time, so its upload paths and rename templates work as typed
|
||||
* there: `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}`, `PS_{event}_{timesort}`. The date is the
|
||||
* capture's (IPTC Date Created), in Lisbon time; without a capture time, the event's day.
|
||||
*/
|
||||
function photoMechanicDates(day: Date, shot: Date | undefined): Record<string, string | undefined> {
|
||||
const p = parts(day);
|
||||
const t = shot ? parts(shot) : undefined;
|
||||
const date = {
|
||||
year4: p.y,
|
||||
year2: p.y.slice(2),
|
||||
month0: p.m,
|
||||
month: String(Number(p.m)),
|
||||
day0: p.d,
|
||||
day: String(Number(p.d)),
|
||||
datesort: `${p.y}${p.m}${p.d}`,
|
||||
};
|
||||
return {
|
||||
...date,
|
||||
iptcyear4: date.year4,
|
||||
iptcyear2: date.year2,
|
||||
iptcmonth0: date.month0,
|
||||
iptcmonth: date.month,
|
||||
iptcday0: date.day0,
|
||||
iptcday: date.day,
|
||||
hour: t?.hh,
|
||||
minute: t?.mm,
|
||||
second: t?.ss,
|
||||
/** hhmmss plus hundredths: sorts in shooting order and tells burst frames apart. */
|
||||
timesort: t ? `${t.hh}${t.mm}${t.ss}${t.cs}` : undefined,
|
||||
};
|
||||
}
|
||||
@@ -530,6 +530,24 @@ export class ApiClient {
|
||||
return this.request<DeliveryTarget & { example: { folder: string; fileName: string } }>("POST", `/v1/orgs/${orgId}/delivery-targets`, input);
|
||||
}
|
||||
|
||||
/** A copy of a target with another name (and folder): same server and credentials. */
|
||||
duplicateDeliveryTarget(orgId: string, targetId: string, input: { name: string; folderTemplate?: string }) {
|
||||
return this.request<DeliveryTarget & { example: { folder: string; fileName: string } }>("POST", `/v1/orgs/${orgId}/delivery-targets/${targetId}/duplicate`, input);
|
||||
}
|
||||
|
||||
/** Rename on arrival (Photo Mechanic's Live Ingest "Rename as"), for the organisation. */
|
||||
renameTemplate(orgId: string) {
|
||||
return this.request<{ template: string | null; example: string | null }>("GET", `/v1/orgs/${orgId}/rename-template`);
|
||||
}
|
||||
|
||||
setRenameTemplate(orgId: string, template: string | null) {
|
||||
return this.request<{ template: string | null; example: string | null }>("PUT", `/v1/orgs/${orgId}/rename-template`, { template });
|
||||
}
|
||||
|
||||
previewRename(orgId: string, template: string) {
|
||||
return this.request<{ example: string }>("POST", `/v1/orgs/${orgId}/rename-template/preview`, { template });
|
||||
}
|
||||
|
||||
/** Connects with the saved settings; an SFTP server's host key is remembered on the first test. */
|
||||
testDeliveryTarget(orgId: string, targetId: string) {
|
||||
return this.request<{ ok: true; account?: string; fingerprint?: string }>("POST", `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`);
|
||||
@@ -552,6 +570,10 @@ export class ApiClient {
|
||||
return this.request<{ password: string }>("POST", `/v1/orgs/${orgId}/ftp-accounts/${accountId}/password`);
|
||||
}
|
||||
|
||||
updateFtpAccount(orgId: string, accountId: string, input: { clockOffsetSec?: number; renameTemplate?: string | null }) {
|
||||
return this.request<FtpAccount>("PATCH", `/v1/orgs/${orgId}/ftp-accounts/${accountId}`, input);
|
||||
}
|
||||
|
||||
deleteFtpAccount(orgId: string, accountId: string) {
|
||||
return this.request<void>("DELETE", `/v1/orgs/${orgId}/ftp-accounts/${accountId}`);
|
||||
}
|
||||
|
||||
@@ -187,6 +187,10 @@ export interface DeliveryTarget {
|
||||
hostFingerprint?: string | null;
|
||||
/** Whether the service gives public folder links (Nextcloud, Dropbox). */
|
||||
shareLinks?: boolean;
|
||||
sharpen?: boolean;
|
||||
dpi?: number;
|
||||
keepExif?: boolean;
|
||||
srgb?: boolean;
|
||||
username: string;
|
||||
folderTemplate: string;
|
||||
fileNameTemplate: string;
|
||||
@@ -202,6 +206,8 @@ export interface FtpAccount {
|
||||
user: { id: string; name: string; email: string };
|
||||
hasPassword?: boolean;
|
||||
lastLoginAt?: string | null;
|
||||
/** This photographer's rename template; null: the organisation's; "": keep the camera names. */
|
||||
renameTemplate?: string | null;
|
||||
}
|
||||
|
||||
export interface DeliveryTargetInput {
|
||||
@@ -214,6 +220,10 @@ export interface DeliveryTargetInput {
|
||||
fileNameTemplate: string;
|
||||
longEdge?: number;
|
||||
jpegQuality?: number;
|
||||
sharpen?: boolean;
|
||||
dpi?: number;
|
||||
keepExif?: boolean;
|
||||
srgb?: boolean;
|
||||
}
|
||||
|
||||
export interface PersonSummary {
|
||||
|
||||
Reference in new issue
Block a user