Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68588e0296 | ||
|
|
c61d371819 | ||
|
|
707420a579 | ||
|
|
92ceeee2fe | ||
|
|
81bd777e87 | ||
|
|
0d6a9e27e0 | ||
|
|
1652b6ba3c | ||
|
|
6e956f0ff8 | ||
|
|
d6a7edda38 | ||
|
|
8020574415 | ||
|
|
a8f6a0f03d | ||
|
|
c4c524c58b | ||
|
|
1aaa3857b0 | ||
|
|
ec9679c609 | ||
|
|
5ed0f94e04 | ||
|
|
22dda8726e | ||
|
|
5df809eedf | ||
|
|
999ab6d78d | ||
|
|
68c4f48cd6 | ||
|
|
7b08b78b40 | ||
|
|
a25d65c2c3 | ||
|
|
5cdfc19bf8 | ||
|
|
cfe9ecc59f | ||
|
|
9d1bf4849b | ||
|
|
11cbf64608 | ||
|
|
d95d3f7c3a | ||
|
|
2ccbce13d7 | ||
|
|
07300f592b | ||
|
|
5d286299f8 | ||
|
|
2fc1f73254 | ||
|
|
fa14bf91f5 | ||
|
|
db84533632 | ||
|
|
02a1440d66 | ||
|
|
7ac4c67176 | ||
|
|
9123d97918 | ||
|
|
3a0d3877f3 | ||
|
|
8a8218c6b3 | ||
|
|
34e8c27036 |
No files matched your search
@@ -9,7 +9,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16
|
||||
# Faces need pgvector (the migrations create the extension).
|
||||
image: pgvector/pgvector:pg16
|
||||
env:
|
||||
POSTGRES_USER: photoreport
|
||||
POSTGRES_PASSWORD: photoreport
|
||||
|
||||
@@ -3,6 +3,13 @@ PORT=3000
|
||||
LOG_LEVEL=info
|
||||
APP_VERSION=dev
|
||||
DATABASE_URL=postgresql://photoreport:CHANGE_ME@pr-db:5432/photoreport
|
||||
# The worker sizes its own pool from these three so the total stays under Postgres' max_connections. Leave unset
|
||||
# unless this install's PM2 api instances, API pool size, or Postgres max_connections differ from the defaults
|
||||
# (2, 10, 100).
|
||||
# API_DB_POOL_SIZE=
|
||||
# API_INSTANCES=
|
||||
# DB_MAX_CONNECTIONS=
|
||||
# DB_SUPERUSER_RESERVED_CONNECTIONS=
|
||||
# At least 32 random characters, e.g. `openssl rand -base64 48`
|
||||
JWT_SECRET=
|
||||
ACCESS_TOKEN_TTL_SEC=900
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
-- The face queue finishes the last month of photos (when they were taken, or the game's date) before the older
|
||||
-- archive. `created_at` is when the file arrived, so a scan of an old season was jumping ahead of this month.
|
||||
ALTER TABLE "photos" ADD COLUMN "taken_at" TIMESTAMP(3);
|
||||
|
||||
CREATE OR REPLACE FUNCTION photos_set_taken_at() RETURNS trigger AS $$
|
||||
DECLARE
|
||||
game timestamp(3);
|
||||
BEGIN
|
||||
IF NEW.captured_at IS NULL AND NEW.event_id IS NOT NULL THEN
|
||||
SELECT starts_at INTO game FROM events WHERE id = NEW.event_id;
|
||||
END IF;
|
||||
NEW.taken_at := COALESCE(NEW.captured_at, game, NEW.created_at, CURRENT_TIMESTAMP);
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER photos_taken_at
|
||||
BEFORE INSERT OR UPDATE OF captured_at, event_id ON photos
|
||||
FOR EACH ROW EXECUTE FUNCTION photos_set_taken_at();
|
||||
|
||||
UPDATE photos AS p
|
||||
SET taken_at = COALESCE(p.captured_at, e.starts_at, p.created_at)
|
||||
FROM events e
|
||||
WHERE p.event_id = e.id;
|
||||
|
||||
UPDATE photos
|
||||
SET taken_at = COALESCE(captured_at, created_at)
|
||||
WHERE taken_at IS NULL;
|
||||
|
||||
ALTER TABLE "photos" ALTER COLUMN "taken_at" SET NOT NULL;
|
||||
ALTER TABLE "photos" ALTER COLUMN "taken_at" SET DEFAULT CURRENT_TIMESTAMP;
|
||||
|
||||
-- Recent photos: boosted first, then the newest game. The older archive keeps the created_at index.
|
||||
CREATE INDEX "photos_faces_pending_taken_idx"
|
||||
ON "photos" ("faces_boosted_at" DESC NULLS LAST, "taken_at" DESC)
|
||||
WHERE "faces_status" = 'PENDING';
|
||||
@@ -373,6 +373,9 @@ model Photo {
|
||||
width Int?
|
||||
height Int?
|
||||
capturedAt DateTime? @map("captured_at")
|
||||
/// When it was taken, or the game's start, or when the file arrived. Face analysis finishes the last month of
|
||||
/// this before the older archive.
|
||||
takenAt DateTime @default(now()) @map("taken_at")
|
||||
cameraMake String? @map("camera_make")
|
||||
cameraModel String? @map("camera_model")
|
||||
cameraSerial String? @map("camera_serial")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { sameTeam } from "../delivery/zerozero.js";
|
||||
import { sameTeam, sameWords, words } from "../delivery/zerozero.js";
|
||||
import { officialSigla } from "../sports/fpa-siglas.js";
|
||||
|
||||
/**
|
||||
@@ -27,11 +27,22 @@ export interface FolderGame {
|
||||
}
|
||||
|
||||
const LIGA_FOLDERS: [RegExp, string][] = [
|
||||
[/^lp\s*betclic\b|^liga\s*portugal\s*betclic\b|^i\s*liga\b/i, "ligaportugalbetclic"],
|
||||
[/^lp\s*betclic\b|^liga\s*portugal\s*betclic\b|^i\s*liga\b|^lp\s*bwin\b|^liga\s*portugal\s*bwin\b/i, "ligaportugalbetclic"],
|
||||
[/^lp\s*meu\s*super\b|^liga\s*portugal\s*(2\s*)?meu\s*super\b|^ii\s*liga\b|^liga\s*2\b/i, "ligaportugalmeusuper"],
|
||||
[/^allianz\s*cup\b|^taca\s*da\s*liga\b|^taça\s*da\s*liga\b/i, "allianzcup"],
|
||||
];
|
||||
|
||||
/** The name shown on a gallery when the folder names a Liga competition and the official game is not in yet. */
|
||||
const LIGA_NAMES: Record<string, string> = {
|
||||
ligaportugalbetclic: "Liga Portugal Betclic",
|
||||
ligaportugalmeusuper: "Liga Portugal Meu Super",
|
||||
allianzcup: "Allianz Cup",
|
||||
};
|
||||
|
||||
export function competitionLabel(id: string | null): string | null {
|
||||
return id ? (LIGA_NAMES[id.toLowerCase()] ?? null) : null;
|
||||
}
|
||||
|
||||
const toSeason = (a: string, b: string): string | null => {
|
||||
const start = a.length === 2 ? 2000 + Number(a) : Number(a);
|
||||
const end = b.length === 2 ? 2000 + Number(b) : Number(b);
|
||||
@@ -44,17 +55,35 @@ function seasonIn(name: string): string | null {
|
||||
return m ? toSeason(m[1]!, m[2]!) : null;
|
||||
}
|
||||
|
||||
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date). */
|
||||
/**
|
||||
* "ALMADA AC / EXT. GIL EANES": a slash between two names, in any archive. A slash with no letters on a side
|
||||
* ("2025/2026", "26/27") is a season, not two teams. The slash may be the ascii one or a lookalike the cloud kept
|
||||
* in a folder name.
|
||||
*/
|
||||
export function slashSides(name: string): { home: string; away: string } | null {
|
||||
const m = /^(.+?[A-Za-zÀ-ÿ].*?)\s+[//∕⁄]\s+(.+?[A-Za-zÀ-ÿ].+)$/.exec(name.trim());
|
||||
if (!m) return null;
|
||||
const side = (s: string) => s.replace(/\s+/g, " ").trim();
|
||||
const home = side(m[1]!);
|
||||
const away = side(m[2]!);
|
||||
if (!/[A-Za-zÀ-ÿ]{2}/.test(home) || !/[A-Za-zÀ-ÿ]{2}/.test(away)) return null;
|
||||
return { home, away };
|
||||
}
|
||||
|
||||
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date), "ALMADA AC / EXT. GIL EANES". */
|
||||
function teamsIn(name: string, dashOk = false): { home: string; away: string } | null {
|
||||
// "A x B", "A vs B", "A va B" (a slip for vs); "A - B" only after a date or a game's number, or two codes
|
||||
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game.
|
||||
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game. "A / B" is two teams in every archive.
|
||||
const dash = /^(.+?)\s+[-–]\s+(.+)$/.exec(name.trim());
|
||||
const codes = dash && /^[A-Z]{2,6}$/.test(dash[1]!.trim()) && /^[A-Z]{2,6}$/.test(dash[2]!.trim());
|
||||
const slash = slashSides(name);
|
||||
const m =
|
||||
/^(.+?)\s+(?:x|vs\.?|va|v)\s+(.+)$/i.exec(name.trim()) ??
|
||||
(dashOk || codes ? dash : null) ??
|
||||
// "POR_FRA", "PTxES": two codes
|
||||
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim());
|
||||
(slash ? { 1: slash.home, 2: slash.away } : null) ??
|
||||
// "POR_FRA", "PTxES": two codes. "CPACxRAFC", "1.GVFCxPSC": the Liga's old folders glue the siglas.
|
||||
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim()) ??
|
||||
/^([A-Za-z]{2,6})x([A-Za-z]{2,6})$/.exec(name.trim());
|
||||
if (!m) return null;
|
||||
const clean = (s: string) => s.replace(/\s*[([].*?[)\]]\s*$/, "").replace(/\s+/g, " ").trim();
|
||||
// "1ª J - FCG x VFC", "Champions - FCP x HCMZ": the home side is after the last dash; "SCP x SLB - Final": the
|
||||
@@ -67,6 +96,13 @@ function teamsIn(name: string, dashOk = false): { home: string; away: string } |
|
||||
return home && away ? { home, away } : null;
|
||||
}
|
||||
|
||||
/** A stored side that is really two clubs ("ALMADA AC / EXT. GIL EANES"): both names, for the teams directory. */
|
||||
export function directorySides(name: string): string[] {
|
||||
if (!slashSides(name)) return [name];
|
||||
const teams = teamsIn(name, true);
|
||||
return teams ? [teams.home, teams.away] : [name];
|
||||
}
|
||||
|
||||
const foldName = (s: string) =>
|
||||
s
|
||||
.normalize("NFD")
|
||||
@@ -154,8 +190,20 @@ export interface FolderPlace {
|
||||
* Where a gallery folder sits: the occasion it belongs to (a game's halves and warm-up are the game; an athlete's
|
||||
* folder in a photo session is the session, with that athlete named), and a name for it.
|
||||
*/
|
||||
/**
|
||||
* Path segments. A slash with spaces on both sides is how a folder names two clubs ("ALMADA AC / EXT. GIL EANES"),
|
||||
* not another directory. A slash without spaces stays a directory ("2025/2026", "/FPA/Fotos").
|
||||
*/
|
||||
export function pathParts(path: string): string[] {
|
||||
const glued = path.replace(/([^\s/])\s+\/\s+([^\s/])/g, "$1\u0001$2");
|
||||
return glued
|
||||
.split("/")
|
||||
.filter(Boolean)
|
||||
.map((part) => part.replaceAll("\u0001", " / "));
|
||||
}
|
||||
|
||||
export function describeFolder(path: string): FolderPlace {
|
||||
const parts = path.split("/").filter(Boolean);
|
||||
const parts = pathParts(path);
|
||||
let section: string | null = null;
|
||||
let people: FolderPerson[] = [];
|
||||
// At most three levels up ("Torneio/_TEAM PORTUGAL_/PHOTOS MATCH/POR_FRA/M4 - ICONSPORT" stops at the game).
|
||||
@@ -190,7 +238,7 @@ export function describeFolder(path: string): FolderPlace {
|
||||
export function parseFolder(path: string): FolderGame | null {
|
||||
// A game's photos may sit one or two levels down (a folder per photographer, "Selecionadas", the halves): the
|
||||
// game is the nearest folder above whose name is one.
|
||||
const parts = describeFolder(path).occasion.split("/").filter(Boolean);
|
||||
const parts = pathParts(describeFolder(path).occasion);
|
||||
for (let up = 0; up <= 2 && parts.length - up > 0; up++) {
|
||||
const game = parseGameFolder(parts.slice(0, parts.length - up));
|
||||
if (game) return game;
|
||||
@@ -433,6 +481,40 @@ export function canonicalTeam(name: string, teams: readonly { name: string; abbr
|
||||
return fits.length === 1 ? fits[0]!.name : label;
|
||||
}
|
||||
|
||||
/**
|
||||
* `canonicalTeam` for many names against the same teams: each team's folded names, words and code are worked out
|
||||
* once, not once per name (thousands of folder names times every Liga team took minutes).
|
||||
*/
|
||||
export function teamMatcher(teams: readonly { name: string; abbreviation: string | null; slug: string }[]): (name: string) => string {
|
||||
const prepared = teams.map((t) => {
|
||||
const sigla = officialSigla(t.name);
|
||||
return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "" };
|
||||
});
|
||||
return (raw: string) => {
|
||||
const label = teamLabel(raw);
|
||||
if (!label) return raw.trim();
|
||||
const n = fold(label);
|
||||
if (!n) return label;
|
||||
const variant = isVariantSide(label);
|
||||
const nameWords = words(label);
|
||||
const short = label.trim().length <= 6 && !/\s/.test(label.trim());
|
||||
const fits = new Map<string, (typeof prepared)[number]["t"]>();
|
||||
for (const p of prepared) {
|
||||
// The same tests as isTeam, in the same order.
|
||||
if (variant !== p.variant && p.abbr !== n) continue;
|
||||
const fit =
|
||||
(!!p.t.abbreviation && p.abbr === n) ||
|
||||
p.slug === n ||
|
||||
p.name === n ||
|
||||
sameWords(nameWords, p.words) ||
|
||||
(!!p.sigla && p.sigla === n) ||
|
||||
(short && isInitials(label, p.t.name));
|
||||
if (fit) fits.set(p.name, p.t);
|
||||
}
|
||||
return fits.size === 1 ? [...fits.values()][0]!.name : label;
|
||||
};
|
||||
}
|
||||
|
||||
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[], now = new Date()): FixtureCandidate | null {
|
||||
// A game still to be played has no photos yet.
|
||||
fixtures = fixtures.filter((f) => f.startsAt.getTime() <= now.getTime() + 6 * 3600_000);
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { Readable } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import { NextcloudError } from "../delivery/nextcloud.js";
|
||||
import { isTransientStatus, NextcloudError } from "../delivery/nextcloud.js";
|
||||
|
||||
/** Backoff before retrying a transient failure (a locked file, Nextcloud briefly unavailable): one request, then up to three retries. */
|
||||
const RETRY_DELAYS_MS = [200, 600, 1500];
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/**
|
||||
* Reading a Nextcloud for the archive: list folders (WebDAV PROPFIND with Nextcloud's file ids and etags),
|
||||
@@ -46,7 +50,8 @@ const encodePath = (p: string) => p.split("/").map(encodeURIComponent).join("/")
|
||||
export async function startLogin(baseUrl: string, fetchImpl: typeof fetch = fetch, appName = "PhotoReport Arquivo"): Promise<LoginStart> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" } });
|
||||
// A cloud that does not answer is said at once, not after the proxy gives up.
|
||||
res = await fetchImpl(`${cleanBase(baseUrl)}/index.php/login/v2`, { method: "POST", headers: { "user-agent": appName, accept: "application/json" }, signal: AbortSignal.timeout(15_000) });
|
||||
} catch (err) {
|
||||
throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
|
||||
}
|
||||
@@ -179,11 +184,25 @@ export class CloudClient {
|
||||
return `${this.base}${this.davRoot}${encodePath(path.startsWith("/") ? path : `/${path}`)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* One photo's 423 (locked while the owner's client syncs it) or a cloud's 503 under load is usually gone a
|
||||
* moment later: retried here so it never reaches the caller as a failure, instead of one error per blip.
|
||||
*/
|
||||
private async call(method: string, url: string, init: RequestInit = {}): Promise<Response> {
|
||||
try {
|
||||
return await this.fetchImpl(url, { ...init, method, headers: { authorization: this.authHeader, ...(init.headers ?? {}) } });
|
||||
} catch (err) {
|
||||
throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await this.fetchImpl(url, { ...init, method, headers: { authorization: this.authHeader, ...(init.headers ?? {}) } });
|
||||
} catch (err) {
|
||||
if (attempt >= RETRY_DELAYS_MS.length) throw new NextcloudError(`network error: ${(err as Error).message}`, 0);
|
||||
await sleep(RETRY_DELAYS_MS[attempt]!);
|
||||
continue;
|
||||
}
|
||||
if (isTransientStatus(res.status) && attempt < RETRY_DELAYS_MS.length) {
|
||||
await sleep(RETRY_DELAYS_MS[attempt]!);
|
||||
continue;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,7 @@ const ReviewQuery = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(120).default(60),
|
||||
});
|
||||
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 Recognition = z.object({ enabled: z.boolean(), removeConfirmed: z.boolean().default(false) });
|
||||
|
||||
export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: Deps) {
|
||||
@@ -74,6 +75,43 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
return { name: v.n, canReview, canManagePeople: editable === "all", pending };
|
||||
});
|
||||
|
||||
/**
|
||||
* People an editor may name a face as. The official face, the club and the shirt number travel with the name,
|
||||
* so two players who share a name are not the same choice.
|
||||
*/
|
||||
app.get("/v1/archive/:sourceId/people/search", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
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 } });
|
||||
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,
|
||||
COALESCE(p.club, t.name) AS club,
|
||||
COALESCE(p.number, sp.number) AS number,
|
||||
p.reference_key IS NOT NULL AS reference
|
||||
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.organization_id = ${source.organizationId}::uuid
|
||||
AND p.recognition_off_at IS NULL
|
||||
AND (
|
||||
p.name ILIKE ${like}
|
||||
OR COALESCE(p.club, '') ILIKE ${like}
|
||||
OR COALESCE(t.name, '') ILIKE ${like}
|
||||
OR COALESCE(sp.full_name, '') ILIKE ${like}
|
||||
OR p.number = ${q}
|
||||
OR sp.number = ${q}
|
||||
)
|
||||
ORDER BY (p.number = ${q} OR sp.number = ${q}) DESC, (p.reference_key IS NOT NULL) DESC, length(p.name)
|
||||
LIMIT 8`;
|
||||
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 })),
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -132,7 +170,7 @@ export async function registerArchiveReviewRoutes(app: FastifyInstance, deps: De
|
||||
row_number() OVER (PARTITION BY f.group_id ORDER BY f.sharpness DESC NULLS LAST, f.score DESC) AS rank
|
||||
FROM faces f JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${scope.sql}
|
||||
WHERE f.group_id = ANY(${ids}::uuid[])
|
||||
) s WHERE rank <= 4`
|
||||
) s WHERE rank <= 8`
|
||||
: [];
|
||||
const photos = await db.photo.findMany({
|
||||
where: { id: { in: [...new Set(samples.map((s) => s.photo_id))] } },
|
||||
|
||||
@@ -14,8 +14,7 @@ import type { IngestLogger, IngestService } from "../ingest/service.js";
|
||||
import { ingestWindow } from "../library/events.js";
|
||||
import { waitUntil } from "../lib/idle.js";
|
||||
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
|
||||
import { describeFolder, type FolderGame, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js";
|
||||
import { canonicalTeam, exhibitionName, isExhibition } from "./match.js";
|
||||
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js";
|
||||
|
||||
export const IMAGE = /\.(jpe?g)$/i;
|
||||
/** How long the person has to authorise in their cloud (Nextcloud keeps the flow 20 minutes). */
|
||||
@@ -24,6 +23,8 @@ const LOGIN_TTL_MS = 20 * 60_000;
|
||||
export const RESCAN_EVERY_MS = 6 * 3600_000;
|
||||
const MAX_ATTEMPTS = 3;
|
||||
const DAY_MS = 86_400_000;
|
||||
/** A finished Liga Portugal league (18 clubs, 34 rounds). A past season with fewer games was only partly read. */
|
||||
const LIGA_LEAGUE_FULL = 280;
|
||||
/** Played FPA games of a season above which it counts as read (a national season has well over a thousand). */
|
||||
const FPA_SEASON_KNOWN = 300;
|
||||
/** The season ("20252026", July to June) a game's day falls in. */
|
||||
@@ -373,7 +374,7 @@ export class ArchiveService {
|
||||
if (fixture) return { eventId: await this.eventForFixture(source, fixture), matchedBy: "FIXTURE" };
|
||||
const teams = await this.teamNames(game, source);
|
||||
const day = game.day ?? (game.month ? `${game.month}-15` : null);
|
||||
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, competitionName: exhibitionName(game), round: game.round, season: game.season }, day, modified, folder.eventId), matchedBy: "NAME" };
|
||||
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, competitionName: exhibitionName(game) ?? competitionLabel(game.competition), round: game.round, season: game.season }, day, modified, folder.eventId), matchedBy: "NAME" };
|
||||
}
|
||||
return { eventId: await this.eventForOccasion(source, folder, modified), matchedBy: "FOLDER" };
|
||||
}
|
||||
@@ -615,8 +616,14 @@ export class ArchiveService {
|
||||
const season = game.season ?? (day ? seasonOfDay(day) : null);
|
||||
if (season && liga && this.deps.ligaSeason && !this.seasonsAsked.has(`LIGA|${season}`)) {
|
||||
this.seasonsAsked.add(`LIGA|${season}`);
|
||||
const known = await this.deps.db.sportsFixture.count({ where: { season, competition: { provider: "LIGA" } } });
|
||||
if (!known) await this.deps.ligaSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: liga season not read"));
|
||||
// One read brings the league and the cup. A cup already stored, or a league only partly read, must not hide
|
||||
// the rest of that year: a finished league is 306 games, and a past season under that is read again.
|
||||
const league = await this.deps.db.sportsFixture.count({
|
||||
where: { season, competition: { provider: "LIGA", externalId: "ligaportugalbetclic" } },
|
||||
});
|
||||
const past = season.replace(/\D/g, "") < seasonOf(lisbonDay(new Date()));
|
||||
if ((past && league < LIGA_LEAGUE_FULL) || (!past && league === 0))
|
||||
await this.deps.ligaSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: liga season not read"));
|
||||
}
|
||||
if (season && !liga && this.deps.fpaSeason && !this.seasonsAsked.has(`FPA|${season}`)) {
|
||||
this.seasonsAsked.add(`FPA|${season}`);
|
||||
@@ -805,12 +812,17 @@ export class ArchiveService {
|
||||
return moved;
|
||||
}
|
||||
|
||||
/**
|
||||
* One statement, not read-then-delete: a read-then-delete let another gallery just matched to this event (its
|
||||
* `setFolderEvent` landing in the gap after the count was read) get silently taken back out by the delete, and
|
||||
* then fail with a foreign key error moving its photos in here — the "empty" check now lives in the delete's own
|
||||
* `WHERE`, so Postgres re-reads it against whatever just committed (BIT-31531).
|
||||
*/
|
||||
private async dropIfEmpty(eventId: string): Promise<void> {
|
||||
const { db } = this.deps;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { archivedAt: true, _count: { select: { photos: true, cloudFolders: true, galleries: true, deliveries: true } } } });
|
||||
if (!event?.archivedAt) return;
|
||||
const c = event._count;
|
||||
if (c.photos + c.cloudFolders + c.galleries + c.deliveries === 0) await db.event.delete({ where: { id: eventId } }).catch(() => undefined);
|
||||
await db.event.deleteMany({
|
||||
where: { id: eventId, archivedAt: { not: null }, photos: { none: {} }, cloudFolders: { none: {} }, galleries: { none: {} }, deliveries: { none: {} } },
|
||||
});
|
||||
}
|
||||
|
||||
// --- indexing --------------------------------------------------------------------------------------------------
|
||||
@@ -962,7 +974,10 @@ export class ArchiveService {
|
||||
await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } });
|
||||
// A file moved since the walk: read its folder again next time.
|
||||
if (gone) await db.cloudFolder.update({ where: { id: file.folderId }, data: { etag: null } });
|
||||
log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
|
||||
// A transient blip is given a free retry and costs nothing (BIT-31513): logged at info so it never reaches
|
||||
// the error hub as a warning, unlike a real decoding/matching failure or one burning the attempt budget.
|
||||
if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry");
|
||||
else log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { SecretBox } from "../delivery/secrets.js";
|
||||
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 { canonicalTeam, describeFolder } from "./match.js";
|
||||
import { describeFolder, directorySides, teamMatcher } from "./match.js";
|
||||
import type { FaceService } from "../faces/service.js";
|
||||
import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
|
||||
import { registerArchiveDownloadRoutes } from "./downloads.js";
|
||||
@@ -381,17 +381,41 @@ export async function registerArchiveViewerRoutes(
|
||||
* Leixões SC"), and the known team's official name when exactly one fits ("SCP", "Sporting" → "Sporting CP").
|
||||
* Each with the names its galleries use, so filtering by it finds them all.
|
||||
*/
|
||||
/**
|
||||
* Each source's folder team names and the known team they are (`canonicalTeam` compares a name with every known
|
||||
* team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while,
|
||||
* shared by every viewer of the source.
|
||||
*/
|
||||
const canonicalNames = new Map<string, { at: number; known: Promise<(name: string) => string>; names: Map<string, string> }>();
|
||||
const CANONICAL_TTL_MS = 6 * 3600_000;
|
||||
const DIRECTORY_WAIT_MS = 10_000;
|
||||
const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise<Map<string, { names: Set<string>; galleries: number }>> => {
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
|
||||
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
|
||||
const known = await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
|
||||
let memo = canonicalNames.get(sourceId);
|
||||
if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) {
|
||||
const known = (async () => {
|
||||
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
|
||||
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
|
||||
return teamMatcher(await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } }));
|
||||
})();
|
||||
known.catch(() => canonicalNames.delete(sourceId));
|
||||
memo = { at: Date.now(), known, names: new Map() };
|
||||
canonicalNames.set(sourceId, memo);
|
||||
}
|
||||
const canonical = await memo.known;
|
||||
const out = new Map<string, { names: Set<string>; galleries: number }>();
|
||||
const byKey = new Map<string, string>();
|
||||
const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
||||
let fresh = 0;
|
||||
for (const g of games)
|
||||
for (const raw of [g.home, g.away]) {
|
||||
for (const raw of [g.home, g.away].flatMap((side) => (side ? directorySides(side) : []))) {
|
||||
if (!raw) continue;
|
||||
const name = canonicalTeam(raw, known);
|
||||
let name = memo.names.get(raw);
|
||||
if (name === undefined) {
|
||||
name = canonical(raw);
|
||||
memo.names.set(raw, name);
|
||||
// Let other requests in between the new names (the first reading of a big archive).
|
||||
if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r));
|
||||
}
|
||||
const key = fold(name);
|
||||
const label = byKey.get(key) ?? name;
|
||||
byKey.set(key, label);
|
||||
@@ -403,6 +427,21 @@ export async function registerArchiveViewerRoutes(
|
||||
return out;
|
||||
};
|
||||
|
||||
// The team names of every archive read once in the background after a start, so the first viewer of "Equipas"
|
||||
// does not wait for them (and the proxy does not give up first).
|
||||
const warmTeams = async () => {
|
||||
const sources = await db.cloudSource.findMany({ where: { secretEnc: { not: null } }, select: { id: true } });
|
||||
for (const s of sources) {
|
||||
const rows = await db.cloudFolder.findMany({ where: { sourceId: s.id, matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } });
|
||||
await teamGroups(s.id, rows.flatMap((r) => (r.event ? [r.event] : [])));
|
||||
}
|
||||
};
|
||||
if (!process.env.VITEST) {
|
||||
app.addHook("onReady", async () => {
|
||||
setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref();
|
||||
});
|
||||
}
|
||||
|
||||
/** Galleries the viewer may see, newest first; by words in the name, a team or a player. */
|
||||
app.get("/v1/archive/:sourceId/galleries", async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
@@ -459,7 +498,7 @@ export async function registerArchiveViewerRoutes(
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const v = viewerOf(req, sourceId);
|
||||
const visible = await visibleFolders(v);
|
||||
const teams = await remembered(sourceId, "teams", visible, async () => {
|
||||
const reading = remembered(sourceId, "teams", visible, async () => {
|
||||
const folders = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { id: true, home: true, away: true } } } });
|
||||
// Teams of games only (a session or a day of an event is named in "home" too), each game counted once.
|
||||
const games = new Map<string, { home: string; away: string }>();
|
||||
@@ -468,6 +507,10 @@ export async function registerArchiveViewerRoutes(
|
||||
.map(([name, g]) => ({ name, galleries: g.galleries }))
|
||||
.sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name));
|
||||
});
|
||||
// The first reading of a big archive can take a while: say so (the page asks again) rather than let the proxy
|
||||
// time out. The reading goes on and is kept for the next ask.
|
||||
const teams = await Promise.race([reading, new Promise<null>((r) => setTimeout(() => r(null), DIRECTORY_WAIT_MS).unref())]);
|
||||
if (!teams) return { teams: [], preparing: true };
|
||||
return { teams };
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,14 @@ const Env = z.object({
|
||||
.default("0")
|
||||
.transform((v) => v === "1" || v === "true"),
|
||||
DATABASE_URL: z.string().url(),
|
||||
/** Prisma/pg pool size of one API process (infra/pm2/api.config.cjs runs API_INSTANCES of these). */
|
||||
API_DB_POOL_SIZE: z.coerce.number().int().positive().default(10),
|
||||
/** PM2 cluster instances for the API; mirror a pm2-api.override.json `instances` change here too. */
|
||||
API_INSTANCES: z.coerce.number().int().positive().default(2),
|
||||
/** Postgres' max_connections, so the worker leaves it enough room for the API and admin/migration connections. */
|
||||
DB_MAX_CONNECTIONS: z.coerce.number().int().positive().default(100),
|
||||
/** Postgres' superuser_reserved_connections: never available to the app, whatever max_connections says. */
|
||||
DB_SUPERUSER_RESERVED_CONNECTIONS: z.coerce.number().int().nonnegative().default(3),
|
||||
JWT_SECRET: z.string().min(32, "JWT_SECRET must have at least 32 characters"),
|
||||
ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),
|
||||
REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
|
||||
|
||||
@@ -8,6 +8,9 @@ export interface NextcloudAuth {
|
||||
password: string;
|
||||
}
|
||||
|
||||
/** Worth retrying: network trouble, rate limits and server errors (a locked file, Nextcloud under load). Auth and path errors are not. */
|
||||
export const isTransientStatus = (status: number): boolean => status === 0 || status === 408 || status === 423 || status === 429 || status >= 500;
|
||||
|
||||
export class NextcloudError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -16,9 +19,8 @@ export class NextcloudError extends Error {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/** Worth retrying: network trouble, rate limits and server errors. Auth and path errors are not. */
|
||||
get transient(): boolean {
|
||||
return this.status === 0 || this.status === 408 || this.status === 423 || this.status === 429 || this.status >= 500;
|
||||
return isTransientStatus(this.status);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -442,7 +442,10 @@ export class DeliveryService {
|
||||
let cloud: { file: string; done: () => Promise<void> } | null = null;
|
||||
if (!item.photo.originalStored && this.deps.originals) {
|
||||
cloud = await this.deps.originals.downloadOriginal(item.photoId).catch((err) => {
|
||||
log.warn({ err, itemId }, "delivery: original not read from the cloud");
|
||||
// A transient cloud blip (BIT-31513) is retried below (QUEUED with a backoff), so it is logged at info,
|
||||
// not warn, to keep it out of the error hub like the archive indexer's own download already is.
|
||||
if (isTransient(err)) log.info({ err, itemId }, "delivery: original download blipped from the cloud, retrying");
|
||||
else log.warn({ err, itemId }, "delivery: original not read from the cloud");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -301,7 +301,7 @@ export function zerozeroGameId(input: string): string | null {
|
||||
}
|
||||
|
||||
const STOP = new Set(["fc", "sc", "cf", "cd", "ud", "sad", "ac", "ad", "gd", "cs", "sl", "sport", "clube", "club", "futebol", "football", "afc", "the", "de", "da", "do", "e", "fk", "sk"]);
|
||||
const words = (name: string) =>
|
||||
export const words = (name: string) =>
|
||||
name
|
||||
.normalize("NFD")
|
||||
.replace(/[̀-ͯ]/g, "")
|
||||
@@ -312,8 +312,11 @@ const words = (name: string) =>
|
||||
|
||||
/** Whether two names are the same team ("Torreense" / "SC Torreense", "Sporting CP" / "Sporting"). */
|
||||
export function sameTeam(a: string, b: string): boolean {
|
||||
const wa = words(a);
|
||||
const wb = words(b);
|
||||
return sameWords(words(a), words(b));
|
||||
}
|
||||
|
||||
/** `sameTeam` on names already split into `words` (to compare one name with many teams). */
|
||||
export function sameWords(wa: string[], wb: string[]): boolean {
|
||||
if (!wa.length || !wb.length) return false;
|
||||
const [short, long] = wa.length <= wb.length ? [wa, wb] : [wb, wa];
|
||||
return short.every((w) => long.some((x) => x === w || (w.length >= 4 && (x.startsWith(w) || w.startsWith(x)))));
|
||||
|
||||
@@ -109,6 +109,45 @@ export async function registerFaceRoutes(
|
||||
return { groups: out, pending, unclear, available: deps.engineOnline ? deps.engineOnline() : true };
|
||||
});
|
||||
|
||||
/** Suggested faces across the library, one row per group, so an editor can clear them while others are selecting. */
|
||||
app.get("/v1/orgs/:orgId/face-review", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
const groups = await db.faceGroup.findMany({
|
||||
where: { organizationId: orgId, personId: null, ignoredAt: null, suggestedPersonId: { not: null } },
|
||||
orderBy: [{ suggestionScore: "desc" }, { size: "desc" }],
|
||||
take: 80,
|
||||
include: {
|
||||
suggested: true,
|
||||
event: { select: { home: true, away: true, startsAt: true } },
|
||||
faces: {
|
||||
take: SAMPLES,
|
||||
orderBy: [{ sharpness: { sort: "desc", nulls: "last" } }, { score: "desc" }],
|
||||
select: { id: true, photoId: true, x0: true, y0: true, x1: true, y1: true, photo: { select: { width: true, height: true } } },
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
groups: groups.map((g) => ({
|
||||
id: g.id,
|
||||
eventId: g.eventId,
|
||||
size: g.size,
|
||||
suggestion: g.suggested && g.suggestionScore !== null ? { ...personOut(g.suggested)!, score: g.suggestionScore } : null,
|
||||
event: { title: g.event.away ? `${g.event.home} x ${g.event.away}` : g.event.home, startsAt: g.event.startsAt },
|
||||
samples: g.faces.map((f) => ({
|
||||
faceId: f.id,
|
||||
photoId: f.photoId,
|
||||
x0: f.x0,
|
||||
y0: f.y0,
|
||||
x1: f.x1,
|
||||
y1: f.y1,
|
||||
aspect: f.photo.width && f.photo.height ? f.photo.width / f.photo.height : 1.5,
|
||||
preview: signer.url(f.photoId, "preview"),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => {
|
||||
const { groupId } = GroupParams.parse(req.params);
|
||||
const body = ConfirmFaceGroup.parse(req.body);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { expandCodes, parseCodeList } from "@photoreport/metadata";
|
||||
import type { Db } from "../db.js";
|
||||
import { Prisma } from "../generated/prisma/client.js";
|
||||
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
|
||||
import type { FaceGroup, Person } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
@@ -16,7 +17,7 @@ export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
|
||||
|
||||
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
|
||||
import { numberContext, numbersIn, type NumberContext } from "./numbers.js";
|
||||
import { numberContext, numbersIn, rosterOf, type NumberContext } from "./numbers.js";
|
||||
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import type { FaceEngine } from "./process.js";
|
||||
|
||||
@@ -24,6 +25,8 @@ import type { FaceEngine } from "./process.js";
|
||||
const MIN_FACE_SIDE = 0.012;
|
||||
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
|
||||
export const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** Photos taken inside this window (or just arrived, when they have no date) are read before the older archive. */
|
||||
const RECENT_FACES = Prisma.sql`interval '30 days'`;
|
||||
|
||||
export class FaceRejected extends Error {
|
||||
constructor(readonly code: string) {
|
||||
@@ -55,11 +58,29 @@ export class FaceService {
|
||||
|
||||
async claim(limit: number): Promise<string[]> {
|
||||
if (limit <= 0) return [];
|
||||
// Asked for by hand ("Analisar caras"), whatever the date.
|
||||
const boosted = await this.claimWhere(limit, Prisma.sql`faces_boosted_at IS NOT NULL`, Prisma.sql`faces_boosted_at DESC`);
|
||||
let left = limit - boosted.length;
|
||||
if (left <= 0) return boosted;
|
||||
// The last month, newest game first. A gallery that just arrived of a current game is in here.
|
||||
const recent = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at >= now() - ${RECENT_FACES}`, Prisma.sql`taken_at DESC`);
|
||||
left -= recent.length;
|
||||
if (left <= 0) return [...boosted, ...recent];
|
||||
// The older archive, only once that month is clear. A folder that just arrived still comes before one that has been waiting.
|
||||
const rest = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at < now() - ${RECENT_FACES}`, Prisma.sql`created_at DESC`);
|
||||
return [...boosted, ...recent, ...rest];
|
||||
}
|
||||
|
||||
/** Locks and takes the next pending photos matching `where`, in `order`. */
|
||||
private async claimWhere(limit: number, where: Prisma.Sql, order: Prisma.Sql): Promise<string[]> {
|
||||
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
|
||||
UPDATE photos SET faces_status = 'RUNNING', updated_at = now()
|
||||
WHERE id IN (
|
||||
SELECT id FROM photos WHERE faces_status = 'PENDING' AND status = 'READY'
|
||||
ORDER BY faces_boosted_at DESC NULLS LAST, created_at DESC LIMIT ${limit} FOR UPDATE SKIP LOCKED
|
||||
SELECT id FROM photos
|
||||
WHERE faces_status = 'PENDING' AND status = 'READY' AND ${where}
|
||||
ORDER BY ${order}
|
||||
LIMIT ${limit}
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
RETURNING id`;
|
||||
return rows.map((r) => r.id);
|
||||
@@ -78,6 +99,27 @@ export class FaceService {
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos whose analysis failed, a few at a time, once they have been quiet for a few hours. Recent games first.
|
||||
* A photo that fails again waits before the next try, so one bad file does not sit at the front forever.
|
||||
*/
|
||||
async requeueFailed(limit = 40, now = new Date()): Promise<number> {
|
||||
const quietSince = new Date(now.getTime() - 6 * 3600_000);
|
||||
return Number(
|
||||
await this.deps.db.$executeRaw`
|
||||
UPDATE photos AS p
|
||||
SET faces_status = 'PENDING', updated_at = now()
|
||||
WHERE p.id IN (
|
||||
SELECT ph.id FROM photos ph
|
||||
JOIN organizations org ON org.id = ph.organization_id
|
||||
WHERE ph.faces_status = 'FAILED' AND ph.status = 'READY' AND org.biometrics_enabled
|
||||
AND ph.updated_at < ${quietSince}
|
||||
ORDER BY ph.taken_at DESC
|
||||
LIMIT ${limit}
|
||||
)`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos left without analysis in an organization that has face analysis on (they arrived while it was off, or
|
||||
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
|
||||
@@ -96,8 +138,8 @@ export class FaceService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The "Analisar caras" button: this event's photos go ahead of the oldest-first backlog, including ones already
|
||||
* pending. A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned
|
||||
* The "Analisar caras" button: this event's photos go ahead of the queue, including ones already pending.
|
||||
* A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned
|
||||
* is queued again.
|
||||
*/
|
||||
async boostEvent(eventId: string, now = new Date()): Promise<number> {
|
||||
@@ -271,9 +313,10 @@ export class FaceService {
|
||||
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
|
||||
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
|
||||
const ctx = await numberContext(db, eventId);
|
||||
// A game linked to its two clubs: only those squads. Another club's player who looks alike is not a guess.
|
||||
const squadIds = ctx?.teamIds.length ? await playerIdsOnSquads(db, ctx.teamIds, ctx.season) : null;
|
||||
const candidates = squadIds ? people.filter((p) => p.sportsPlayerId !== null && squadIds.has(p.sportsPlayerId)) : people;
|
||||
// A game: the match sheet first (players, coaches, referees who already have a face). A session has no sheet,
|
||||
// so the face is compared with everyone of that sport. The wider list is only for a face the sheet does not explain.
|
||||
const sheet = await rosterOf(db, eventId);
|
||||
const onSheet = sheet && sheet.length ? new Set(sheet) : null;
|
||||
const worn = new Map<string, string | null>();
|
||||
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
|
||||
const missing = ids.filter((id) => !worn.has(id));
|
||||
@@ -283,10 +326,10 @@ export class FaceService {
|
||||
}
|
||||
return worn;
|
||||
};
|
||||
for (const g of groups) {
|
||||
const pick = async (pool: typeof people, g: (typeof groups)[number], allowNumber: boolean) => {
|
||||
const { match, margin } = this.thresholds(g.model);
|
||||
const rejected = notThem.get(g.id);
|
||||
const ranked = candidates
|
||||
const ranked = pool
|
||||
.filter((p) => p.model === g.model && !rejected?.has(p.id))
|
||||
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
|
||||
.sort((a, b) => b.s - a.s);
|
||||
@@ -302,7 +345,7 @@ export class FaceService {
|
||||
} else if (ok && read && firstNumber === read.number) {
|
||||
// Face and shirt agree on the same player: surer than either alone.
|
||||
suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000;
|
||||
} else if (!ok && read) {
|
||||
} else if (!ok && read && allowNumber) {
|
||||
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones,
|
||||
// and when two of them wear it (one per team), the kit colour.
|
||||
const close = ranked.filter((r) => r.s >= match * 0.8);
|
||||
@@ -326,6 +369,13 @@ export class FaceService {
|
||||
suggestedPersonId = null;
|
||||
suggestionScore = null;
|
||||
}
|
||||
return { suggestedPersonId, suggestionScore };
|
||||
};
|
||||
for (const g of groups) {
|
||||
const first = onSheet ? people.filter((p) => onSheet.has(p.id)) : people;
|
||||
let { suggestedPersonId, suggestionScore } = await pick(first, g, true);
|
||||
// Nobody on the sheet: only then a face from outside it. The shirt stays with the two clubs.
|
||||
if (!suggestedPersonId && onSheet) ({ suggestedPersonId, suggestionScore } = await pick(people, g, false));
|
||||
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
|
||||
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
|
||||
}
|
||||
@@ -484,6 +534,15 @@ export class FaceService {
|
||||
const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId);
|
||||
await this.nameConfirmedPhotos([...new Set(photoIds)]);
|
||||
await this.refreshSuggestions(group.eventId);
|
||||
// The same person suggested in other games: their cards are read again with this face included, so confirming
|
||||
// one pulls the rest together instead of leaving a separate guess in every event.
|
||||
const others = await db.faceGroup.findMany({
|
||||
where: { suggestedPersonId: person.id, personId: null, ignoredAt: null, eventId: { not: group.eventId } },
|
||||
select: { eventId: true },
|
||||
distinct: ["eventId"],
|
||||
take: 25,
|
||||
});
|
||||
for (const other of others) await this.refreshSuggestions(other.eventId);
|
||||
this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId });
|
||||
return person;
|
||||
}
|
||||
@@ -712,31 +771,6 @@ export function normSport(s: string | null | undefined): string | null {
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Squad entries of these teams this season, plus the same player written under another season (the federation id,
|
||||
* or the same name at the same club). Null when this season's squad is not here yet: then a face may still be
|
||||
* matched more widely. An empty set means the squad is known and nobody outside it is a candidate.
|
||||
*/
|
||||
async function playerIdsOnSquads(db: Db, teamIds: string[], season: string): Promise<Set<string> | null> {
|
||||
const squad = await db.sportsPlayer.findMany({
|
||||
where: { teamId: { in: teamIds }, season },
|
||||
select: { id: true, teamId: true, name: true, externalId: true },
|
||||
});
|
||||
if (!squad.length) return null;
|
||||
const externalIds = [...new Set(squad.map((s) => s.externalId).filter((x): x is string => !!x))];
|
||||
const same = await db.sportsPlayer.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ id: { in: squad.map((s) => s.id) } },
|
||||
...squad.map((s) => ({ teamId: s.teamId, name: s.name })),
|
||||
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
|
||||
],
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
return new Set(same.map((s) => s.id));
|
||||
}
|
||||
|
||||
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
|
||||
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
|
||||
const rows = await db.$queryRaw<{ sport: string | null }[]>`
|
||||
@@ -810,6 +844,7 @@ export class FaceWorker {
|
||||
start(): void {
|
||||
void this.service.requeueStale();
|
||||
let missedAt = 0;
|
||||
let failedAt = 0;
|
||||
const tick = async () => {
|
||||
this.ticking = true;
|
||||
try {
|
||||
@@ -819,6 +854,11 @@ export class FaceWorker {
|
||||
const n = await this.service.queueMissed();
|
||||
if (n) this.opts.log.info({ photos: n }, "faces: queued photos left without analysis");
|
||||
}
|
||||
if (Date.now() - failedAt > 3_600_000) {
|
||||
failedAt = Date.now();
|
||||
const n = await this.service.requeueFailed();
|
||||
if (n) this.opts.log.info({ photos: n }, "faces: failed photos queued again");
|
||||
}
|
||||
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
|
||||
for (const id of ids) {
|
||||
|
||||
@@ -131,3 +131,40 @@ export class Pressure {
|
||||
return Math.max(1, Math.floor(full * this.share(burst)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How many Postgres connections the worker's pool may open for `wanted`, leaving room under `max` (Postgres'
|
||||
* `max_connections`) for: the API's own Prisma pool, one per PM2 cluster instance; each of those instances'
|
||||
* realtime connections (`attachRealtime` in `realtime.ts`: a 2-connection publish pool plus one dedicated
|
||||
* `LISTEN` client, so 3 per instance — not just the worker's own 1-connection remote broadcaster); one extra
|
||||
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
|
||||
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
|
||||
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
|
||||
* -state budget into Postgres' `superuser_reserved_connections`); Postgres' `superuser_reserved_connections`
|
||||
* itself (reserved below `max_connections`, never available to the app no matter how much headroom is left —
|
||||
* this is what "reserved for roles with the SUPERUSER attribute" means); and extra headroom for ad hoc
|
||||
* connections (migrations, scripts, psql, admin tools) that aren't sized here.
|
||||
*/
|
||||
export function dbConnectionBudget(
|
||||
wanted: number,
|
||||
{
|
||||
max = 100,
|
||||
apiInstances = 2,
|
||||
apiPoolSize = 10,
|
||||
realtimePerInstance = 3,
|
||||
apiReloadOverlap = 1,
|
||||
superuserReserved = 3,
|
||||
headroom = 10,
|
||||
}: {
|
||||
max?: number;
|
||||
apiInstances?: number;
|
||||
apiPoolSize?: number;
|
||||
realtimePerInstance?: number;
|
||||
apiReloadOverlap?: number;
|
||||
superuserReserved?: number;
|
||||
headroom?: number;
|
||||
} = {},
|
||||
): number {
|
||||
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
|
||||
return Math.max(1, Math.min(wanted, available));
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { createDb } from "./db.js";
|
||||
|
||||
preferIpv4();
|
||||
const config = loadConfig();
|
||||
const db = createDb(config.DATABASE_URL);
|
||||
const db = createDb(config.DATABASE_URL, config.API_DB_POOL_SIZE);
|
||||
const reporter = reporterFor(config);
|
||||
reporter.watchProcess("api");
|
||||
const app = await buildApp({ config, db, realtime: "socket", reporter });
|
||||
|
||||
@@ -42,6 +42,8 @@ export interface FixtureData {
|
||||
competitionName?: string;
|
||||
gender?: string | null;
|
||||
season: string;
|
||||
/** Liga named this season on the fixture. Absent means the caller asked for a season and Liga did not confirm it. */
|
||||
seasonNamed?: boolean;
|
||||
home: TeamData;
|
||||
away: TeamData;
|
||||
startsAt: Date;
|
||||
@@ -68,9 +70,19 @@ export interface OfficialData {
|
||||
|
||||
const TIMEOUT_MS = 20_000;
|
||||
|
||||
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text") {
|
||||
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`);
|
||||
/** An HTTP error from a federation's own API, with its status so callers can tell "not available yet" (4xx) from a real outage. */
|
||||
export class ProviderHttpError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text", timeoutMs = TIMEOUT_MS) {
|
||||
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
|
||||
if (!res.ok) throw new ProviderHttpError(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`, res.status);
|
||||
return as === "json" ? res.json() : res.text();
|
||||
}
|
||||
|
||||
@@ -111,11 +123,14 @@ const url = (...vs: unknown[]): string | null => {
|
||||
// --- Liga Portugal ------------------------------------------------------------------------------------------------
|
||||
|
||||
export const LIGA_COMPETITIONS = [
|
||||
{ externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", aliases: ["Liga Portugal Betclic"] },
|
||||
{ externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", aliases: ["Liga Portugal Meu Super", "Liga Portugal 2 Meu Super"] },
|
||||
{ externalId: "allianzcup", name: "Allianz Cup", aliases: ["Allianz Cup"] },
|
||||
// The same two leagues, under every sponsor Liga has used. A 2022 folder is "bwin"; 2026 is "Betclic".
|
||||
{ externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", aliases: ["Liga Portugal Betclic", "Liga Portugal bwin", "Liga NOS"] },
|
||||
{ externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", aliases: ["Liga Portugal Meu Super", "Liga Portugal 2 Meu Super", "Liga Portugal SABSEG", "LigaPro"] },
|
||||
{ externalId: "allianzcup", name: "Allianz Cup", aliases: ["Allianz Cup", "Allianz CUP", "Taça da Liga", "Taca da Liga"] },
|
||||
] as const;
|
||||
|
||||
const foldComp = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
|
||||
export class LigaProvider {
|
||||
static readonly BASE = "https://www.ligaportugal.pt/api/v1";
|
||||
private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" };
|
||||
@@ -125,7 +140,8 @@ export class LigaProvider {
|
||||
private async api(path: string, params: Record<string, string>): Promise<unknown> {
|
||||
const u = new URL(`${LigaProvider.BASE}/${path}`);
|
||||
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
|
||||
return get(this.fetcher, u.toString(), LigaProvider.HEADERS, "json");
|
||||
// The calendar is slow from the archive host. A short timeout used to abort a whole season after one month.
|
||||
return get(this.fetcher, u.toString(), LigaProvider.HEADERS, "json", 45_000);
|
||||
}
|
||||
|
||||
async teams(competition: string, season: string): Promise<TeamData[]> {
|
||||
@@ -219,18 +235,23 @@ export class LigaProvider {
|
||||
for (const day of days as { date?: string; fixtures?: Record<string, unknown>[] }[]) {
|
||||
for (const f of day.fixtures ?? []) {
|
||||
const name = str(f.competitionName) ?? "";
|
||||
const comp = LIGA_COMPETITIONS.find((c) => (c.aliases as readonly string[]).includes(name));
|
||||
const comp = LIGA_COMPETITIONS.find((c) => c.aliases.some((a) => foldComp(a) === foldComp(name)));
|
||||
const home = ligaTeam(f.homeTeam);
|
||||
const away = ligaTeam(f.awayTeam);
|
||||
const when = str(f.matchDate) ?? str(f.fixtureDate) ?? day.date;
|
||||
if (!comp || !home || !away || !when || f.canceledFixture) continue;
|
||||
const code = str(f.fixtureCode) ?? `${f.round ?? f.matchweekNumber}-${home.externalId}-${away.externalId}`;
|
||||
const finished = typeof f.fixtureStateTypeId === "number" && f.fixtureStateTypeId >= 5;
|
||||
const named = str(f.seasonCode);
|
||||
// Liga reuses fixtureCode every season: 10101 is a different match in 2023 and in 2025. The season is part
|
||||
// of the id, or the later year's import overwrites the earlier year.
|
||||
const seasonKey = named ?? season;
|
||||
out.push({
|
||||
externalId: code,
|
||||
externalId: `${seasonKey}-${code}`,
|
||||
competition: comp.externalId,
|
||||
competitionName: comp.name,
|
||||
season: str(f.seasonCode) ?? season,
|
||||
season: seasonKey,
|
||||
seasonNamed: named !== null,
|
||||
home,
|
||||
away,
|
||||
startsAt: new Date(when),
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
LigaProvider,
|
||||
type OfficialData,
|
||||
type PlayerData,
|
||||
ProviderHttpError,
|
||||
type TeamData,
|
||||
UEFA_COMPETITIONS,
|
||||
UEFA_PITCH_OFFICIALS,
|
||||
@@ -161,11 +162,27 @@ export class SportsService {
|
||||
async importLigaSeason(season: string): Promise<number> {
|
||||
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } });
|
||||
const byExternal = new Map(comps.map((c) => [c.externalId, c]));
|
||||
const asked = season.replace(/\D/g, "");
|
||||
let saved = 0;
|
||||
for (const month of [7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6]) {
|
||||
for (const f of await this.liga.month(month, season)) {
|
||||
// One slow month must not drop the rest of the year. It is tried twice; the months already read stay.
|
||||
let fixtures: Awaited<ReturnType<LigaProvider["month"]>> = [];
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
fixtures = await this.liga.month(month, season);
|
||||
break;
|
||||
} catch (err) {
|
||||
fixtures = [];
|
||||
this.deps.log.warn({ err, season, month, attempt }, "sports: liga month not read");
|
||||
}
|
||||
}
|
||||
for (const f of fixtures) {
|
||||
// Only a season Liga itself named. The fixture id includes that season, so another year is another row.
|
||||
if (!f.seasonNamed) continue;
|
||||
const theirs = f.season.replace(/\D/g, "");
|
||||
if (theirs !== asked) continue;
|
||||
const c = byExternal.get(f.competition);
|
||||
if (c) saved += await this.saveFixture(c, "LIGA", { ...f, season });
|
||||
if (c) saved += await this.saveFixture(c, "LIGA", f);
|
||||
}
|
||||
}
|
||||
this.deps.log.info({ season, saved }, "sports: liga season imported");
|
||||
@@ -848,10 +865,13 @@ export class SportsService {
|
||||
const fixture = event.fixture;
|
||||
if (!named.length && fixture?.competition.provider === "LIGA" && fixture.round) {
|
||||
try {
|
||||
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId);
|
||||
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId.replace(/^\d{8}-/, ""));
|
||||
if (named.length) await db.sportsFixture.update({ where: { id: fixture.id }, data: { officials: named as unknown as object } });
|
||||
} catch (err) {
|
||||
log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
|
||||
// Liga 400s a round's nominations until it publishes them, days before the match: expected, not an
|
||||
// outage, so it is logged at info to keep it out of the error hub (it is read again on the next refresh).
|
||||
if (err instanceof ProviderHttpError && err.status === 400) log.info({ err, fixture: fixture.id }, "sports: liga nominations not published yet for this round");
|
||||
else log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
|
||||
}
|
||||
}
|
||||
const officials = named.filter((o) => PEOPLE_OFFICIALS.includes(o.role));
|
||||
|
||||
+14
-3
@@ -5,7 +5,7 @@ import { preferIpv4 } from "./lib/prefer-ipv4.js";
|
||||
import { reporterFor } from "./lib/reporter.js";
|
||||
import pino from "pino";
|
||||
import { loadConfig } from "./config.js";
|
||||
import { planCapacity, Pressure } from "./lib/capacity.js";
|
||||
import { dbConnectionBudget, planCapacity, Pressure } from "./lib/capacity.js";
|
||||
import { modelsDir } from "./lib/models.js";
|
||||
import { createDb } from "./db.js";
|
||||
import { closeRenderer } from "./delivery/render.js";
|
||||
@@ -63,8 +63,19 @@ const capacity = planCapacity({
|
||||
delivery: config.DELIVERY_CONCURRENCY,
|
||||
});
|
||||
log.info(capacity, "capacity");
|
||||
// Enough connections for everything running at once, within Postgres' default 100 (the API keeps its own 10).
|
||||
const db = createDb(config.DATABASE_URL, Math.min(80, 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2)));
|
||||
// Enough connections for everything running at once, within what's left of Postgres' max_connections once the
|
||||
// API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster
|
||||
// and ad hoc connections (migrations, scripts, psql) have theirs.
|
||||
const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2);
|
||||
const db = createDb(
|
||||
config.DATABASE_URL,
|
||||
dbConnectionBudget(wanted, {
|
||||
max: config.DB_MAX_CONNECTIONS,
|
||||
apiInstances: config.API_INSTANCES,
|
||||
apiPoolSize: config.API_DB_POOL_SIZE,
|
||||
superuserReserved: config.DB_SUPERUSER_RESERVED_CONNECTIONS,
|
||||
}),
|
||||
);
|
||||
const storage = new LocalStorage(config.STORAGE_ROOT);
|
||||
const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed"));
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
|
||||
import { parseMultistatus } from "../src/archive/nextcloud.js";
|
||||
import { canonicalTeam, describeFolder, directorySides, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js";
|
||||
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
|
||||
import { ArchiveService, localDirs } from "../src/archive/service.js";
|
||||
import { SecretBox } from "../src/delivery/secrets.js";
|
||||
import { IngestService } from "../src/ingest/service.js";
|
||||
@@ -29,6 +29,44 @@ describe("archive folder names", () => {
|
||||
expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09A/20251102 - Madeira SAD x Colégio de Gaia")?.competition).toBe("PO09A");
|
||||
});
|
||||
|
||||
it("reads Liga bwin folders whose teams are written as one code", () => {
|
||||
expect(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")).toMatchObject({
|
||||
home: "CPAC",
|
||||
away: "RAFC",
|
||||
day: null,
|
||||
season: "20222023",
|
||||
competition: "ligaportugalbetclic",
|
||||
round: "11",
|
||||
});
|
||||
expect(parseFolder("/LPbwin - 22-23/JORNADA 1/1.GVFCxPSC")).toMatchObject({ home: "GVFC", away: "PSC", round: "1", competition: "ligaportugalbetclic" });
|
||||
const t = (name: string, abbreviation: string) => ({ name, abbreviation, slug: name.toLowerCase() });
|
||||
const fixture: FixtureCandidate = {
|
||||
id: "cpac",
|
||||
startsAt: new Date("2022-10-29T19:30:00Z"),
|
||||
season: "20222023",
|
||||
round: "11",
|
||||
competition: { externalId: "ligaportugalbetclic" },
|
||||
homeTeam: t("Casa Pia AC", "CPAC"),
|
||||
awayTeam: t("Rio Ave FC", "RAFC"),
|
||||
};
|
||||
expect(pickFixture(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")!, [fixture], new Date("2026-10-19T00:00:00Z"))?.id).toBe("cpac");
|
||||
});
|
||||
|
||||
it("reads a slash between two clubs, in any archive, and leaves a season slash alone", () => {
|
||||
expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09/20250913 - ALMADA AC / EXT. GIL EANES")).toMatchObject({
|
||||
home: "ALMADA AC",
|
||||
away: "EXT. GIL EANES",
|
||||
day: "2025-09-13",
|
||||
season: "20252026",
|
||||
competition: "PO09",
|
||||
});
|
||||
expect(parseFolder("/Liga/04.11.23 ALMADA AC / EXT. GIL EANES")).toMatchObject({ home: "ALMADA AC", away: "EXT. GIL EANES", day: "2023-11-04" });
|
||||
expect(directorySides("ALMADA AC / EXT. GIL EANES")).toEqual(["ALMADA AC", "EXT. GIL EANES"]);
|
||||
expect(parseFolder("/x/20250913 - 2025/2026")).toBeNull();
|
||||
expect(parseFolder("/x/20250913 - Final / Video")).toBeNull();
|
||||
expect(directorySides("Sporting CP")).toEqual(["Sporting CP"]);
|
||||
});
|
||||
|
||||
it("reads Liga folders: competition and season from the top, matchday, numbered games", () => {
|
||||
expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga")).toMatchObject({
|
||||
home: "Sporting CP",
|
||||
@@ -224,6 +262,10 @@ describe("archive folder names", () => {
|
||||
expect(canonicalTeam("06_SPORTING CP", known)).toBe("Sporting CP");
|
||||
expect(canonicalTeam("02.2024 Benfica B", known)).toBe("SL Benfica B");
|
||||
expect(canonicalTeam("09.2023 Leiria", known)).toBe("U. Leiria");
|
||||
// The prepared matcher (many names, same teams) answers the same.
|
||||
const match = teamMatcher(known);
|
||||
for (const name of ["01 SCP", "06_SPORTING CP", "02.2024 Benfica B", "09.2023 Leiria", "Benfica", "UDL", "SLB B", "FC Porto", "", "12"])
|
||||
expect(match(name)).toBe(canonicalTeam(name, known));
|
||||
});
|
||||
|
||||
it("picks the one fixture with those teams on that day", () => {
|
||||
@@ -271,6 +313,63 @@ describe("WebDAV listing", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("CloudClient retries transient failures", () => {
|
||||
const whoami = (url: URL) => (url.pathname.endsWith("/ocs/v2.php/cloud/user") ? Response.json({ ocs: { data: { id: "peter" } } }) : null);
|
||||
|
||||
it("retries a 423/503 blip on a download and succeeds, instead of failing on the first try", async () => {
|
||||
let calls = 0;
|
||||
const fetchImpl: typeof fetch = async (input) => {
|
||||
const url = new URL(String(input));
|
||||
const who = whoami(url);
|
||||
if (who) return who;
|
||||
calls++;
|
||||
return calls <= 2 ? new Response(null, { status: 503 }) : new Response(new Uint8Array(Buffer.from("hello")), { status: 200 });
|
||||
};
|
||||
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-"));
|
||||
try {
|
||||
await client.download("/a.jpg", path.join(dir, "out.jpg"));
|
||||
expect(calls).toBe(3);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("gives up after exhausting retries and throws a transient NextcloudError", async () => {
|
||||
const fetchImpl: typeof fetch = async (input) => {
|
||||
const url = new URL(String(input));
|
||||
return whoami(url) ?? new Response(null, { status: 503 });
|
||||
};
|
||||
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-"));
|
||||
try {
|
||||
await expect(client.download("/a.jpg", path.join(dir, "out.jpg"))).rejects.toMatchObject({ status: 503 });
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("retries a 503 blip on a PROPFIND (BIT-31498) and succeeds, instead of failing the whole walk", async () => {
|
||||
const multistatus = `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
|
||||
<d:response><d:href>/remote.php/dav/files/peter/FPA/Fotos/</d:href>
|
||||
<d:propstat><d:prop><d:getetag>"abc"</d:getetag><d:resourcetype><d:collection/></d:resourcetype><oc:fileid>10</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
|
||||
</d:response>
|
||||
</d:multistatus>`;
|
||||
let calls = 0;
|
||||
const fetchImpl: typeof fetch = async (input) => {
|
||||
const url = new URL(String(input));
|
||||
const who = whoami(url);
|
||||
if (who) return who;
|
||||
calls++;
|
||||
return calls <= 2 ? new Response(null, { status: 503 }) : new Response(multistatus, { status: 207 });
|
||||
};
|
||||
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
|
||||
const { self } = await client.list("/FPA/Fotos");
|
||||
expect(self.fileId).toBe("10");
|
||||
expect(calls).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
interface Node {
|
||||
id: string;
|
||||
data?: Buffer;
|
||||
@@ -509,6 +608,70 @@ describe("archive from a Nextcloud", () => {
|
||||
expect(after.lastScanAt).not.toBeNull();
|
||||
});
|
||||
|
||||
it("requeues a photo instead of failing it when a download blip outlasts the cloud client's own retries (BIT-31505)", async () => {
|
||||
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);
|
||||
|
||||
const [id] = await worker.claim(1);
|
||||
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
|
||||
expect(claimed).toMatchObject({ status: "WORKING", attempts: 1 });
|
||||
|
||||
// Nextcloud stays unavailable for longer than CloudClient.call's own retry budget (BIT-31491): the GET for
|
||||
// this file keeps answering 503 past the last retry, so download() gives up and throws.
|
||||
const realFetch = cloud.fetch;
|
||||
const name = claimed.path.split("/").pop()!;
|
||||
cloud.fetch = async (input, init) => {
|
||||
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
|
||||
return realFetch(input, init);
|
||||
};
|
||||
await worker.index(id);
|
||||
cloud.fetch = realFetch;
|
||||
|
||||
// Given back to the walk, not failed outright, and the claim's attempt is given back with it: a cloud blip
|
||||
// never counts toward the permanent-failure limit the way a real decoding/matching error would.
|
||||
const requeued = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
|
||||
expect(requeued).toMatchObject({ status: "PENDING", attempts: 0 });
|
||||
expect(requeued.error).toContain("503");
|
||||
|
||||
const [again] = await worker.claim(1);
|
||||
expect(again).toBe(id);
|
||||
await worker.index(again);
|
||||
expect(await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: "DONE" });
|
||||
});
|
||||
|
||||
it("logs a download blip at info, not warn, so a free retry never reaches the error hub as a new error (BIT-31513)", async () => {
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
|
||||
const calls: { level: "info" | "warn"; msg: string }[] = [];
|
||||
const spy = {
|
||||
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
|
||||
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
|
||||
};
|
||||
const storage = new LocalStorage(storageRoot);
|
||||
const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet });
|
||||
const spied = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: spy, ingest, fetchImpl: fetchProxy });
|
||||
await spied.scan(source.id);
|
||||
|
||||
const [id] = await spied.claim(1);
|
||||
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
|
||||
const realFetch = cloud.fetch;
|
||||
const name = claimed.path.split("/").pop()!;
|
||||
cloud.fetch = async (input, init) => {
|
||||
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
|
||||
return realFetch(input, init);
|
||||
};
|
||||
await spied.index(id);
|
||||
cloud.fetch = realFetch;
|
||||
|
||||
// Same recoverable blip as BIT-31505: a free retry, not an error to page on, so logHooks (reporter.ts) must
|
||||
// never see it as a "warn" carrying an err (it would otherwise reach errors.bitreport.pt and reopen the Loop).
|
||||
expect(calls).toContainEqual({ level: "info", msg: "archive: image download blipped, requeued for a free retry" });
|
||||
expect(calls.some((c) => c.level === "warn")).toBe(false);
|
||||
});
|
||||
|
||||
it("puts a game's halves in one event with the clubs' names, and names a session's athletes on their photos", async () => {
|
||||
const game = "/FPA/Fotos/2024_2025/Supertaça Kempa 2024/20240824 - SCP x ABC";
|
||||
cloud.add(`${game}/1P/H_0001.jpg`, await jpeg(6));
|
||||
@@ -568,6 +731,55 @@ describe("archive from a Nextcloud", () => {
|
||||
expect(await ctx.db.event.findUnique({ where: { id: oldEvent } })).toBeNull();
|
||||
});
|
||||
|
||||
it("never drops an event a match lands on while its own cleanup still thinks it is empty (BIT-31531)", async () => {
|
||||
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 gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } });
|
||||
const galaFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } });
|
||||
const gameEventId = gameFolder.eventId!;
|
||||
const galaEventId = galaFolder.eventId!;
|
||||
|
||||
// galaFolder is galaEventId's only folder, so moving it onto the game's event makes galaEventId empty and
|
||||
// triggers dropIfEmpty(galaEventId) at the end of the move. Hold that cleanup open right at its delete — as if
|
||||
// another match had just made it look empty a moment ago — while a second move lands gameFolder (and its
|
||||
// photos) on galaEventId. Before BIT-31531 dropIfEmpty read "empty" and deleted on that stale read regardless
|
||||
// of what arrived after; the fix folds the check into the delete's own WHERE, so it must see the new tenant.
|
||||
let releaseDelete!: () => void;
|
||||
const heldOpen = new Promise<void>((resolve) => (releaseDelete = resolve));
|
||||
let reachedDelete!: () => void;
|
||||
const deleteReached = new Promise<void>((resolve) => (reachedDelete = resolve));
|
||||
const gated = ctx.db.$extends({
|
||||
query: {
|
||||
event: {
|
||||
async deleteMany({ args, query }) {
|
||||
if (args.where?.id === galaEventId) {
|
||||
reachedDelete();
|
||||
await heldOpen;
|
||||
}
|
||||
return query(args);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const slowWorker = new ArchiveService({ db: gated as unknown as TestContext["db"], secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy });
|
||||
|
||||
const held = slowWorker.setFolderEvent(galaFolder.id, { eventId: gameEventId });
|
||||
await deleteReached;
|
||||
await worker.setFolderEvent(gameFolder.id, { eventId: galaEventId });
|
||||
releaseDelete();
|
||||
await held;
|
||||
|
||||
const gameAfter = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: gameFolder.id } });
|
||||
expect(gameAfter.eventId).toBe(galaEventId);
|
||||
expect(await ctx.db.event.findUnique({ where: { id: galaEventId } })).not.toBeNull();
|
||||
const gamePhotos = await ctx.db.photo.findMany({ where: { originalName: { in: ["PS_0001.jpg", "PS_0002.jpg"] } } });
|
||||
expect(gamePhotos.every((p) => p.eventId === galaEventId)).toBe(true);
|
||||
});
|
||||
|
||||
it("asks again when the cloud revokes the app password", async () => {
|
||||
const source = await connect();
|
||||
cloud.authorised = true;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
|
||||
import { dbConnectionBudget, planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
|
||||
|
||||
const GB = 1e9;
|
||||
|
||||
@@ -38,3 +38,24 @@ describe("capacity", () => {
|
||||
expect(at({ free: 6 * GB }).allow(36, true)).toBe(18);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dbConnectionBudget", () => {
|
||||
it("stays under what the API's cluster, a deploy's reload overlap, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
|
||||
// 100 - 3 superuser reserved - ((2 api instances + 1 reload overlap) * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 47.
|
||||
expect(dbConnectionBudget(500)).toBe(47);
|
||||
expect(dbConnectionBudget(10)).toBe(10);
|
||||
});
|
||||
|
||||
it("follows a differently sized API cluster or Postgres limit", () => {
|
||||
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(96);
|
||||
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
||||
});
|
||||
|
||||
it("can be told a deploy never overlaps instances (e.g. a non-cluster or single-instance API)", () => {
|
||||
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(60);
|
||||
});
|
||||
|
||||
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {
|
||||
expect(dbConnectionBudget(50, { max: 20, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { NextcloudError } from "../src/delivery/nextcloud.js";
|
||||
import { closeRenderer } from "../src/delivery/render.js";
|
||||
import { SecretBox } from "../src/delivery/secrets.js";
|
||||
import { DeliveryService } from "../src/delivery/service.js";
|
||||
@@ -530,7 +531,7 @@ describe("delivery", () => {
|
||||
// Only the best: without the autopilot, the photographer's stars decide.
|
||||
await ctx.db.photo.update({ where: { id: b }, data: { rating: 3 } });
|
||||
const best = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/best`, headers: bearer(token), payload: { targetId, eventId: event.id, count: 1, dryRun: true } });
|
||||
expect(best.json()).toEqual({ chosen: [b], queued: [], skipped: [] });
|
||||
expect(best.json()).toEqual({ chosen: [b], rest: [], queued: [], skipped: [] });
|
||||
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a, b] } });
|
||||
expect(res.statusCode).toBe(202);
|
||||
zz.logins = 0;
|
||||
@@ -705,6 +706,37 @@ describe("delivery", () => {
|
||||
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
|
||||
});
|
||||
|
||||
it("logs a blip reading an archive original from the cloud at info, not warn, so it never reaches the error hub (BIT-31522)", async () => {
|
||||
const { orgId, token } = await setup();
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
|
||||
});
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const a = await photo("archived.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
|
||||
|
||||
const calls: { level: "info" | "warn"; msg: string }[] = [];
|
||||
const spy = {
|
||||
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
|
||||
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
|
||||
};
|
||||
// A cloud "originals" source whose download always comes back as the Nextcloud 503 seen in BIT-31522 — the
|
||||
// same self-healing blip BIT-31513 already stopped from reaching the error hub out of the archive indexer.
|
||||
const originals = { downloadOriginal: async () => { throw new NextcloudError("GET /archived.jpg failed: 503", 503); } };
|
||||
const spied = new DeliveryService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), secrets: new SecretBox(KEY), broadcaster, log: spy, fetchImpl: nc.fetch, originals });
|
||||
|
||||
const [claimed] = await delivery.claim(5);
|
||||
await spied.process(claimed!);
|
||||
|
||||
expect(calls).toContainEqual({ level: "info", msg: "delivery: original download blipped from the cloud, retrying" });
|
||||
expect(calls.some((c) => c.level === "warn")).toBe(false);
|
||||
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "QUEUED", lastError: "waiting_for_original" });
|
||||
});
|
||||
|
||||
it("retries transient errors with back-off and stops at auth errors", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("a.jpg", "2026:09:23 21:10:00");
|
||||
|
||||
@@ -490,6 +490,33 @@ describe("faces", () => {
|
||||
expect(await faces.claim(1)).toEqual([newer.id]);
|
||||
});
|
||||
|
||||
it("reads the last month before an older gallery that arrived later", async () => {
|
||||
const { orgId, day1 } = await setup();
|
||||
const photo = (name: string, capturedAt: Date, createdAt: Date) =>
|
||||
ctx.db.photo.create({
|
||||
data: {
|
||||
organizationId: orgId,
|
||||
eventId: day1.id,
|
||||
source: "UPLOAD",
|
||||
originalName: name,
|
||||
sha256: name.padEnd(64, "0"),
|
||||
byteSize: 1,
|
||||
storageKey: name,
|
||||
status: "READY",
|
||||
facesStatus: "PENDING",
|
||||
capturedAt,
|
||||
createdAt,
|
||||
},
|
||||
});
|
||||
const archive = await photo("archive.jpg", new Date("2024-03-01T15:00:00Z"), new Date());
|
||||
const recent = await photo("recent.jpg", new Date(Date.now() - 2 * 24 * 60 * 60_000), new Date(Date.now() - 5 * 24 * 60 * 60_000));
|
||||
const waiting = await photo("waiting.jpg", new Date("2023-11-01T15:00:00Z"), new Date(Date.now() - 2 * 24 * 60 * 60_000));
|
||||
expect(await faces.claim(1)).toEqual([recent.id]);
|
||||
// The month is clear: the gallery that just arrived comes before one that has been waiting.
|
||||
expect(await faces.claim(1)).toEqual([archive.id]);
|
||||
expect(await faces.claim(1)).toEqual([waiting.id]);
|
||||
});
|
||||
|
||||
it("puts the event at the front of the queue and requeues a face the worker abandoned", async () => {
|
||||
const { orgId, token, day1 } = await setup();
|
||||
const photoOf = (name: string, facesStatus: "PENDING" | "FAILED" | "RUNNING") =>
|
||||
|
||||
@@ -306,7 +306,7 @@ describe("library", () => {
|
||||
headers: bearer(admin),
|
||||
payload: { ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } },
|
||||
});
|
||||
expect(patch.json()).toEqual({ updated: 2, changed: 2, resent: 0 });
|
||||
expect(patch.json()).toEqual({ updated: 2 });
|
||||
expect(broadcaster.sent[0]?.message).toEqual({ type: "photo.updated", ids, patch: { flag: "PICK", rating: 4, players: ["Miguel Silva (VSC)"] } });
|
||||
|
||||
const picks = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?flag=PICK&minRating=4`, headers: bearer(admin) });
|
||||
|
||||
@@ -5,6 +5,7 @@ import { t } from "./i18n.js";
|
||||
import { ArchivePage } from "./pages/ArchivePage.js";
|
||||
import { DevelopPage } from "./pages/DevelopPage.js";
|
||||
import { DeliveryPage } from "./pages/DeliveryPage.js";
|
||||
import { FacesQueuePage } from "./pages/FacesQueuePage.js";
|
||||
import { NumbersPage } from "./pages/NumbersPage.js";
|
||||
import { PrintPage } from "./pages/PrintPage.js";
|
||||
import { ShopPage } from "./pages/ShopPage.js";
|
||||
@@ -33,6 +34,7 @@ function Gate() {
|
||||
<Route path="delivery" element={<DeliveryPage />} />
|
||||
<Route path="shop" element={<ShopPage />} />
|
||||
<Route path="print" element={<PrintPage />} />
|
||||
<Route path="faces" element={<FacesQueuePage />} />
|
||||
<Route path="numbers" element={<NumbersPage />} />
|
||||
<Route path="members" element={<MembersPage />} />
|
||||
<Route path="preferences" element={<PreferencesPage />} />
|
||||
|
||||
@@ -31,6 +31,8 @@ export const t = {
|
||||
develop: "Revelar",
|
||||
metadata: "Metadados",
|
||||
archiveNav: "Arquivo",
|
||||
facesNav: "Caras",
|
||||
numbersNav: "Camisolas",
|
||||
delivery: "Entregar",
|
||||
soon: "Em breve",
|
||||
events: "Eventos",
|
||||
@@ -457,6 +459,8 @@ export const t = {
|
||||
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.",
|
||||
hostnameSave: "Guardar",
|
||||
rename: "Nome do arquivo",
|
||||
renameHelp: "Aparece aqui e no título do site de consulta.",
|
||||
resume: "Retomar",
|
||||
remove: "Desligar",
|
||||
removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.",
|
||||
|
||||
@@ -121,6 +121,8 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
|
||||
const viewerUrl = source.hostname ? `https://${source.hostname}` : `${VIEWER_BASE.replace(/\/+$/, "")}/arquivo/${source.id}`;
|
||||
const [hostname, setHostname] = useState(source.hostname ?? "");
|
||||
useEffect(() => setHostname(source.hostname ?? ""), [source.hostname]);
|
||||
const [name, setName] = useState(source.name);
|
||||
useEffect(() => setName(source.name), [source.name]);
|
||||
|
||||
const run = (fn: () => Promise<CloudSource | void>) => {
|
||||
setBusy(true);
|
||||
@@ -212,6 +214,30 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<form
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (name.trim()) void run(() => api.updateCloudSource(source.id, { name: name.trim() }));
|
||||
}}
|
||||
>
|
||||
<span className="text-muted">{A.rename}:</span>
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={80}
|
||||
disabled={busy}
|
||||
className="h-6 min-w-[220px] border border-black bg-cell px-2 text-[11px] text-ink"
|
||||
/>
|
||||
{name.trim() && name.trim() !== source.name && (
|
||||
<button type="submit" disabled={busy} className="h-6 border border-black bg-cell px-2 text-[11px] text-ink hover:bg-cell-on disabled:opacity-40">
|
||||
{A.hostnameSave}
|
||||
</button>
|
||||
)}
|
||||
<span className="w-full text-faint">{A.renameHelp}</span>
|
||||
</form>
|
||||
)}
|
||||
{isAdmin && (
|
||||
<form
|
||||
className="flex w-full flex-wrap items-center gap-2"
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { FaceCrop } from "../library/FacesView.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
interface Sample {
|
||||
faceId: string;
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
aspect: number;
|
||||
preview: string;
|
||||
}
|
||||
interface Row {
|
||||
id: string;
|
||||
eventId: string;
|
||||
size: number;
|
||||
suggestion: { id: string; name: string; club: string | null; number: string | null; score: number } | null;
|
||||
event: { title: string; startsAt: string };
|
||||
samples: Sample[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Faces waiting across the library, grouped by the person they seem to be. Confirming one names every game of
|
||||
* that person on this page and teaches the next match. Shirt numbers are checked on Camisolas.
|
||||
*/
|
||||
export function FacesQueuePage() {
|
||||
const { api, organization } = useAuth();
|
||||
const orgId = organization?.id ?? "";
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<Sample[] | null>(null);
|
||||
const [at, setAt] = useState(0);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
const body = await api.request<{ groups: Row[] }>("GET", `/v1/orgs/${orgId}/face-review`);
|
||||
setRows(body.groups);
|
||||
}, [api, orgId]);
|
||||
useEffect(() => {
|
||||
void load().catch(() => setRows([]));
|
||||
}, [load]);
|
||||
|
||||
const piles = new Map<string, Row[]>();
|
||||
for (const row of rows ?? []) {
|
||||
const key = row.suggestion?.id ?? row.id;
|
||||
piles.set(key, [...(piles.get(key) ?? []), row]);
|
||||
}
|
||||
|
||||
const confirm = async (pile: Row[]) => {
|
||||
const personId = pile[0]?.suggestion?.id;
|
||||
if (!personId) return;
|
||||
setBusy(personId);
|
||||
try {
|
||||
for (const row of pile) await api.request("POST", `/v1/face-groups/${row.id}/confirm`, { personId });
|
||||
setRows((cur) => cur?.filter((r) => !pile.some((p) => p.id === r.id)) ?? null);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<PageHeader title={t.faces.title} />
|
||||
<p className="px-4 pt-3 text-[13px] text-muted">
|
||||
As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>.
|
||||
</p>
|
||||
<div className="grid flex-1 content-start gap-3 overflow-auto p-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{rows === null && <p className="text-sm text-muted">A carregar…</p>}
|
||||
{rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>}
|
||||
{[...piles.values()].map((pile) => {
|
||||
const who = pile[0]!.suggestion;
|
||||
const faces = pile.flatMap((r) => r.samples);
|
||||
return (
|
||||
<article key={who?.id ?? pile[0]!.id} className="flex flex-col gap-2 border border-[#151516] bg-cell p-2">
|
||||
<button type="button" className="flex flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}>
|
||||
{faces.slice(0, 6).map((s) => (
|
||||
<FaceCrop key={s.faceId} src={api.absolute(s.preview)} box={s} aspect={s.aspect} size={faces.length > 3 ? 52 : 72} />
|
||||
))}
|
||||
</button>
|
||||
<div className="text-[13px]">
|
||||
<p className="text-ink">{who?.name}</p>
|
||||
<p className="text-[11px] text-faint">
|
||||
{[who?.number && `nº ${who.number}`, who?.club, `${pile.reduce((n, r) => n + r.size, 0)} fotos`, pile.length > 1 ? `${pile.length} jogos` : pile[0]!.event.title]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="h-8 border border-black bg-accent text-[12px] text-ink" disabled={busy === who?.id} onClick={() => void confirm(pile)}>
|
||||
Confirmar
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{open && open[at] && (
|
||||
<div className="fixed inset-0 z-40 flex items-center justify-center gap-4 bg-black/80 p-6" onClick={() => setOpen(null)}>
|
||||
<button type="button" className="h-12 w-12 rounded-full bg-white text-2xl" onClick={(e) => (e.stopPropagation(), setAt((at + open.length - 1) % open.length))} aria-label="Anterior">
|
||||
‹
|
||||
</button>
|
||||
<span onClick={(e) => e.stopPropagation()}>
|
||||
<FaceCrop src={api.absolute(open[at].preview)} box={open[at]} aspect={open[at].aspect} size={420} />
|
||||
</span>
|
||||
<button type="button" className="h-12 w-12 rounded-full bg-white text-2xl" onClick={(e) => (e.stopPropagation(), setAt((at + 1) % open.length))} aria-label="Seguinte">
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -97,6 +97,18 @@ export function Shell() {
|
||||
<NavLink to="/archive" className={moduleClass}>
|
||||
{t.archiveNav}
|
||||
</NavLink>
|
||||
<span aria-hidden="true" className="text-[#3a3a3a]">
|
||||
|
|
||||
</span>
|
||||
<NavLink to="/faces" className={moduleClass}>
|
||||
{t.facesNav}
|
||||
</NavLink>
|
||||
<span aria-hidden="true" className="text-[#3a3a3a]">
|
||||
|
|
||||
</span>
|
||||
<NavLink to="/numbers" className={moduleClass}>
|
||||
{t.numbersNav}
|
||||
</NavLink>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
@@ -257,7 +257,7 @@ function SignIn({ info, logo, owner, onDone }: { info: ArchiveInfo; logo: string
|
||||
},
|
||||
() => {
|
||||
win?.close();
|
||||
setError("Não foi possível iniciar a entrada. Tenta daqui a pouco.");
|
||||
setError("O serviço de entrada não está a responder. Tenta daqui a pouco.");
|
||||
},
|
||||
)
|
||||
.finally(() => setBusy(false));
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { cached, call, fold, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
|
||||
import { cached, call, fold, forget, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
|
||||
import { Icon, Loading, PersonFace } from "./parts";
|
||||
|
||||
export type Tab = "galleries" | "people" | "teams" | "review";
|
||||
@@ -37,6 +37,7 @@ export function Browse({
|
||||
const [total, setTotal] = useState(0);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [teams, setTeams] = useState<Directory["teams"] | null>(null);
|
||||
const [teamsTry, setTeamsTry] = useState(0);
|
||||
const [players, setPlayers] = useState<NonNullable<Directory["players"]> | null>(null);
|
||||
const [people, setPeople] = useState<PeopleList | null>(null);
|
||||
const [club, setClub] = useState<string | null>(null);
|
||||
@@ -86,16 +87,28 @@ export function Browse({
|
||||
|
||||
useEffect(() => {
|
||||
let cancel = false;
|
||||
let retry: ReturnType<typeof setTimeout> | undefined;
|
||||
setFailed(false);
|
||||
if (tab === "teams") {
|
||||
cached<Directory>(`/v1/archive/${sourceId}/directory`, token, (body) => !cancel && setTeams(body.teams)).catch((err) => !cancel && guard(err));
|
||||
const url = `/v1/archive/${sourceId}/directory`;
|
||||
cached<Directory>(url, token, (body) => {
|
||||
if (cancel) return;
|
||||
// The server is still reading a big archive's teams: ask again in a moment (the list keeps loading).
|
||||
if (body.preparing) {
|
||||
forget(url);
|
||||
retry = setTimeout(() => setTeamsTry((n) => n + 1), 4000);
|
||||
return;
|
||||
}
|
||||
setTeams(body.teams);
|
||||
}).catch((err) => !cancel && guard(err));
|
||||
cached<Directory>(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([]));
|
||||
}
|
||||
if (tab === "people") cached<PeopleList>(`/v1/archive/${sourceId}/people`, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err));
|
||||
return () => {
|
||||
cancel = true;
|
||||
clearTimeout(retry);
|
||||
};
|
||||
}, [tab, sourceId, token, guard, attempt]);
|
||||
}, [tab, sourceId, token, guard, attempt, teamsTry]);
|
||||
|
||||
const more = () => {
|
||||
if (!list || loadingMore) return;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { call, fold, forget, Forbidden, shortDay, Unauthorised, type Me, type PeopleList, type ReviewGroup, type ReviewResult, type ReviewStatus } from "./api";
|
||||
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 { FaceCrop, Icon, Loading, PersonFace } from "./parts";
|
||||
|
||||
const STATUS: [ReviewStatus, string][] = [
|
||||
@@ -26,7 +26,10 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [everyone, setEveryone] = useState<PeopleList["people"] | null>(null);
|
||||
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;
|
||||
}, [sourceId, token]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancel = false;
|
||||
@@ -47,12 +50,6 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
};
|
||||
}, [sourceId, token, status, person, onExpired, attempt]);
|
||||
|
||||
// Names to give an unnamed face: the people of the archive.
|
||||
useEffect(() => {
|
||||
if (status !== "unnamed" || everyone) return;
|
||||
call<PeopleList>(`/v1/archive/${sourceId}/people`, token).then(({ body }) => setEveryone(body.people), () => setEveryone([]));
|
||||
}, [status, everyone, sourceId, token]);
|
||||
|
||||
const act = useCallback(
|
||||
async (ids: string[], action: Action, personId?: string) => {
|
||||
setError(null);
|
||||
@@ -83,7 +80,14 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
[sourceId, token, status, onExpired, onChanged],
|
||||
);
|
||||
|
||||
const toggle = (id: string) => setSelected((s) => (s.has(id) ? new Set([...s].filter((x) => x !== id)) : new Set([...s, id])));
|
||||
const togglePile = (pile: ReviewGroup[]) =>
|
||||
setSelected((s) => {
|
||||
const on = pile.every((g) => s.has(g.id));
|
||||
const next = new Set(s);
|
||||
for (const g of pile) if (on) next.delete(g.id);
|
||||
else next.add(g.id);
|
||||
return next;
|
||||
});
|
||||
const chosen = data?.people.find((p) => p.id === person) ?? null;
|
||||
const ids = [...selected];
|
||||
|
||||
@@ -154,9 +158,19 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
{!data && !error && <Loading cards />}
|
||||
{data && data.groups.length === 0 && <p className="arq-empty">{status === "suggested" ? "Nada por confirmar aqui. Bom trabalho." : "Nada nesta lista."}</p>}
|
||||
<div className="arq-review">
|
||||
{data?.groups.map((g) => (
|
||||
<Card key={g.id} g={g} status={status} busy={busy.has(g.id)} selected={selected.has(g.id)} onToggle={() => toggle(g.id)} onAct={(a, p) => void act([g.id], a, p)} everyone={everyone} />
|
||||
))}
|
||||
{data &&
|
||||
piles(data.groups, status).map((pile) => (
|
||||
<Card
|
||||
key={pile.map((g) => g.id).join("-")}
|
||||
groups={pile}
|
||||
status={status}
|
||||
busy={pile.some((g) => busy.has(g.id))}
|
||||
selected={pile.every((g) => selected.has(g.id))}
|
||||
onToggle={() => togglePile(pile)}
|
||||
onAct={(a, p) => void act(pile.map((g) => g.id), a, p)}
|
||||
searchPeople={searchPeople}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -199,27 +213,88 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
);
|
||||
}
|
||||
|
||||
function NameSearch({ placeholder, searchPeople, onPick }: { placeholder: string; searchPeople: (q: string) => Promise<ReviewPerson[]>; onPick: (id: string) => void }) {
|
||||
const [q, setQ] = useState("");
|
||||
const [hits, setHits] = useState<ReviewPerson[]>([]);
|
||||
useEffect(() => {
|
||||
const query = q.trim();
|
||||
if (query.length < 2) {
|
||||
setHits([]);
|
||||
return;
|
||||
}
|
||||
let cancel = false;
|
||||
const timer = setTimeout(() => {
|
||||
searchPeople(query).then(
|
||||
(rows) => {
|
||||
if (!cancel) setHits(rows);
|
||||
},
|
||||
() => {
|
||||
if (!cancel) setHits([]);
|
||||
},
|
||||
);
|
||||
}, 200);
|
||||
return () => {
|
||||
cancel = true;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [q, searchPeople]);
|
||||
return (
|
||||
<span className="arq-name-it">
|
||||
<input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={placeholder} aria-label={placeholder} />
|
||||
{hits.map((p) => (
|
||||
<button key={p.id} type="button" className="arq-name-hit" onClick={() => onPick(p.id)}>
|
||||
<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>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The same person in several games is one card: confirming once names all of them and teaches the next match. */
|
||||
function piles(groups: ReviewGroup[], status: ReviewStatus): ReviewGroup[][] {
|
||||
if (status !== "suggested" && status !== "confirmed") return groups.map((g) => [g]);
|
||||
const order: string[] = [];
|
||||
const by = new Map<string, ReviewGroup[]>();
|
||||
for (const g of groups) {
|
||||
const who = status === "confirmed" ? g.person : g.suggested;
|
||||
const key = who?.id ?? g.id;
|
||||
const list = by.get(key);
|
||||
if (list) list.push(g);
|
||||
else {
|
||||
by.set(key, [g]);
|
||||
order.push(key);
|
||||
}
|
||||
}
|
||||
return order.map((key) => by.get(key)!);
|
||||
}
|
||||
|
||||
function Card({
|
||||
g,
|
||||
groups,
|
||||
status,
|
||||
busy,
|
||||
selected,
|
||||
onToggle,
|
||||
onAct,
|
||||
everyone,
|
||||
searchPeople,
|
||||
}: {
|
||||
g: ReviewGroup;
|
||||
groups: ReviewGroup[];
|
||||
status: ReviewStatus;
|
||||
busy: boolean;
|
||||
selected: boolean;
|
||||
onToggle: () => void;
|
||||
onAct: (a: Action, personId?: string) => void;
|
||||
everyone: PeopleList["people"] | null;
|
||||
searchPeople: (q: string) => Promise<ReviewPerson[]>;
|
||||
}) {
|
||||
const [q, setQ] = useState("");
|
||||
const g = groups[0]!;
|
||||
const who = g.person ?? g.suggested;
|
||||
const [first, ...rest] = g.faces;
|
||||
const matches = useMemo(() => (q.trim().length < 2 ? [] : (everyone ?? []).filter((p) => fold(`${p.name} ${p.club ?? ""} ${p.number ?? ""}`).includes(fold(q.trim()))).slice(0, 6)), [q, everyone]);
|
||||
const faces = groups.flatMap((item) => item.faces);
|
||||
const photos = groups.reduce((n, item) => n + item.photos, 0);
|
||||
const [open, setOpen] = useState<number | null>(null);
|
||||
const [first, ...rest] = faces;
|
||||
const onKey = (e: React.KeyboardEvent) => {
|
||||
if (busy || e.target instanceof HTMLInputElement) return;
|
||||
const k = e.key.toLowerCase();
|
||||
@@ -232,9 +307,9 @@ function Card({
|
||||
};
|
||||
return (
|
||||
<article className={`arq-rcard${selected ? " on" : ""}${busy ? " busy" : ""}`} tabIndex={0} onKeyDown={onKey} aria-label={who ? who.name : "Rosto sem nome"}>
|
||||
<button type="button" className="arq-rfaces" onClick={onToggle} aria-pressed={selected} aria-label={selected ? "Tirar da seleção" : "Selecionar"}>
|
||||
<button type="button" className="arq-rfaces" onClick={() => first && setOpen(0)} aria-label={who ? `Ver as fotos de ${who.name}` : "Ver as fotos"}>
|
||||
{first ? <FaceCrop src={first.src} box={first.box} aspect={first.aspect} size={160} round={false} /> : <span className="arq-crop" style={{ width: 160, height: 160 }} />}
|
||||
<span className="arq-check" aria-hidden="true">
|
||||
<span className="arq-check" role="checkbox" aria-checked={selected} aria-label={selected ? "Tirar da seleção" : "Selecionar"} onClick={(e) => (e.stopPropagation(), onToggle())}>
|
||||
{selected ? "✓" : ""}
|
||||
</span>
|
||||
{g.score !== null && status === "suggested" && <span className="arq-badge dark arq-conf">{Math.round(g.score * 100)}%</span>}
|
||||
@@ -249,20 +324,21 @@ function Card({
|
||||
<div className="arq-rbody">
|
||||
<strong>{who ? who.name : "Sem nome"}</strong>
|
||||
<small>
|
||||
{[who?.number && `nº ${who.number}`, who?.club, `${g.photos} ${g.photos === 1 ? "foto" : "fotos"}`].filter(Boolean).join(" · ")}
|
||||
{[who?.number && `nº ${who.number}`, who?.club, `${photos} ${photos === 1 ? "foto" : "fotos"}`, groups.length > 1 ? `${groups.length} jogos` : null].filter(Boolean).join(" · ")}
|
||||
</small>
|
||||
{g.event && <small>{[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}</small>}
|
||||
{groups.length === 1 && g.event && <small>{[g.event.title, g.event.startsAt ? shortDay.format(new Date(g.event.startsAt)) : null].filter(Boolean).join(" · ")}</small>}
|
||||
{groups.length > 1 && (
|
||||
<small>
|
||||
{groups
|
||||
.map((item) => item.event?.title)
|
||||
.filter(Boolean)
|
||||
.slice(0, 4)
|
||||
.join(" · ")}
|
||||
</small>
|
||||
)}
|
||||
{g.notThem.length > 0 && <small>Não é: {g.notThem.map((n) => n.name).join(", ")}</small>}
|
||||
{status === "unnamed" && (
|
||||
<span className="arq-name-it">
|
||||
<input type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Quem é? Nome ou número" aria-label="Quem é?" />
|
||||
{matches.map((p) => (
|
||||
<button key={p.id} type="button" className="arq-pill" onClick={() => onAct("confirm", p.id)}>
|
||||
{p.name}
|
||||
{p.number && <span className="arq-n">{p.number}</span>}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
{(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)} />
|
||||
)}
|
||||
</div>
|
||||
<div className="arq-ractions">
|
||||
@@ -291,6 +367,22 @@ function Card({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open !== null && faces[open] && (
|
||||
<div className="arq-lightbox" role="dialog" aria-modal="true" aria-label={who ? who.name : "Fotos do grupo"} onClick={() => setOpen(null)}>
|
||||
<button type="button" className="arq-lightbox-x" onClick={() => setOpen(null)} aria-label="Fechar">
|
||||
×
|
||||
</button>
|
||||
<button type="button" className="arq-lightbox-nav" aria-label="Foto anterior" onClick={(e) => (e.stopPropagation(), setOpen((open + faces.length - 1) % faces.length))}>
|
||||
‹
|
||||
</button>
|
||||
<span onClick={(e) => e.stopPropagation()}>
|
||||
<FaceCrop src={faces[open].src} box={faces[open].box} aspect={faces[open].aspect} size={420} round={false} eager />
|
||||
</span>
|
||||
<button type="button" className="arq-lightbox-nav" aria-label="Foto seguinte" onClick={(e) => (e.stopPropagation(), setOpen((open + 1) % faces.length))}>
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -107,6 +107,8 @@ export interface Directory {
|
||||
teams: { name: string; galleries: number }[];
|
||||
/** Named on the photos (a session's folder per athlete, the editors' tags). */
|
||||
players?: { name: string; club: string | null; photos: number }[];
|
||||
/** The server is still reading the teams of a big archive: ask again shortly. */
|
||||
preparing?: boolean;
|
||||
}
|
||||
|
||||
export interface PeopleList {
|
||||
|
||||
@@ -1627,6 +1627,57 @@
|
||||
border: 1px solid var(--line);
|
||||
background: var(--card);
|
||||
}
|
||||
.arq-name-hit {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 4px 10px 4px 4px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--line);
|
||||
background: var(--card);
|
||||
text-align: left;
|
||||
color: inherit;
|
||||
}
|
||||
.arq-name-hit > span {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
.arq-name-hit strong {
|
||||
font-size: 14px;
|
||||
}
|
||||
.arq-name-hit small {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.arq-lightbox {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
padding: 24px;
|
||||
background: rgba(0, 0, 0, 0.86);
|
||||
}
|
||||
.arq-lightbox-nav,
|
||||
.arq-lightbox-x {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #111;
|
||||
font-size: 28px;
|
||||
line-height: 1;
|
||||
}
|
||||
.arq-lightbox-x {
|
||||
position: absolute;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
}
|
||||
.arq-ractions {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Catches render errors anywhere under the root layout (pages, nested layouts) so a transient API or DB
|
||||
* hiccup shows a retry screen instead of a hard crash. The real error already reached errors.bitreport.pt
|
||||
* via instrumentation.ts's onRequestError, which fires regardless of this boundary.
|
||||
*/
|
||||
export default function Error({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
|
||||
return (
|
||||
<main className="wrap empty">
|
||||
<p>Não foi possível carregar esta página. Tenta novamente.</p>
|
||||
<button type="button" onClick={() => reset()}>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import "./globals.css";
|
||||
|
||||
/**
|
||||
* Catches errors thrown by the root layout itself (e.g. getSite() failing for a reason other than
|
||||
* NotFound). Next only reaches this boundary for root-layout errors, so it must render its own
|
||||
* html/body — the layout that would normally do that is what just failed.
|
||||
*/
|
||||
export default function GlobalError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
|
||||
return (
|
||||
<html lang="pt">
|
||||
<body>
|
||||
<main className="wrap empty">
|
||||
<p>Não foi possível carregar esta página. Tenta novamente.</p>
|
||||
<button type="button" onClick={() => reset()}>
|
||||
Tentar novamente
|
||||
</button>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
+13
-2
@@ -184,7 +184,13 @@ it when files must be served from more than one host.
|
||||
## Faces
|
||||
|
||||
Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9).
|
||||
Each photo that arrives is queued (`photos.faces_status`); the worker runs `workers/faces` on the original:
|
||||
Each photo that arrives is queued (`photos.faces_status`); the worker reads the last 30 days first (when the photo
|
||||
was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive.
|
||||
A folder of an old season that has just been indexed waits until that month is clear, then comes ahead of the
|
||||
archive that has been waiting. Asking to analyse one event still puts it first. A photo whose analysis failed is
|
||||
queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face
|
||||
improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the
|
||||
detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original:
|
||||
YuNet finds faces, each is aligned to the ArcFace template and embedded by AuraFace (512 numbers, Apache-2.0;
|
||||
model files pinned and checked by SHA-256, `infra/faces/download-models.sh`). Faces of the same person within an
|
||||
event are grouped (cosine to the group's mean, threshold per model). An editor names a group once (the
|
||||
@@ -228,8 +234,13 @@ number for that event's context:
|
||||
|
||||
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
|
||||
old game gets the number worn then, even for players who have since left.
|
||||
- **Official match (linked to its teams):** that season's squad first; then what the shirts clearly read (three
|
||||
- **Official match (linked to its teams):** the match sheet first — that season's players and coaches, and the
|
||||
referees of the fixture, when they already have a face. A face none of them explains is then compared with
|
||||
everyone of that sport. A session (no away side) has no sheet: the face alone, against everyone of the sport.
|
||||
The shirt, when it is read, stays with those two clubs. Then what the shirts clearly read (three
|
||||
or more clear readings) in the person's confirmed photos of the same season and competition.
|
||||
- An editor of the folder can give a face another name. The list shows the official face, the club and the shirt
|
||||
number.
|
||||
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
|
||||
squad.
|
||||
- **National team** (a country on either side, or a "Seleção" folder): club squads and club numbers never apply,
|
||||
|
||||
@@ -82,6 +82,10 @@ Gitea -> webhook -> the container pulls and redeploys itself. No manual `scp`/`r
|
||||
Stripe secret key and webhook secret; in Stripe add the shown endpoint for `checkout.session.completed`,
|
||||
`checkout.session.async_payment_succeeded`, `checkout.session.async_payment_failed` and
|
||||
`checkout.session.expired`. Set `SMTP_URL` on the worker for order emails.
|
||||
An archive's own address (app -> Arquivo -> "Endereço próprio", e.g. `ligaportugal.photoreport.pt`) is one
|
||||
more host on the same port 3100: in Nginx Proxy Manager a Proxy Host for it, forwarded like
|
||||
`events.next.photoreport.pt` (Host passed as is), with its Let's Encrypt certificate. With a wildcard
|
||||
certificate (DNS challenge) one Proxy Host for `*.photoreport.pt` covers every archive under that domain.
|
||||
|
||||
11. SFTPGo (pr-ingest): no users in SFTPGo itself. Set `data_provider.external_auth_hook` to
|
||||
`http://<api>/v1/sftpgo/auth?key=<SFTPGO_HOOK_KEY>` and `external_auth_scope` to 1 (passwords), with the same
|
||||
|
||||
+3
-2
@@ -166,8 +166,9 @@ browser follows it. Photos kept at full size are made 2048 px on the way out.
|
||||
An archive can have its own host (`cloud_sources.hostname`, app → Arquivo → "Endereço próprio"), e.g.
|
||||
`arquivo.ligaportugal.pt`: the site's middleware asks the API (`GET /v1/archive/host?host=`, kept 5 minutes) and
|
||||
serves that archive at the root (`/g/…`, `/p/…`, `/f/…`); links stay at the root. The host's DNS points at the
|
||||
proxy; Caddy gets its certificate on demand, after asking the same endpoint (`?domain=`, 200 only for an archive's
|
||||
host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
|
||||
proxy, which sends it to the site like the other domains (Nginx Proxy Manager: a Proxy Host with its certificate,
|
||||
`docs/DEPLOY.md`). With Caddy instead, on-demand TLS can ask the same endpoint (`?domain=`, 200 only for an
|
||||
archive's host; `infra/proxy/Caddyfile.example`). A host can be one archive's or one public site's, never both.
|
||||
|
||||
### People and faces (viewers too)
|
||||
|
||||
|
||||
@@ -205,10 +205,11 @@ impl Engine {
|
||||
want: usize,
|
||||
embed: &mut dyn FnMut(&[u8]) -> Option<Vec<f32>>,
|
||||
) -> Option<Vec<f32>> {
|
||||
if let Some(vector) = embed(crop) {
|
||||
if vector.len() == want && vector.iter().all(|value| value.is_finite()) {
|
||||
return Some(vector);
|
||||
}
|
||||
if let Some(vector) = embed(crop)
|
||||
&& vector.len() == want
|
||||
&& vector.iter().all(|value| value.is_finite())
|
||||
{
|
||||
return Some(vector);
|
||||
}
|
||||
self.models.embedder.embed(crop).ok()
|
||||
}
|
||||
|
||||
@@ -22,8 +22,16 @@ struct Request {
|
||||
#[derive(Serialize)]
|
||||
#[serde(untagged)]
|
||||
enum Response {
|
||||
Ok { id: String, width: usize, height: usize, faces: Vec<FoundFace> },
|
||||
Err { id: String, error: String },
|
||||
Ok {
|
||||
id: String,
|
||||
width: usize,
|
||||
height: usize,
|
||||
faces: Vec<FoundFace>,
|
||||
},
|
||||
Err {
|
||||
id: String,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -35,7 +43,12 @@ fn main() {
|
||||
match arg.as_str() {
|
||||
"--models" => models_dir = args.next().unwrap_or_default(),
|
||||
"--embedder" => embedder = args.next().unwrap_or_default(),
|
||||
"--min-score" => min_score = args.next().and_then(|v| v.parse().ok()).unwrap_or(min_score),
|
||||
"--min-score" => {
|
||||
min_score = args
|
||||
.next()
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(min_score)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +61,11 @@ fn main() {
|
||||
};
|
||||
let stdout = std::io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
let _ = writeln!(out, "{}", serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() }));
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{}",
|
||||
serde_json::json!({ "ready": true, "embedder": embedder, "dim": models.dim() })
|
||||
);
|
||||
let _ = out.flush();
|
||||
for line in std::io::stdin().lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
@@ -57,12 +74,23 @@ fn main() {
|
||||
}
|
||||
let response = match serde_json::from_str::<Request>(&line) {
|
||||
Ok(req) => match models.analyse(Path::new(&req.path)) {
|
||||
Ok(read) => Response::Ok { id: req.id, width: read.width, height: read.height, faces: read.faces },
|
||||
Ok(read) => Response::Ok {
|
||||
id: req.id,
|
||||
width: read.width,
|
||||
height: read.height,
|
||||
faces: read.faces,
|
||||
},
|
||||
Err(error) => Response::Err { id: req.id, error },
|
||||
},
|
||||
Err(e) => Response::Err { id: String::new(), error: format!("bad request: {e}") },
|
||||
Err(e) => Response::Err {
|
||||
id: String::new(),
|
||||
error: format!("bad request: {e}"),
|
||||
},
|
||||
};
|
||||
if serde_json::to_writer(&mut out, &response).is_err() || writeln!(out).is_err() || out.flush().is_err() {
|
||||
if serde_json::to_writer(&mut out, &response).is_err()
|
||||
|| writeln!(out).is_err()
|
||||
|| out.flush().is_err()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user