From ea669672d4dd3bfa878ac0289b7a24d72f45156e Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 27 Oct 2026 21:17:42 +0000 Subject: [PATCH] Add archive search-by-photo for cloud editors (FPA news desk). Editors with folder edit rights can upload a portrait and find matching faces across the archive they can see. The option is per cloud source (on by default for FPA), requires biometrics, and never stores the probe. --- .../migration.sql | 4 + apps/api/prisma/schema.prisma | 2 + apps/api/src/app.ts | 34 ++- apps/api/src/archive/find.ts | 178 +++++++++++++ apps/api/src/archive/review.ts | 9 +- apps/api/src/archive/routes.ts | 4 + apps/api/src/archive/service.ts | 5 +- apps/api/src/archive/viewer.ts | 20 +- apps/api/test/archive.test.ts | 100 +++++++- apps/api/test/helpers.ts | 18 +- apps/app/src/i18n.ts | 2 + apps/app/src/pages/ArchivePage.tsx | 12 + .../site/src/app/arquivo/[id]/ArchiveView.tsx | 42 +++- .../site/src/app/arquivo/[id]/FindByPhoto.tsx | 235 ++++++++++++++++++ apps/site/src/app/arquivo/[id]/api.ts | 11 + apps/site/src/app/arquivo/[id]/page.tsx | 1 + docs/ARCHITECTURE.md | 6 +- docs/archive.md | 7 + packages/sdk/src/client.ts | 5 +- packages/sdk/src/types.ts | 2 + 20 files changed, 671 insertions(+), 26 deletions(-) create mode 100644 apps/api/prisma/migrations/20261027210000_archive_photo_find/migration.sql create mode 100644 apps/api/src/archive/find.ts create mode 100644 apps/site/src/app/arquivo/[id]/FindByPhoto.tsx diff --git a/apps/api/prisma/migrations/20261027210000_archive_photo_find/migration.sql b/apps/api/prisma/migrations/20261027210000_archive_photo_find/migration.sql new file mode 100644 index 0000000..1c635ec --- /dev/null +++ b/apps/api/prisma/migrations/20261027210000_archive_photo_find/migration.sql @@ -0,0 +1,4 @@ +-- Editors on the cloud: search the archive by uploading a photo of a person (news desk). Off by default; +-- on for FPA archives already connected with that look. +ALTER TABLE "cloud_sources" ADD COLUMN "photo_find_enabled" BOOLEAN NOT NULL DEFAULT false; +UPDATE "cloud_sources" SET "photo_find_enabled" = true WHERE "look" = 'fpa'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 6f71885..57817b0 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1634,6 +1634,8 @@ model CloudSource { status String @default("LOGIN") /// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport). look String? + /// Editors on the cloud may upload a photo and search for that face across the archive (news desk). Off by default. + photoFindEnabled Boolean @default(false) @map("photo_find_enabled") /// The archive's own address ("arquivo.ligaportugal.pt"): the site serves this archive at its root there. hostname String? @unique /// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token). diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 1db9910..9c18c6a 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -146,17 +146,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give await registerArchiveRoutes(app, { db, sessions, archive, storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 }); // The API never runs the face engine: it confirms and merges groups; the worker detects and groups. const faces = new FaceService({ db, storage, broadcaster, log: app.log }); - await registerArchiveViewerRoutes(app, { db, secrets, signer, archive, tokens: new ViewerTokens(config.JWT_SECRET), faces, storage, secret: config.JWT_SECRET, fetchImpl, sports }); - await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); - await registerSearchRoutes(app, { db, sessions, signer }); - await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); - const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log }); - ingest.arrivals = (photo) => delivery.queueArrival(photo); - await registerUploadRoutes(app, { db, sessions, ingest, storage, signer }); - // The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise. - const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT))); - await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline }); - // Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand. + // Search by photo (library, archive editors, "Encontra-te"): the API's own face engine, started on demand. const facePaths = faceEnginePaths(config); const slots = scanSlots(); const lookupEngine = new IdleEngine( @@ -168,6 +158,28 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give ); app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close())); const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() }); + await registerArchiveViewerRoutes(app, { + db, + secrets, + signer, + archive, + tokens: new ViewerTokens(config.JWT_SECRET), + faces, + storage, + secret: config.JWT_SECRET, + fetchImpl, + sports, + lookup, + }); + await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT }); + await registerSearchRoutes(app, { db, sessions, signer }); + await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY }); + const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log }); + ingest.arrivals = (photo) => delivery.queueArrival(photo); + await registerUploadRoutes(app, { db, sessions, ingest, storage, signer }); + // The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise. + const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT))); + await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline }); let jerseyOnce: Promise | null = null; const jerseyOf = (): Promise => { if (jersey !== undefined) return Promise.resolve(jersey); diff --git a/apps/api/src/archive/find.ts b/apps/api/src/archive/find.ts new file mode 100644 index 0000000..e1b68e4 --- /dev/null +++ b/apps/api/src/archive/find.ts @@ -0,0 +1,178 @@ +import type { FastifyInstance, FastifyRequest } from "fastify"; +import { eventName } from "@photoreport/metadata"; +import { z } from "zod"; +import { Prisma } from "../generated/prisma/client.js"; +import type { Db } from "../db.js"; +import { facesOut, lookupFailed, lookupImage, LookupQuery } from "../faces/lookupRoutes.js"; +import type { FaceLookup, MatchLevel } from "../faces/lookup.js"; +import { conflict, forbidden, notFound } from "../lib/errors.js"; +import type { UrlSigner } from "../storage/storage.js"; +import { faceBox } from "./people.js"; +import { publishedPhotos } from "./gallery.js"; +import type { Viewer } from "./viewer.js"; + +/** + * Search the archive by a photo: for editors on the cloud (same rights as "Rever rostos"), when the archive has + * the option on and the organization has biometrics on. The search photo is read in memory and never kept. + * Results stay inside the folders the viewer may see. + */ +interface Deps { + db: Db; + signer: UrlSigner; + lookup: FaceLookup; + viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer; + visibleFolders: (v: Viewer) => Promise; + editableFolders: (v: Viewer) => Promise; +} + +const SourceParams = z.object({ sourceId: z.uuid() }); + +type CardLevel = "confirmed" | "probable" | "similar"; + +const toCardLevel = (level: MatchLevel, named: boolean): CardLevel => { + if (named && level === "strong") return "confirmed"; + if (level === "strong") return "probable"; + return "similar"; +}; + +export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps) { + const { db, signer, lookup, viewerOf, visibleFolders, editableFolders } = deps; + + const scopeOf = async (v: Viewer): Promise => { + const visible = await visibleFolders(v); + if (visible !== "all" && !visible.length) return null; + if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`; + return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`; + }; + + const requireFind = async (v: Viewer) => { + const editable = await editableFolders(v); + if (editable !== "all" && !editable.length) throw forbidden("archive_edit_required"); + const source = await db.cloudSource.findUnique({ + where: { id: v.s }, + select: { id: true, organizationId: true, photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } }, + }); + if (!source) throw notFound("source_not_found"); + if (!source.photoFindEnabled || !source.organization.biometricsEnabled) throw conflict("find_unavailable"); + return source; + }; + + /** + * A photo of the person (headshot, press cutout) against faces already indexed in the folders this editor may + * see. Best matches first. The uploaded file is not stored. + */ + app.post("/v1/archive/:sourceId/find", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } } }, async (req) => { + const { sourceId } = SourceParams.parse(req.params); + const q = LookupQuery.parse(req.query); + const v = viewerOf(req, sourceId); + const source = await requireFind(v); + const scope = await scopeOf(v); + if (!scope) return { faces: [], used: 0, people: [], total: 0, photos: [] }; + + const image = await lookupImage(req); + const read = await lookup.facesIn(image).catch(lookupFailed); + const used = Math.min(q.face, read.faces.length - 1); + const probe = read.faces[used]!; + + const events = await db.$queryRaw<{ event_id: string }[]>` + SELECT DISTINCT ph.event_id AS event_id + FROM photos ph + JOIN cloud_files cf ON cf.photo_id = ph.id AND ${scope} + WHERE ph.event_id IS NOT NULL`; + const eventIds = events.map((e) => e.event_id); + if (!eventIds.length) return { faces: facesOut(read.faces), used, people: [], total: 0, photos: [] }; + + const [people, groups] = await Promise.all([ + lookup.people(source.organizationId, probe.embedding, read.model), + lookup.groups(source.organizationId, probe.embedding, read.model, { eventIds, limit: 400 }), + ]); + + const best = new Map(); + const keep = (photoId: string, faceId: string, score: number, level: CardLevel, sharpness: number | null) => { + const was = best.get(photoId); + if (!was || score > was.score) best.set(photoId, { faceId, score, level, sharpness }); + }; + + if (groups.length) { + const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>` + SELECT f.id, f.photo_id, f.group_id, f.sharpness + FROM faces f + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE f.group_id = ANY(${groups.map((g) => g.groupId)}::uuid[])`; + const byGroup = new Map(groups.map((g) => [g.groupId, g])); + for (const f of faces) { + const g = byGroup.get(f.group_id)!; + keep(f.photo_id, f.id, g.score, toCardLevel(g.level, !!g.personId), f.sharpness); + } + } + + const sure = people.filter((p) => p.level === "strong"); + if (sure.length) { + const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null }[]>` + SELECT f.id, f.photo_id, f.sharpness, g.person_id + FROM faces f + JOIN face_groups g ON g.id = f.group_id + JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope} + WHERE g.ignored_at IS NULL AND g.person_id = ANY(${sure.map((p) => p.id)}::uuid[])`; + const scoreOf = new Map(sure.map((p) => [p.id, p.score])); + for (const f of named) { + const score = (f.person_id && scoreOf.get(f.person_id)) || sure[0]!.score; + keep(f.photo_id, f.id, score, "confirmed", f.sharpness); + } + } + + const hits = [...best.entries()] + .map(([photoId, h]) => ({ photoId, ...h })) + .sort((a, b) => b.score - a.score || (b.sharpness ?? 0) - (a.sharpness ?? 0)); + const shown = hits.slice(0, 500); + if (!shown.length) return { faces: facesOut(read.faces), used, people, total: 0, photos: [] }; + + const ids = shown.map((h) => h.photoId); + const links = await db.$queryRaw<{ photo_id: string; folder_id: string }[]>` + SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id + FROM cloud_files cf + WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope} + ORDER BY cf.photo_id, cf.path`; + const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id])); + const photos = await db.photo.findMany({ + where: { id: { in: ids } }, + select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true }, + }); + const byId = new Map(photos.map((p) => [p.id, p])); + const faceRows = await db.face.findMany({ where: { id: { in: shown.map((h) => h.faceId) } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }); + const faceById = new Map(faceRows.map((f) => [f.id, f])); + const folders = await db.cloudFolder.findMany({ where: { id: { in: [...new Set(folderOf.values())] } }, include: { event: true } }); + const galleries = new Map( + folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }]), + ); + + const cards = shown + .filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId)) + .map((h) => { + const p = byId.get(h.photoId)!; + const f = faceById.get(h.faceId); + return { + id: p.id, + name: p.originalName, + width: p.width, + height: p.height, + players: p.players, + capturedAt: p.capturedAt, + thumb: signer.url(p.id, "thumb", p.renderedSeq), + preview: signer.url(p.id, "preview", p.renderedSeq), + level: h.level, + score: h.score, + face: f ? faceBox(f, p) : null, + gallery: galleries.get(folderOf.get(h.photoId)!) ?? null, + }; + }); + + return { + faces: facesOut(read.faces), + used, + people, + total: hits.length, + photos: cards, + }; + }); +} diff --git a/apps/api/src/archive/review.ts b/apps/api/src/archive/review.ts index 9ea6722..d7f1f42 100644 --- a/apps/api/src/archive/review.ts +++ b/apps/api/src/archive/review.ts @@ -82,12 +82,17 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De const log = (v: Viewer, action: string, data: { personId?: string | null; groupId?: string | null; faces?: number }) => db.archiveFaceAction.create({ data: { sourceId: v.s, viewer: v.n, action, personId: data.personId ?? null, groupId: data.groupId ?? null, faces: data.faces ?? 0 } }); - /** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything). */ + /** What this viewer may do: review faces (some folder with edit rights), act on people (edits everything), search by photo. */ app.get("/v1/archive/:sourceId/me", async (req) => { const { sourceId } = SourceParams.parse(req.params); const v = viewerOf(req, sourceId); const editable = await editableFolders(v); const canReview = editable === "all" || editable.length > 0; + const source = await db.cloudSource.findUnique({ + where: { id: sourceId }, + select: { photoFindEnabled: true, organization: { select: { biometricsEnabled: true } } }, + }); + const canFind = canReview && !!source?.photoFindEnabled && !!source.organization.biometricsEnabled; const pending = canReview ? await (async () => { const scope = await editScope(v); @@ -100,7 +105,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De return row?.n ?? 0; })() : 0; - return { name: v.n, canReview, canManagePeople: editable === "all", pending }; + return { name: v.n, canReview, canManagePeople: editable === "all", canFind, pending }; }); /** diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index b07c037..53dca96 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -23,6 +23,8 @@ const Update = z.object({ rootPath: z.string().trim().min(1).max(500).optional(), paused: z.boolean().optional(), look: z.enum(ARCHIVE_LOOKS).nullable().optional(), + /** Editors on the cloud may search the archive by uploading a photo of a person. */ + photoFindEnabled: z.boolean().optional(), /** The archive's own address (a host name, no scheme or path); empty or null takes it away. */ hostname: z .string() @@ -116,6 +118,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db baseUrl: s.baseUrl, rootPath: s.rootPath, look: s.look, + photoFindEnabled: s.photoFindEnabled, hostname: s.hostname, account: s.username || null, status: s.status, @@ -193,6 +196,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db ...(status && { status }), ...(status === "READY" && { nextScanAt: new Date() }), ...(body.look !== undefined && { look: body.look }), + ...(body.photoFindEnabled !== undefined && { photoFindEnabled: body.photoFindEnabled }), ...(hostname !== undefined && { hostname }), }, }); diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index f45abe8..dbc9cd6 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -221,6 +221,7 @@ export class ArchiveService { if (!/^https?:\/\/[^/]+/i.test(baseUrl)) throw new ArchiveRejected("invalid_url"); const box = this.box(); const flow = await startLogin(baseUrl, this.fetchImpl); + const look = lookFor(input.name, input.rootPath); const source = await this.deps.db.cloudSource.create({ data: { organizationId, @@ -228,7 +229,9 @@ export class ArchiveService { name: input.name.trim() || new URL(baseUrl).hostname, baseUrl, rootPath: normalisePath(input.rootPath), - look: lookFor(input.name, input.rootPath), + look, + // FPA news desk: editors on the cloud may search by photo from day one; other archives stay off. + photoFindEnabled: look === "fpa", status: "LOGIN", loginPoll: box.seal(JSON.stringify({ endpoint: flow.endpoint, token: flow.token, loginUrl: flow.loginUrl } satisfies LoginState)), loginExpires: new Date(Date.now() + LOGIN_TTL_MS), diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index 97ca34a..f9e9565 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -15,8 +15,10 @@ import { readStoredRaws, readStoredTeams } from "./directory.js"; import type { FaceService } from "../faces/service.js"; import { clubKind, faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import { registerArchiveDownloadRoutes } from "./downloads.js"; +import { registerArchiveFindRoutes } from "./find.js"; import { registerArchiveReviewRoutes } from "./review.js"; import type { ArchiveService } from "./service.js"; +import type { FaceLookup } from "../faces/lookup.js"; import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js"; import { peopleInVideos } from "./video-faces.js"; @@ -110,7 +112,20 @@ const ListQuery = z.object({ export async function registerArchiveViewerRoutes( app: FastifyInstance, - deps: { db: Db; secrets: SecretBox | undefined; signer: UrlSigner; archive: ArchiveService; tokens: ViewerTokens; faces: FaceService; storage: LocalStorage; secret: string; fetchImpl?: typeof fetch | undefined; sports?: Pick | undefined }, + deps: { + db: Db; + secrets: SecretBox | undefined; + signer: UrlSigner; + archive: ArchiveService; + tokens: ViewerTokens; + faces: FaceService; + storage: LocalStorage; + secret: string; + fetchImpl?: typeof fetch | undefined; + sports?: Pick | undefined; + /** Search by photo for editors (absent → find route not registered). */ + lookup?: FaceLookup; + }, ) { const { db, signer, tokens } = deps; const fetchImpl = deps.fetchImpl ?? fetch; @@ -738,6 +753,9 @@ export async function registerArchiveViewerRoutes( await deps.archive.rebuildDirectory(sourceId); }, }); + if (deps.lookup) { + await registerArchiveFindRoutes(app, { db, signer, lookup: deps.lookup, viewerOf, visibleFolders, editableFolders }); + } await registerArchiveDownloadRoutes(app, { db, storage: deps.storage, secret: deps.secret, viewerOf, visibleFolders }); } diff --git a/apps/api/test/archive.test.ts b/apps/api/test/archive.test.ts index eed618f..a5ddbfe 100644 --- a/apps/api/test/archive.test.ts +++ b/apps/api/test/archive.test.ts @@ -10,6 +10,7 @@ import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryR import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js"; import { ArchiveService, localDirs } from "../src/archive/service.js"; import { FaceService } from "../src/faces/service.js"; +import { normalize } from "../src/faces/math.js"; import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js"; import { execFileSync } from "node:child_process"; import { SecretBox } from "../src/delivery/secrets.js"; @@ -18,6 +19,24 @@ 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"; +/** Face for archive search-by-photo tests: a fixed direction plus optional noise. */ +function faceVec(seed: number, noise = 0): number[] { + const rand = (k: number) => { + const x = Math.sin(k * 127.1 + 311.7) * 43758.5453; + return (x - Math.floor(x)) * 2 - 1; + }; + return normalize(Array.from({ length: 64 }, (_, i) => rand(seed * 1000 + i) + (noise ? rand(noise * 7919 + i) * 0.15 : 0))); +} + +class FindEngine implements FaceEngine { + readonly model = "auraface-v1"; + next: FaceAnalysis = { width: 800, height: 1000, faces: [] }; + async analyse(): Promise { + return this.next; + } + async close(): Promise {} +} + const KEY = Buffer.alloc(32, 7).toString("base64"); const quiet = { info: () => {}, warn: () => {} }; @@ -553,6 +572,7 @@ describe("archive from a Nextcloud", () => { let orgId: string; let ownerId: string; let worker: ArchiveService; + const findEngine = new FindEngine(); // The cloud, and the handball federation's portal for a licence lookup. const fetchProxy: typeof fetch = (input, init) => { @@ -569,7 +589,7 @@ describe("archive from a Nextcloud", () => { beforeAll(async () => { storageRoot = await mkdtemp(path.join(tmpdir(), "pr-archive-test-")); - ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy); + ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy, undefined, findEngine); }); afterAll(async () => { await ctx.app.close(); @@ -1363,11 +1383,87 @@ describe("archive from a Nextcloud", () => { expect(photos.every((f) => f.photo?.eventId === fixed.eventId)).toBe(true); }); + it("lets cloud editors search the archive by a photo when the option is on", async () => { + await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); + const source = await connect(); + cloud.authorised = true; + await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); + await worker.scan(source.id); + for (const id of await worker.claim(10)) await worker.index(id); + + const photo = await ctx.db.photo.findFirstOrThrow({ where: { originalName: "PS_0001.jpg" } }); + const martim = await ctx.db.person.create({ + data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: faceVec(1), model: "auraface-v1" }, + }); + const group = await ctx.db.faceGroup.create({ + data: { organizationId: orgId, eventId: photo.eventId!, centroid: faceVec(1, 2), model: "auraface-v1", size: 1, personId: martim.id }, + }); + await ctx.db.face.create({ + data: { + organizationId: orgId, + photoId: photo.id, + groupId: group.id, + x0: 0.4, + y0: 0.2, + x1: 0.5, + y1: 0.35, + score: 0.9, + sharpness: 120, + embedding: faceVec(1, 3), + model: "auraface-v1", + }, + }); + + const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); + cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] }); + cloud.viewers.set("leitor", { password: "l-pass", shared: [po01] }); + const signIn = async (who: string) => { + cloud.loginAs = who; + cloud.authorised = false; + const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; + cloud.authorised = true; + return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; + }; + const as = (t: string) => ({ authorization: `Archive ${t}` }); + const editor = await signIn("abc"); + const reader = await signIn("leitor"); + + expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: true, canReview: true }); + expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(reader) })).json()).toMatchObject({ canFind: false }); + + const probe = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#777" } }).jpeg().toBuffer(); + const multipart = (data: Buffer) => { + const boundary = "----pr-find"; + const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="retrato.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`); + return { payload: Buffer.concat([head, data, Buffer.from(`\r\n--${boundary}--\r\n`)]), type: `multipart/form-data; boundary=${boundary}` }; + }; + findEngine.next = { + width: 800, + height: 1000, + faces: [{ x0: 0.3, y0: 0.2, x1: 0.7, y1: 0.6, score: 0.95, sharpness: 300, landmarks: [], embedding: faceVec(1) }], + }; + const mp = multipart(probe); + let res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload }); + expect(res.statusCode).toBe(200); + const body = res.json() as { people: { name: string }[]; photos: { id: string }[]; total: number }; + expect(body.people[0]?.name).toBe("Martim Costa"); + expect(body.photos.map((p) => p.id)).toContain(photo.id); + + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(reader), "content-type": mp.type }, payload: mp.payload }); + expect(res.statusCode).toBe(403); + + await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { photoFindEnabled: false } }); + res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/find`, headers: { ...as(editor), "content-type": mp.type }, payload: mp.payload }); + expect(res.statusCode).toBe(409); + expect(res.json()).toMatchObject({ error: "find_unavailable" }); + expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) })).json()).toMatchObject({ canFind: false }); + }); + it("gives the archive's site its owner's look, which can be changed", async () => { const source = await connect(); cloud.authorised = true; let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); - expect(res.json()).toMatchObject({ look: "fpa" }); + expect(res.json()).toMatchObject({ look: "fpa", photoFindEnabled: true }); expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ look: "fpa", name: "Cloud FPA" }); res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "liga" } }); expect(res.json()).toMatchObject({ look: "liga" }); diff --git a/apps/api/test/helpers.ts b/apps/api/test/helpers.ts index 875ec43..de8a4eb 100644 --- a/apps/api/test/helpers.ts +++ b/apps/api/test/helpers.ts @@ -3,6 +3,7 @@ import { hashPassword } from "../src/auth/passwords.js"; import { buildApp } from "../src/app.js"; import { loadConfig, type Config } from "../src/config.js"; import { createDb, type Db } from "../src/db.js"; +import type { FaceEngine } from "../src/faces/process.js"; import type { Role } from "../src/generated/prisma/client.js"; import type { Broadcaster } from "../src/realtime.js"; import { assertTestDatabase } from "./guard.js"; @@ -13,7 +14,13 @@ export interface TestContext { config: Config; } -export async function createTestApp(overrides: Record = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise { +export async function createTestApp( + overrides: Record = {}, + realtime?: Broadcaster, + fetchImpl?: typeof fetch, + engineOnline?: () => boolean, + faceEngine?: FaceEngine, +): Promise { const config = loadConfig({ NODE_ENV: "test", DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST), @@ -23,7 +30,14 @@ export async function createTestApp(overrides: Record = {}, real ...overrides, }); const db = createDb(config.DATABASE_URL); - const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }), ...(engineOnline && { engineOnline }) }); + const app = await buildApp({ + config, + db, + ...(realtime && { realtime }), + ...(fetchImpl && { fetchImpl }), + ...(engineOnline && { engineOnline }), + ...(faceEngine && { faceEngine }), + }); return { app, db, config }; } diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 34253e8..f13d6f8 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -631,6 +631,8 @@ export const t = { pause: "Pausar", look: "Aspeto do site", looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record, + photoFind: "Procura por foto", + photoFindHelp: "Quem edita pastas na cloud (como a Federação) pode carregar uma foto e procurar essa cara no arquivo. A foto de pesquisa não fica guardada. Requer reconhecimento de caras ligado.", hostname: "Endereço próprio", hostnamePlaceholder: "arquivo.ligaportugal.pt", hostnameHelp: "Opcional. Aponta esse endereço (DNS, CNAME) para o mesmo servidor do arquivo: o arquivo abre na raiz e o certificado é pedido sozinho.", diff --git a/apps/app/src/pages/ArchivePage.tsx b/apps/app/src/pages/ArchivePage.tsx index 1da41dc..dfcccd8 100644 --- a/apps/app/src/pages/ArchivePage.tsx +++ b/apps/app/src/pages/ArchivePage.tsx @@ -223,6 +223,18 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove )} + {isAdmin && ( + + )} {isAdmin && (
= { @@ -82,7 +83,9 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } ? `${base}/g/${v.id}` : v.kind === "person" ? `${base}/p/${v.id}` - : `${base}/f/${v.id}`; + : v.kind === "find" + ? `${home}?t=procurar` + : `${base}/f/${v.id}`; router.push(href); window.scrollTo({ top: 0 }); }, @@ -100,7 +103,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } [view.kind, go, home], ); - const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : "galleries"; + const current: Tab | null = view.kind === "browse" ? tab : view.kind === "person" || view.kind === "face" ? "people" : view.kind === "find" ? null : "galleries"; const brand = ( (e.preventDefault(), openTab("galleries"))}> @@ -161,12 +164,43 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View } {t === "review" && !!me?.pending && {me.pending}} ))} + {me?.canFind && ( + + )}
- {view.kind === "gallery" ? ( + {view.kind === "find" && me?.canFind && token ? ( + go({ kind: "browse" })} + onExpired={expired} + onPerson={(id) => go({ kind: "person", id })} + onGallery={(id) => go({ kind: "gallery", id })} + onFace={(id) => go({ kind: "face", id })} + /> + ) : view.kind === "find" ? ( +
+
+ +

+ Só para quem pode editar +

+

+ A procura por foto é para quem tem permissão de edição nas pastas destas fotos. +

+ +
+
+ ) : view.kind === "gallery" ? ( go({ kind: "browse" })} onExpired={expired} onFace={(id) => go({ kind: "face", id })} onPerson={(id) => go({ kind: "person", id })} onReview={(id) => go({ kind: "browse", tab: "review", gallery: id })} /> ) : view.kind === "person" || view.kind === "face" ? ( void; + onExpired: () => void; + onPerson: (id: string) => void; + onGallery: (id: string) => void; + onFace: (id: string) => void; +}) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [file, setFile] = useState(null); + const [result, setResult] = useState(null); + const [only, setOnly] = useState(null); + const [index, setIndex] = useState(null); + + const search = async (next: File, face = 0) => { + setBusy(true); + setError(null); + setFile(next); + setOnly(null); + setIndex(null); + const form = new FormData(); + form.append("file", next, "foto.jpg"); + try { + const res = await fetch(`/v1/archive/${sourceId}/find${face ? `?face=${face}` : ""}`, { + method: "POST", + body: form, + headers: { authorization: `Archive ${token}` }, + }); + const body = (await res.json().catch(() => ({}))) as FindByPhotoResult & { error?: string }; + if (!res.ok) { + if (res.status === 401) { + onExpired(); + return; + } + if (res.status === 403) throw new Forbidden(); + const msg: Record = { + no_face: "Não encontrámos nenhuma cara nessa foto. Experimenta uma com a cara de frente e bem iluminada.", + not_an_image: "Esse ficheiro não é uma foto.", + find_unavailable: "A procura por foto não está disponível neste arquivo.", + archive_edit_required: "Só quem edita pastas na cloud pode usar esta procura.", + engine_unavailable: "O reconhecimento de caras não está disponível de momento. Tenta daqui a pouco.", + rate_limited: "Muitas pesquisas seguidas. Tenta daqui a um minuto.", + }; + setError(msg[body.error ?? ""] ?? "Não foi possível pesquisar agora."); + setResult(null); + return; + } + setResult(body); + } catch (err) { + if (err instanceof Unauthorised) onExpired(); + else if (err instanceof Forbidden) setError("Só quem edita pastas na cloud pode usar esta procura."); + else setError("Não foi possível pesquisar agora."); + setResult(null); + } finally { + setBusy(false); + } + }; + + const counts = useMemo(() => { + const c: Record = { confirmed: 0, probable: 0, similar: 0 }; + for (const p of result?.photos ?? []) if (p.level) c[p.level]++; + return c; + }, [result]); + + const photos = useMemo(() => (result ? (only ? result.photos.filter((p) => p.level === only) : result.photos) : []), [result, only]); + const person = result?.people[0] ?? null; + + const rememberFaces = (photoId: string, faces: PhotoFace[] | undefined) => { + setResult((cur) => (cur ? { ...cur, photos: cur.photos.map((p) => (p.id === photoId ? { ...p, faces } : p)) } : cur)); + }; + + return ( +
+ + +
+ Procura por foto +

+ Encontrar fotos de uma pessoa +

+

+ Carrega uma fotografia com a cara bem visível (retrato, recorte de imprensa). Mostramos as fotos do arquivo em que essa pessoa aparece. A foto só serve para esta pesquisa: não fica guardada. +

+
+ + {result && result.faces.length > 1 && file && ( + + )} +
+ {error && ( +

+ {error} +

+ )} +
+ + {result && ( + <> +
+ {person && ( +

+ Mais parecido:{" "} + + {person.club ? ` · ${person.club}` : ""} + {person.number ? ` · #${person.number}` : ""} +

+ )} +
+ + {result.total} + fotos + + {(Object.keys(LEVEL) as Level[]).map((l) => + counts[l] ? ( + + {counts[l]} + {LEVEL[l]} + + ) : null, + )} +
+
+ + {result.total > 0 && ( +
+ + {(Object.keys(LEVEL) as Level[]) + .filter((l) => counts[l] > 0) + .map((l) => ( + + ))} +
+ )} + + {!result.total ? ( +
Não encontrámos fotos desta cara nas pastas que podes ver.
+ ) : ( +
+ {photos.map((p, i) => ( + + ))} +
+ )} + + )} + + {index !== null && photos[index] && ( + undefined } : undefined} + onDownload={(photoId) => void download(sourceId, token, { photoIds: [photoId] }).catch((err) => (err instanceof Unauthorised ? onExpired() : undefined))} + extra={(p) => + p.gallery ? ( + <> + Galeria + + + + + ) : null + } + /> + )} +
+ ); +} diff --git a/apps/site/src/app/arquivo/[id]/api.ts b/apps/site/src/app/arquivo/[id]/api.ts index 05153b7..c5c20b3 100644 --- a/apps/site/src/app/arquivo/[id]/api.ts +++ b/apps/site/src/app/arquivo/[id]/api.ts @@ -208,10 +208,21 @@ export interface Me { canReview: boolean; /** They edit the whole archive: they may act on a person as a whole. */ canManagePeople: boolean; + /** Search by photo (option on + edit rights + biometrics). */ + canFind: boolean; /** Suggestions waiting in their folders. */ pending: number; } +/** Result of searching the archive by a photo of a person. */ +export interface FindByPhotoResult { + faces: { box: Box; clear: boolean }[]; + used: number; + people: { id: string; name: string; club: string | null; number: string | null; score: number; level: string }[]; + total: number; + photos: ArchivePhoto[]; +} + export type ReviewStatus = "suggested" | "unnamed" | "confirmed" | "rejected" | "ignored"; export interface ReviewPerson { diff --git a/apps/site/src/app/arquivo/[id]/page.tsx b/apps/site/src/app/arquivo/[id]/page.tsx index 9938b36..6b4448b 100644 --- a/apps/site/src/app/arquivo/[id]/page.tsx +++ b/apps/site/src/app/arquivo/[id]/page.tsx @@ -17,6 +17,7 @@ export async function generateMetadata({ params }: Params): Promise { */ export default async function ArchivePage({ params, searchParams }: Params) { const { t, p, g } = await searchParams; + if (t === "procurar") return ; const tab = t === "pessoas" ? "people" : t === "equipas" ? "teams" : t === "rever" ? "review" : "galleries"; const uuid = (x?: string) => (x && /^[0-9a-f-]{36}$/i.test(x) ? x : undefined); const person = uuid(p); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a2b7afe..5ad3860 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -521,8 +521,10 @@ run on the `next` containers (the phase gate). numbers with squads, global search (parity with old projects validated), search by photo (done: in the library, a photo's face against every event's face groups and the named people, `POST /v1/orgs/:orgId/faces/lookup`; on the sites, "Encontra-te" finds a visitor's face in one gallery, `POST - /v1/public/galleries/:slug/find`). Only with biometrics on; the search photo is read in memory and never kept. - The API runs its own face engine for this, started on the first search and stopped after 10 idle minutes. + /v1/public/galleries/:slug/find`; in the archive, editors on the cloud with the option on search the whole + archive they can see, `POST /v1/archive/:source/find`). Only with biometrics on; the search photo is read in + memory and never kept. The API runs its own face engine for this, started on the first search and stopped + after 10 idle minutes. 6. Cutover: final import, redirects, old projects read-only, then switched off. ## Deploy diff --git a/docs/archive.md b/docs/archive.md index 9620ffe..817cdf8 100644 --- a/docs/archive.md +++ b/docs/archive.md @@ -232,6 +232,13 @@ Each archive photo keeps about 1.6 MB on the server (the 2048 px preview with it the thumbnail). The Arquivo page shows the disk's free space and what the photos still to index will take; the worker stops indexing while less than `ARCHIVE_MIN_FREE_GB` (default 25) is free and resumes by itself. +### Search by photo (editors on the cloud) + +When `cloud_sources.photo_find_enabled` is on (default off; on for FPA) and the organization has biometrics on, +viewers with edit rights on at least one folder see "Procurar por foto": they upload a portrait (read in memory, +never kept) and the archive returns matching photos in the folders they may see (`POST /v1/archive/:source/find`). +Same gate as face review — Federação, Ana Teixeira, etc., not read-only viewers and not the public "Encontra-te". + ### Face review (viewers who edit on the cloud) Rights come from the cloud, never from PhotoReport: a share's `permissions` with update (2) or create (4) makes its diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts index 339b12f..608f2a4 100644 --- a/packages/sdk/src/client.ts +++ b/packages/sdk/src/client.ts @@ -835,7 +835,10 @@ export class ApiClient { return this.request("POST", `/v1/cloud-sources/${sourceId}/login`); } - updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null; hostname?: string | null }) { + updateCloudSource( + sourceId: string, + input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null; hostname?: string | null; photoFindEnabled?: boolean }, + ) { return this.request("PATCH", `/v1/cloud-sources/${sourceId}`, input); } diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts index 8e9c42e..569ed88 100644 --- a/packages/sdk/src/types.ts +++ b/packages/sdk/src/types.ts @@ -462,6 +462,8 @@ export interface CloudSource { rootPath: string; /** How the archive's site looks: Liga Portugal's or FPA's colours and type, or PhotoReport's (null). */ look?: "liga" | "fpa" | null; + /** Editors on the cloud may search the archive by uploading a photo of a person. */ + photoFindEnabled?: boolean; /** The archive's own address ("arquivo.ligaportugal.pt"): the site serves it at the root there. */ hostname?: string | null; /** The cloud account (once authorised). */ -- 2.47.3