- POST /v1/orgs/:orgId/uploads: one JPEG per request through the FTP pipeline (dedupe, EXIF, routing or an explicit event, previews, live message); the web library imports by button or drag and drop, 4 at a time with progress - Ingest reads the IPTC already in a file (XMP first; IIM from Lightroom/Photo Mechanic on the Mac is Mac Roman without a charset flag and is repaired) and keeps it next to ours; the info panel shows it and can reuse its Title as the players - Tokens for client-made connections are refreshed a minute before they expire Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
260 lines
15 KiB
TypeScript
260 lines
15 KiB
TypeScript
import { mkdir, mkdtemp, readdir, 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 { 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("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("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("marks unreadable files as failed instead of losing them", async () => {
|
|
await setup();
|
|
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", Buffer.from("not really a jpeg")));
|
|
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("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("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);
|
|
});
|
|
});
|