Compare commits

...
Author SHA1 Message Date
paula-alves c652715707 fix(desktop): don't 500 the installer download when Gitea releases is unreachable (BIT-31961)
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 8m1s
GET /v1/desktop/download/:releaseId/:name called DesktopReleases.file()
with no try/catch, unlike the sibling update-check route. A transient
network failure fetching the release/asset from Gitea threw a bare
undici TypeError (no file/line in its stack, since it originates
inside undici) straight through the route handler, landing on the
error hub as an unlocatable "TypeError: fetch failed" and a 500 to the
desktop app instead of a graceful retry signal.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31961
Paperclip-Run: 431a287c-0cb3-4f73-9288-ac8d20e18df8
2026-11-01 00:24:18 +00:00
spark b1561da69a Merge pull request 'fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)' (#132) from task/BIT-31700-vips-sos-corrupt-source into main
ci / rust (push) Successful in 3m49s
ci / typescript (push) Successful in 7m8s
2026-10-29 11:12:25 +00:00
jos-alves b540ab447b fix(archive): classify libvips sequential-JPEG SOS errors as corrupt source (BIT-31700)
ci / rust (pull_request) Successful in 3m51s
ci / typescript (pull_request) Successful in 7m31s
VipsJpeg: Invalid SOS parameters for sequential JPEG is another shape of the
same truncated/corrupted cloud-archive JPEG that premature end and corrupt
header already cover; isCorruptSourceMessage didn't match it, so it fell
through to the generic failure path and reached the error hub as a warning
instead of being marked corrupt_source at info level.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31700
Paperclip-Run: 6435a4c4-0daa-41c4-8641-a0431c981ee8
2026-10-29 11:03:19 +00:00
spark 0b7af4f992 Merge pull request 'fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)' (#131) from fix/BIT-31898-fpa-associate-name-collision into main
ci / rust (push) Successful in 4m50s
ci / typescript (push) Successful in 8m50s
2026-10-28 02:02:58 +00:00
paula-alves 018cefaf7a fix(sports): tell FPA homonyms apart by licence instead of a 409 (BIT-31898)
ci / rust (pull_request) Successful in 4m3s
ci / typescript (pull_request) Successful in 7m58s
Two different people can share the exact same full name in the FPA
register; personFromFpaAssociate (full club register sync) and
personFromFpaLicence (add-by-licence) both threw person_name_taken in
that case, which fpaAssociates only logged and swallowed, but which
silently dropped that associate from the sync. The federation's
licence number is always free for this, so suffix it onto the name
instead of giving up.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31898
Paperclip-Run: aa809c11-1594-449d-bc49-93e96efbe4e5
2026-10-28 01:49:30 +00:00
spark f847cbff56 Site: câmara in-page para Tirar foto (iPhone) (#130)
ci / rust (push) Successful in 3m47s
ci / typescript (push) Successful in 7m27s
Site: câmara in-page para Tirar foto (iPhone) (#130)
2026-10-28 01:21:27 +00:00
spark 1b1dadda6c Site: open the front camera in-page for Tirar foto
ci / rust (pull_request) Successful in 5m30s
ci / typescript (pull_request) Successful in 8m27s
iPhone file+capture often returns HEIC or fails the hidden input.
Use getUserMedia like the kiosk so the probe is always JPEG.
2026-10-28 01:10:29 +00:00
spark 1dbd4156df Merge pull request 'Arquivo: procura pela ficha FPA (registo do clube) e câmara no telemóvel' (#129) from task/126-find-registry-first into main
ci / rust (push) Successful in 5m2s
ci / typescript (push) Successful in 9m34s
2026-10-28 01:02:24 +00:00
spark c5e90e6d89 Expect club-register people in the FPA squad sync test.
ci / rust (pull_request) Successful in 5m10s
ci / typescript (pull_request) Successful in 8m31s
2026-10-28 00:49:22 +00:00
spark 9d0b19d1f0 Reset FPA retry clocks between sports tests after a DB wipe.
ci / rust (pull_request) Successful in 5m0s
ci / typescript (pull_request) Failing after 7m24s
2026-10-28 00:32:31 +00:00
spark faaa3406d2 Arquivo: procura pela ficha FPA (registo do clube) e câmara no telemóvel
ci / rust (pull_request) Successful in 3m52s
ci / typescript (pull_request) Failing after 7m11s
Match the probe to FPA licence photos from getCipClubeEpoca first, then
load that person's archive photos — not only people named on match sheets.
On phones, open the front camera and convert HEIC to JPEG before upload so
"Tirar foto" works on iPhone.
2026-10-28 00:22:51 +00:00
spark 697676de56 Arquivo: acelerar procura por foto (HNSW + cache) (#128)
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 7m31s
Speed up archive find with pgvector HNSW and short event-id caches.
2026-10-27 23:04:37 +00:00
spark 7edac9dae1 Do not cache the archive find toggle; keep only the event-id cache.
ci / rust (pull_request) Successful in 3m54s
ci / typescript (pull_request) Successful in 7m14s
The enabled flag must take effect immediately when an admin turns it off.
2026-10-27 22:56:58 +00:00
spark 602c64ca0d Speed up archive search-by-photo with HNSW and short caches.
ci / rust (pull_request) Successful in 3m49s
ci / typescript (pull_request) Failing after 6m53s
Rank face groups via pgvector instead of a full cosine scan, cache the
viewer's event ids and source settings, and warm the face engine when an
editor opens the archive so the first upload is not cold.
2026-10-27 22:48:59 +00:00
spark a8e5d97954 Arquivo: procura por foto (editores cloud / FPA) (#127)
ci / rust (push) Successful in 3m55s
ci / typescript (push) Successful in 7m16s
Arquivo: procura por foto para editores cloud (FPA).

Closes #126
2026-10-27 21:29:01 +00:00
spark ea669672d4 Add archive search-by-photo for cloud editors (FPA news desk).
ci / rust (pull_request) Successful in 3m45s
ci / typescript (pull_request) Successful in 7m17s
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.
2026-10-27 21:17:42 +00:00
spark ece55190c3 Merge pull request 'Arquivo: abrir torneio no próprio sítio e adicionar pessoas pela licença FPA' (#123) from task/archive-licence into main
ci / rust (push) Successful in 3m58s
ci / typescript (push) Successful in 7m58s
2026-10-27 18:33:01 +00:00
paula-alves 824ca7ae49 Merge main into task/archive-licence: resolve viewer.ts, sports/service.ts, Browse.tsx
ci / rust (pull_request) Successful in 5m28s
ci / typescript (pull_request) Successful in 8m46s
Bring the archive-licence branch up to date with main (videos, stored directory, EHF provider, squad linking) while keeping the PR delta: the FPA-licence person flow (sports.service.personFromFpaLicence + fpaLatestRole/fpaClubName), the sports dep wired through the archive viewer and review routes, and the site LicenceAdd UI.

Conflicts resolved keeping main behaviour and adding only the PR delta:
- apps/api/src/archive/viewer.ts: keep main video/directory rewrite; add SportsService dep and pass sports to registerArchiveReviewRoutes.
- apps/api/src/sports/service.ts: keep main EHF/squads/identity changes; add AppError import, FpaMember/FpaRegistration/fpaShortName imports, licence match in linkSquadPerson, personFromFpaLicence, fpaLatestRole, fpaClubName.
- apps/site/src/app/arquivo/[id]/Browse.tsx: keep main eventLayout/teamGroups/peopleSeason; add addFromLicence + FpaCard import, fpa prop, openGroup reset on filter change, LicenceAdd component.
- apps/api/src/archive/review.ts: rename FPA member cache to memberCache to avoid shadowing main SQL members() helper.

Paperclip-Issue: BIT-31882
Paperclip-Run: d2cbc1f6-e181-4c2e-a3ce-7ca8e15b2279
2026-10-27 18:00:10 +00:00
spark 21e33ba0c6 Keep folder edits local and upload originals without waiting on detection
ci / rust (push) Successful in 4m42s
ci / typescript (push) Successful in 7m53s
The contact sheet writes the JPEG and XMP beside the file. Merged DNGs pin D50. Local FTP uploads four originals at once.
2026-10-25 13:54:49 +00:00
sparkandClaude Opus 5.5 9d79270859 Archive: open a tournament in place, and add people by their FPA licence.
ci / rust (pull_request) Successful in 2m46s
ci / typescript (pull_request) Successful in 11m38s
- A tournament's tile opens its galleries in place of the tiles (they opened below the whole list, out of sight).
- The FPA licence (CIPA) is not the id the federation keeps registrations under: the portal page gives that id,
  then every registration (season, role, club) is read. A person can be added by licence number from Pessoas or
  while naming a face in the review ("198159" offers the federation's person); the licence photo becomes the
  reference, so coaches, delegates and staff are recognised in event photos no match report covers.
- people.licence: the same licence is always the same person, also when a match report names them later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-19 10:55:15 +00:00
35 changed files with 1910 additions and 76 deletions

No files matched your search

@@ -0,0 +1,3 @@
-- Handball: a person's federation licence number (CIPA).
ALTER TABLE "people" ADD COLUMN "licence" TEXT;
CREATE UNIQUE INDEX "people_organization_id_licence_key" ON "people"("organization_id", "licence");
@@ -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';
+5
View File
@@ -659,6 +659,8 @@ model Person {
referenceEmbedding Float[] @default([]) @map("reference_embedding")
/// The squad entry this person came from (kept in step when squads change).
sportsPlayerId String? @map("sports_player_id") @db.Uuid
/// Handball: the federation licence number (CIPA), when the person was added by it or seen on a match report.
licence String?
/// Face recognition turned off for this person (an archive editor): no centroid, no reference, never suggested;
/// still named by hand.
recognitionOffAt DateTime? @map("recognition_off_at")
@@ -673,6 +675,7 @@ model Person {
@@unique([organizationId, name])
@@unique([organizationId, sportsPlayerId])
@@unique([organizationId, licence])
@@map("people")
}
@@ -1631,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).
+23 -11
View File
@@ -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 });
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<JerseyReader | null> | null = null;
const jerseyOf = (): Promise<JerseyReader | null> => {
if (jersey !== undefined) return Promise.resolve(jersey);
@@ -26,6 +26,7 @@ describe("corrupt / incomplete archive sources (BIT-31621)", () => {
expect(isCorruptSourceMessage("premature end of JPEG")).toBe(true);
expect(isCorruptSourceMessage("Input file contains unsupported image format")).toBe(true);
expect(isCorruptSourceMessage("VipsForeignLoad: \"/tmp/x/original.jpg\" is not a known file format")).toBe(true);
expect(isCorruptSourceMessage("VipsJpeg: Invalid SOS parameters for sequential JPEG")).toBe(true);
expect(isCorruptSourceMessage("ffmpeg exited 234: Stream map '0:v:0' matches no streams")).toBe(false);
expect(isCorruptSourceMessage("GET /a failed: 503")).toBe(false);
});
+1 -1
View File
@@ -24,7 +24,7 @@ export class IncompleteDownload extends Error {
/** ffprobe/ffmpeg/sharp messages that mean the cloud file itself is damaged, not our pipeline. */
export function isCorruptSourceMessage(message: string): boolean {
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input/i.test(
return /moov atom not found|premature end|not a known file format|corrupt (?:jpeg )?header|Corrupt JPEG|Input file has corrupt header|Input file contains unsupported image format|unsupported image format|Invalid data found when processing input|Invalid SOS parameters/i.test(
message,
);
}
+321
View File
@@ -0,0 +1,321 @@
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 } from "../faces/lookup.js";
import { cosine, POSSIBLE_BELOW, THRESHOLDS } from "../faces/math.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.
*
* Registry first: the probe is compared to registered people (FPA licence / Liga headshot centroids). A clear
* match loads that person's archive photos by person_id — no blind scan of every face group. Only when nobody
* in the registry is sure enough do we fall back to HNSW over the viewer's face groups.
*/
interface Deps {
db: Db;
signer: UrlSigner;
lookup: FaceLookup;
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
visibleFolders: (v: Viewer) => Promise<string[] | "all">;
editableFolders: (v: Viewer) => Promise<string[] | "all">;
}
const SourceParams = z.object({ sourceId: z.uuid() });
const EVENTS_TTL_MS = 5 * 60_000;
const NEAREST = 400;
const MAX_PHOTOS = 500;
/** How many registry candidates to keep for the editor (strong + possible). */
const PEOPLE_LIMIT = 8;
type CardLevel = "confirmed" | "probable" | "similar";
type Via = "registry" | "faces";
const levelOf = (score: number, match: number): CardLevel => (score >= match ? "probable" : "similar");
export async function registerArchiveFindRoutes(app: FastifyInstance, deps: Deps) {
const { db, signer, lookup, viewerOf, visibleFolders, editableFolders } = deps;
/** Event ids of a viewer's archive scope: the heavy DISTINCT over cloud_files, reused while they search. */
const eventsCache = new Map<string, { at: number; ids: string[] }>();
const scopeOf = async (v: Viewer): Promise<{ sql: Prisma.Sql; key: string } | null> => {
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.length) return null;
const key = visible === "all" ? "all" : [...visible].sort().join(",");
const sql =
visible === "all"
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
: 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}`;
return { sql, key };
};
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;
};
const eventsInScope = async (sourceId: string, scope: Prisma.Sql, cacheKey: string): Promise<string[]> => {
const key = `${sourceId}:${cacheKey}`;
const hit = eventsCache.get(key);
if (hit && Date.now() - hit.at < EVENTS_TTL_MS) return hit.ids;
const rows = 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 ids = rows.map((r) => r.event_id);
eventsCache.set(key, { at: Date.now(), ids });
return ids;
};
/**
* Face groups in the viewer's events like the probe. Production (512-d) uses the HNSW index; shorter test
* vectors fall back to a cosine over the float array. Used only when the registry has no sure person.
*/
const nearGroups = async (eventIds: string[], embedding: number[], model: string) => {
if (!eventIds.length) return [] as { id: string; personId: string | null; score: number }[];
const match = (THRESHOLDS[model] ?? { match: 0.5 }).match;
const floor = match - POSSIBLE_BELOW;
if (embedding.length === 512) {
const literal = `[${embedding.map((n) => (Number.isFinite(n) ? n : 0)).join(",")}]`;
const rows = await db.$queryRaw<{ id: string; person_id: string | null; score: number }[]>`
SELECT id, person_id, score FROM (
SELECT g.id, g.person_id, (1 - (g.centroid_vec <=> ${literal}::vector))::float AS score
FROM face_groups g
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.centroid_vec IS NOT NULL AND g.size > 0
AND g.event_id = ANY(${eventIds}::uuid[])
ORDER BY g.centroid_vec <=> ${literal}::vector
LIMIT ${NEAREST}
) ranked
WHERE score >= ${floor}`;
return rows.map((r) => ({ id: r.id, personId: r.person_id, score: Number(r.score) }));
}
const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>`
SELECT g.id, g.centroid, g.person_id
FROM face_groups g
WHERE g.ignored_at IS NULL AND g.model = ${model} AND g.size > 0 AND cardinality(g.centroid) > 0
AND g.event_id = ANY(${eventIds}::uuid[])`;
const asVector = (v: unknown): number[] =>
Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : [];
return groups
.map((g) => ({ id: g.id, personId: g.person_id, score: cosine(embedding, asVector(g.centroid)) }))
.filter((x) => x.score >= floor)
.sort((a, b) => b.score - a.score)
.slice(0, NEAREST);
};
/** Licence / headshot / federation label for the people the registry returned. */
const enrichPeople = async (ids: string[]) => {
if (!ids.length) return new Map<string, { licence: string | null; reference: string | null; registry: "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null }>();
const rows = await db.$queryRaw<{ id: string; licence: string | null; reference: boolean; provider: string | null }[]>`
SELECT p.id, p.licence, p.reference_key IS NOT NULL AS reference, t.provider
FROM people p
LEFT JOIN sports_players sp ON sp.id = p.sports_player_id
LEFT JOIN sports_teams t ON t.id = sp.team_id
WHERE p.id = ANY(${ids}::uuid[])`;
const asRegistry = (provider: string | null, licence: string | null): "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null => {
if (licence || provider === "FPA") return "fpa";
if (provider === "LIGA" || provider === "LPFP") return "liga";
if (provider === "UEFA") return "uefa";
if (provider === "EHF") return "ehf";
if (provider === "FPF") return "fpf";
return null;
};
return new Map(
rows.map((r) => [
r.id,
{
licence: r.licence,
reference: r.reference ? signer.personUrl(r.id) : null,
registry: asRegistry(r.provider, r.licence),
},
]),
);
};
const photoCards = async (
shown: { photoId: string; faceId: string; score: number; level: CardLevel; sharpness: number | null }[],
scope: Prisma.Sql,
) => {
if (!shown.length) return [];
const ids = shown.map((h) => h.photoId);
const faceIds = shown.map((h) => h.faceId);
const [links, photos, faceRows] = await Promise.all([
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`,
db.photo.findMany({
where: { id: { in: ids } },
select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true },
}),
db.face.findMany({ where: { id: { in: faceIds } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } }),
]);
const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id]));
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 byId = new Map(photos.map((p) => [p.id, p]));
const faceById = new Map(faceRows.map((f) => [f.id, f]));
return 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,
};
});
};
/** Starts the face engine so the first real search does not wait on model load. */
app.get("/v1/archive/:sourceId/find/ready", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
await requireFind(v);
return { ready: lookup.available };
});
/**
* A photo of the person against the registry, then their archive photos (or a blind face-group search when
* nobody in the registry is sure). 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 scoped = await scopeOf(v);
if (!scoped) return { faces: [], used: 0, via: "faces" as Via, identity: null, people: [], total: 0, photos: [] };
const { sql: scope, key: scopeKey } = scoped;
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 match = (THRESHOLDS[read.model] ?? { match: 0.5 }).match;
// 1) Registry first: FPA / Liga / UEFA people with a face on file (smaller set than every photo).
const matched = await lookup.people(source.organizationId, probe.embedding, read.model, PEOPLE_LIMIT);
const extra = await enrichPeople(matched.map((p) => p.id));
const people = matched.map((p) => {
const e = extra.get(p.id);
return {
id: p.id,
name: p.name,
club: p.club,
number: p.number,
score: p.score,
level: p.level,
licence: e?.licence ?? null,
reference: e?.reference ?? null,
registry: e?.registry ?? null,
};
});
const sure = people.filter((p) => p.level === "strong");
const best = new Map<string, { faceId: string; score: number; level: CardLevel; sharpness: number | null }>();
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 });
};
let via: Via = "faces";
if (sure.length) {
// 2a) Known person: archive photos already named (or suggested) as them — no blind group scan.
via = "registry";
const sureIds = sure.map((p) => p.id);
const scoreOf = new Map(sure.map((p) => [p.id, p.score]));
const named = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggested_person_id: string | null }[]>`
SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggested_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(${sureIds}::uuid[]) OR g.suggested_person_id = ANY(${sureIds}::uuid[]))`;
for (const f of named) {
const personId = f.person_id ?? f.suggested_person_id!;
const score = scoreOf.get(personId) ?? sure[0]!.score;
keep(f.photo_id, f.id, score, f.person_id ? "confirmed" : "probable", f.sharpness);
}
} else {
// 2b) Nobody sure in the registry: fall back to face groups in the viewer's galleries.
const eventIds = await eventsInScope(sourceId, scope, scopeKey);
if (!eventIds.length) {
return { faces: facesOut(read.faces), used, via, identity: null, people, total: 0, photos: [] };
}
const groups = await nearGroups(eventIds, probe.embedding, read.model);
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.id)}::uuid[])`;
const byGroup = new Map(groups.map((g) => [g.id, g]));
for (const f of faces) {
const g = byGroup.get(f.group_id)!;
const level: CardLevel = g.personId && g.score >= match ? "confirmed" : levelOf(g.score, match);
keep(f.photo_id, f.id, g.score, level, 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, MAX_PHOTOS);
const top = sure[0] ?? null;
const identity = top
? {
id: top.id,
name: top.name,
club: top.club,
number: top.number,
licence: top.licence,
reference: top.reference,
registry: top.registry,
score: top.score,
}
: null;
return {
faces: facesOut(read.faces),
used,
via,
identity,
people,
total: hits.length,
photos: await photoCards(shown, scope),
};
});
}
+80 -7
View File
@@ -6,6 +6,8 @@ import type { Db } from "../db.js";
import { FaceRejected, type FaceService } from "../faces/service.js";
import { AppError, forbidden, notFound } from "../lib/errors.js";
import type { UrlSigner } from "../storage/storage.js";
import { fpaLatestRole, type SportsService } from "../sports/service.js";
import type { FpaMember } from "../sports/providers.js";
import { galleryMemberIds } from "./gallery.js";
import { clubKey, faceBox } from "./people.js";
import type { Viewer } from "./viewer.js";
@@ -27,6 +29,8 @@ interface Deps {
faces: FaceService;
viewerOf: (req: FastifyRequest, sourceId?: string) => Viewer;
editableFolders: (v: Viewer) => Promise<string[] | "all">;
/** Handball: people by their federation licence (CIPA), for FPA archives. */
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
/** After "Juntar nomes": lists built with the old names are dropped. */
onClubsChanged?: (sourceId: string) => void | Promise<void>;
}
@@ -46,6 +50,7 @@ const ReviewQuery = z.object({
const Act = z.object({ action: z.enum(["confirm", "reject", "ignore", "undo"]), personId: z.uuid().optional() });
const ChooseQuery = z.object({ q: z.string().trim().min(2).max(80) });
const Merge = z.object({ into: z.string().trim().min(1).max(120), names: z.array(z.string().trim().min(1).max(120)).min(1).max(20) });
const Licence = z.object({ licence: z.string().trim().regex(/^\d{3,9}$/) });
const Unmerge = z.object({ name: z.string().trim().min(1).max(120) });
const Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) });
@@ -77,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);
@@ -95,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 };
});
/**
@@ -107,11 +117,11 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
const v = viewerOf(req, sourceId);
const { q } = ChooseQuery.parse(req.query);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true } });
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source) throw notFound("source_not_found");
const like = `%${q.replace(/[\\%_]/g, "")}%`;
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean }[]>`
SELECT p.id, p.name,
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; licence: string | null }[]>`
SELECT p.id, p.name, p.licence,
COALESCE(p.club, t.name) AS club,
COALESCE(p.number, sp.number) AS number,
p.reference_key IS NOT NULL AS reference
@@ -127,14 +137,77 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
OR COALESCE(sp.full_name, '') ILIKE ${like}
OR p.number = ${q}
OR sp.number = ${q}
OR p.licence = ${q}
OR sp.external_id = ${q}
)
ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
ORDER BY (p.licence = ${q} OR sp.external_id = ${q}) DESC, (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
LIMIT 8`;
// A licence number nobody here has yet: who the federation says it is, to add them.
const fpa = fpaArchive(source) && /^\d{5,9}$/.test(q) && !rows.some((r) => r.licence === q) ? await memberOf(q) : null;
return {
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null })),
people: rows.map((r) => ({ id: r.id, name: r.name, club: r.club, number: r.number, reference: r.reference ? signer.personUrl(r.id) : null, ...(r.licence && { licence: r.licence }) })),
...(fpa && { fpa: memberOut(fpa) }),
};
});
/** Handball archives look people up by licence. Kept a while: typing a number asks once per number. */
const fpaArchive = (source: { look: string | null }) => !!deps.sports && source.look === "fpa";
const memberCache = new Map<string, { at: number; member: Promise<FpaMember | null> }>();
const memberOf = (licence: string): Promise<FpaMember | null> => {
const hit = memberCache.get(licence);
if (hit && Date.now() - hit.at < 30 * 60_000) return hit.member;
const member = deps.sports!.fpa.member(licence).catch(() => null);
memberCache.set(licence, { at: Date.now(), member });
if (memberCache.size > 500) for (const [k, m] of memberCache) if (Date.now() - m.at > 30 * 60_000) memberCache.delete(k);
return member;
};
const memberOut = (m: FpaMember) => {
const latest = fpaLatestRole(m);
return {
licence: m.licence,
name: m.name,
photo: m.photo,
club: latest?.club ?? null,
role: latest ? `${latest.role} · ${latest.season}` : m.registeredAs,
// Every season, newest first, as "2024/25 · Treinador · Estarreja AC" (no birth date: not needed here).
history: [...m.registrations]
.sort((a, b) => b.season.localeCompare(a.season))
.slice(0, 12)
.map((r) => [r.season, r.level ? `${r.role} ${r.level}` : r.role, r.club].filter(Boolean).join(" · ")),
};
};
/** Who a licence number is, for those who review (to add them before naming a face). */
app.get("/v1/archive/:sourceId/fpa/:licence", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const { licence } = Licence.parse(req.params);
const v = viewerOf(req, sourceId);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
const member = await memberOf(licence);
if (!member) throw notFound("fpa_member_not_found");
const person = await db.person.findFirst({ where: { organizationId: source.organizationId, licence }, select: { id: true, name: true } });
return { member: memberOut(member), person };
});
/**
* Adds (or brings up to date) a person from their licence: name, club, and the licence photo as the reference,
* so recognition finds them in event photos where no match report names them.
*/
app.post("/v1/archive/:sourceId/people/from-licence", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
if (!(await editScope(v))) throw forbidden("archive_edit_required");
const { licence } = Licence.parse(req.body);
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { organizationId: true, look: true } });
if (!source || !fpaArchive(source)) throw notFound("fpa_not_available");
const done = await deps.sports!.personFromFpaLicence(source.organizationId, licence);
memberCache.delete(licence);
await log(v, done.created ? "person_from_licence" : "person_licence_update", { personId: done.person.id });
return { person: { ...done.person, licence, reference: done.reference }, created: done.created, member: memberOut(done.member) };
});
/**
* Face groups to review in the viewer's editable folders, one card per group: its sharpest faces, who it is
* (named) or might be (suggested, with how sure), its event; and the people with suggestions waiting.
+4
View File
@@ -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 }),
},
});
+4 -1
View File
@@ -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),
+21 -1
View File
@@ -10,12 +10,15 @@ import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
import { GALLERY_KINDS, galleryMemberIds, gallerySeasons, listStoredGalleries, publishedPhotos, seasonOf } from "./gallery.js";
import type { SportsService } from "../sports/service.js";
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";
@@ -109,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 },
deps: {
db: Db;
secrets: SecretBox | undefined;
signer: UrlSigner;
archive: ArchiveService;
tokens: ViewerTokens;
faces: FaceService;
storage: LocalStorage;
secret: string;
fetchImpl?: typeof fetch | undefined;
sports?: Pick<SportsService, "fpa" | "personFromFpaLicence"> | undefined;
/** Search by photo for editors (absent → find route not registered). */
lookup?: FaceLookup;
},
) {
const { db, signer, tokens } = deps;
const fetchImpl = deps.fetchImpl ?? fetch;
@@ -730,12 +746,16 @@ export async function registerArchiveViewerRoutes(
faces: deps.faces,
viewerOf,
editableFolders,
sports: deps.sports,
onClubsChanged: async (sourceId) => {
forgetLists(sourceId, "teams");
await deps.archive.markDirectoryDirty(sourceId);
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 });
}
+7 -1
View File
@@ -165,7 +165,13 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
app.get("/v1/desktop/download/:releaseId/:name", async (req, reply) => {
const { releaseId, name } = z.object({ releaseId: z.coerce.number().int().positive(), name: z.string().min(1).max(200) }).parse(req.params);
const file = releases ? await releases.file(releaseId, name) : null;
let file: { body: Readable; size: string | null } | null;
try {
file = releases ? await releases.file(releaseId, name) : null;
} catch (err) {
req.log.warn({ err }, "desktop download failed");
return reply.code(503).send({ error: "download_unavailable" });
}
if (!file) return reply.code(404).send({ error: "not_found" });
if (file.size) reply.header("content-length", file.size);
return reply.header("content-type", "application/octet-stream").header("content-disposition", `attachment; filename="${name.replace(/[^\w.-]+/g, "_")}"`).send(file.body);
+1
View File
@@ -180,6 +180,7 @@ export class FaceLookup {
/ NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score
FROM people p
WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length}
AND p.recognition_off_at IS NULL
AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[]))
) s
WHERE score >= ${match - POSSIBLE_BELOW}
+147 -2
View File
@@ -344,8 +344,9 @@ const FPA_GAME_OFFICIAL: [RegExp, string][] = [
/**
* The FPA's public pages, the same the portal links to: the agenda (JSON), a club's games of a season and level
* (JSON), the match report ("Boletim do Jogo": every player with shirt number and licence number, the bench officials
* with their letter, the referees), a match page (the referees, published before the match) and an athlete's page
* (the licence photo). Asked for sparingly and cached in the database.
* with their letter, the referees), a match page (the referees, published before the match), a club's full register
* (`getCipClubeEpoca`: every associate with licence and photo) and an athlete's page (the licence photo). Asked for
* sparingly and cached in the database. Shared shape with ehf-stats / livereport (`WsFpa.clubAssociates`).
*/
export class FpaProvider {
static readonly AGENDA = "https://ws.fpa.pt/index.php/getAgendaJogosFAP/";
@@ -421,11 +422,155 @@ export class FpaProvider {
return parseFpaMatchPage(await this.html(`${FpaProvider.PORTAL}/jogo/${encodeURIComponent(gameId)}/`));
}
/**
* Someone registered with the federation, by licence number (CIPA, as printed on match reports and the portal):
* name, licence photo and every registration (season, as what, where). The portal's page gives the federation's
* internal id, which the registrations are kept under (it is not the licence number). Null when unknown.
*/
async member(licence: string): Promise<FpaMember | null> {
if (!/^\d{1,9}$/.test(licence)) return null;
const page = parseFpaMemberPage(await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(licence)}/`));
if (!page) return null;
let registrations: FpaRegistration[] = [];
if (page.internalId) {
const rows = await get(this.fetcher, `${FpaProvider.WS}/getCipaInscricoes/${encodeURIComponent(page.internalId)}`, { accept: "application/json" }, "json");
if (Array.isArray(rows)) registrations = (rows as Record<string, unknown>[]).map(fpaRegistration).filter((r): r is FpaRegistration => !!r);
}
return { ...page, licence, registrations };
}
/** An athlete's licence photo (by licence number), if the federation has one. */
async athletePhoto(cipa: string): Promise<string | null> {
const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`);
return /https:\/\/si\.fpa\.pt\/blob\/obj_anexo\/FOTO_CIPA\/\d+_\d+\.(?:jpe?g|png)/i.exec(html)?.[0] ?? null;
}
/**
* Everyone registered at a club for a season (athletes, coaches, officials, referees), with licence number and
* licence photo when the federation has one. This is the club register — not only the people named on a match
* sheet. Season ids are the portal's (`373` = 2025/26); see `fpaEpochFor`.
*/
async clubAssociates(clubId: string, seasonId: string): Promise<FpaClubAssociate[]> {
if (!/^\d+$/.test(clubId) || !/^\d+$/.test(seasonId)) return [];
const path = ["getCipClubeEpoca", clubId, seasonId].map(encodeURIComponent).join("/");
const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json");
await this.pause();
if (!Array.isArray(rows)) return [];
const out: FpaClubAssociate[] = [];
const seen = new Set<string>();
for (const raw of rows as Record<string, unknown>[]) {
const a = fpaClubAssociate(raw);
if (!a || seen.has(a.licence)) continue;
seen.add(a.licence);
out.push(a);
}
return out;
}
}
/** Someone on a club's FPA register for a season (from `getCipClubeEpoca`). */
export interface FpaClubAssociate {
licence: string;
/** Federation internal id (portal history); not the printed CIPA. */
internalId: string | null;
name: string;
photo: string | null;
kind: "athlete" | "coach" | "official" | "referee" | "other";
}
/** Handball seasons start in August; portal epoch ids advance one per year (2025/26 = 373). */
export function fpaEpochFor(date: Date = new Date()): string {
const year = date.getUTCFullYear();
const start = date.getUTCMonth() >= 7 ? year : year - 1;
return String(start - 1652);
}
function fpaClubAssociate(r: Record<string, unknown>): FpaClubAssociate | null {
const licence = String(r.CIP_NUMERO ?? "").trim().replace(/\.0+$/, "");
const name = cellText(String(r.CIP_NOME ?? ""));
if (!/^\d{1,9}$/.test(licence) || !name) return null;
const photo = str(r.URL_FOTO);
const kind: FpaClubAssociate["kind"] =
String(r.ATLETA ?? "").toUpperCase() === "S"
? "athlete"
: String(r.TECNICO ?? "").toUpperCase() === "S"
? "coach"
: String(r.OFICIAL ?? "").toUpperCase() === "S"
? "official"
: String(r.ARBITRO ?? "").toUpperCase() === "S"
? "referee"
: "other";
return {
licence,
internalId: str(r.ID_CIPA),
name,
photo: photo && /^https:\/\/si\.fpa\.pt\//i.test(photo) ? photo : null,
kind,
};
}
/** A registration of a member for one season: athlete, coach, official, table official or referee. */
export interface FpaRegistration {
season: string;
kind: "athlete" | "coach" | "official" | "table" | "referee" | "other";
/** "Atleta", "Treinador", "Delegado técnico", "Árbitro regional"... */
role: string;
/** The club or team ("AA AVANCA", "Sel.Nac.M"); null for referees. */
club: string | null;
clubName: string | null;
/** The age level for athletes ("Juvenis F"). */
level: string | null;
association: string | null;
}
export interface FpaMember {
licence: string;
internalId: string | null;
name: string;
photo: string | null;
/** "Árbitro, Oficial, Técnico, Atleta", as the portal says. */
registeredAs: string | null;
registrations: FpaRegistration[];
}
const FPA_KINDS: Record<string, FpaRegistration["kind"]> = { AT01: "athlete", TEC: "coach", OFI: "official", OMS: "table", ARB: "referee" };
function fpaRegistration(r: Record<string, unknown>): FpaRegistration | null {
const season = str(r.EPO_DESCRICAO);
if (!season) return null;
const code = str(r.GCI_TIP_INSCRICAO_TI013) ?? "";
const kind = FPA_KINDS[code] ?? (code.startsWith("AT") ? "athlete" : "other");
const detail = str(r.FOF_ABREV) ?? str(r.CJU_ABREV);
const role =
kind === "athlete" ? "Atleta" : kind === "coach" ? "Treinador" : kind === "table" ? "Oficial de mesa" : kind === "referee" ? (detail ?? "Árbitro") : (detail ? detail.charAt(0) + detail.slice(1).toLowerCase() : "Oficial");
return { season, kind, role: fpaAccents(role), club: str(r.CLU_ABREV), clubName: str(r.CLU_NOME), level: str(r.ESC_DESCRICAO), association: str(r.ASS_ABREV) };
}
/** The federation's codes are written without accents ("Delegado tecnico", "Funcionario"). */
function fpaAccents(s: string): string {
const fix: Record<string, string> = { tecnico: "técnico", tecnica: "técnica", funcionario: "funcionário", medico: "médico", fisioterapeuta: "fisioterapeuta", seccionista: "seccionista", estagiario: "estagiário", arb: "Árb" };
return s.replace(/\p{L}+/gu, (w) => {
const f = fix[w.toLowerCase()];
if (!f) return w;
return w[0] === w[0]!.toUpperCase() ? f[0]!.toUpperCase() + f.slice(1) : f;
});
}
/** A member's page on the portal: name, photo, the internal id its history is under. Null for an unknown licence. */
export function parseFpaMemberPage(html: string): Omit<FpaMember, "licence" | "registrations"> | null {
const $ = cheerio.load(html);
const box = $(".association-detail");
const name = box.find("h3").first().text().replace(/\s+/g, " ").trim();
if (!box.length || !name) return null;
let registeredAs: string | null = null;
box.find("tr").each((_, tr) => {
const cells = $(tr).children("td");
if (/inscrito como/i.test(cells.first().text())) registeredAs = cells.eq(1).text().replace(/\s+/g, " ").trim() || null;
});
const photo = box.find("img").attr("src") ?? null;
// The history table's settings carry the internal id ("cipa":"203445"); the photo's file name ends with it too.
const internalId = /TABLE_CONTENT_\d+\s*=\s*\{[^;]*?"cipa"\s*:\s*"(\d+)"/.exec(html)?.[1] ?? /FOTO_CIPA\/\d+_(\d+)\./i.exec(photo ?? "")?.[1] ?? null;
return { name, photo: photo && /^https:\/\/si\.fpa\.pt\//.test(photo) ? photo : null, registeredAs, internalId };
}
export interface FpaBoletim {
+183
View File
@@ -14,7 +14,12 @@ import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
import {
type Fetch,
type FixtureData,
type FpaClubAssociate,
type FpaMember,
FpaProvider,
type FpaRegistration,
fpaEpochFor,
fpaShortName,
FpfProvider,
LIGA_COMPETITIONS,
type LigaClubCompetition,
@@ -60,6 +65,13 @@ const FPA_REPORTS_PER_REFRESH = 30;
const FPA_RETRY_MS = 3 * 86400_000;
/** Reports read before licence numbers were kept, read again per refresh until none are left. */
const FPA_REREADS_PER_REFRESH = 40;
/**
* Clubs whose full FPA register (every associate with a licence photo) is pulled per refresh — not only the people
* on match sheets. Covers coaches, officials, youth and anyone else the federation lists for the club.
*/
const FPA_ASSOCIATE_CLUBS_PER_REFRESH = 12;
/** Skip a club's register again until this long has passed (the list changes slowly). */
const FPA_ASSOCIATE_RETRY_MS = 7 * 86400_000;
/** The handball referees and table officials, kept as one "team" so their licence (and photo) is known by name. */
const FPA_REFEREES_TEAM = { externalId: "ARBITRAGEM", name: REFEREES };
/** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */
@@ -505,6 +517,7 @@ export class SportsService {
}
await this.fpaSquads(fixtures, now, result);
await this.fpaReferees(now, result);
await this.fpaAssociates(fixtures, now, result);
if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: fpa refresh had errors");
log.info({ ...result, errors: result.errors.length }, "sports: fpa refreshed");
return result;
@@ -513,6 +526,15 @@ export class SportsService {
private readonly fpaTried = new Map<string, number>();
/** Reports read again for licence numbers (once each: some list none). */
private readonly fpaReread = new Set<string>();
/** Last time a club's full associate register was pulled. */
private readonly fpaAssociateAt = new Map<string, number>();
/** Clears in-memory FPA retry clocks (tests after a DB reset; production keeps them for the process). */
resetFpaClocks(): void {
this.fpaTried.clear();
this.fpaReread.clear();
this.fpaAssociateAt.clear();
}
private fpaCompetition(f: FixtureData): Promise<SportsCompetition> {
return this.deps.db.sportsCompetition.upsert({
@@ -1176,6 +1198,9 @@ export class SportsService {
const { db, log } = this.deps;
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
let created = false;
// Handball: someone added by their licence number is the same person on the match report.
if (!person && team.provider === "FPA" && p.externalId)
person = await db.person.findFirst({ where: { organizationId: orgId, licence: p.externalId, sportsPlayerId: null } });
if (!person) person = await this.personForIdentity(orgId, p);
if (!person) {
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
@@ -1219,6 +1244,147 @@ export class SportsService {
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
}
/**
* A person from their handball federation licence (CIPA): the name, club and role of their latest registration,
* and (with biometrics on) the licence photo as the reference, so they are recognised in event photos too (a
* coach, a delegate, a former player), not only where a match report names them. The same licence is always the
* same person: one already added, or seen on a match report, is brought up to date instead.
*/
async personFromFpaLicence(orgId: string, licence: string): Promise<{ person: { id: string; name: string; club: string | null }; member: FpaMember; created: boolean; reference: boolean }> {
const { db, log } = this.deps;
const member = await this.fpa.member(licence.trim());
if (!member) throw notFound("fpa_member_not_found");
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org) throw notFound("organization_not_found");
const latest = fpaLatestRole(member);
const club = latest?.club ?? null;
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: member.licence } } });
if (!person) {
// Seen on a match report: the squad entry with this licence.
const players = await db.sportsPlayer.findMany({ where: { externalId: member.licence, team: { provider: "FPA" } }, select: { id: true } });
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
}
let created = false;
if (!person) {
const short = fpaShortName(member.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : member.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== member.licence) {
name = `${member.name} (${member.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club, licence: member.licence } }));
created = !other;
}
if (person.licence !== member.licence || (!person.club && club)) {
person = await db.person.update({ where: { id: person.id }, data: { licence: member.licence, ...(!person.club && club && { club }) } });
}
let reference = false;
if (org.biometricsEnabled && member.photo && !person.referenceKey && !person.recognitionOffAt) {
try {
reference = await this.saveHeadshot(orgId, person.id, member.photo);
} catch (err) {
log.warn({ err, licence: member.licence }, "sports: fpa licence photo failed");
}
}
return { person: { id: person.id, name: person.name, club: person.club }, member, created, reference };
}
/**
* Full FPA club registers into people (every associate the federation lists for the club this season, with
* licence photo). Match sheets alone miss coaches, officials, youth and anyone not on a boletim — this closes
* that gap for face search. Clubs come from the agenda; a few per refresh, then again after a week.
*/
private async fpaAssociates(agenda: FixtureData[], now: Date, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
const clubIds = [...new Set(agenda.flatMap((f) => [f.home.clubId, f.away.clubId]).filter((id): id is string => !!id && /^\d+$/.test(id)))];
const due = clubIds.filter((id) => {
const at = this.fpaAssociateAt.get(id);
return !at || now.getTime() - at >= FPA_ASSOCIATE_RETRY_MS;
});
if (!due.length) return;
const orgs = await db.organization.findMany({ where: { biometricsEnabled: true }, select: { id: true } });
if (!orgs.length) return;
const epoch = fpaEpochFor(now);
let clubs = 0;
for (const clubId of due) {
if (clubs >= FPA_ASSOCIATE_CLUBS_PER_REFRESH) break;
clubs++;
this.fpaAssociateAt.set(clubId, now.getTime());
let associates: FpaClubAssociate[];
try {
associates = await this.fpa.clubAssociates(clubId, epoch);
} catch (err) {
result.errors.push(`fpa associates ${clubId}: ${(err as Error).message}`);
continue;
}
if (!associates.length) continue;
for (const org of orgs) {
for (const a of associates) {
try {
const done = await this.personFromFpaAssociate(org.id, a);
if (done.created) result.players++;
} catch (err) {
log.warn({ err, licence: a.licence, org: org.id }, "sports: fpa associate failed");
}
}
}
log.info({ clubId, associates: associates.length, orgs: orgs.length }, "sports: fpa club register");
}
}
/**
* Someone from a club's FPA register row (licence + name + photo already known — no second portal hit).
* Same person as `personFromFpaLicence` when the licence matches.
*/
async personFromFpaAssociate(
orgId: string,
a: FpaClubAssociate,
clubName: string | null = null,
): Promise<{ person: { id: string; name: string; club: string | null }; created: boolean; reference: boolean }> {
const { db, log } = this.deps;
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org) throw notFound("organization_not_found");
let person = await db.person.findUnique({ where: { organizationId_licence: { organizationId: orgId, licence: a.licence } } });
if (!person) {
const players = await db.sportsPlayer.findMany({ where: { externalId: a.licence, team: { provider: "FPA" } }, select: { id: true } });
if (players.length) person = await db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: players.map((p) => p.id) }, licence: null } });
}
let created = false;
if (!person) {
const short = fpaShortName(a.name);
const same = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: short } } });
// A name taken by someone else: the full name, and if that is taken too (by another licence), the licence
// number — guaranteed free — tells the two apart for sure.
let name = !same ? short : a.name;
let other = same ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
if (other && other.licence && other.licence !== a.licence) {
name = `${a.name} (${a.licence})`;
other = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } });
}
person = other ?? (await db.person.create({ data: { organizationId: orgId, name, club: clubName, licence: a.licence } }));
created = !other;
}
if (person.licence !== a.licence || (!person.club && clubName)) {
person = await db.person.update({
where: { id: person.id },
data: { licence: a.licence, ...(!person.club && clubName ? { club: clubName } : {}) },
});
}
let reference = false;
if (org.biometricsEnabled && a.photo && !person.referenceKey && !person.recognitionOffAt) {
try {
reference = await this.saveHeadshot(orgId, person.id, a.photo);
} catch (err) {
log.warn({ err, licence: a.licence }, "sports: fpa associate photo failed");
}
}
return { person: { id: person.id, name: person.name, club: person.club }, created, reference };
}
/** The person already created for this human at another club or in another season. */
private async personForIdentity(orgId: string, p: SportsPlayer) {
const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = [];
@@ -1483,3 +1649,20 @@ export class SportsWorker {
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
}
}
/** The role a member is best known by now: the latest season's, a player or coach before an official. */
export function fpaLatestRole(member: FpaMember): { season: string; role: string; club: string | null } | null {
const order: FpaRegistration["kind"][] = ["athlete", "coach", "official", "table", "referee", "other"];
const regs = [...member.registrations].sort((a, b) => b.season.localeCompare(a.season) || order.indexOf(a.kind) - order.indexOf(b.kind) || Number(a.club === "F.A.P.") - Number(b.club === "F.A.P."));
const r = regs[0];
if (!r) return null;
return { season: r.season, role: r.role, club: r.clubName ? fpaClubName(r.clubName) : r.club };
}
/** "Estarreja Andebol Clube" as is; "Selecções Nacionais Masculinas" → "Seleção Nacional Masculina"; capitals fixed. */
export function fpaClubName(name: string): string {
const sel = /^selec[cç][oõ]es nacionais (masculinas|femininas)/i.exec(name);
if (sel) return `Seleção Nacional ${sel[1]!.toLowerCase().startsWith("m") ? "Masculina" : "Feminina"}`;
if (/^federa[cç]ao andebol portugal$/i.test(name)) return "Federação de Andebol de Portugal";
return name === name.toUpperCase() ? name.toLowerCase().replace(/(^|\s)\p{L}/gu, (m) => m.toUpperCase()) : name;
}
+121 -3
View File
@@ -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<FaceAnalysis> {
return this.next;
}
async close(): Promise<void> {}
}
const KEY = Buffer.alloc(32, 7).toString("base64");
const quiet = { info: () => {}, warn: () => {} };
@@ -553,12 +572,24 @@ describe("archive from a Nextcloud", () => {
let orgId: string;
let ownerId: string;
let worker: ArchiveService;
const findEngine = new FindEngine();
const fetchProxy: typeof fetch = (input, init) => cloud.fetch(input, init);
// The cloud, and the handball federation's portal for a licence lookup.
const fetchProxy: typeof fetch = (input, init) => {
const u = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
if (u.host === "portal.fpa.pt")
return Promise.resolve(
u.pathname === "/associado/198159/"
? new Response('<div class="association-detail"><h3>Maria Ema Bastos Silva</h3><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_203445.JPG"></div><script>var TABLE_CONTENT_1 = {"cipa":"203445"};</script>', { headers: { "content-type": "text/html" } })
: new Response("<html></html>", { headers: { "content-type": "text/html" } }),
);
if (u.host === "ws.fpa.pt") return Promise.resolve(Response.json([{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" }]));
return cloud.fetch(input, init);
};
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();
@@ -1120,6 +1151,17 @@ describe("archive from a Nextcloud", () => {
const scoped = res.json() as { gallery: { id: string; title: string } | null; counts: Record<string, number> };
expect(scoped.gallery?.id).toBe(gid);
expect(scoped.counts.suggested).toBe(2);
// Handball archives: a licence number nobody has yet is looked up at the federation, and the person added.
await ctx.db.cloudSource.update({ where: { id: source.id }, data: { look: "fpa" } });
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
expect(res.json()).toMatchObject({ people: [], fpa: { licence: "198159", name: "Maria Ema Bastos Silva", club: "Estarreja Andebol Clube", role: "Treinador · 2024/25" } });
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(reader), payload: { licence: "198159" } });
expect(res.statusCode).toBe(403);
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/from-licence`, headers: as(editor), payload: { licence: "198159" } });
expect(res.json()).toMatchObject({ created: true, person: { name: "Maria Silva", club: "Estarreja Andebol Clube", licence: "198159" } });
res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/search?q=198159`, headers: as(editor) });
expect(res.json().fpa).toBeUndefined();
expect(res.json().people).toMatchObject([{ name: "Maria Silva", licence: "198159" }]);
// "Juntar nomes" is for those who edit everything.
res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/merge`, headers: as(editor), payload: { into: "Sporting CP", names: ["Sporting"] } });
expect(res.statusCode).toBe(403);
@@ -1341,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" });
+14 -1
View File
@@ -1,5 +1,6 @@
import Fastify from "fastify";
import { describe, expect, it } from "vitest";
import { DesktopReleases, newer } from "../src/desktop/updates.js";
import { DesktopReleases, newer, registerDesktopRoutes } from "../src/desktop/updates.js";
const API = "https://git.example/api/v1/repos/o/r";
@@ -70,4 +71,16 @@ describe("desktop updates", () => {
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
});
it("answers 503 instead of crashing the route when Gitea is unreachable (BIT-31961)", async () => {
const releases = new DesktopReleases({ api: API, token: "t" }, async () => {
throw new TypeError("fetch failed");
});
const app = Fastify({ logger: false });
await registerDesktopRoutes(app, { releases, publicApiUrl: "https://app.example" });
const res = await app.inject({ method: "GET", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
expect(res.statusCode).toBe(503);
expect(res.json()).toEqual({ error: "download_unavailable" });
});
});
+16 -2
View File
@@ -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<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise<TestContext> {
export async function createTestApp(
overrides: Record<string, string> = {},
realtime?: Broadcaster,
fetchImpl?: typeof fetch,
engineOnline?: () => boolean,
faceEngine?: FaceEngine,
): Promise<TestContext> {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST),
@@ -23,7 +30,14 @@ export async function createTestApp(overrides: Record<string, string> = {}, 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 };
}
+73 -1
View File
@@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js";
import { type Fetch, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
import { SportsService } from "../src/sports/service.js";
import { LocalStorage } from "../src/storage/storage.js";
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
@@ -56,6 +56,8 @@ describe("federation data", () => {
expect(lisbonTime("2026-12-01").timeKnown).toBe(false);
expect(seasonOf(new Date("2026-10-13"))).toBe("20262027");
expect(seasonOf(new Date("2027-03-01"))).toBe("20262027");
expect(fpaEpochFor(new Date("2026-10-27T12:00:00Z"))).toBe("374");
expect(fpaEpochFor(new Date("2026-03-01T12:00:00Z"))).toBe("373");
});
it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => {
@@ -243,6 +245,15 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
"utf8",
),
);
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/associado/198159/") return bytes(Buffer.from(MEMBER_PAGE, "utf8"));
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipaInscricoes/203445") return json(MEMBER_REGISTRATIONS);
// Full club register (every associate, not only the match sheet): Vitória club 140, season 374.
if (state.handball && u.host === "ws.fpa.pt" && u.pathname === "/index.php/getCipClubeEpoca/140/374")
return json([
{ CIP_NUMERO: "100001", CIP_NOME: "Rui Manuel Sousa Lopes", ID_CIPA: "370001", ATLETA: "S", TECNICO: null, OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG" },
{ CIP_NUMERO: "250001", CIP_NOME: "Ana Filipa Mendes Costa", ID_CIPA: "370999", ATLETA: null, TECNICO: "S", OFICIAL: null, ARBITRO: null, URL_FOTO: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG" },
]);
if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getCipClubeEpoca")) return json([]);
const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1];
if (state.handball && u.host === "portal.fpa.pt" && licence)
return bytes(Buffer.from(`<html><body><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/555_${licence}.JPG"></body></html>`, "utf8"));
@@ -341,6 +352,7 @@ describe("sports data service", () => {
});
beforeEach(async () => {
await resetDb(ctx.db);
sports.resetFpaClocks();
state.handball = false;
state.benfica = [
{ shirtNumber: 14, name: "Vangelis Pavlidis", photos: "https://www.ligaportugal.pt/p/pavlidis.png" },
@@ -479,6 +491,55 @@ describe("sports data service", () => {
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "a", away: "b", startsAt: fixture.startsAt, homeTeamId: org!.id } })).statusCode).toBe(400);
});
it("FPA: a person from their licence number (name, latest role, licence photo), the same one on match reports", async () => {
state.handball = true;
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "OWNER" });
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
const member = await sports.fpa.member("198159");
expect(member).toMatchObject({ name: "Maria Ema Bastos Silva", internalId: "203445", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG" });
expect(member!.registrations.map((r) => [r.season, r.kind, r.club])).toEqual([
["2010/11", "athlete", "ADA CANELAS"],
["2024/25", "coach", "ESTARREJA AC"],
["2025/26", "official", "Sel.Nac.M"],
]);
expect(await sports.fpa.member("99999999")).toBeNull();
const first = await sports.personFromFpaLicence(org!.id, "198159");
expect(first).toMatchObject({ created: true, reference: true, person: { name: "Maria Silva", club: "Seleção Nacional Masculina" } });
const again = await sports.personFromFpaLicence(org!.id, "198159");
expect(again).toMatchObject({ created: false, person: { id: first.person.id } });
expect((await ctx.db.person.findUniqueOrThrow({ where: { id: first.person.id } })).licence).toBe("198159");
});
it("FPA: the whole club register (getCipClubeEpoca) becomes people with licence photos, not only match-sheet names", async () => {
state.handball = true;
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-reg", role: "OWNER" });
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
const list = await sports.fpa.clubAssociates("140", "374");
expect(list).toEqual([
{ licence: "100001", internalId: "370001", name: "Rui Manuel Sousa Lopes", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/1_370001.JPG", kind: "athlete" },
{ licence: "250001", internalId: "370999", name: "Ana Filipa Mendes Costa", photo: "https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/2_370999.JPG", kind: "coach" },
]);
const r = await sports.refreshFpa(now);
expect(r.errors).toEqual([]);
const coach = await ctx.db.person.findUnique({ where: { organizationId_licence: { organizationId: org!.id, licence: "250001" } } });
expect(coach).toMatchObject({ name: "Ana Costa", licence: "250001" });
expect(coach!.referenceKey).toBeTruthy();
});
it("FPA: two associates with the exact same name get told apart by licence, instead of a person_name_taken error", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa-homonimos", role: "OWNER" });
const first = await sports.personFromFpaAssociate(org!.id, { licence: "900001", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(first).toMatchObject({ created: true, person: { name: "Maria Silva" } });
const second = await sports.personFromFpaAssociate(org!.id, { licence: "900002", internalId: null, name: "Maria Silva", photo: null, kind: "athlete" });
expect(second).toMatchObject({ created: true, person: { name: "Maria Silva (900002)" } });
expect(second.person.id).not.toBe(first.person.id);
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { licence: "asc" } });
expect(people.map((p) => [p.name, p.licence])).toEqual([
["Maria Silva", "900001"],
["Maria Silva (900002)", "900002"],
]);
});
it("keeps sports data to members and FPF links to admins", async () => {
const { user } = await seedUser(ctx.db, "[email protected]", { org: "abola", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, user.email)).body.accessToken;
@@ -528,7 +589,9 @@ describe("sports data service", () => {
expect(created.statusCode).toBe(201);
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) })).statusCode).toBe(200);
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
// Ana Costa comes from the club register (getCipClubeEpoca), not the match sheet — coaches and the rest of the club.
expect(people.map((p) => [p.name, p.club, p.number, !!p.referenceKey])).toEqual([
["Ana Costa", null, null, true],
["Bruno Costa", "Arbitragem", null, false],
["Carlos Mesa", "Arbitragem", null, false],
["Duarte Sá", "Arbitragem", null, true],
@@ -628,3 +691,12 @@ describe("sports data service", () => {
]);
});
});
const MEMBER_PAGE = `<html><body><div class="association-detail"><div class="association-detail__image"><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/636722_203445.JPG"></div>
<div class="association-detail__content"><h3>Maria Ema Bastos Silva</h3><table><tr><td>CIPA</td><td>198159</td></tr><tr><td>Inscrito como</td><td>Oficial, Técnico, Atleta</td></tr></table></div></div>
<script>var TABLE_CONTENT_1 = {"title":"Hist\\u00f3rico","tabs":[],"cipa":"203445"};</script></body></html>`;
const MEMBER_REGISTRATIONS = [
{ EPO_DESCRICAO: "2010/11", GCI_TIP_INSCRICAO_TI013: "AT01", CLU_ABREV: "ADA CANELAS", CLU_NOME: "Associacao Desportiva Arsenal Canelas", ESC_DESCRICAO: "Iniciados F" },
{ EPO_DESCRICAO: "2024/25", GCI_TIP_INSCRICAO_TI013: "TEC", CLU_ABREV: "ESTARREJA AC", CLU_NOME: "Estarreja Andebol Clube" },
{ EPO_DESCRICAO: "2025/26", GCI_TIP_INSCRICAO_TI013: "OFI", CLU_ABREV: "Sel.Nac.M", CLU_NOME: "Selecções Nacionais Masculinas", FOF_ABREV: "DELEGADO TECNICO" },
];
+2
View File
@@ -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<string, string>,
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.",
+12
View File
@@ -223,6 +223,18 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
</select>
</label>
)}
{isAdmin && (
<label className="flex w-full flex-wrap items-center gap-2">
<input
type="checkbox"
checked={!!source.photoFindEnabled}
disabled={busy}
onChange={(e) => void run(() => api.updateCloudSource(source.id, { photoFindEnabled: e.target.checked }))}
/>
<span className="text-[12px] text-ink">{A.photoFind}</span>
<span className="w-full text-faint">{A.photoFindHelp}</span>
</label>
)}
{isAdmin && (
<form
className="flex w-full flex-wrap items-center gap-2"
+45 -5
View File
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { cached, call, readStored, storageKey, writeStored, type Me } from "./api";
import { Browse, type Tab } from "./Browse";
import { FindByPhoto } from "./FindByPhoto";
import { Gallery } from "./Gallery";
import { Icon } from "./parts";
import fpaLogo from "./logos/fpa.png";
@@ -13,7 +14,7 @@ import { Review } from "./Review";
import type { ArchiveInfo } from "./page";
/** Where the viewer is: one of the lists, in a gallery, on a person's photos, or on "more of this face". */
export type View = { kind: "browse"; tab?: Tab; person?: string; gallery?: string } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string };
export type View = { kind: "browse"; tab?: Tab; person?: string; gallery?: string } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string } | { kind: "find" };
/** Each owner's template: its name and logo. Colours and type are in archive.css (`data-look`). */
const TEMPLATE: Record<"liga" | "fpa", { owner: string; logo: string }> = {
@@ -57,6 +58,12 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
cached<Me>(`/v1/archive/${info.id}/me`, token, setMe).catch(() => setMe(null));
}, [token, info.id, meTick]);
// Editors who can search by photo: start the face engine as soon as they are in, so the first search is quicker.
useEffect(() => {
if (!token || !me?.canFind) return;
void fetch(`/v1/archive/${info.id}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined);
}, [token, me?.canFind, info.id]);
/** Ends the session here and on the server (which revokes the app password kept on the cloud). */
const signOut = useCallback(() => {
const t = readStored(storageKey(info.id));
@@ -82,7 +89,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 +109,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 = (
<a className="arq-brand" href={home} onClick={(e) => (e.preventDefault(), openTab("galleries"))}>
@@ -161,12 +170,43 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
{t === "review" && !!me?.pending && <span className="arq-count">{me.pending}</span>}
</button>
))}
{me?.canFind && (
<button type="button" aria-current={view.kind === "find" ? "page" : undefined} onClick={() => go({ kind: "find" })}>
Procurar por foto
</button>
)}
</div>
</nav>
</header>
<main className="arq-main">
{view.kind === "gallery" ? (
{view.kind === "find" && me?.canFind && token ? (
<FindByPhoto
sourceId={info.id}
token={token}
me={me}
onClose={() => 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" ? (
<div className="arq-wrap arq-body">
<div className="arq-lock">
<Icon name="lock" size={48} />
<h1 className="arq-disp" style={{ margin: 0 }}>
Só para quem pode editar
</h1>
<p className="arq-muted" style={{ maxWidth: 520, margin: 0 }}>
A procura por foto é para quem tem permissão de edição nas pastas destas fotos.
</p>
<button type="button" className="arq-btn" onClick={() => openTab("galleries")}>
Voltar às galerias
</button>
</div>
</div>
) : view.kind === "gallery" ? (
<Gallery id={view.id} sourceId={info.id} me={me} token={token} onBack={() => 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" ? (
<PhotosOf
@@ -220,7 +260,7 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
</div>
</div>
) : (
<Browse sourceId={info.id} token={token} tab={tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} />
<Browse sourceId={info.id} token={token} tab={tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} canManage={!!me?.canManagePeople} fpa={info.look === "fpa"} />
)}
</main>
+98 -1
View File
@@ -1,7 +1,7 @@
"use client";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { addFromLicence, cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type FpaCard, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { eventLayout } from "./events";
import { Icon, Loading, PersonFace } from "./parts";
@@ -24,7 +24,10 @@ export function Browse({
onPerson,
canReview = false,
canManage = false,
fpa = false,
}: {
/** A handball archive: people can be added by their federation licence (for those who review). */
fpa?: boolean;
/** The viewer edits the whole archive: may join a club's names ("Juntar nomes"). */
canManage?: boolean;
/** The viewer edits on the cloud: sees the suggestions waiting for confirmation. */
@@ -144,6 +147,9 @@ export function Browse({
};
}, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick, peopleSeason]);
// Another filter: back to the tournaments' tiles.
useEffect(() => setOpenGroup(null), [kind, season, sort, q, team, player]);
/** Joins (or parts) club names, then reads people and teams again. */
const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => {
setJoinNote(null);
@@ -493,6 +499,7 @@ export function Browse({
<>
<div className="arq-people-head">
<h1 className="arq-disp arq-h1">Pessoas</h1>
{fpa && canReview && <LicenceAdd sourceId={sourceId} token={token} onPerson={onPerson} onExpired={onExpired} />}
{!!people?.seasons?.length && (
<label className="arq-filter">
<span>Época</span>
@@ -744,3 +751,93 @@ export function Browse({
</>
);
}
/**
* Adds someone by their handball federation licence (CIPA): who the federation says it is (name, photo, every
* registration), then the person, with the licence photo to be recognised by. For people events show who no match
* report names: coaches of other years, delegates, staff.
*/
function LicenceAdd({ sourceId, token, onPerson, onExpired }: { sourceId: string; token: string; onPerson: (id: string) => void; onExpired: () => void }) {
const [open, setOpen] = useState(false);
const [licence, setLicence] = useState("");
const [found, setFound] = useState<{ member: FpaCard; person: { id: string; name: string } | null } | null>(null);
const [state, setState] = useState<"idle" | "looking" | "adding" | "missing" | "failed">("idle");
const look = (e: React.FormEvent) => {
e.preventDefault();
const n = licence.trim();
if (!/^\d{3,9}$/.test(n)) return setState("missing");
setState("looking");
setFound(null);
call<{ member: FpaCard; person: { id: string; name: string } | null }>(`/v1/archive/${sourceId}/fpa/${n}`, token).then(
({ body }) => {
setFound(body);
setState("idle");
},
(err) => (err instanceof Unauthorised ? onExpired() : setState(String(err?.message) === "404" ? "missing" : "failed")),
);
};
const add = () => {
if (!found) return;
setState("adding");
addFromLicence(sourceId, token, found.member.licence).then(
(p) => onPerson(p.id),
(err) => (err instanceof Unauthorised ? onExpired() : setState("failed")),
);
};
if (!open)
return (
<button type="button" className="arq-btn ghost" onClick={() => setOpen(true)}>
Adicionar pela licença FPA
</button>
);
return (
<div className="arq-licence">
<form onSubmit={look} className="arq-licence-form">
<label>
<span className="arq-sr">Número de licença (CIPA)</span>
<input inputMode="numeric" value={licence} onChange={(e) => setLicence(e.target.value.replace(/\D/g, ""))} placeholder="Nº de licença (CIPA)" autoFocus />
</label>
<button type="submit" className="arq-btn" disabled={state === "looking"}>
{state === "looking" ? "A procurar…" : "Procurar"}
</button>
<button type="button" className="arq-link" onClick={() => (setOpen(false), setFound(null), setState("idle"))}>
Fechar
</button>
</form>
{state === "missing" && <p className="arq-muted">A federação não tem ninguém com esse número.</p>}
{state === "failed" && <p className="arq-muted">Não foi possível falar com a federação. Tenta outra vez.</p>}
{found && (
<div className="arq-licence-card">
<PersonFace p={{ reference: found.member.photo, face: null, name: found.member.name }} size={88} round={false} />
<div>
<strong>{found.member.name}</strong>
<small className="arq-muted">
Licença {found.member.licence}
{found.member.role ? ` · ${found.member.role}` : ""}
{found.member.club ? ` · ${found.member.club}` : ""}
</small>
{found.member.history.length > 0 && (
<ul>
{found.member.history.map((h) => (
<li key={h}>{h}</li>
))}
</ul>
)}
{found.person ? (
<button type="button" className="arq-btn" onClick={() => onPerson(found.person!.id)}>
Já está no arquivo: ver {found.person.name}
</button>
) : (
<button type="button" className="arq-btn accent" disabled={state === "adding"} onClick={add}>
{state === "adding" ? "A adicionar…" : "Adicionar ao arquivo"}
</button>
)}
<small className="arq-muted">A foto da licença passa a ser a referência para o reconhecimento facial.</small>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,261 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { asJpeg } from "../../../lib/asJpeg";
import { SelfieCamera } from "../../../lib/SelfieCamera";
import { day, download, Forbidden, LEVEL, Unauthorised, type FindByPhotoResult, type Level, type Me, type PhotoFace } from "./api";
import { Lightbox } from "./Lightbox";
import { Icon } from "./parts";
/**
* Internal search for editors on the cloud: upload a photo of a person and find that face across the archive
* (folders they may see). The photo is not kept. Used by the news desk (FPA and similar).
*/
export function FindByPhoto({
sourceId,
token,
me,
onClose,
onExpired,
onPerson,
onGallery,
onFace,
}: {
sourceId: string;
token: string;
me: Me;
onClose: () => void;
onExpired: () => void;
onPerson: (id: string) => void;
onGallery: (id: string) => void;
onFace: (id: string) => void;
}) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [file, setFile] = useState<File | null>(null);
const [result, setResult] = useState<FindByPhotoResult | null>(null);
const [only, setOnly] = useState<Level | null>(null);
const [index, setIndex] = useState<number | null>(null);
const [camera, setCamera] = useState(false);
// Start the face engine while the editor is on this page, so the first upload does not wait on model load.
useEffect(() => {
void fetch(`/v1/archive/${sourceId}/find/ready`, { headers: { authorization: `Archive ${token}` } }).catch(() => undefined);
}, [sourceId, token]);
const search = async (next: File, face = 0) => {
setBusy(true);
setError(null);
setOnly(null);
setIndex(null);
try {
// Phones (esp. iPhone) often hand over HEIC; the API only reads JPEG/PNG/WebP. Decode here and send JPEG.
const jpeg = await asJpeg(next);
setFile(jpeg);
const form = new FormData();
form.append("file", jpeg, "foto.jpg");
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<string, string> = {
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. Tira outra ou escolhe um JPEG da galeria.",
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 if (err instanceof Error && err.message === "convert_failed")
setError("Não conseguimos ler essa foto. Tira outra com a câmara ou escolhe um JPEG da galeria.");
else setError("Não foi possível pesquisar agora. Confirma a rede e tenta outra vez.");
setResult(null);
} finally {
setBusy(false);
}
};
const counts = useMemo(() => {
const c: Record<Level, number> = { 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?.identity ?? result?.people[0] ?? null;
const licence = person && "licence" in person ? (person.licence ?? null) : 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 (
<div className="arq-wrap arq-body">
<nav className="arq-crumbs" aria-label="Caminho">
<button type="button" onClick={onClose}>
<Icon name="back" size={16} />
Voltar
</button>
</nav>
<section style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 20 }}>
<span className="arq-badge">Procura por foto</span>
<h1 className="arq-disp" style={{ margin: 0 }}>
Encontrar fotos de uma pessoa
</h1>
<p className="arq-muted" style={{ margin: 0, maxWidth: 560 }}>
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.
</p>
<div style={{ display: "flex", flexWrap: "wrap", gap: 10, alignItems: "center" }}>
<button type="button" className="arq-btn" disabled={busy} aria-busy={busy} onClick={() => setCamera(true)}>
{busy ? "A procurar…" : "Tirar foto"}
</button>
<label className="arq-link" style={{ cursor: busy ? "wait" : "pointer", position: "relative" }}>
{result ? "Outra da galeria" : "Escolher da galeria"}
<input
type="file"
accept="image/*,.heic,.heif"
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }}
disabled={busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
{result && result.faces.length > 1 && file && (
<button type="button" className="arq-link" disabled={busy} onClick={() => void search(file, (result.used + 1) % result.faces.length)}>
Há {result.faces.length} caras — usar a {((result.used + 1) % result.faces.length) + 1}.ª
</button>
)}
</div>
{error && (
<p role="alert" className="arq-muted" style={{ color: "#b00020", margin: 0 }}>
{error}
</p>
)}
</section>
{result && (
<>
<div style={{ display: "flex", flexWrap: "wrap", gap: 16, alignItems: "center", marginBottom: 12 }}>
{person && (
<p style={{ margin: 0 }}>
{result.via === "registry" ? "Ficha FPA: " : "Mais parecido: "}
<button type="button" className="arq-link" onClick={() => onPerson(person.id)}>
{person.name}
</button>
{person.club ? ` · ${person.club}` : ""}
{licence ? ` · CIPA ${licence}` : person.number ? ` · #${person.number}` : ""}
</p>
)}
<div className="arq-stats" style={{ marginLeft: "auto" }}>
<span>
<b>{result.total}</b>
<small>fotos</small>
</span>
{(Object.keys(LEVEL) as Level[]).map((l) =>
counts[l] ? (
<span key={l}>
<b>{counts[l]}</b>
<small>{LEVEL[l]}</small>
</span>
) : null,
)}
</div>
</div>
{result.total > 0 && (
<div className="arq-pills scroll" role="group" aria-label="Mostrar" style={{ marginBottom: 12 }}>
<button type="button" className="arq-pill" aria-pressed={only === null} onClick={() => setOnly(null)}>
Todas <span className="arq-n">{result.photos.length}</span>
</button>
{(Object.keys(LEVEL) as Level[])
.filter((l) => counts[l] > 0)
.map((l) => (
<button key={l} type="button" className="arq-pill" aria-pressed={only === l} onClick={() => setOnly(only === l ? null : l)}>
{LEVEL[l]} <span className="arq-n">{counts[l]}</span>
</button>
))}
</div>
)}
{!result.total ? (
<div className="arq-empty">Não encontrámos fotos desta cara nas pastas que podes ver.</div>
) : (
<div className="arq-grid">
{photos.map((p, i) => (
<button key={p.id} type="button" className="arq-tile" onClick={() => setIndex(i)} aria-label={p.gallery?.title ?? p.name}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={p.thumb} alt="" loading={i < 12 ? "eager" : "lazy"} decoding="async" />
{p.level && (
<span className={`arq-badge ${p.level === "confirmed" ? "ok" : p.level === "probable" ? "maybe" : "sim"}`}>
{LEVEL[p.level]}
{p.level === "similar" && p.score ? ` ${Math.round(p.score * 100)}%` : ""}
</span>
)}
<span className="arq-names">
<span>{[p.gallery?.title, p.gallery?.startsAt ? day.format(new Date(p.gallery.startsAt)) : null].filter(Boolean).join(" · ")}</span>
</span>
</button>
))}
</div>
)}
</>
)}
{camera && (
<SelfieCamera
onCancel={() => setCamera(false)}
onShot={(shot) => {
setCamera(false);
void search(shot);
}}
/>
)}
{index !== null && photos[index] && (
<Lightbox
photos={photos}
index={index}
onIndex={setIndex}
token={token}
onLoaded={rememberFaces}
onFace={onFace}
onPerson={onPerson}
review={me.canReview ? { sourceId, onDone: () => undefined } : undefined}
onDownload={(photoId) => void download(sourceId, token, { photoIds: [photoId] }).catch((err) => (err instanceof Unauthorised ? onExpired() : undefined))}
extra={(p) =>
p.gallery ? (
<>
<span className="arq-label">Galeria</span>
<span>
<button type="button" className="arq-link" onClick={() => onGallery(p.gallery!.id)}>
{p.gallery.title}
</button>
</span>
</>
) : null
}
/>
)}
</div>
);
}
+55 -12
View File
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { call, forget, Forbidden, shortDay, Unauthorised, type Me, type ReviewGroup, type ReviewPerson, type ReviewResult, type ReviewStatus } from "./api";
import { addFromLicence, call, forget, Forbidden, shortDay, Unauthorised, type Me, type PeopleSearch, type ReviewGroup, type ReviewResult, type ReviewStatus } from "./api";
import { FaceCrop, Icon, Loading, PersonFace } from "./parts";
const STATUS: [ReviewStatus, string][] = [
@@ -51,10 +51,12 @@ export function Review({
const [selected, setSelected] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
const [attempt, setAttempt] = useState(0);
const searchPeople = useCallback(async (q: string): Promise<ReviewPerson[]> => {
const { body } = await call<{ people: ReviewPerson[] }>(`/v1/archive/${sourceId}/people/search?q=${encodeURIComponent(q)}`, token);
return body.people;
const searchPeople = useCallback(async (q: string): Promise<PeopleSearch> => {
const { body } = await call<PeopleSearch>(`/v1/archive/${sourceId}/people/search?q=${encodeURIComponent(q)}`, token);
return body;
}, [sourceId, token]);
/** A face named by licence number: the person is added from the federation first. */
const addLicence = useCallback(async (licence: string) => (await addFromLicence(sourceId, token, licence)).id, [sourceId, token]);
useEffect(() => {
let cancel = false;
@@ -252,6 +254,7 @@ export function Review({
onToggle={() => togglePile(pile)}
onAct={(a, p) => void act(pile.map((g) => g.id), a, p)}
searchPeople={searchPeople}
addLicence={addLicence}
/>
))}
</div>
@@ -296,26 +299,43 @@ export function Review({
);
}
function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string; searchPeople: (q: string) => Promise<ReviewPerson[]>; onPick: (id: string) => void }) {
function NameSearch({
placeholder,
searchPeople,
onPick,
addLicence,
}: {
placeholder: string;
searchPeople: (q: string) => Promise<PeopleSearch>;
onPick: (id: string) => void;
addLicence?: (licence: string) => Promise<string>;
}) {
const [q, setQ] = useState("");
const [hits, setHits] = useState<ReviewPerson[]>([]);
const [hits, setHits] = useState<PeopleSearch["people"]>([]);
const [fpa, setFpa] = useState<PeopleSearch["fpa"] | null>(null);
const [adding, setAdding] = useState(false);
const [failed, setFailed] = useState(false);
useEffect(() => {
const query = q.trim();
setFailed(false);
if (query.length < 2) {
setHits([]);
setFpa(null);
return;
}
let cancel = false;
const timer = setTimeout(() => {
searchPeople(query).then(
(rows) => {
if (!cancel) setHits(rows);
(found) => {
if (cancel) return;
setHits(found.people);
setFpa(found.fpa ?? null);
},
() => {
if (!cancel) setHits([]);
},
);
}, 200);
}, /^\d+$/.test(query) ? 450 : 200);
return () => {
cancel = true;
clearTimeout(timer);
@@ -329,10 +349,31 @@ function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string
<PersonFace p={{ reference: p.reference, face: null, name: p.name }} size={36} />
<span>
<strong>{p.name}</strong>
<small>{[p.number ? `nº ${p.number}` : null, p.club].filter(Boolean).join(" · ")}</small>
<small>{[p.number ? `nº ${p.number}` : null, p.club, p.licence ? `licença ${p.licence}` : null].filter(Boolean).join(" · ")}</small>
</span>
</button>
))}
{fpa && addLicence && (
<button
type="button"
className="arq-name-hit arq-fpa-hit"
disabled={adding}
onClick={() => {
setAdding(true);
setFailed(false);
addLicence(fpa.licence).then(onPick, () => setFailed(true)).finally(() => setAdding(false));
}}
title={fpa.history.join("\n")}
>
<PersonFace p={{ reference: fpa.photo, face: null, name: fpa.name }} size={36} />
<span>
<strong>{adding ? "A adicionar…" : fpa.name}</strong>
<small>{[`Licença FPA ${fpa.licence}`, fpa.role, fpa.club].filter(Boolean).join(" · ")}</small>
<small className="arq-fpa-add">+ Adicionar e confirmar</small>
</span>
</button>
)}
{failed && <small role="alert">Não foi possível adicionar. Tenta outra vez.</small>}
</span>
);
}
@@ -363,6 +404,7 @@ function Card({
onToggle,
onAct,
searchPeople,
addLicence,
}: {
groups: ReviewGroup[];
status: ReviewStatus;
@@ -370,7 +412,8 @@ function Card({
selected: boolean;
onToggle: () => void;
onAct: (a: Action, personId?: string) => void;
searchPeople: (q: string) => Promise<ReviewPerson[]>;
searchPeople: (q: string) => Promise<PeopleSearch>;
addLicence: (licence: string) => Promise<string>;
}) {
const g = groups[0]!;
const who = g.person ?? g.suggested;
@@ -422,7 +465,7 @@ function Card({
)}
{g.notThem.length > 0 && <small>Não é: {g.notThem.map((n) => n.name).join(", ")}</small>}
{(status === "unnamed" || status === "suggested") && (
<NameSearch placeholder={status === "unnamed" ? "Quem é? Nome, clube ou número" : "Outro nome, clube ou número"} searchPeople={searchPeople} onPick={(id) => onAct("confirm", id)} />
<NameSearch placeholder={status === "unnamed" ? "Quem é? Nome, clube ou número" : "Outro nome, clube ou número"} searchPeople={searchPeople} addLicence={addLicence} onPick={(id) => onAct("confirm", id)} />
)}
</div>
<div className="arq-ractions">
+59
View File
@@ -208,10 +208,43 @@ 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;
/** `registry` = matched a federation person first; `faces` = blind scan of archive face groups. */
via?: "registry" | "faces";
identity?: {
id: string;
name: string;
club: string | null;
number: string | null;
licence: string | null;
reference: string | null;
registry: "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null;
score: number;
} | null;
people: {
id: string;
name: string;
club: string | null;
number: string | null;
score: number;
level: string;
licence?: string | null;
reference?: string | null;
registry?: "fpa" | "liga" | "uefa" | "ehf" | "fpf" | null;
}[];
total: number;
photos: ArchivePhoto[];
}
export type ReviewStatus = "suggested" | "unnamed" | "confirmed" | "rejected" | "ignored";
export interface ReviewPerson {
@@ -221,6 +254,32 @@ export interface ReviewPerson {
number: string | null;
reference: string | null;
recognitionOff?: boolean;
licence?: string;
}
/** Someone registered with the handball federation, by licence number (CIPA). */
export interface FpaCard {
licence: string;
name: string;
photo: string | null;
club: string | null;
/** "Treinador · 2024/25". */
role: string | null;
/** "2024/25 · Treinador · ESTARREJA AC", newest first. */
history: string[];
}
export interface PeopleSearch {
people: ReviewPerson[];
/** A licence number nobody here has yet (FPA archives). */
fpa?: FpaCard;
}
/** Adds (or updates) a person from their licence; returns who. */
export async function addFromLicence(sourceId: string, token: string, licence: string): Promise<{ id: string; name: string; reference: boolean }> {
const { body } = await call<{ person: { id: string; name: string; reference: boolean } }>(`/v1/archive/${sourceId}/people/from-licence`, token, { method: "POST", body: JSON.stringify({ licence }) });
forget(`/v1/archive/${sourceId}/people`);
return body.person;
}
export interface ReviewGroup {
@@ -2636,3 +2636,79 @@
.arq-aside > * {
flex-shrink: 0;
}
.arq-group-open {
scroll-margin-top: 140px;
}
.arq-group-open .arq-kind-head {
flex-wrap: wrap;
align-items: center;
}
.arq-group-open .arq-kind-head .arq-link {
white-space: nowrap;
}
/* Pessoas: add someone by their federation licence. */
.arq-people-head {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px 24px;
}
.arq-licence {
display: flex;
flex-direction: column;
gap: 12px;
flex: 1 1 100%;
padding: 16px;
border-radius: var(--r);
background: var(--panel);
box-shadow: inset 0 0 0 1px var(--line);
}
.arq-licence-form {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.arq-licence-form input {
height: 44px;
width: 220px;
max-width: 100%;
padding: 0 14px;
border-radius: 999px;
border: 1px solid var(--line);
background: var(--card);
color: var(--ink);
font-size: 16px;
}
.arq-licence-card {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.arq-licence-card > div {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
flex: 1 1 260px;
min-width: 0;
}
.arq-licence-card strong {
font-size: 20px;
}
.arq-licence-card ul {
margin: 4px 0;
padding-left: 18px;
font-size: 14px;
color: var(--muted);
columns: 2 220px;
}
.arq-fpa-hit {
box-shadow: inset 0 0 0 1px var(--line);
}
.arq-fpa-add {
color: var(--tag-c) !important;
font-weight: 700;
}
+1
View File
@@ -17,6 +17,7 @@ export async function generateMetadata({ params }: Params): Promise<Metadata> {
*/
export default async function ArchivePage({ params, searchParams }: Params) {
const { t, p, g } = await searchParams;
if (t === "procurar") return <ArchiveFrame id={(await params).id} start={{ kind: "find" }} />;
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);
@@ -4,6 +4,8 @@ import type { OrderView, ProductSummary, PublicComment, PublicGallery } from "@p
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { asJpeg } from "../../../lib/asJpeg";
import { SelfieCamera } from "../../../lib/SelfieCamera";
import { addToCart, useCart } from "../../../lib/cart";
import { eur, shotAt, sizeLabel } from "../../../lib/format";
import { useProofing } from "../../../lib/proofing";
@@ -483,17 +485,20 @@ function BundleBar({ gallery, products, cartGallery }: { gallery: PublicGallery;
*/
function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string | null; onFound: (photoIds: string[], moreFaces: boolean) => void; onClose: () => void }) {
const [state, setState] = useState<{ busy: boolean; error: string | null; file: File | null; faces: number; face: number }>({ busy: false, error: null, file: null, faces: 0, face: 0 });
const search = async (file: File, face = 0) => {
setState((s) => ({ ...s, busy: true, error: null, file, face }));
const form = new FormData();
form.append("file", file, "foto.jpg");
const [camera, setCamera] = useState(false);
const search = async (picked: File, face = 0) => {
setState((s) => ({ ...s, busy: true, error: null, face }));
try {
const file = await asJpeg(picked);
setState((s) => ({ ...s, file }));
const form = new FormData();
form.append("file", file, "foto.jpg");
const res = await fetch(`/v1/public/galleries/${encodeURIComponent(slug)}/find${face ? `?face=${face}` : ""}`, { method: "POST", body: form, headers: token ? { "x-gallery-token": token } : {} });
const body = (await res.json().catch(() => ({}))) as { error?: string; faces?: unknown[]; matches?: { photoId: string; level: string }[] };
if (!res.ok) {
const msg: Record<string, string> = {
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.",
not_an_image: "Esse ficheiro não é uma foto. Tira outra ou escolhe um JPEG da galeria.",
find_unavailable: "A pesquisa por cara não está disponível nesta galeria.",
rate_limited: "Muitas pesquisas seguidas. Tenta daqui a um minuto.",
};
@@ -504,7 +509,7 @@ function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string
setState((s) => ({ ...s, busy: false, faces }));
onFound((body.matches ?? []).map((m) => m.photoId), faces > 1);
} catch {
setState((s) => ({ ...s, busy: false, error: "Não foi possível pesquisar agora." }));
setState((s) => ({ ...s, busy: false, error: "Não conseguimos ler essa foto. Tira outra com a câmara ou escolhe um JPEG da galeria." }));
}
};
return (
@@ -513,21 +518,25 @@ function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string
<h2 className="title h3">Encontra-te nas fotos</h2>
<p>Envia uma foto tua (ou de quem procuras) com a cara bem visível. Mostramos as fotos desta galeria em que essa pessoa aparece.</p>
<p className="meta">A foto só serve para esta pesquisa: não fica guardada.</p>
<label className="button" style={{ display: "inline-block", marginTop: 12, cursor: "pointer" }} aria-busy={state.busy}>
{state.busy ? "A procurar…" : "Escolher foto"}
<input
type="file"
accept="image/*"
capture="user"
hidden
disabled={state.busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
<div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginTop: 12, alignItems: "center" }}>
<button type="button" className="button" disabled={state.busy} aria-busy={state.busy} onClick={() => setCamera(true)}>
{state.busy ? "A procurar…" : "Tirar foto"}
</button>
<label style={{ cursor: "pointer", color: "var(--accent)", textDecoration: "underline", position: "relative" }}>
Escolher da galeria
<input
type="file"
accept="image/*,.heic,.heif"
style={{ position: "absolute", inset: 0, width: "100%", height: "100%", opacity: 0, cursor: "pointer" }}
disabled={state.busy}
onChange={(e) => {
const f = e.target.files?.[0];
if (f) void search(f);
e.target.value = "";
}}
/>
</label>
</div>
{state.faces > 1 && state.file && (
<p className="meta">
Há {state.faces} caras nessa foto; a galeria mostra as fotos da {state.face === 0 ? "maior" : `${state.face + 1}.ª`}.{" "}
@@ -547,6 +556,15 @@ function FindMe({ slug, token, onFound, onClose }: { slug: string; token: string
</button>
</p>
</div>
{camera && (
<SelfieCamera
onCancel={() => setCamera(false)}
onShot={(shot) => {
setCamera(false);
void search(shot);
}}
/>
)}
</div>
);
}
+149
View File
@@ -0,0 +1,149 @@
"use client";
import { useEffect, useRef, useState, type CSSProperties } from "react";
/**
* Front-camera capture in the page (getUserMedia → canvas JPEG). Prefer this over
* `<input capture>` on iPhone: the system picker often returns HEIC the face API cannot read,
* and a hidden file input inside a label is unreliable on iOS Safari.
*/
export function SelfieCamera({ onShot, onCancel }: { onShot: (file: File) => void; onCancel: () => void }) {
const video = useRef<HTMLVideoElement>(null);
const [problem, setProblem] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
let stream: MediaStream | null = null;
let cancelled = false;
const start = async () => {
if (!navigator.mediaDevices?.getUserMedia) {
setProblem("Este browser não dá acesso à câmara. Usa «Escolher da galeria» ou abre no Safari/Chrome.");
return;
}
try {
stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "user" }, width: { ideal: 1280 }, height: { ideal: 960 } },
audio: false,
});
if (cancelled) {
stream.getTracks().forEach((t) => t.stop());
return;
}
const el = video.current;
if (el) {
el.srcObject = stream;
await el.play().catch(() => undefined);
}
} catch {
if (!cancelled) setProblem("Não foi possível abrir a câmara. Autoriza a câmara neste site e tenta outra vez.");
}
};
void start();
return () => {
cancelled = true;
stream?.getTracks().forEach((t) => t.stop());
};
}, []);
const shoot = () => {
const v = video.current;
if (!v || !v.videoWidth || busy) return;
setBusy(true);
const canvas = document.createElement("canvas");
canvas.width = v.videoWidth;
canvas.height = v.videoHeight;
const ctx = canvas.getContext("2d");
if (!ctx) {
setProblem("Não foi possível capturar a imagem.");
setBusy(false);
return;
}
ctx.drawImage(v, 0, 0);
canvas.toBlob(
(blob) => {
setBusy(false);
if (!blob) {
setProblem("Não foi possível capturar a imagem.");
return;
}
onShot(new File([blob], "foto.jpg", { type: "image/jpeg" }));
},
"image/jpeg",
0.92,
);
};
return (
<div
role="dialog"
aria-modal="true"
aria-label="Tirar foto"
style={{
position: "fixed",
inset: 0,
zIndex: 80,
background: "rgba(8, 8, 9, 0.92)",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 16,
padding: 20,
boxSizing: "border-box",
}}
>
{problem ? (
<>
<p role="alert" style={{ color: "#fff", textAlign: "center", maxWidth: 360, margin: 0 }}>
{problem}
</p>
<button type="button" onClick={onCancel} style={btnGhost}>
Voltar
</button>
</>
) : (
<>
<video
ref={video}
playsInline
muted
autoPlay
style={{
maxWidth: "100%",
maxHeight: "70vh",
borderRadius: 12,
transform: "scaleX(-1)",
background: "#000",
}}
/>
<div style={{ display: "flex", gap: 12, flexWrap: "wrap", justifyContent: "center" }}>
<button type="button" onClick={shoot} disabled={busy} style={btnPrimary}>
{busy ? "A capturar…" : "Capturar"}
</button>
<button type="button" onClick={onCancel} disabled={busy} style={btnGhost}>
Cancelar
</button>
</div>
</>
)}
</div>
);
}
const btnPrimary: CSSProperties = {
padding: "12px 22px",
fontSize: 16,
fontWeight: 600,
border: 0,
borderRadius: 8,
background: "#fff",
color: "#111",
cursor: "pointer",
};
const btnGhost: CSSProperties = {
...btnPrimary,
background: "transparent",
color: "#fff",
border: "1px solid rgba(255,255,255,0.45)",
};
+57
View File
@@ -0,0 +1,57 @@
const JPEG_MAX_SIDE = 1600;
/**
* Phones often give HEIC (iPhone) or huge camera JPEGs. Decode in the browser and send a JPEG the face
* engine can read — the API's sharp build does not decode HEIC.
*/
export async function asJpeg(file: File): Promise<File> {
const already = /^image\/(jpeg|jpg|png|webp)$/i.test(file.type);
if (already && file.size <= 3 * 1024 * 1024) return file;
const bitmap = await decode(file);
try {
const scale = Math.min(1, JPEG_MAX_SIDE / Math.max(bitmap.width, bitmap.height));
const w = Math.max(1, Math.round(bitmap.width * scale));
const h = Math.max(1, Math.round(bitmap.height * scale));
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("convert_failed");
ctx.drawImage(bitmap.source, 0, 0, w, h);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.92));
if (!blob) throw new Error("convert_failed");
return new File([blob], "foto.jpg", { type: "image/jpeg" });
} finally {
bitmap.close();
}
}
type Decoded = { source: CanvasImageSource; width: number; height: number; close: () => void };
async function decode(file: File): Promise<Decoded> {
try {
const bitmap = await createImageBitmap(file);
return { source: bitmap, width: bitmap.width, height: bitmap.height, close: () => bitmap.close() };
} catch {
// Safari sometimes cannot createImageBitmap(HEIC) even when <img> can paint it.
}
const url = URL.createObjectURL(file);
try {
const img = await new Promise<HTMLImageElement>((resolve, reject) => {
const el = new Image();
el.onload = () => resolve(el);
el.onerror = () => reject(new Error("convert_failed"));
el.src = url;
});
return {
source: img,
width: img.naturalWidth || img.width,
height: img.naturalHeight || img.height,
close: () => URL.revokeObjectURL(url),
};
} catch (err) {
URL.revokeObjectURL(url);
throw err instanceof Error ? err : new Error("convert_failed");
}
}
+12 -5
View File
@@ -287,9 +287,12 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
level ids → `getJogosClubeEpocaEscalao`), eight teams per refresh; after that each report of a game played is read
once (reports read before licence numbers were kept are read again, 40 per refresh). Referees and table officials
come from the report, or from the match page (named some days before) for games with an event; both become people.
Licence photos (`portal.fpa.pt/associado/<CIPA>/`) are looked up only for the people of an event being synced,
with biometrics on, and become their reference photos. Names are first + last name ("Rui Lopes"), the full name
kept beside it.
Licence photos come from the club register (`ws.fpa.pt` `getCipClubeEpoca/{club}/{epoch}`: every associate the
federation lists for that club and season — athletes, coaches, officials, referees — with `CIP_NUMERO` and
`URL_FOTO`), so face search covers the whole FPA register, not only people named on a match sheet. A few clubs
per refresh; again after a week. Event sync still fills gaps via `portal.fpa.pt/associado/<CIPA>/` when a
boletim names someone the register has not yet brought. With biometrics on, photos become reference faces.
Names are first + last name ("Rui Lopes"), the full name kept beside it.
- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads
from each match sheet, read from 1 h before to 2 h after kick-off.
- **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's
@@ -521,8 +524,12 @@ 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. On phones, "Tirar foto" uses the front camera in the page (`getUserMedia` → JPEG),
not `<input capture>` (iOS often hands HEIC the API cannot read). Gallery picks still convert to JPEG in
the browser before upload. 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
+9
View File
@@ -232,6 +232,15 @@ 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".
Groups are ranked with pgvector HNSW (`centroid_vec`); event ids of the viewer's scope are cached a few minutes.
`GET …/find/ready` starts the face engine before the first upload.
### 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
+4 -1
View File
@@ -835,7 +835,10 @@ export class ApiClient {
return this.request<CloudSource>("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<CloudSource>("PATCH", `/v1/cloud-sources/${sourceId}`, input);
}
+2
View File
@@ -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). */