Files
photoreport/apps/api/test/library.test.ts
sparkandClaude Opus 5.5 8a8218c6b3 Make CI green: pgvector in the test database, two stale test expectations, and rustfmt.
- CI's Postgres is pgvector/pgvector:pg16: the face migrations create the vector extension.
- Delivery's "best of the event" answers `rest` too (since the best frames / the rest split).
- A batch cull answers `{ updated }`; `changed` and `resent` belong to the IPTC save.
- workers/faces/src/main.rs through rustfmt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-18 23:41:43 +00:00

395 lines
26 KiB
TypeScript

import { mkdir, mkdtemp, readdir, rm, stat, 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 { parseExifDate } from "../src/ingest/exif.js";
import { IngestScanner } from "../src/ingest/scanner.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: () => {} };
async function jpeg(opts: { color?: string; taken?: string; width?: number; height?: number } = {}): Promise<Buffer> {
return sharp({ create: { width: opts.width ?? 600, height: opts.height ?? 400, channels: 3, background: opts.color ?? "#336699" } })
.jpeg()
.withExif({ IFD0: { Make: "Canon", Model: "Canon EOS R1" }, IFD2: { DateTimeOriginal: opts.taken ?? "2026:09:23 21:14:07" } })
.toBuffer();
}
describe("EXIF dates", () => {
it("reads Lisbon wall-clock time, honouring the camera offset when present", () => {
expect(parseExifDate("2026:09:23 21:14:07")?.toISOString()).toBe("2026-09-23T20:14:07.000Z"); // summer, UTC+1
expect(parseExifDate("2026:12:05 21:14:07")?.toISOString()).toBe("2026-12-05T21:14:07.000Z"); // winter, UTC+0
expect(parseExifDate("2026:09:23 21:14:07", "+02:00", "25")?.toISOString()).toBe("2026-09-23T19:14:07.250Z");
expect(parseExifDate("0000:00:00 00:00:00")).toBeUndefined();
});
});
describe("library", () => {
let ctx: TestContext;
let dir: string;
let broadcaster: MemoryBroadcaster;
let service: IngestService;
let ingestRoot: string;
beforeAll(async () => {
dir = await mkdtemp(path.join(tmpdir(), "pr-lib-"));
ingestRoot = path.join(dir, "ingest");
broadcaster = new MemoryBroadcaster();
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot }, broadcaster);
service = new IngestService({
db: ctx.db,
storage: new LocalStorage(ctx.config.STORAGE_ROOT),
signer: new UrlSigner(ctx.config.JWT_SECRET, ctx.config.FILE_URL_TTL_SEC),
broadcaster,
ingestRoot,
log: quiet,
});
});
afterAll(async () => {
await ctx.app.close();
await ctx.db.$disconnect();
await rm(dir, { recursive: true, force: true });
});
beforeEach(async () => {
await resetDb(ctx.db);
broadcaster.sent.length = 0;
await rm(ingestRoot, { recursive: true, force: true });
});
async function setup() {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "ADMIN" });
const { user: photographer } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const { user: other } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const admin = (await login(ctx.app, "[email protected]")).body.accessToken;
const foto = (await login(ctx.app, "[email protected]")).body.accessToken;
const orgId = org!.id;
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: {
home: "VSC",
away: "AAAS",
venue: "Pavilhão Unidade Vimaranense",
city: "Guimarães",
sport: "andebol",
competition: "Campeonato Betclic",
competitionCode: "PO01",
startsAt: "2026-09-23T19:30:00Z",
photographerIds: [photographer.id],
},
});
expect(created.statusCode).toBe(201);
const event = created.json() as { id: string; ingestFrom: string; ingestUntil: string; photographers: { id: string }[] };
const ftp = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/ftp-accounts`,
headers: bearer(admin),
payload: { userId: photographer.id, login: "foto.r1" },
});
expect(ftp.statusCode).toBe(201);
return { orgId, admin, foto, photographer, other, event };
}
async function drop(login: string, name: string, data: Buffer): Promise<string> {
const file = path.join(ingestRoot, login, "DCIM", name);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, data);
return file;
}
it("creates events with a default ingest window and agenda; photographers only see theirs", async () => {
const { orgId, foto, event, photographer } = await setup();
expect(event.ingestFrom).toBe("2026-09-23T17:30:00.000Z");
expect(event.ingestUntil).toBe("2026-09-23T23:30:00.000Z");
expect(event.photographers.map((p) => p.id)).toEqual([photographer.id]);
const denied = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(foto), payload: { home: "A", away: "B", startsAt: "2026-10-01T10:00:00Z" } });
expect(denied.statusCode).toBe(403);
const other = (await login(ctx.app, "[email protected]")).body.accessToken;
const mine = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(foto) });
const theirs = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(other) });
expect((mine.json() as { events: unknown[] }).events).toHaveLength(1);
expect((theirs.json() as { events: unknown[] }).events).toHaveLength(0);
expect((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}`, headers: bearer(other) })).statusCode).toBe(404);
});
it("makes generic events: a name and no away team, the caption left to the editor", async () => {
const { orgId, admin } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", city: "Porto", startsAt: "2026-10-14T10:00:00Z" },
});
expect(created.statusCode).toBe(201);
const event = created.json() as { id: string; away: string; title: string; iptcTemplate: Record<string, unknown> };
expect(event).toMatchObject({ away: "", title: "Conferência de imprensa do FC Porto", iptcTemplate: { location: "{venue}" } });
expect(event.iptcTemplate.caption).toBeUndefined();
// Turning a match into another kind of event keeps its template; the caption still reads well.
const match = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin) })).json() as { events: { id: string; away: string }[] };
const vsc = match.events.find((e) => e.away === "AAAS")!;
const patched = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${vsc.id}`, headers: bearer(admin), payload: { home: "Apresentação do plantel", away: "" } });
expect(patched.json()).toMatchObject({ title: "Apresentação do plantel", away: "" });
});
it("ingests an FTP upload into the right event, with previews and a live message", async () => {
const { orgId, admin, event } = await setup();
const file = await drop("foto.r1", "R1_04126.JPG", await jpeg());
const outcome = await service.ingestFile(file);
expect(outcome).toMatchObject({ status: "ingested", eventId: event.id });
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=${event.id}`, headers: bearer(admin) });
const body = list.json() as { total: number; photos: { id: string; status: string; width: number; capturedAt: string; cameraModel: string; urls: { thumb: string } }[] };
expect(body.total).toBe(1);
expect(body.photos[0]).toMatchObject({ status: "READY", width: 600, capturedAt: "2026-09-23T20:14:07.000Z", cameraModel: "Canon EOS R1" });
expect(broadcaster.sent.map((s) => s.message.type)).toEqual(["photo.added"]);
expect(await readdir(path.join(ingestRoot, "foto.r1", "DCIM"))).toEqual([]); // moved out of the drop folder
const thumb = await ctx.app.inject({ method: "GET", url: body.photos[0]!.urls.thumb });
expect(thumb.statusCode).toBe(200);
expect(thumb.headers["content-type"]).toBe("image/jpeg");
const meta = await sharp(thumb.rawPayload).metadata();
expect(Math.max(meta.width ?? 0, meta.height ?? 0)).toBe(480);
const forged = await ctx.app.inject({ method: "GET", url: body.photos[0]!.urls.thumb.replace(/sig=[^&]+/, "sig=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") });
expect(forged.statusCode).toBe(404);
});
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
const { orgId, admin, foto, other, event } = await setup();
const until = new Date(Date.now() + 3600_000).toISOString();
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
// The photographer sees only their own login; the editor sees all.
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
const mine = (res.json() as { accounts: { id: string; login: string; here: boolean }[] }).accounts;
expect(mine.map((a) => [a.login, a.here])).toEqual([["foto.r1", false]]);
const all = ((await ctx.app.inject({ method: "GET", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin) })).json() as { accounts: { id: string; login: string }[] }).accounts;
expect(all.map((a) => a.login)).toEqual(["foto.r1", "outro.r1"]);
const theirs = all.find((a) => a.login === "outro.r1")!;
expect((await ctx.app.inject({ method: "PUT", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto), payload: { accountIds: [theirs.id] } })).statusCode).toBe(403);
// The editor points the photographer's login at the press conference.
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
// Taken during the game, but sent while the login points at the press conference: it goes there.
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
// Switched off: by the time again.
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
expect(await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#654321" })))).toMatchObject({ status: "ingested", eventId: event.id });
// A time gone by: back by the time too.
await ctx.db.ftpAccount.updateMany({ data: { targetEventId: press.id, targetUntil: new Date(Date.now() - 1000) } });
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
});
it("deletes an event: its photos go back to Sem evento; put-away events are listed apart", async () => {
const { orgId, admin, foto, event } = await setup();
const outcome = await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg()));
expect(outcome).toMatchObject({ eventId: event.id });
await ctx.app.inject({ method: "PUT", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: (await ctx.db.ftpAccount.findMany()).map((a) => a.id), until: new Date(Date.now() + 3600_000).toISOString() } });
expect((await ctx.app.inject({ method: "DELETE", url: `/v1/events/${event.id}`, headers: bearer(foto) })).statusCode).toBe(403);
const del = await ctx.app.inject({ method: "DELETE", url: `/v1/events/${event.id}`, headers: bearer(admin) });
expect(del.json()).toMatchObject({ deleted: event.id, photos: 1 });
expect(await ctx.db.photo.findFirst({ where: { id: (outcome as { photoId: string }).photoId } })).toMatchObject({ eventId: null });
expect(await ctx.db.ftpAccount.findFirst()).toMatchObject({ targetEventId: null });
// Put away by hand: out of the list, in the "archived" one; the archive's own games never are.
const other = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Gala", startsAt: "2026-10-01T20:00:00Z" } })).json() as { id: string };
await ctx.app.inject({ method: "PATCH", url: `/v1/events/${other.id}`, headers: bearer(admin), payload: { archived: true } });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin) })).json() as { events: unknown[] }).events).toHaveLength(0);
const archived = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events?archived=true`, headers: bearer(admin) })).json() as { events: { id: string }[] };
expect(archived.events.map((e) => e.id)).toEqual([other.id]);
});
it("drops duplicates, sets aside unknown logins and RAW files, and sends unmatched photos to the inbox", async () => {
const { orgId, admin } = await setup();
const data = await jpeg();
const first = await service.ingestFile(await drop("foto.r1", "a.jpg", data));
const again = await service.ingestFile(await drop("foto.r1", "a-copy.jpg", data));
expect(again).toEqual({ status: "duplicate", photoId: (first as { photoId: string }).photoId });
expect(await service.ingestFile(await drop("ninguem", "x.jpg", await jpeg({ color: "#111111" })))).toEqual({ status: "skipped", reason: "unknown_login" });
expect(await service.ingestFile(await drop("foto.r1", "x.CR3", Buffer.from("raw")))).toEqual({ status: "skipped", reason: "unsupported_type" });
expect(await readdir(path.join(ingestRoot, "_unclaimed", "ninguem", "DCIM"))).toEqual(["x.jpg"]);
expect(await readdir(path.join(ingestRoot, "_unsupported", "foto.r1", "DCIM"))).toEqual(["x.CR3"]);
const late = await service.ingestFile(await drop("foto.r1", "late.jpg", await jpeg({ color: "#993333", taken: "2026:09:25 12:00:00" })));
expect(late).toMatchObject({ status: "ingested", eventId: null });
const inbox = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=inbox`, headers: bearer(admin) });
expect((inbox.json() as { total: number }).total).toBe(1);
});
it("an event created (or moved) after its photos arrived claims them from the inbox, live", async () => {
const { orgId, admin, photographer } = await setup();
const early = await service.ingestFile(await drop("foto.r1", "early.jpg", await jpeg({ color: "#994400", taken: "2026:10:09 20:26:47" })));
const later = await service.ingestFile(await drop("foto.r1", "later.jpg", await jpeg({ color: "#004499", taken: "2026:10:09 22:17:05" })));
const elsewhere = await service.ingestFile(await drop("foto.r1", "other.jpg", await jpeg({ color: "#449900", taken: "2026:09:03 16:37:46" })));
expect([early, later, elsewhere].map((o) => (o as { eventId: string | null }).eventId)).toEqual([null, null, null]);
broadcaster.sent.length = 0;
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/events`,
headers: bearer(admin),
payload: { home: "SC Braga", away: "Sporting CP", startsAt: "2026-10-09T19:15:00Z", photographerIds: [photographer.id] },
});
expect(created.statusCode).toBe(201);
const event = created.json() as { id: string; photoCount: number };
expect(event.photoCount).toBe(2);
const ids = [early, later].map((o) => (o as { photoId: string }).photoId);
expect(broadcaster.sent.map((s) => s.message)).toContainEqual({ type: "photo.updated", ids: expect.arrayContaining(ids), patch: { eventId: event.id } });
const inbox = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=inbox`, headers: bearer(admin) });
expect((inbox.json() as { photos: { id: string }[] }).photos.map((p) => p.id)).toEqual([(elsewhere as { photoId: string }).photoId]);
// Moving its time to cover the September photo claims that one too.
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${event.id}`, headers: bearer(admin), payload: { startsAt: "2026-09-03T15:00:00Z" } });
expect((moved.json() as { photoCount: number }).photoCount).toBe(3);
});
it("says why a photo failed", async () => {
const { orgId, admin } = await setup();
// End marker present, so this is a finished file that cannot be decoded, not one still arriving.
const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]);
await service.ingestFile(await drop("foto.r1", "cut.jpg", unreadable));
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?status=FAILED`, headers: bearer(admin) });
const [photo] = (list.json() as { photos: { status: string; error?: string }[] }).photos;
expect(photo).toMatchObject({ status: "FAILED", error: expect.any(String) });
});
it("marks unreadable files as failed instead of losing them", async () => {
await setup();
const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]);
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", unreadable));
expect(outcome.status).toBe("failed");
const photo = await ctx.db.photo.findFirstOrThrow();
expect(photo.status).toBe("FAILED");
});
it("waits until an upload stops growing before ingesting it", async () => {
await setup();
const scanner = new IngestScanner(service, ingestRoot, { intervalMs: 10, concurrency: 2, log: quiet });
await drop("foto.r1", "one.jpg", await jpeg());
expect(await scanner.scanOnce()).toEqual([]); // first sighting
expect(await scanner.scanOnce()).toHaveLength(1); // unchanged: ready
expect(await ctx.db.photo.count()).toBe(1);
});
it("leaves a jpeg that is still transferring where the camera is writing it", async () => {
await setup();
const scanner = new IngestScanner(service, ingestRoot, { intervalMs: 10, concurrency: 2, log: quiet });
const file = await drop("foto.r1", "part.jpg", Buffer.from([0xff, 0xd8, 0x00, 0x11, 0x22]));
expect(await scanner.scanOnce()).toEqual([]);
expect(await scanner.scanOnce()).toEqual([]);
expect(await ctx.db.photo.count()).toBe(0);
expect((await stat(file)).size).toBe(5);
const outcome = await service.ingestFile(file);
expect(outcome).toEqual({ status: "skipped", reason: "incomplete" });
expect((await stat(file)).size).toBe(5);
});
it("culls in batch, live, and keeps photographers to their own photos", async () => {
const { orgId, admin, foto } = await setup();
const a = await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#101010" })));
const b = await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#202020" })));
const ids = [a, b].map((o) => (o as { photoId: string }).photoId);
broadcaster.sent.length = 0;
const patch = await ctx.app.inject({
method: "PATCH",
url: `/v1/orgs/${orgId}/photos`,
headers: bearer(admin),
payload: { ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } },
});
expect(patch.json()).toEqual({ updated: 2 });
expect(broadcaster.sent[0]?.message).toEqual({ type: "photo.updated", ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } });
const picks = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?flag=PICK&minRating=4`, headers: bearer(admin) });
expect((picks.json() as { total: number }).total).toBe(2);
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(foto), payload: { ids, patch: { flag: "REJECT" } } })).statusCode).toBe(403);
const own = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(foto) });
expect((own.json() as { total: number }).total).toBe(2);
const other = (await login(ctx.app, "[email protected]")).body.accessToken;
const none = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(other) });
expect((none.json() as { total: number }).total).toBe(0);
});
it("previews the IPTC a delivery will write, with codes and identified players", async () => {
const { orgId, admin } = await setup();
const saved = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/code-list`, headers: bearer(admin), payload: { content: "v7\tMiguel Silva (VSC)\nbad\n" } });
expect(saved.json()).toMatchObject({ entries: 1, issues: [{ line: 2 }] });
const { photoId } = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg()))) as { photoId: string };
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/photos`, headers: bearer(admin), payload: { ids: [photoId], patch: { players: ["\\v7\\"] } } });
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).players).toEqual(["Miguel Silva (VSC)"]);
const iptc = await ctx.app.inject({ method: "GET", url: `/v1/photos/${photoId}/iptc`, headers: bearer(admin) });
const { values } = iptc.json() as { values: Record<string, unknown> };
expect(values).toMatchObject({
title: "Miguel Silva (VSC)",
caption: "VSC x AAAS, em Guimarães, no Pavilhão Unidade Vimaranense",
event: "VSC x AAAS",
keywords: ["ANDEBOL"],
personsShown: ["Miguel Silva (VSC)"],
creator: "foto / PhotoReport.pt",
});
});
it("sets IPTC fields on several photos at once (Photo Mechanic's Info window), over the event's template", async () => {
const { orgId, admin } = await setup();
const a = (await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#111111" })))) as { photoId: string };
const b = (await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#222222" })))) as { photoId: string };
const put = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [a.photoId, b.photoId], set: { caption: "Golo de {home}, em {city}", keywords: ["ANDEBOL", "GOLO"] } } });
expect(put.json()).toEqual({ updated: 2, changed: 2, resent: 0 });
const got = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${b.photoId}/iptc`, headers: bearer(admin) })).json() as { values: Record<string, unknown>; overrides: Record<string, unknown>; template: Record<string, unknown> };
expect(got.values).toMatchObject({ caption: "Golo de VSC, em Guimarães", keywords: ["ANDEBOL", "GOLO"], event: "VSC x AAAS" });
expect(got.overrides).toEqual({ caption: "Golo de {home}, em {city}", keywords: ["ANDEBOL", "GOLO"] });
// Back to the template for one field; the other stays.
await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [b.photoId], set: { caption: null } } });
const again = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${b.photoId}/iptc`, headers: bearer(admin) })).json() as { values: Record<string, unknown>; overrides: Record<string, unknown> };
expect(again.overrides).toEqual({ keywords: ["ANDEBOL", "GOLO"] });
expect(again.values.caption).toBe("VSC x AAAS, em Guimarães, no Pavilhão Unidade Vimaranense");
const bad = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/photos/iptc`, headers: bearer(admin), payload: { ids: [a.photoId], set: { nonsense: "x" } } });
expect(bad.statusCode).toBe(400);
});
it("accepts uploads from the browser into the same pipeline, live", async () => {
const { orgId, foto, event } = await setup();
const form = (name: string, data: Buffer) => {
const boundary = "----pr" + Math.random().toString(16).slice(2);
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: image/jpeg\r\n\r\n`);
return { payload: Buffer.concat([head, data, Buffer.from(`\r\n--${boundary}--\r\n`)]), headers: { ...bearer(foto), "content-type": `multipart/form-data; boundary=${boundary}` } };
};
const data = await jpeg({ color: "#445566" });
const first = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/uploads`, ...form("IMG_0001.JPG", data) });
expect(first.statusCode).toBe(201);
expect(first.json()).toMatchObject({ status: "ingested", photo: { originalName: "IMG_0001.JPG", eventId: event.id, status: "READY" } });
expect(broadcaster.sent.map((m) => m.message.type)).toEqual(["photo.added"]);
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/uploads`, ...form("copy.jpg", data) });
expect(again.statusCode).toBe(200);
expect(again.json()).toMatchObject({ status: "duplicate" });
const raw = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/uploads`, ...form("x.CR3", Buffer.from("raw")) });
expect(raw.statusCode).toBe(415);
const outsider = await seedUser(ctx.db, "[email protected]", { org: "liga", role: "ADMIN" });
const token = (await login(ctx.app, outsider.user.email)).body.accessToken;
const body = form("y.jpg", data);
const denied = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/uploads`, payload: body.payload, headers: { ...body.headers, ...bearer(token) } });
expect(denied.statusCode).toBe(403);
});
it("lets only admins manage FTP logins", async () => {
const { orgId, foto, photographer } = await setup();
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(foto), payload: { userId: photographer.id, login: "outra" } });
expect(res.statusCode).toBe(403);
const admin = (await login(ctx.app, "[email protected]")).body.accessToken;
const taken = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: photographer.id, login: "foto.r1" } });
expect(taken.statusCode).toBe(409);
const bad = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: photographer.id, login: "../x" } });
expect(bad.statusCode).toBe(400);
});
});