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 { 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(["/"]); files = new Map(); shares = new Map(); 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)?.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("", { 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; 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("
", { 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, "admin@fpa.pt", { org: "fpa", role: "ADMIN" }); const { user: foto } = await seedUser(ctx.db, "foto@fpa.pt", { org: "fpa", role: "PHOTOGRAPHER" }); await ctx.db.user.update({ where: { id: foto.id }, data: { name: "Peter Spark" } }); const token = (await login(ctx.app, "admin@fpa.pt")).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 }; } async function photo(name: string, taken: string, size = { width: 600, height: 400 }): Promise { 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; 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 }).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("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], 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, "outro@fpa.pt", { 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("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; 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) => 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"); }); });