Files
photoreport/apps/api/test/delivery.test.ts
jos-alves 81bd777e87
ci / rust (push) Successful in 3m48s
ci / typescript (push) Successful in 7m9s
Stop a transient Nextcloud blip reading an archive original from reaching the error hub
BIT-31513 already downgraded this exact self-healing retry to log.info inside
ArchiveService.index(), but DeliveryService.process() hits the same
CloudClient.download() through downloadOriginal() and unconditionally logged the
catch at warn with the raw err, so a 503/423 blip still fingerprinted into
errors.bitreport.pt and reopened the Error Loop (BIT-31522, same cluster pattern
as BIT-31491/BIT-31498/BIT-31505/BIT-31513). The retry behaviour was already
correct (the item is requeued with a backoff); only the log level was wrong.

Use the isTransient() check already imported in this file (and used at the two
other catch sites) to log at info instead of warn when the download blip is
transient, keeping warn for a real failure. Added a regression test mirroring
BIT-31513's.

Paperclip-Issue: BIT-31522
Paperclip-Run: fa16b650-eeb3-4067-81ff-879c78e4c0c1
2026-10-19 04:47:35 +01:00

812 lines
52 KiB
TypeScript

import { createHash } from "node:crypto";
import { exiftool } from "exiftool-vendored";
import { mkdir, mkdtemp, readFile, 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 { NextcloudError } from "../src/delivery/nextcloud.js";
import { closeRenderer } from "../src/delivery/render.js";
import { SecretBox } from "../src/delivery/secrets.js";
import { DeliveryService } from "../src/delivery/service.js";
import { CookieJar, matchGame, sameTeam, zerozeroGameId } from "../src/delivery/zerozero.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 KEY = Buffer.alloc(32, 7).toString("base64");
const quiet = { info: () => {}, warn: () => {} };
/** In-memory Nextcloud: WebDAV MKCOL/PUT and the OCS share endpoint. */
class FakeNextcloud {
folders = new Set<string>(["/"]);
files = new Map<string, Buffer>();
shares = new Map<string, string>();
failPuts = 0;
status: number | undefined;
auth: string[] = [];
fetch: typeof fetch = async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
this.auth.push(String((init?.headers as Record<string, string>)?.authorization));
if (this.status) return new Response("nope", { status: this.status });
const dav = /^\/remote\.php\/dav\/files\/[^/]+(\/.*)$/.exec(url.pathname);
if (dav) {
const p = decodeURIComponent(dav[1]!).replace(/\/$/, "") || "/";
const parent = p.slice(0, p.lastIndexOf("/")) || "/";
if (method === "MKCOL") {
if (this.folders.has(p)) return new Response(null, { status: 405 });
if (!this.folders.has(parent)) return new Response(null, { status: 409 });
this.folders.add(p);
return new Response(null, { status: 201 });
}
if (method === "PUT") {
if (this.failPuts > 0) {
this.failPuts--;
return new Response(null, { status: 503 });
}
if (!this.folders.has(parent)) return new Response(null, { status: 409 });
this.files.set(p, Buffer.from(init!.body as Uint8Array));
return new Response(null, { status: 201 });
}
}
if (dav && method === "PROPFIND") return new Response("<d:multistatus/>", { status: 207 });
if (url.pathname === "/ocs/v2.php/apps/files_sharing/api/v1/shares") {
if (method === "GET") {
const p = url.searchParams.get("path")!;
const share = this.shares.get(p);
return Response.json({ ocs: { data: share ? [{ share_type: 3, url: share }] : [] } });
}
const p = new URLSearchParams(String(init!.body)).get("path")!;
const link = `https://cloud.test/s/${this.shares.size + 1}`;
this.shares.set(p, link);
return Response.json({ ocs: { data: { url: link } } });
}
return new Response(null, { status: 404 });
};
}
/**
* fotos.zerozero.pt as its web app sees it: OAuth through www.zerozero.pt (ax_login.php), a session cookie on the
* desk, the games list, and tus uploads.
*/
class FakeZerozero {
logins = 0;
removed: string[] = [];
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
password = "zz-pass";
private cookie(init: RequestInit | undefined, name: string) {
const c = new Headers(init?.headers).get("cookie") ?? "";
return c.split(/;\s*/).some((p) => p.startsWith(`${name}=`));
}
handles(input: RequestInfo | URL) {
return /zerozero\.pt$/.test(new URL(String(input)).hostname);
}
fetch: typeof fetch = async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const redirect = (to: string, setCookie?: string) => new Response(null, { status: 302, headers: { location: to, ...(setCookie ? { "set-cookie": setCookie } : {}) } });
if (url.hostname === "www.zerozero.pt") {
if (url.pathname === "/oauth.php") {
if (this.cookie(init, "zzuser")) return redirect(`https://fotos.zerozero.pt/api/auth/callback?code=c1&state=${url.searchParams.get("state")}`);
return new Response("<form id=zz-login-form>", { status: 200, headers: { "set-cookie": "PHPSESSID=s1; path=/; domain=.zerozero.pt" } });
}
if (url.pathname === "/ax_login.php" && method === "POST") {
const form = init!.body as FormData;
this.logins++;
if (form.get("login_username") !== "kapta" || form.get("login_password") !== this.password) return new Response(JSON.stringify({ status: false, msg: "Dados de acesso inválidos" }));
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; path=/; domain=.zerozero.pt" } });
}
}
if (url.hostname !== "fotos.zerozero.pt") return new Response(null, { status: 404 });
if (url.pathname === "/api/auth/login") return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&client_id=fotos&state=st1" });
if (url.pathname === "/api/auth/callback") return redirect("/", "desk=ok; Path=/; HttpOnly");
const signedIn = this.cookie(init, "desk");
if (!signedIn) return Response.json({ error: "unauthorized" }, { status: 401 });
if (url.pathname === "/api/auth/me") return Response.json({ role: "photographer", photographer_name: "Kapta+" });
const game = (id: string, date: string, home: string, away: string) => ({ id, edition_id: "219039", date, home_team_name: home, away_team_name: away, edition_name: "UEFA Europa League 2026/27" });
const games = [game("12627747", "2026-10-15 17:45:00", "Torreense", "Sunderland"), game("12627748", "2026-10-22 20:00:00", "Torreense", "Sunderland")];
if (url.pathname === "/api/content/upcoming") return Response.json(games);
const one = /^\/api\/content\/games\/(\d+)$/.exec(url.pathname);
if (one) {
const g = games.find((x) => x.id === one[1]);
return g ? Response.json(g) : Response.json({ error: "not found" }, { status: 404 });
}
if (url.pathname === "/api/upload" && method === "POST") {
const h = new Headers(init?.headers);
const meta = Object.fromEntries(
(h.get("upload-metadata") ?? "").split(",").map((pair) => {
const [k, v] = pair.split(" ");
return [k!, Buffer.from(v ?? "", "base64").toString("utf8")];
}),
);
const id = `img-${this.uploads.size + 1}`;
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
}
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
if (gone && method === "DELETE") {
this.removed.push(gone[1]!);
return new Response(null, { status: 204 });
}
const patch = /^\/upload\/(.+)$/.exec(url.pathname);
if (patch && method === "PATCH") {
const up = this.uploads.get(patch[1]!)!;
if (Number(new Headers(init?.headers).get("upload-offset")) !== up.data.length) return new Response(null, { status: 409 });
up.data = Buffer.concat([up.data, Buffer.from(init!.body as Uint8Array)]);
return new Response(null, { status: 204, headers: { "upload-offset": String(up.data.length) } });
}
return new Response(null, { status: 404 });
};
}
describe("zerozero", () => {
it("reads game ids from links, knows teams by their names and finds the event's game", () => {
expect(zerozeroGameId("https://fotos.zerozero.pt/edicoes/219039/12627747")).toBe("12627747");
expect(zerozeroGameId(" 12627747 ")).toBe("12627747");
expect(zerozeroGameId("https://www.zerozero.pt/jogo/2026-10-15-torreense-sunderland/12627747")).toBe("12627747");
expect(zerozeroGameId("https://example.com/12627747")).toBeNull();
expect(sameTeam("SC Torreense", "Torreense")).toBe(true);
expect(sameTeam("Sporting CP", "Sporting")).toBe(true);
expect(sameTeam("SL Benfica", "FC Porto")).toBe(false);
const games = [
{ id: "1", date: "2026-10-15 17:45:00", home: "Torreense", away: "Sunderland", competition: null },
{ id: "2", date: "2026-10-15 17:45:00", home: "Sunderland", away: "Torreense", competition: null },
];
const lisbon = (d: string) => new Date(`${d.replace(" ", "T")}+01:00`);
expect(matchGame(games, { home: "SC Torreense", away: "Sunderland AFC", startsAt: new Date("2026-10-15T16:45:00Z") }, lisbon)?.id).toBe("1");
expect(matchGame(games, { home: "Torreense", away: "Sunderland", startsAt: new Date("2026-10-16T16:45:00Z") }, lisbon)).toBeNull();
const jar = new CookieJar();
jar.store("https://www.zerozero.pt/x", new Headers([["set-cookie", "a=1; Domain=.zerozero.pt; Path=/"]]));
jar.store("https://fotos.zerozero.pt/x", new Headers([["set-cookie", "b=2; Path=/"]]));
expect(jar.header("https://fotos.zerozero.pt/api")).toBe("a=1; b=2");
expect(jar.header("https://www.zerozero.pt/")).toBe("a=1");
});
});
describe("delivery", () => {
let ctx: TestContext;
let dir: string;
let ingestRoot: string;
let nc: FakeNextcloud;
let zz: FakeZerozero;
let broadcaster: MemoryBroadcaster;
let ingest: IngestService;
let delivery: DeliveryService;
beforeAll(async () => {
dir = await mkdtemp(path.join(tmpdir(), "pr-del-"));
ingestRoot = path.join(dir, "ingest");
nc = new FakeNextcloud();
zz = new FakeZerozero();
const sites: typeof fetch = (input, init) => (zz.handles(input) ? zz.fetch(input, init) : nc.fetch(input, init));
broadcaster = new MemoryBroadcaster();
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot, DELIVERY_SECRET_KEY: KEY }, broadcaster, sites);
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 3600), broadcaster, ingestRoot, log: quiet });
delivery = new DeliveryService({ db: ctx.db, storage, secrets: new SecretBox(KEY), broadcaster, log: quiet, fetchImpl: sites });
});
afterAll(async () => {
await ctx.app.close();
await ctx.db.$disconnect();
await closeRenderer();
await exiftool.end();
await rm(dir, { recursive: true, force: true });
});
beforeEach(async () => {
await resetDb(ctx.db);
Object.assign(nc, { folders: new Set(["/"]), files: new Map(), shares: new Map(), failPuts: 0, status: undefined, auth: [] });
Object.assign(zz, { logins: 0, uploads: new Map(), password: "zz-pass" });
broadcaster.sent.length = 0;
});
async function setup() {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "ADMIN" });
const { user: foto } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
await ctx.db.user.update({ where: { id: foto.id }, data: { name: "Peter Spark" } });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
const orgId = org!.id;
const event = (
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(token),
payload: { home: "VSC", away: "AAAS", venue: "Pavilhão", city: "Guimarães", sport: "andebol", competition: "Campeonato Betclic", competitionCode: "PO01", startsAt: "2026-09-23T19:30:00Z" },
})
).json() as { id: string };
await ctx.db.ftpAccount.create({ data: { organizationId: orgId, userId: foto.id, login: "foto" } });
const target = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: {
name: "FPA",
baseUrl: "https://cloud.test",
username: "photoreport",
password: "app-password-123",
folderTemplate: "/FPA/Fotos/{season}/Competições Nacionais/{competitionCode} - {competition}/{dateCompact} - {home} x {away}/",
fileNameTemplate: "PS_{home} x {away}_{n}.jpg",
},
});
expect(target.statusCode).toBe(201);
return { orgId, token, eventId: event.id, target: target.json() as { id: string; example: { folder: string; fileName: string } } & Record<string, unknown> };
}
async function photo(name: string, taken: string, size = { width: 600, height: 400 }): Promise<string> {
const file = path.join(ingestRoot, "foto", name);
await mkdir(path.dirname(file), { recursive: true });
const data = await sharp({ create: { ...size, channels: 3, background: { r: name.length * 20, g: 90, b: 140 } } })
.jpeg()
.withExif({ IFD0: { Make: "Canon", Model: "Canon EOS R1" }, IFD2: { DateTimeOriginal: taken } })
.toBuffer();
await writeFile(file, data);
const outcome = await ingest.ingestFile(file);
if (outcome.status !== "ingested") throw new Error(`ingest failed: ${JSON.stringify(outcome)}`);
return outcome.photoId;
}
async function drain() {
for (let ids = await delivery.claim(10); ids.length; ids = await delivery.claim(10)) await Promise.all(ids.map((id) => delivery.process(id)));
}
it("stores the app password encrypted and refuses broken templates", async () => {
const { orgId, token, target } = await setup();
expect(target).not.toHaveProperty("secretEnc");
expect(target).not.toHaveProperty("password");
expect(target.example).toEqual({ folder: "/FPA/Fotos/2026_2027/Competições Nacionais/C01 - Competição/20260923 - Casa x Fora/", fileName: "PS_Casa x Fora_1.jpg" });
const row = await ctx.db.deliveryTarget.findFirstOrThrow();
expect(row.secretEnc).not.toContain("app-password");
expect(new SecretBox(KEY).open(row.secretEnc)).toBe("app-password-123");
const bad = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "X", baseUrl: "https://x.test", username: "u", password: "p", folderTemplate: "/{nope}/", fileNameTemplate: "{n}" },
});
expect(bad.statusCode).toBe(400);
expect(bad.json()).toMatchObject({ error: "invalid_template" });
});
it("delivers 4000 px JPEGs with IPTC into the FPA folder, numbered in capture order", async () => {
const { orgId, token, target } = await setup();
const second = await photo("b.jpg", "2026:09:23 21:20:00");
const first = await photo("a.jpg", "2026:09:23 21:10:00", { width: 6000, height: 4000 });
await ctx.db.photo.update({ where: { id: first }, data: { players: ["Miguel Silva (VSC)"] } });
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [second, first] } });
expect(res.statusCode).toBe(202);
const queued = (res.json() as { queued: { photoId: string; sequence: number }[] }).queued;
expect(queued.map((q) => [q.photoId, q.sequence])).toEqual([
[first, 1],
[second, 2],
]);
await drain();
const folder = "/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20260923 - VSC x AAAS";
expect([...nc.files.keys()].sort()).toEqual([`${folder}/PS_VSC x AAAS_1.jpg`, `${folder}/PS_VSC x AAAS_2.jpg`]);
expect(nc.auth[0]).toBe("Basic " + Buffer.from("photoreport:app-password-123").toString("base64"));
const delivered = nc.files.get(`${folder}/PS_VSC x AAAS_1.jpg`)!;
const meta = await sharp(delivered).metadata();
expect([meta.width, meta.height]).toEqual([4000, 2667]);
const out = path.join(dir, "check.jpg");
await writeFile(out, delivered);
const tags = (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record<string, unknown>;
expect(tags["IPTC:ObjectName"]).toBe("Miguel Silva (VSC)");
expect(tags["IPTC:Caption-Abstract"]).toBe("VSC x AAAS, em Guimarães, no Pavilhão");
expect(tags["IPTC:By-line"]).toBe("Peter Spark / PhotoReport.pt");
expect(tags["IPTC:Keywords"]).toBe("ANDEBOL");
expect(tags["XMP-iptcExt:PersonInImage"]).toBe("Miguel Silva (VSC)");
expect(tags["XMP-iptcExt:Event"]).toBe("VSC x AAAS");
expect(tags["IFD0:Model"]).toBe("Canon EOS R1");
expect(tags["IPTC:DateCreated"]).toBe("2026:09:23");
expect(tags["IPTC:TimeCreated"]).toBe("21:10:00+01:00");
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries?targetId=${target.id}`, headers: bearer(token) });
expect((list.json() as { counts: Record<string, number> }).counts).toEqual({ DONE: 2 });
// The library shows them as sent (the "Enviadas" / "Por enviar" filters).
const photos = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(token) });
expect((photos.json() as { photos: { delivery: string }[] }).photos.map((p) => p.delivery)).toEqual(["DONE", "DONE"]);
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first] } });
expect(again.json()).toMatchObject({ queued: [], skipped: [{ photoId: first, reason: "already_delivered" }] });
const resend = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first], again: true } });
expect((resend.json() as { queued: { sequence: number }[] }).queued[0]?.sequence).toBe(3); // numbers are never reused
});
it("a client's own IPTC: its agency in Creator, and the players in Title from left to right", async () => {
const { orgId, token, target, eventId } = await setup();
const saved = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { iptcOverrides: { creator: "Peter Spark / Movephoto", title: "{players}" } },
});
expect(saved.statusCode).toBe(200);
expect((saved.json() as { iptcOverrides: unknown }).iptcOverrides).toEqual({ creator: "Peter Spark / Movephoto", title: "{players}" });
const id = await photo("a.jpg", "2026:09:23 21:10:00");
// Identified right one first: the photo lists them in that order; on the photo, Rui is on the left.
await ctx.db.photo.update({ where: { id }, data: { players: ["Miguel Silva (VSC)", "Rui Costa (AAAS)"] } });
for (const [name, x0] of [
["Miguel Silva", 0.7],
["Rui Costa", 0.1],
] as const) {
const person = await ctx.db.person.create({ data: { organizationId: orgId, name } });
const group = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, personId: person.id, model: "test" } });
await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: group.id, x0, y0: 0.2, x1: x0 + 0.1, y1: 0.4, score: 0.9, model: "test" } });
}
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
await drain();
const out = path.join(dir, "client.jpg");
await writeFile(out, [...nc.files.values()][0]!);
const tags = (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record<string, unknown>;
expect(tags["IPTC:By-line"]).toBe("Peter Spark / Movephoto");
expect(tags["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)");
// The rest is the event's, as before.
expect(tags["IPTC:Caption-Abstract"]).toBe("VSC x AAAS, em Guimarães, no Pavilhão");
// Cleared: back to the event's photographer.
const cleared = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, headers: bearer(token), payload: { iptcOverrides: null } });
expect((cleared.json() as { iptcOverrides: unknown }).iptcOverrides).toBeNull();
});
it("names the best guess (face and shirt) without waiting for anyone to confirm, and keeps a copy on the computer", async () => {
const { orgId, token, target, eventId } = await setup();
const local = (
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Cópia Record", kind: "LOCAL", baseUrl: "/Users/peter/Record", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
})
).json() as { id: string };
expect(
(await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`, headers: bearer(token), payload: { copyTargetId: target.id } })).json(),
).toMatchObject({ error: "copy_to_itself" });
const saved = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { copyTargetId: local.id, iptcOverrides: { creator: "Peter Spark / Movephoto", title: "{players}" } },
});
expect((saved.json() as { copyTargetId: string }).copyTargetId).toBe(local.id);
const id = await photo("guess.jpg", "2026:09:23 21:10:00");
// Nobody confirmed: one face is only suggested (face and shirt agree), the other was confirmed earlier.
const guessed = await ctx.db.person.create({ data: { organizationId: orgId, name: "Rui Costa (AAAS)" } });
const known = await ctx.db.person.create({ data: { organizationId: orgId, name: "Miguel Silva (VSC)" } });
const g1 = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, suggestedPersonId: guessed.id, suggestionScore: 0.9, model: "test" } });
const g2 = await ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, personId: known.id, model: "test" } });
await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: g2.id, x0: 0.6, y0: 0.2, x1: 0.7, y1: 0.4, score: 0.9, model: "test" } });
await ctx.db.face.create({ data: { organizationId: orgId, photoId: id, groupId: g1.id, x0: 0.1, y0: 0.2, x1: 0.2, y1: 0.4, score: 0.9, model: "test" } });
await ctx.db.photo.update({ where: { id }, data: { players: ["Miguel Silva (VSC)"] } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
await drain();
const read = async (data: Buffer, name: string) => {
const out = path.join(dir, name);
await writeFile(out, data);
return (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record<string, unknown>;
};
const sent = await read([...nc.files.values()][0]!, "record.jpg");
expect(sent["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)");
expect(sent["IPTC:By-line"]).toBe("Peter Spark / Movephoto");
// The copy on the computer is the same file the client got (its IPTC, not the event's).
const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId: local.id } });
expect([copy.status, copy.viaTargetId]).toEqual(["WAITING", target.id]);
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${copy.id}/local-file`, headers: bearer(token) });
const copied = await read(file.rawPayload, "copy.jpg");
expect(copied["IPTC:By-line"]).toBe("Peter Spark / Movephoto");
expect(copied["IPTC:ObjectName"]).toBe("Rui Costa (AAAS), Miguel Silva (VSC)");
});
it("saves the same export into a computer folder named by the day, the game and the destination", async () => {
const { orgId, token, target } = await setup();
const saved = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { localFolder: "/Users/cyclop/Desktop/2026", localMachine: "desktop-0000000000000001", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" },
});
expect(saved.statusCode).toBe(200);
expect(saved.json()).toMatchObject({ baseUrl: "https://cloud.test", localFolder: "/Users/cyclop/Desktop/2026", localFolderTemplate: "/{iptcdate} - {event} - {destination}/" });
const listed = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token) })).json() as { targets: { name: string }[] };
expect(listed.targets.map((t) => t.name)).toEqual(["FPA"]);
const id = await photo("a.jpg", "2026:09:23 21:10:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
await drain();
const sentPath = [...nc.files.keys()][0]!;
expect(sentPath.endsWith("/PS_VSC x AAAS_1.jpg")).toBe(true);
const copy = await ctx.db.deliveryItem.findFirstOrThrow({ where: { viaTargetId: target.id } });
expect([copy.status, copy.sequence, copy.remotePath]).toEqual(["WAITING", 1, "20260923 - VSC x AAAS - FPA/PS_VSC x AAAS_1.jpg"]);
const mirror = await ctx.db.deliveryTarget.findFirstOrThrow({ where: { mirrorOfId: target.id } });
expect(mirror).toMatchObject({ kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", disabledAt: null });
const cleared = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/delivery-targets/${target.id}`,
headers: bearer(token),
payload: { localFolder: null },
});
expect(cleared.statusCode).toBe(200);
expect((cleared.json() as { localFolder: null }).localFolder).toBeNull();
expect((await ctx.db.deliveryTarget.findFirstOrThrow({ where: { id: mirror.id } })).disabledAt).not.toBeNull();
const later = await photo("b.jpg", "2026:09:23 21:20:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [later] } });
await drain();
expect(await ctx.db.deliveryItem.count({ where: { viaTargetId: target.id } })).toBe(1);
// A destination that is already a folder does not grow a second copy of itself.
const localOnly = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Pasta", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "desktop-0000000000000001", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}", localFolder: "/tmp/outra", localMachine: "desktop-0000000000000001" },
});
expect(localOnly.statusCode).toBe(201);
expect((localOnly.json() as { localFolder: null }).localFolder).toBeNull();
});
it("waits a little for the faces to be read before sending, so the names go with the photo", async () => {
const { orgId, token, target } = await setup();
await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "test" } });
const id = await photo("faces.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "PENDING" } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
const [itemId] = await delivery.claim(10);
const waiting = await delivery.process(itemId!);
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_faces", 0]);
expect(nc.files.size).toBe(0);
// Read: it goes.
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "DONE" } });
await ctx.db.deliveryItem.update({ where: { id: itemId! }, data: { nextAttemptAt: new Date() } });
await drain();
expect(nc.files.size).toBe(1);
});
it("an IPTC change in the Info window sends the photo again where it went, replacing the old file", async () => {
const { orgId, token, target } = await setup();
const id = await photo("info.jpg", "2026:09:23 21:10:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [id] } });
await drain();
const [file] = [...nc.files.keys()];
const read = async () => {
const out = path.join(dir, "info-check.jpg");
await writeFile(out, nc.files.get(file!)!);
return (await exiftool.readRaw(out, { readArgs: ["-G1", "-a"] })) as Record<string, unknown>;
};
expect((await read())["IPTC:ObjectName"]).toBeUndefined();
const put = (set: Record<string, unknown>) => ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(token), payload: { ids: [id], set } });
expect((await put({ title: "Miguel Silva (VSC)" })).json()).toEqual({ updated: 1, changed: 1, resent: 1 });
await drain();
// Same file, same name: replaced, not a second copy.
expect([...nc.files.keys()]).toEqual([file]);
expect((await read())["IPTC:ObjectName"]).toBe("Miguel Silva (VSC)");
// Saving the same values again sends nothing.
expect((await put({ title: "Miguel Silva (VSC)" })).json()).toEqual({ updated: 1, changed: 0, resent: 0 });
});
it("ZeroZero: signs in, finds the event's game, and uploads with the photographer as author", async () => {
const { orgId, token } = await setup();
const event = (
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(token), payload: { home: "SC Torreense", away: "Sunderland", sport: "futebol", startsAt: "2026-10-15T16:45:00Z" } })
).json() as { id: string };
const bad = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "ZZ errado", kind: "ZEROZERO", baseUrl: "https://example.com", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "{originalName}" },
});
expect(bad.statusCode).toBe(400);
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "PS_{home} x {away}_{n}.jpg", longEdge: 3000, jpegQuality: 92 },
});
expect(created.statusCode).toBe(201);
const targetId = (created.json() as { id: string }).id;
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) })).json()).toEqual({ ok: true, account: "Kapta+" });
// The game is found by teams and time; a link chooses another one.
const found = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game?eventId=${event.id}`, headers: bearer(token) });
expect(found.json()).toMatchObject({ chosen: false, game: { id: "12627747", home: "Torreense", away: "Sunderland" } });
const chosen = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: "https://fotos.zerozero.pt/edicoes/219039/12627748" } });
expect(chosen.json()).toMatchObject({ chosen: true, game: { id: "12627748" } });
const forgot = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: null } });
expect(forgot.json()).toMatchObject({ chosen: false, game: { id: "12627747" } });
expect((await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: "99999999" } })).statusCode).toBe(502);
const a = await photo("zz-a.jpg", "2026:10:15 18:10:00", { width: 6000, height: 4000 });
const b = await photo("zz-b.jpg", "2026:10:15 18:20:00");
await ctx.db.photo.updateMany({ where: { id: { in: [a, b] } }, data: { eventId: event.id } });
// Only the best: without the autopilot, the photographer's stars decide.
await ctx.db.photo.update({ where: { id: b }, data: { rating: 3 } });
const best = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/best`, headers: bearer(token), payload: { targetId, eventId: event.id, count: 1, dryRun: true } });
expect(best.json()).toEqual({ chosen: [b], rest: [], queued: [], skipped: [] });
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a, b] } });
expect(res.statusCode).toBe(202);
zz.logins = 0;
await drain();
const items = await ctx.db.deliveryItem.findMany({ where: { targetId }, orderBy: { sequence: "asc" } });
expect(items.map((i) => [i.status, i.lastError])).toEqual([
["DONE", null],
["DONE", null],
]);
expect(items.map((i) => i.remotePath).sort()).toEqual(["12627747/img-1", "12627747/img-2"]);
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: event.id } })).zerozeroGameId).toBe("12627747");
const first = [...zz.uploads.values()].find((u) => u.meta.filename?.endsWith("_1.jpg"))!;
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
expect(first.data.length).toBe(first.length);
expect((await sharp(first.data).metadata()).width).toBe(3000);
// Signed in once for the whole batch.
expect(zz.logins).toBe(1);
// The crop of a delivered photo put right: once the edits pause, the new version goes up and the old one is
// taken back (never while still being edited).
const itemA = items.find((i) => i.photoId === a)!;
await ctx.db.photo.update({ where: { id: a }, data: { developSeq: 3, editedAt: new Date() } });
expect(await delivery.queueEdited()).toBe(0);
await ctx.db.photo.update({ where: { id: a }, data: { editedAt: new Date(Date.now() - 2 * 60_000) } });
expect(await delivery.queueEdited()).toBe(1);
const again = await ctx.db.deliveryItem.findUniqueOrThrow({ where: { id: itemA.id } });
expect([again.status, again.replacesPath, again.sequence]).toEqual(["QUEUED", itemA.remotePath, itemA.sequence]);
// (No render engine here: the edit itself is not rendered, the round trip is what is checked.)
await ctx.db.photo.update({ where: { id: a }, data: { developSeq: 0 } });
await drain();
const resent = await ctx.db.deliveryItem.findUniqueOrThrow({ where: { id: itemA.id } });
expect(resent.status).toBe("DONE");
expect(resent.remotePath).not.toBe(itemA.remotePath);
expect(resent.replacesPath).toBeNull();
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
// Same name ({n} kept), shown once in the game.
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(await delivery.queueEdited()).toBe(0);
// A wrong password stops at once, with the desk's message.
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
expect(failed.statusCode).toBe(502);
expect(failed.json()).toMatchObject({ message: "zerozero: Dados de acesso inválidos" });
});
it("a folder on a computer: rendered here, then taken and saved by that computer's desktop app", async () => {
const { orgId, token } = await setup();
const noMachine = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token), payload: { name: "Pasta", kind: "LOCAL", baseUrl: "relativa/pasta", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" } });
expect(noMachine.statusCode).toBe(400);
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "PS_{home} x {away}_{n}.jpg" },
});
expect(created.statusCode).toBe(201);
const targetId = (created.json() as { id: string }).id;
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) })).json()).toEqual({ ok: true, account: "/Users/peter/Entregas" });
const a = await photo("local-a.jpg", "2026:09:23 21:10:00");
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
await drain();
const waiting = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } });
expect([waiting.status, waiting.remotePath]).toEqual(["WAITING", "VSC x AAAS/PS_VSC x AAAS_1.jpg"]);
// Still on its way: the library shows it as queued, and it is not sent twice.
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
expect(again.json()).toMatchObject({ queued: [], skipped: [{ reason: "already_delivered" }] });
// Another computer gets nothing; this one gets the file and where it goes.
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0002-other" } })).json()).toEqual({ items: [] });
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string; folder: string; path: string }[] };
expect(claim.items.map((i) => [i.folder, i.path])).toEqual([["/Users/peter/Entregas", "VSC x AAAS/PS_VSC x AAAS_1.jpg"]]);
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
expect(file.statusCode).toBe(200);
expect((await sharp(file.rawPayload).metadata()).format).toBe("jpeg");
const done = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-result`, headers: bearer(token), payload: { ok: true, path: "/Users/peter/Entregas/VSC x AAAS/PS_VSC x AAAS_1.jpg" } });
expect(done.json()).toMatchObject({ status: "DONE", remotePath: "/Users/peter/Entregas/VSC x AAAS/PS_VSC x AAAS_1.jpg" });
// The server's copy is gone once the computer has it.
expect((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) })).statusCode).toBe(404);
});
it("a backup of the originals on a computer: every arrival, untouched, with its metadata and Photo Mechanic's names", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Backup 2026", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "mac-0001-peter", folderTemplate: "/{iptcdate} - {event}/", fileNameTemplate: "PS_{event}_{timesort}", originals: true, onArrival: true },
});
expect(created.json()).toMatchObject({ originals: true, onArrival: true });
const targetId = (created.json() as { id: string }).id;
ingest.arrivals = (p) => delivery.queueArrival(p);
try {
// Bigger than any delivery size: the copy keeps every pixel.
const id = await photo("backup.jpg", "2026:09:23 21:10:05", { width: 6000, height: 4000 });
await drain();
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId, photoId: id } });
expect([item.status, item.remotePath]).toEqual(["WAITING", "20260923 - VSC x AAAS/PS_VSC x AAAS_21100500.jpg"]);
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string }[] };
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
expect(await sharp(file.rawPayload).metadata()).toMatchObject({ width: 6000, height: 4000 });
// The same compressed image as the original (only the metadata around it changed).
const original = await ctx.db.photo.findUniqueOrThrow({ where: { id } });
const pixels = async (b: Buffer | string) => createHash("sha256").update(await sharp(b).raw().toBuffer()).digest("hex");
expect(await pixels(file.rawPayload)).toBe(await pixels(new LocalStorage(ctx.config.STORAGE_ROOT).resolve(original.storageKey)));
expect(file.rawPayload.toString("latin1")).toContain("VSC x AAAS");
} finally {
ingest.arrivals = undefined;
}
});
it("the central FTP as a relay: chosen logins' photos, exactly as they arrived, to a computer's ingest folder", async () => {
const { orgId, token } = await setup();
const { user: other } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const outro = await ctx.db.ftpAccount.create({ data: { organizationId: orgId, userId: other.id, login: "outro" } });
const mine = await ctx.db.ftpAccount.findFirstOrThrow({ where: { organizationId: orgId, login: "foto" } });
const target = async (name: string, logins: string[]) =>
(
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name, kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/ingest", username: "mac-0001-peter", folderTemplate: "/", fileNameTemplate: "{originalName}", originals: true, untouched: true, onArrival: true, arrivalLogins: logins },
})
).json() as { id: string; arrivalLogins: string[]; untouched: boolean };
const relay = await target("Relay foto", [mine.id]);
expect(relay).toMatchObject({ arrivalLogins: [mine.id], untouched: true });
const others = await target("Relay outro", [outro.id]);
// Someone else's login is refused.
const bad = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${relay.id}`, headers: bearer(token), payload: { arrivalLogins: ["00000000-0000-4000-8000-000000000000"] } });
expect(bad.json()).toMatchObject({ error: "unknown_ftp_login" });
ingest.arrivals = (p) => delivery.queueArrival(p);
try {
const id = await photo("IMG_0042.JPG", "2026:09:23 21:10:05");
await drain();
expect(await ctx.db.deliveryItem.count({ where: { targetId: others.id } })).toBe(0);
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId: relay.id, photoId: id } });
expect([item.status, item.remotePath]).toEqual(["WAITING", "IMG_0042.jpg"]);
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string }[] };
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
// Byte for byte the file the camera sent: no metadata written.
const original = await ctx.db.photo.findUniqueOrThrow({ where: { id } });
const sent = await readFile(new LocalStorage(ctx.config.STORAGE_ROOT).resolve(original.storageKey));
expect(Buffer.compare(file.rawPayload, sent)).toBe(0);
} finally {
ingest.arrivals = undefined;
}
});
it("waits for an original still on the photographer's computer instead of delivering its preview", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
});
const targetId = (created.json() as { id: string }).id;
const a = await photo("preview-only.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
await drain();
const waiting = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } });
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_original", 0]);
expect(waiting.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now());
// The original arrives (the ingest moves waiting deliveries forward): now it is rendered.
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: true } });
await ctx.db.deliveryItem.updateMany({ where: { photoId: a, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
await drain();
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
});
it("logs a blip reading an archive original from the cloud at info, not warn, so it never reaches the error hub (BIT-31522)", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
});
const targetId = (created.json() as { id: string }).id;
const a = await photo("archived.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
const calls: { level: "info" | "warn"; msg: string }[] = [];
const spy = {
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
};
// A cloud "originals" source whose download always comes back as the Nextcloud 503 seen in BIT-31522 — the
// same self-healing blip BIT-31513 already stopped from reaching the error hub out of the archive indexer.
const originals = { downloadOriginal: async () => { throw new NextcloudError("GET /archived.jpg failed: 503", 503); } };
const spied = new DeliveryService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), secrets: new SecretBox(KEY), broadcaster, log: spy, fetchImpl: nc.fetch, originals });
const [claimed] = await delivery.claim(5);
await spied.process(claimed!);
expect(calls).toContainEqual({ level: "info", msg: "delivery: original download blipped from the cloud, retrying" });
expect(calls.some((c) => c.level === "warn")).toBe(false);
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "QUEUED", lastError: "waiting_for_original" });
});
it("retries transient errors with back-off and stops at auth errors", async () => {
const { orgId, token, target } = await setup();
const id = await photo("a.jpg", "2026:09:23 21:10:00");
await delivery.enqueue({ organizationId: orgId, targetId: target.id, photoIds: [id], again: false, requestedById: (await ctx.db.user.findFirstOrThrow()).id });
nc.failPuts = 1;
const [claimed] = await delivery.claim(5);
const retried = await delivery.process(claimed!);
expect(retried).toMatchObject({ status: "QUEUED", attempts: 1 });
expect(retried.nextAttemptAt.getTime()).toBeGreaterThan(Date.now() + 5_000);
expect(await delivery.claim(5)).toEqual([]); // not due yet
await ctx.db.deliveryItem.updateMany({ data: { nextAttemptAt: new Date() } });
nc.status = 401;
const [again] = await delivery.claim(5);
expect(await delivery.process(again!)).toMatchObject({ status: "FAILED", attempts: 2 });
nc.status = undefined;
const retry = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${again}/retry`, headers: bearer(token) });
expect(retry.json()).toMatchObject({ status: "QUEUED", attempts: 0 });
await drain();
expect(nc.files.size).toBe(1);
expect(broadcaster.sent.filter((s) => s.message.type === "delivery.updated").map((s) => (s.message as { item: { status: string } }).item.status)).toEqual(["QUEUED", "QUEUED", "FAILED", "DONE"]);
});
it("writes long venues whole in IIM and XMP, flagged as UTF-8", async () => {
const src = path.join(dir, "src.jpg");
await writeFile(src, await sharp({ create: { width: 300, height: 200, channels: 3, background: "#123456" } }).jpeg().toBuffer());
const { renderDelivery } = await import("../src/delivery/render.js");
const out = await renderDelivery(src, { location: "Pavilhão da Escola EB 2/3 André Soares", city: "Braga" }, { longEdge: 4000, quality: 100 });
await writeFile(src, out);
const tags = (await exiftool.readRaw(src, { readArgs: ["-G1", "-a"] })) as Record<string, unknown>;
expect(tags["XMP-iptcCore:Location"]).toBe("Pavilhão da Escola EB 2/3 André Soares");
expect(tags["IPTC:City"]).toBe("Braga");
expect(tags["IPTC:Sub-location"]).toBe("Pavilhão da Escola EB 2/3 André Soares"); // whole, like Lightroom writes it
expect(tags["IPTC:CodedCharacterSet"]).toBe("UTF8");
});
it("takes SFTP, FTP and Dropbox targets, checks their addresses, and offers links only where they exist", async () => {
const { orgId, token, eventId } = await setup();
const make = (payload: Record<string, unknown>) =>
ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token), payload: { username: "abola", password: "x", folderTemplate: "/{event}/", fileNameTemplate: "PS_{event}_{n:pad3}", ...payload } });
expect((await make({ name: "Bad", kind: "SFTP", baseUrl: "https://transfer.ringier.ch" })).json()).toMatchObject({ error: "invalid_address" });
expect((await make({ name: "Bad2", kind: "FTP", baseUrl: "ftp://host/path" })).json()).toMatchObject({ error: "invalid_address" });
const sftp = await make({ name: "A Bola", kind: "SFTP", baseUrl: "sftp://transfer.ringier.ch", longEdge: 12000 });
expect(sftp.statusCode).toBe(201);
expect(sftp.json()).toMatchObject({ kind: "SFTP", shareLinks: false, hostFingerprint: null, example: { folder: "/Casa x Fora/", fileName: "PS_Casa x Fora_001.jpg" } });
expect(sftp.json()).not.toHaveProperty("secretEnc");
const share = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${sftp.json().id}/share`, headers: bearer(token), payload: { eventId } });
expect(share.json()).toMatchObject({ error: "share_not_supported" });
expect((await make({ name: "Dropbox", kind: "DROPBOX", baseUrl: "https://www.dropbox.com", username: "" })).json()).toMatchObject({ kind: "DROPBOX", shareLinks: true });
// A remembered host key is forgotten when asked, or when the server changes.
await ctx.db.deliveryTarget.update({ where: { id: sftp.json().id }, data: { hostFingerprint: "ab".repeat(32) } });
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${sftp.json().id}`, headers: bearer(token), payload: { baseUrl: "sftp://other.example:2222" } });
expect(moved.json()).toMatchObject({ hostFingerprint: null, kind: "SFTP", longEdge: 12000 });
// Nextcloud: the test really logs in.
const nextcloud = (await ctx.db.deliveryTarget.findFirstOrThrow({ where: { organizationId: orgId, kind: "NEXTCLOUD" } })).id;
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${nextcloud}/test`, headers: bearer(token) })).json()).toEqual({ ok: true });
nc.status = 401;
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${nextcloud}/test`, headers: bearer(token) })).json()).toMatchObject({ error: "nextcloud_error" });
});
it("creates (and reuses) a public link to the event folder", async () => {
const { orgId, token, target, eventId } = await setup();
const share = () => ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${target.id}/share`, headers: bearer(token), payload: { eventId } });
const first = (await share()).json() as { folder: string; url: string };
expect(first.url).toBe("https://cloud.test/s/1");
expect(first.folder).toContain("/20260923 - VSC x AAAS/");
expect(((await share()).json() as { url: string }).url).toBe("https://cloud.test/s/1");
});
});