Compare commits
39
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a2148b2ed | ||
|
|
2c34d86742 | ||
|
|
4cd83dc8b9 | ||
|
|
4eac0e6f95 | ||
|
|
a1cf133193 | ||
|
|
156474bb7a | ||
|
|
9bab5a8c25 | ||
|
|
67b86879fd | ||
|
|
68588e0296 | ||
|
|
c61d371819 | ||
|
|
707420a579 | ||
|
|
92ceeee2fe | ||
|
|
81bd777e87 | ||
|
|
67765899a6 | ||
|
|
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 |
No files matched your search
@@ -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';
|
||||
@@ -0,0 +1,7 @@
|
||||
-- A folder can be kept off the public archive site. Existing folders stay published.
|
||||
ALTER TABLE "cloud_folders" ADD COLUMN "published" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
-- Which gallery a folder belongs to. Filled by the scanner, not by the site.
|
||||
ALTER TABLE "cloud_folders" ADD COLUMN "gallery_folder_id" UUID;
|
||||
CREATE INDEX "cloud_folders_source_id_gallery_folder_id_idx" ON "cloud_folders"("source_id", "gallery_folder_id");
|
||||
ALTER TABLE "cloud_folders" ADD CONSTRAINT "cloud_folders_gallery_folder_id_fkey" FOREIGN KEY ("gallery_folder_id") REFERENCES "cloud_folders"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -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")
|
||||
@@ -1659,17 +1662,25 @@ model CloudFolder {
|
||||
matchedBy String? @map("matched_by")
|
||||
/// Its photos were taken on another day than the official game it was matched to: never matched to one again.
|
||||
fixtureRejected Boolean @default(false) @map("fixture_rejected")
|
||||
/// On the public archive site. The app's admin turns this off; the site has no control of its own. Default on.
|
||||
published Boolean @default(true)
|
||||
/// The gallery this folder belongs to. A game or a dated session takes the folders inside it; anything else
|
||||
/// points at itself. Written when the folder is scanned or moved, and again on the periodic check. The site reads it.
|
||||
galleryFolderId String? @map("gallery_folder_id") @db.Uuid
|
||||
seenAt DateTime @default(now()) @map("seen_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
|
||||
files CloudFile[]
|
||||
grants ArchiveGrantFolder[]
|
||||
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
|
||||
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
|
||||
galleryFolder CloudFolder? @relation("GalleryMembers", fields: [galleryFolderId], references: [id], onDelete: SetNull)
|
||||
galleryMembers CloudFolder[] @relation("GalleryMembers")
|
||||
files CloudFile[]
|
||||
grants ArchiveGrantFolder[]
|
||||
|
||||
@@unique([sourceId, fileId])
|
||||
@@index([sourceId, path])
|
||||
@@index([parentId])
|
||||
@@index([sourceId, galleryFolderId])
|
||||
@@map("cloud_folders")
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { Db } from "../db.js";
|
||||
import { AppError, badRequest, notFound } from "../lib/errors.js";
|
||||
import { zipStream, ZipTooLarge, type ZipEntry } from "../lib/zip.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { galleryMemberIds } from "./gallery.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
|
||||
/**
|
||||
@@ -82,13 +83,18 @@ export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps:
|
||||
let ids: string[] = [];
|
||||
if ("folderId" in ask) {
|
||||
if (visible !== "all" && !visible.includes(ask.folderId)) throw notFound("gallery_not_found");
|
||||
const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId }, include: { event: true } });
|
||||
const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId, published: true }, include: { event: true } });
|
||||
if (!folder) throw notFound("gallery_not_found");
|
||||
name = folder.event ? eventName(folder.event) : (folder.path.split("/").pop() ?? null);
|
||||
const n = await db.cloudFile.count({ where: { folderId: folder.id, status: "DONE", photoId: { not: null } } });
|
||||
const memberIds = await galleryMemberIds(db, sourceId, folder);
|
||||
const idsInGallery = visible === "all" ? memberIds : memberIds.filter((id) => visible.includes(id));
|
||||
const galleryId = folder.galleryFolderId ?? folder.id;
|
||||
const head = galleryId === folder.id ? folder : await db.cloudFolder.findFirst({ where: { id: galleryId, sourceId, published: true }, include: { event: true } });
|
||||
const shown = head ?? folder;
|
||||
name = shown.event ? eventName(shown.event) : (shown.path.split("/").pop() ?? null);
|
||||
const n = await db.cloudFile.count({ where: { folderId: { in: idsInGallery }, status: "DONE", photoId: { not: null } } });
|
||||
if (n > MAX_PHOTOS) throw new AppError(413, "too_many_photos");
|
||||
if (!n) throw notFound("photo_not_found");
|
||||
return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: folder.id, n: name })}`, photos: n };
|
||||
return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: shown.id, n: name })}`, photos: n };
|
||||
} else {
|
||||
const files = await db.cloudFile.findMany({ where: { sourceId, status: "DONE", photoId: { in: ask.photoIds }, ...scope }, select: { photoId: true }, distinct: ["photoId"] });
|
||||
ids = ask.photoIds.filter((id) => files.some((f) => f.photoId === id));
|
||||
@@ -102,9 +108,14 @@ export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps:
|
||||
const { t: ticket } = TicketQuery.parse(req.query);
|
||||
const t = open(ticket);
|
||||
if (!t) throw notFound("download_expired");
|
||||
const ids = t.f
|
||||
? (await db.cloudFile.findMany({ where: { folderId: t.f, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((f) => f.photoId!)
|
||||
: (t.ids ?? []);
|
||||
let ids: string[] = t.ids ?? [];
|
||||
if (t.f) {
|
||||
const stored = await db.cloudFolder.findFirst({ where: { id: t.f, sourceId: t.s, published: true }, select: { id: true, galleryFolderId: true } });
|
||||
const folderIds = stored ? await galleryMemberIds(db, t.s, stored) : [];
|
||||
ids = folderIds.length
|
||||
? (await db.cloudFile.findMany({ where: { folderId: { in: folderIds }, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((file) => file.photoId!)
|
||||
: [];
|
||||
}
|
||||
const photos = await db.photo.findMany({
|
||||
where: { id: { in: ids }, cloudFiles: { some: { sourceId: t.s } } },
|
||||
select: { id: true, storageKey: true, originalName: true, originalStored: true, width: true, height: true, capturedAt: true },
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Prisma } from "../generated/prisma/client.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { galleryRoot } from "./match.js";
|
||||
|
||||
/** A photo whose folder is still published on the public site. */
|
||||
export const publishedPhotos = Prisma.sql`EXISTS (SELECT 1 FROM cloud_folders pub WHERE pub.id = cf.folder_id AND pub.published)`;
|
||||
|
||||
/** The gallery id of each folder, from the paths already stored. A missing root points the folder at itself. */
|
||||
export function galleryAssignments(folders: { id: string; path: string }[]): Map<string, string> {
|
||||
const byPath = new Map(folders.map((folder) => [folder.path, folder.id]));
|
||||
const out = new Map<string, string>();
|
||||
for (const folder of folders) {
|
||||
const root = galleryRoot(folder.path);
|
||||
out.set(folder.id, byPath.get(root) ?? folder.id);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders of one gallery: the row the site opened, and every folder stored as part of it.
|
||||
* A folder not yet assigned is its own gallery.
|
||||
*/
|
||||
export async function galleryMemberIds(db: Db, sourceId: string, folder: { id: string; galleryFolderId: string | null }): Promise<string[]> {
|
||||
const galleryId = folder.galleryFolderId ?? folder.id;
|
||||
const rows = await db.cloudFolder.findMany({
|
||||
where: { sourceId, published: true, OR: [{ id: galleryId }, { galleryFolderId: galleryId }] },
|
||||
select: { id: true },
|
||||
});
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
export interface StoredGallery {
|
||||
id: string;
|
||||
path: string;
|
||||
photoCount: number;
|
||||
startsAt: Date | null;
|
||||
home: string | null;
|
||||
away: string | null;
|
||||
competition: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One page of galleries, read from the column the scanner wrote. A folder with no gallery yet is its own card.
|
||||
*/
|
||||
export async function listStoredGalleries(
|
||||
db: Db,
|
||||
args: { sourceId: string; visible: string[] | "all"; words: string[]; teamNames: string[]; player?: string | undefined; offset: number; limit: number },
|
||||
): Promise<{ total: number; galleries: StoredGallery[] }> {
|
||||
const filters: Prisma.Sql[] = [
|
||||
Prisma.sql`f.source_id = ${args.sourceId}::uuid`,
|
||||
Prisma.sql`f.published`,
|
||||
Prisma.sql`f.photo_count > 0`,
|
||||
Prisma.sql`f.event_id IS NOT NULL`,
|
||||
];
|
||||
if (args.visible !== "all") filters.push(Prisma.sql`f.id = ANY(${args.visible}::uuid[])`);
|
||||
for (const word of args.words) {
|
||||
const contains = `%${word.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
|
||||
const exact = word.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
||||
filters.push(
|
||||
Prisma.sql`(e.home ILIKE ${contains} ESCAPE '\\' OR e.away ILIKE ${contains} ESCAPE '\\' OR e.competition ILIKE ${contains} ESCAPE '\\' OR e.home_short ILIKE ${exact} ESCAPE '\\' OR e.away_short ILIKE ${exact} ESCAPE '\\')`,
|
||||
);
|
||||
}
|
||||
if (args.teamNames.length) filters.push(Prisma.sql`(e.home = ANY(${args.teamNames}::text[]) OR e.away = ANY(${args.teamNames}::text[]))`);
|
||||
if (args.player) filters.push(Prisma.sql`EXISTS (SELECT 1 FROM photos ph WHERE ph.event_id = f.event_id AND ${args.player} = ANY(ph.players))`);
|
||||
const where = Prisma.join(filters, " AND ");
|
||||
const rows = await db.$queryRaw<{ id: string; path: string; photo_count: number; starts_at: Date | null; home: string | null; away: string | null; competition: string | null; total: number }[]>`
|
||||
WITH members AS (
|
||||
SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id, f.photo_count, f.event_id, e.starts_at
|
||||
FROM cloud_folders f
|
||||
JOIN events e ON e.id = f.event_id
|
||||
WHERE ${where}
|
||||
),
|
||||
agg AS (
|
||||
SELECT gallery_id,
|
||||
sum(photo_count)::int AS photo_count,
|
||||
count(DISTINCT event_id)::int AS n_events,
|
||||
(array_agg(DISTINCT event_id))[1] AS one_event,
|
||||
max(starts_at) AS latest
|
||||
FROM members
|
||||
GROUP BY gallery_id
|
||||
),
|
||||
cards AS (
|
||||
SELECT root.id, root.path, agg.photo_count,
|
||||
COALESCE(ev.starts_at, agg.latest) AS starts_at,
|
||||
ev.home, ev.away, ev.competition
|
||||
FROM agg
|
||||
JOIN cloud_folders root ON root.id = agg.gallery_id AND root.published
|
||||
LEFT JOIN events ev ON ev.id = COALESCE(root.event_id, CASE WHEN agg.n_events = 1 THEN agg.one_event END)
|
||||
)
|
||||
SELECT id, path, photo_count, starts_at, home, away, competition, count(*) OVER()::int AS total
|
||||
FROM cards
|
||||
ORDER BY starts_at DESC NULLS LAST, path DESC
|
||||
LIMIT ${args.limit} OFFSET ${args.offset}`;
|
||||
const total = Number(rows[0]?.total ?? (args.offset === 0 ? 0 : await countStoredGalleries(db, where)));
|
||||
return {
|
||||
total,
|
||||
galleries: rows.map((row) => ({
|
||||
id: row.id,
|
||||
path: row.path,
|
||||
photoCount: Number(row.photo_count),
|
||||
startsAt: row.starts_at,
|
||||
home: row.home,
|
||||
away: row.away || null,
|
||||
competition: row.competition,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async function countStoredGalleries(db: Db, where: Prisma.Sql): Promise<number> {
|
||||
const rows = await db.$queryRaw<{ n: number }[]>`
|
||||
WITH members AS (
|
||||
SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id
|
||||
FROM cloud_folders f
|
||||
JOIN events e ON e.id = f.event_id
|
||||
WHERE ${where}
|
||||
)
|
||||
SELECT count(DISTINCT members.gallery_id)::int AS n
|
||||
FROM members
|
||||
JOIN cloud_folders root ON root.id = members.gallery_id AND root.published`;
|
||||
return rows[0]?.n ?? 0;
|
||||
}
|
||||
+215
-13
@@ -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,36 @@ 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). */
|
||||
/**
|
||||
* The two pieces of "A / B". A slash with no letters on a side ("2025/2026", "26/27") is a season. This does not
|
||||
* decide whether they are two clubs or a club and its sponsor ("Avanca / Bioria" is still one club).
|
||||
*/
|
||||
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 clubs only when both sides
|
||||
// are written as clubs ("ALMADA AC / EXT. GIL EANES"). "Avanca / Bioria" is Avanca and its sponsor.
|
||||
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 versus = slash && looksLikeClub(slash.home) && looksLikeClub(slash.away) ? slash : null;
|
||||
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());
|
||||
(versus ? { 1: versus.home, 2: versus.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
|
||||
@@ -62,11 +92,24 @@ function teamsIn(name: string, dashOk = false): { home: string; away: string } |
|
||||
const home = clean(m[1]!).split(/\s+[-–]\s+/).pop()!.trim();
|
||||
const away = clean(clean(m[2]!).split(/\s+[-–]\s+/)[0]!);
|
||||
// "Final - Video", "PO03 - Fase Final": parts and codes, not teams.
|
||||
const notTeam = (s: string) => SECTION.test(foldName(s)) || GENERIC.test(foldName(s)) || /^PO\d|\bfase\b|\bvideo\b/i.test(s);
|
||||
if (notTeam(home) || notTeam(away)) return null;
|
||||
if (sideIsNotTeam(home) || sideIsNotTeam(away)) return null;
|
||||
return home && away ? { home, away } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A stored side for the teams directory. Two clubs when both are written as clubs, or (when `knownName` is given)
|
||||
* each side is a different known team. "Avanca / Bioria" stays one name: the sponsor is not a second club.
|
||||
*/
|
||||
export function directorySides(name: string, knownName?: (side: string) => string | null): string[] {
|
||||
const sides = slashSides(name);
|
||||
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return [name];
|
||||
const home = knownName?.(sides.home) ?? null;
|
||||
const away = knownName?.(sides.away) ?? null;
|
||||
const clubs = looksLikeClub(sides.home) && looksLikeClub(sides.away);
|
||||
const different = !!home && !!away && fold(home) !== fold(away);
|
||||
return clubs || different ? [sides.home, sides.away] : [name];
|
||||
}
|
||||
|
||||
const foldName = (s: string) =>
|
||||
s
|
||||
.normalize("NFD")
|
||||
@@ -154,8 +197,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 inside one folder name ("ALMADA AC / EXT. GIL EANES",
|
||||
* "Avanca / Bioria"), 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 +245,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;
|
||||
@@ -198,6 +253,55 @@ export function parseFolder(path: string): FolderGame | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A date written at the start of a folder: "20231217 - …", "04.11.23 …", "15.02.2026 …". */
|
||||
const LEADING_DATE = /^(?:\d{8}|\d{6})\b|^\d{1,2}[.\-/]\d{1,2}[.\-/](?:\d{4}|\d{2})\b/;
|
||||
|
||||
/**
|
||||
* One game, not a label. "SLB x SCP", "4. SLB x GVFC", "POR_FRA" and "ALMADA AC / EXT. GIL EANES" are games.
|
||||
* "PBHT - EXT" is two codes with a dash and no date: a shelf, not a game, so the days under it stay separate.
|
||||
*/
|
||||
function isGameLeaf(leaf: string): boolean {
|
||||
const game = parseFolder(`/${leaf}`);
|
||||
if (!game?.away || game.single) return false;
|
||||
const name = leaf.trim();
|
||||
if (LEADING_DATE.test(name)) return true;
|
||||
if (/\s(?:x|vs\.?|va)\s/i.test(name)) return true;
|
||||
if (/[A-Za-z]{2,6}x[A-Za-z]{2,6}/.test(name)) return true;
|
||||
if (/^[A-Z]{2,3}_[A-Z]{2,3}$/.test(name.trim())) return true;
|
||||
// A slash is two clubs only when the parser already accepted both sides ("Avanca / Bioria" is one club).
|
||||
if (slashSides(name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A studio session on a day ("20231008 - Sessao SNAF"). The big archive shelf that only mentions "sessão" is not one. */
|
||||
function isSessionLeaf(leaf: string): boolean {
|
||||
const name = leaf.trim();
|
||||
return LEADING_DATE.test(name) && SESSION.test(foldName(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* The gallery this folder belongs to. A game (a date and two clubs, or "clube x clube") and a session on a day
|
||||
* take the folders inside them: halves, warm-up, prizes, an athlete's name. A folder that is itself a game or a
|
||||
* dated event stays its own gallery, so a game filed under another game is not merged into it.
|
||||
*
|
||||
* A name shorter than date, club and club is only a hint. Counting those slots on every folder would swallow
|
||||
* "Dia 1" and "FanZone". A folder joins the gallery above only when that gallery is a game or a session, and
|
||||
* this folder is not itself a game or a dated event.
|
||||
*/
|
||||
export function galleryRoot(path: string): string {
|
||||
const parts = pathParts(path);
|
||||
if (!parts.length) return path.startsWith("/") ? path : `/${path}`;
|
||||
const leaf = parts[parts.length - 1]!;
|
||||
if (isGameLeaf(leaf) || isSessionLeaf(leaf) || LEADING_DATE.test(leaf.trim())) return `/${parts.join("/")}`;
|
||||
for (let i = parts.length - 2; i >= 0; i--) {
|
||||
const name = parts[i]!;
|
||||
if (isGameLeaf(name) || isSessionLeaf(name)) return `/${parts.slice(0, i + 1).join("/")}`;
|
||||
// "20180727 - Fase Final" is a day, not a game: the days under it stay their own galleries.
|
||||
if (LEADING_DATE.test(name.trim())) break;
|
||||
}
|
||||
return `/${parts.join("/")}`;
|
||||
}
|
||||
|
||||
const fullYear = (y: string) => (y.length === 2 ? `20${y}` : y);
|
||||
/** A real calendar day ("2023-02-30" is not). */
|
||||
const validDay = (day: string) => {
|
||||
@@ -412,6 +516,58 @@ export function exhibitionName(game: Pick<FolderGame, "parents">): string | null
|
||||
return game.parents.find(isExhibitionName)?.trim() ?? null;
|
||||
}
|
||||
|
||||
/** "Final", "Externo", "PO03": a part of a day, not a club. */
|
||||
function sideIsNotTeam(s: string): boolean {
|
||||
return SECTION.test(foldName(s)) || GENERIC.test(foldName(s)) || /^PO\d|\bfase\b|\bvideo\b/i.test(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* A club or a school written as such ("AC", "FC", "SL", "EXT.", "Colégio"). A sponsor ("Bioria", "Betclic") is not.
|
||||
*/
|
||||
function looksLikeClub(side: string): boolean {
|
||||
return /\b(?:fc|sc|cf|cd|ud|gd|ad|cr|ac|sad|gc|ca|oc|cs|sl|cp|ext|externato|colegio|escola|academia|associacao|clube|atletico|recreativo|desportivo|juventude)\b/.test(foldName(side));
|
||||
}
|
||||
|
||||
type TeamRef = { name: string; abbreviation: string | null; slug: string };
|
||||
|
||||
function oneTeam(name: string, teams: readonly TeamRef[]): string | null {
|
||||
const fits = [...new Map(teams.filter((t) => isTeam(name, t)).map((t) => [fold(t.name), t])).values()];
|
||||
return fits.length === 1 ? fits[0]!.name : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What "A / B" means against known teams. Two different clubs: the name stays whole, so each side is read on its
|
||||
* own. A club and a sponsor ("Avanca / Bioria", "Sporting CP / Betclic"): that club. Undefined when it is not a
|
||||
* slash name.
|
||||
*/
|
||||
function slashClub(label: string, knownName: (side: string) => string | null): string | undefined {
|
||||
const sides = slashSides(label);
|
||||
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return undefined;
|
||||
const home = knownName(sides.home);
|
||||
const away = knownName(sides.away);
|
||||
const clubs = looksLikeClub(sides.home) && looksLikeClub(sides.away);
|
||||
const different = !!home && !!away && fold(home) !== fold(away);
|
||||
if (clubs || different) return label;
|
||||
if (home && !away) return home;
|
||||
if (away && !home) return away;
|
||||
if (home && away) return home;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Benfica / Porto" when both are known clubs and neither is written as a club form (the folder parser leaves
|
||||
* that as one name). "Avanca / Bioria" is not: Bioria is not a club. Null when the parser already split it.
|
||||
*/
|
||||
export function knownVersus(name: string, teams: readonly TeamRef[]): { home: string; away: string } | null {
|
||||
const sides = slashSides(name);
|
||||
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return null;
|
||||
if (looksLikeClub(sides.home) && looksLikeClub(sides.away)) return null;
|
||||
const home = oneTeam(sides.home, teams);
|
||||
const away = oneTeam(sides.away, teams);
|
||||
if (!home || !away || fold(home) === fold(away)) return null;
|
||||
return { home, away };
|
||||
}
|
||||
|
||||
/** A team's name as written in a folder without the date or number before it ("01.23 Leixões SC", "02_Estoril Praia"). */
|
||||
export function teamLabel(name: string): string {
|
||||
return name
|
||||
@@ -426,11 +582,57 @@ export function teamLabel(name: string): string {
|
||||
* The known team a folder's name means, when exactly one fits (abbreviation, initials, name or close name): its
|
||||
* official name, so "SCP", "Sporting" and "Sporting CP" are one team. The cleaned name otherwise.
|
||||
*/
|
||||
export function canonicalTeam(name: string, teams: readonly { name: string; abbreviation: string | null; slug: string }[]): string {
|
||||
export function canonicalTeam(name: string, teams: readonly TeamRef[]): string {
|
||||
const label = teamLabel(name);
|
||||
if (!label) return name.trim();
|
||||
const fits = [...new Map(teams.filter((t) => isTeam(label, t)).map((t) => [fold(t.name), t])).values()];
|
||||
return fits.length === 1 ? fits[0]!.name : label;
|
||||
const slash = slashClub(label, (side) => oneTeam(side, teams));
|
||||
if (slash !== undefined) return slash;
|
||||
return oneTeam(label, teams) ?? 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 type TeamMatch = ((name: string) => string) & { knownName(name: string): string | null };
|
||||
|
||||
export function teamMatcher(teams: readonly TeamRef[]): TeamMatch {
|
||||
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) : "" };
|
||||
});
|
||||
const knownName = (raw: string): string | null => {
|
||||
const label = teamLabel(raw);
|
||||
if (!label) return null;
|
||||
const n = fold(label);
|
||||
if (!n) return null;
|
||||
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 : null;
|
||||
};
|
||||
const match = (raw: string) => {
|
||||
const label = teamLabel(raw);
|
||||
if (!label) return raw.trim();
|
||||
const slash = slashClub(label, knownName);
|
||||
if (slash !== undefined) return slash;
|
||||
return knownName(label) ?? label;
|
||||
};
|
||||
match.knownName = knownName;
|
||||
return match;
|
||||
}
|
||||
|
||||
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[], now = new Date()): FixtureCandidate | null {
|
||||
|
||||
@@ -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),
|
||||
@@ -180,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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { boxInCrop, cropOfSettings } from "../faces/frame.js";
|
||||
import { cosine, inFocus, THRESHOLDS } from "../faces/math.js";
|
||||
import { notFound } from "../lib/errors.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
import { publishedPhotos } from "./gallery.js";
|
||||
import type { Viewer } from "./viewer.js";
|
||||
|
||||
/**
|
||||
@@ -49,8 +50,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
const scopeOf = async (v: Viewer): Promise<Prisma.Sql | null> => {
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.length) return null;
|
||||
if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
|
||||
return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
|
||||
if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`;
|
||||
return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
|
||||
};
|
||||
|
||||
const galleryInfo = async (folderIds: string[]) => {
|
||||
@@ -123,11 +124,11 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.length) return { people: [], clubs: [] };
|
||||
const scope = visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
|
||||
const folderLimit = visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.id = ANY(${visible}::uuid[])`;
|
||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published`
|
||||
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published AND cf.id = ANY(${visible}::uuid[])`;
|
||||
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; confirmed: bigint; probable: bigint }[]>`
|
||||
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference,
|
||||
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
|
||||
|
||||
@@ -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))] } },
|
||||
|
||||
@@ -244,6 +244,46 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Every indexed folder, for the app's publish tree. The public site does not use this: it only receives the
|
||||
* folders that stay published. Paths are from the source root, the way the tree shows them.
|
||||
*/
|
||||
app.get("/v1/cloud-sources/:sourceId/tree", { preHandler: authenticate }, async (req) => {
|
||||
const { sourceId } = SourceParams.parse(req.params);
|
||||
const source = await loadSource(req, sourceId, "EDITOR");
|
||||
const root = source.rootPath.replace(/\/+$/, "");
|
||||
const folders = await db.cloudFolder.findMany({
|
||||
where: { sourceId },
|
||||
select: { id: true, path: true, published: true, photoCount: true },
|
||||
orderBy: { path: "asc" },
|
||||
});
|
||||
return {
|
||||
folders: folders.flatMap((folder) => {
|
||||
const path = folder.path.startsWith(root) ? folder.path.slice(root.length).replace(/^\//, "") : folder.path.replace(/^\//, "");
|
||||
if (!path) return [];
|
||||
return [{ id: folder.id, path, published: folder.published, photoCount: folder.photoCount }];
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
/** Shows or hides a folder, and everything inside it, on the public site. */
|
||||
app.put("/v1/cloud-folders/:folderId/published", { preHandler: authenticate }, async (req) => {
|
||||
const { folderId } = FolderParams.parse(req.params);
|
||||
const body = z.object({ published: z.boolean() }).parse(req.body);
|
||||
const folder = await db.cloudFolder.findUnique({ where: { id: folderId } });
|
||||
if (!folder) throw notFound("folder_not_found");
|
||||
const source = await db.cloudSource.findUnique({ where: { id: folder.sourceId }, select: { organizationId: true } });
|
||||
if (!source) throw notFound("folder_not_found");
|
||||
await requireMembership(db, req, source.organizationId, "EDITOR");
|
||||
const updated = await db.$executeRaw`
|
||||
UPDATE cloud_folders
|
||||
SET published = ${body.published}
|
||||
WHERE source_id = ${folder.sourceId}::uuid
|
||||
AND (id = ${folder.id}::uuid OR starts_with(path, ${`${folder.path}/`}))
|
||||
`;
|
||||
return { published: body.published, updated: Number(updated) };
|
||||
});
|
||||
|
||||
/** Puts a gallery in an event, or in the event of a game (made when there is none). */
|
||||
app.put("/v1/cloud-folders/:folderId/event", { preHandler: authenticate }, async (req) => {
|
||||
const { folderId } = FolderParams.parse(req.params);
|
||||
|
||||
+104
-17
@@ -14,8 +14,8 @@ 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 { galleryAssignments } from "./gallery.js";
|
||||
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides } 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 +24,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. */
|
||||
@@ -277,6 +279,9 @@ export class ArchiveService {
|
||||
const stats = { folders: 0, queued: 0 };
|
||||
try {
|
||||
await this.walk(source, client, source.rootPath, null, stats, !!opts.full);
|
||||
// The gallery of each folder, from the paths just read. A rule change is also applied by the periodic check,
|
||||
// because a walk skips a folder whose etag did not change.
|
||||
await this.assignGalleries(sourceId);
|
||||
// Galleries named from the folder get their official game once it is known (fixtures arrive later, the
|
||||
// matching improves): no cloud calls, only the database.
|
||||
await this.rematch(sourceId);
|
||||
@@ -334,8 +339,17 @@ export class ArchiveService {
|
||||
}
|
||||
await db.cloudFile.deleteMany({ where: { folderId: folder.id, fileId: { notIn: images.map((i) => i.fileId) } } });
|
||||
|
||||
// Sub-folders gone from the cloud go from here too (and their images).
|
||||
await db.cloudFolder.deleteMany({ where: { sourceId: source.id, parentId: folder.id, fileId: { notIn: dirs.map((d) => d.fileId) } } });
|
||||
// Sub-folders gone from the cloud go from here too, with everything filed under them. The parent link is not a
|
||||
// foreign key, so deleting only the child would leave its tree behind.
|
||||
const gone = await db.cloudFolder.findMany({
|
||||
where: { sourceId: source.id, parentId: folder.id, ...(dirs.length ? { fileId: { notIn: dirs.map((d) => d.fileId) } } : {}) },
|
||||
select: { id: true, path: true },
|
||||
});
|
||||
if (gone.length) {
|
||||
const tree = gone.flatMap((g) => [{ id: g.id }, { path: { startsWith: `${g.path}/` } }]);
|
||||
await db.cloudFolder.updateMany({ where: { sourceId: source.id, OR: tree }, data: { galleryFolderId: null } });
|
||||
await db.cloudFolder.deleteMany({ where: { sourceId: source.id, OR: tree } });
|
||||
}
|
||||
|
||||
folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length } });
|
||||
if (images.length && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self);
|
||||
@@ -345,6 +359,53 @@ export class ArchiveService {
|
||||
await db.cloudFolder.update({ where: { id: folder.id }, data: { etag: self.etag } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes each folder's gallery from its path. One cloud, or every cloud. Safe to run while another pass is
|
||||
* already writing: the second waits, then finds nothing left to change.
|
||||
*/
|
||||
async assignGalleries(sourceId?: string): Promise<number> {
|
||||
const { db, log } = this.deps;
|
||||
// One connection for the lock and the writes. A second caller waits, then writes nothing.
|
||||
const changed = await db.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(84120012026)`;
|
||||
const folders = await tx.cloudFolder.findMany({
|
||||
where: sourceId ? { sourceId } : {},
|
||||
select: { id: true, sourceId: true, path: true, galleryFolderId: true },
|
||||
});
|
||||
const bySource = new Map<string, typeof folders>();
|
||||
for (const folder of folders) {
|
||||
const list = bySource.get(folder.sourceId);
|
||||
if (list) list.push(folder);
|
||||
else bySource.set(folder.sourceId, [folder]);
|
||||
}
|
||||
let updated = 0;
|
||||
for (const group of bySource.values()) {
|
||||
const want = galleryAssignments(group);
|
||||
const ids: string[] = [];
|
||||
const galleryIds: string[] = [];
|
||||
for (const folder of group) {
|
||||
const next = want.get(folder.id);
|
||||
if (!next || next === folder.galleryFolderId) continue;
|
||||
ids.push(folder.id);
|
||||
galleryIds.push(next);
|
||||
}
|
||||
const chunk = 2000;
|
||||
for (let i = 0; i < ids.length; i += chunk) {
|
||||
const sliceIds = ids.slice(i, i + chunk);
|
||||
const sliceGalleryIds = galleryIds.slice(i, i + chunk);
|
||||
updated += await tx.$executeRaw`
|
||||
UPDATE cloud_folders AS f
|
||||
SET gallery_folder_id = v.gallery_id
|
||||
FROM (SELECT * FROM unnest(${sliceIds}::uuid[], ${sliceGalleryIds}::uuid[]) AS v(id, gallery_id)) AS v
|
||||
WHERE f.id = v.id AND f.gallery_folder_id IS DISTINCT FROM v.gallery_id`;
|
||||
}
|
||||
}
|
||||
return updated;
|
||||
}, { timeout: 180_000, maxWait: 180_000 });
|
||||
if (changed) log.info({ changed, sourceId: sourceId ?? null }, "archive: galleries stored");
|
||||
return changed;
|
||||
}
|
||||
|
||||
// --- matching folders to games ---------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -369,11 +430,17 @@ export class ArchiveService {
|
||||
// matchday, a season, a month), and the check that a game found without a day is the right one.
|
||||
const shot = game.day ? null : await this.captureDay(folder.id);
|
||||
if (shot) game = { ...game, day: shot, month: null };
|
||||
// "Benfica / Porto": both known clubs, neither written as a club form. "Avanca / Bioria" stays one club.
|
||||
if (!game.away && slashSides(game.home)) {
|
||||
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
|
||||
const versus = knownVersus(game.home, await this.teamCatalog(source, !!liga));
|
||||
if (versus) game = { ...game, home: versus.home, away: versus.away, single: false };
|
||||
}
|
||||
const fixture = folder.fixtureRejected ? null : await this.findFixture(game, source);
|
||||
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" };
|
||||
}
|
||||
@@ -421,6 +488,8 @@ export class ArchiveService {
|
||||
// One check at a time (on start, every six hours, after a season's calendar is read): a second call waits for it.
|
||||
this.verifying ??= (async () => {
|
||||
try {
|
||||
// Paths already stored: a new naming rule has to land even when the cloud etags did not change.
|
||||
await this.assignGalleries();
|
||||
// Every cloud, signed in or not: the check needs only what was indexed.
|
||||
const sources = await this.deps.db.cloudSource.findMany({ select: { id: true } });
|
||||
// First what must never be seen: galleries on a game still to come (a quick query, every cloud at once).
|
||||
@@ -536,16 +605,20 @@ export class ArchiveService {
|
||||
* A game's sides by their clubs' names when the folder names them by initials ("SLB x FCP" → SL Benfica, FC
|
||||
* Porto): one known club with that abbreviation, or those initials. Countries are already named.
|
||||
*/
|
||||
private async teamNames(game: FolderGame, source: Pick<CloudSource, "baseUrl">): Promise<{ home: string; away: string; homeShort: string | null; awayShort: string | null }> {
|
||||
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
|
||||
if (!this.teams || this.teams.liga !== !!liga || Date.now() - this.teams.at > 3_600_000) {
|
||||
private async teamCatalog(source: Pick<CloudSource, "baseUrl">, liga: boolean) {
|
||||
if (!this.teams || this.teams.liga !== liga || Date.now() - this.teams.at > 3_600_000) {
|
||||
const list = await this.deps.db.sportsTeam.findMany({
|
||||
where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } },
|
||||
select: { name: true, abbreviation: true, slug: true },
|
||||
});
|
||||
this.teams = { at: Date.now(), liga: !!liga, list };
|
||||
this.teams = { at: Date.now(), liga, list };
|
||||
}
|
||||
const list = this.teams.list;
|
||||
return this.teams.list;
|
||||
}
|
||||
|
||||
private async teamNames(game: FolderGame, source: Pick<CloudSource, "baseUrl">): Promise<{ home: string; away: string; homeShort: string | null; awayShort: string | null }> {
|
||||
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
|
||||
const list = await this.teamCatalog(source, !!liga);
|
||||
const resolve = (name: string): { name: string; short: string | null } => {
|
||||
// A full name: the known team's official name when exactly one fits ("Sporting" → "Sporting CP").
|
||||
if (!name || name.length > 6 || /\s/.test(name)) return { name: name ? canonicalTeam(name, list) : name, short: null };
|
||||
@@ -615,8 +688,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 +884,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 +1046,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,8 @@ 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 { galleryMemberIds, listStoredGalleries, publishedPhotos } from "./gallery.js";
|
||||
import { directorySides, teamMatcher, type TeamMatch } from "./match.js";
|
||||
import type { FaceService } from "../faces/service.js";
|
||||
import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
|
||||
import { registerArchiveDownloadRoutes } from "./downloads.js";
|
||||
@@ -270,14 +271,15 @@ export async function registerArchiveViewerRoutes(
|
||||
|
||||
/** Indexed files of this source the viewer may see. Joined in later queries; never a list of photo ids. */
|
||||
const fileScope = (sourceId: string, visible: string[] | "all"): Prisma.Sql => {
|
||||
if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
|
||||
return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
|
||||
if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`;
|
||||
return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
|
||||
};
|
||||
|
||||
const folderWhere = (v: Viewer, visible: string[] | "all") => ({
|
||||
sourceId: v.s,
|
||||
photoCount: { gt: 0 },
|
||||
eventId: { not: null },
|
||||
published: true,
|
||||
...(visible !== "all" && { id: { in: visible } }),
|
||||
});
|
||||
|
||||
@@ -386,31 +388,32 @@ export async function registerArchiveViewerRoutes(
|
||||
* 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; abbreviation: string | null; slug: string }[]>; names: Map<string, string> }>();
|
||||
const canonicalNames = new Map<string, { at: number; known: Promise<TeamMatch>; 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 }>> => {
|
||||
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 db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
|
||||
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 known = await memo.known;
|
||||
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, (n) => canonical.knownName(n)) : []))) {
|
||||
if (!raw) continue;
|
||||
let name = memo.names.get(raw);
|
||||
if (name === undefined) {
|
||||
name = canonicalTeam(raw, known);
|
||||
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));
|
||||
@@ -437,6 +440,12 @@ export async function registerArchiveViewerRoutes(
|
||||
};
|
||||
if (!process.env.VITEST) {
|
||||
app.addHook("onReady", async () => {
|
||||
// Before the site is served: the cards are a read of this column.
|
||||
try {
|
||||
await deps.archive.assignGalleries();
|
||||
} catch (err) {
|
||||
app.log.warn({ err }, "archive: galleries not stored");
|
||||
}
|
||||
setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref();
|
||||
});
|
||||
}
|
||||
@@ -455,36 +464,46 @@ export async function registerArchiveViewerRoutes(
|
||||
const groups = await teamGroups(sourceId, rows.flatMap((r) => (r.event ? [r.event] : [])));
|
||||
teamNames = [...(groups.get(query.team)?.names ?? new Set([query.team]))];
|
||||
}
|
||||
const eventFilters = [
|
||||
...words.map((w) => ({ OR: [{ home: { contains: w, mode: "insensitive" as const } }, { away: { contains: w, mode: "insensitive" as const } }, { competition: { contains: w, mode: "insensitive" as const } }, { homeShort: { equals: w, mode: "insensitive" as const } }, { awayShort: { equals: w, mode: "insensitive" as const } }] })),
|
||||
...(query.team ? [{ OR: [{ home: { in: teamNames } }, { away: { in: teamNames } }] }] : []),
|
||||
...(query.player ? [{ photos: { some: { players: { has: query.player } } } }] : []),
|
||||
];
|
||||
const where = { ...folderWhere(v, visible), ...(eventFilters.length && { event: { AND: eventFilters } }) };
|
||||
const [total, folders] = await Promise.all([
|
||||
db.cloudFolder.count({ where }),
|
||||
db.cloudFolder.findMany({ where, include: { event: true }, orderBy: [{ event: { startsAt: "desc" } }, { path: "desc" }], skip: query.offset, take: query.limit }),
|
||||
]);
|
||||
const covers = folders.length
|
||||
? await db.cloudFile.findMany({ where: { folderId: { in: folders.map((f) => f.id) }, status: "DONE", photoId: { not: null } }, distinct: ["folderId"], orderBy: { path: "asc" }, select: { folderId: true, photoId: true } })
|
||||
// One card per game or session, from the gallery written when the folder was scanned. The parts are not more cards.
|
||||
const page = await listStoredGalleries(db, {
|
||||
sourceId,
|
||||
visible,
|
||||
words,
|
||||
teamNames,
|
||||
player: query.player,
|
||||
offset: query.offset,
|
||||
limit: query.limit,
|
||||
});
|
||||
const galleryIds = page.galleries.map((gallery) => gallery.id);
|
||||
const covers = galleryIds.length
|
||||
? await db.$queryRaw<{ gallery_id: string; photo_id: string }[]>`
|
||||
SELECT DISTINCT ON (COALESCE(f.gallery_folder_id, f.id)) COALESCE(f.gallery_folder_id, f.id) AS gallery_id, cf.photo_id
|
||||
FROM cloud_folders f
|
||||
JOIN cloud_files cf ON cf.folder_id = f.id AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL
|
||||
WHERE f.published AND COALESCE(f.gallery_folder_id, f.id) = ANY(${galleryIds}::uuid[])
|
||||
ORDER BY COALESCE(f.gallery_folder_id, f.id), cf.path`
|
||||
: [];
|
||||
const cover = new Map(covers.map((c) => [c.folderId, c.photoId!]));
|
||||
const cover = new Map(covers.map((file) => [file.gallery_id, file.photo_id]));
|
||||
return {
|
||||
viewer: { name: v.n },
|
||||
total,
|
||||
galleries: folders.map((f) => ({
|
||||
id: f.id,
|
||||
title: f.event ? eventName(f.event) : f.path.split("/").pop(),
|
||||
/** The part of the game or session ("1P", "Aquecimento", an athlete's name). */
|
||||
section: describeFolder(f.path).section,
|
||||
home: f.event?.home ?? null,
|
||||
away: f.event?.away || null,
|
||||
competition: f.event?.competition ?? null,
|
||||
startsAt: f.event?.startsAt ?? null,
|
||||
photoCount: f.photoCount,
|
||||
cover: cover.has(f.id) ? signer.url(cover.get(f.id)!, "thumb") : null,
|
||||
coverLarge: cover.has(f.id) ? signer.url(cover.get(f.id)!, "preview") : null,
|
||||
})),
|
||||
total: page.total,
|
||||
galleries: page.galleries.map((gallery) => {
|
||||
const photoId = cover.get(gallery.id) ?? null;
|
||||
const titled = gallery.home ? { home: gallery.home, away: gallery.away } : null;
|
||||
return {
|
||||
id: gallery.id,
|
||||
title: titled ? eventName(titled) : (gallery.path.split("/").pop() ?? gallery.path),
|
||||
/** Parts share the game's card, so the card itself is not "1P" or an athlete. */
|
||||
section: null,
|
||||
home: gallery.home,
|
||||
away: gallery.away,
|
||||
competition: gallery.competition,
|
||||
startsAt: gallery.startsAt,
|
||||
photoCount: gallery.photoCount,
|
||||
cover: photoId ? signer.url(photoId, "thumb") : null,
|
||||
coverLarge: photoId ? signer.url(photoId, "preview") : null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -497,7 +516,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 }>();
|
||||
@@ -506,6 +525,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 };
|
||||
});
|
||||
|
||||
@@ -535,13 +558,20 @@ export async function registerArchiveViewerRoutes(
|
||||
const v = viewerOf(req);
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found");
|
||||
const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } });
|
||||
const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s, published: true }, include: { event: true, source: { select: { baseUrl: true } } } });
|
||||
if (!folder) throw notFound("gallery_not_found");
|
||||
// The halves, the warm-up and a session's athletes are this gallery, not a folder of their own.
|
||||
const memberIds = await galleryMemberIds(db, folder.sourceId, folder);
|
||||
const ids = visible === "all" ? memberIds : memberIds.filter((id) => visible.includes(id));
|
||||
if (!ids.includes(folderId)) throw notFound("gallery_not_found");
|
||||
const galleryId = folder.galleryFolderId ?? folder.id;
|
||||
const head = galleryId === folder.id ? folder : await db.cloudFolder.findFirst({ where: { id: galleryId, sourceId: folder.sourceId, published: true }, include: { event: true } });
|
||||
const shown = head ?? folder;
|
||||
// Links to the cloud only for those who edit there; the others need not know where the photos live.
|
||||
const editable = await editableFolders(v);
|
||||
const onCloud = editable === "all" || editable.includes(folderId);
|
||||
const onCloud = editable === "all" || editable.includes(folderId) || (head ? editable.includes(head.id) : false);
|
||||
const where = {
|
||||
folderId,
|
||||
folderId: { in: ids },
|
||||
status: "DONE" as const,
|
||||
photoId: { not: null },
|
||||
...(query.player && { photo: { players: { has: query.player } } }),
|
||||
@@ -550,8 +580,8 @@ export async function registerArchiveViewerRoutes(
|
||||
// People named anywhere in this game (every part the viewer may see), not only in this folder.
|
||||
const rosterScope =
|
||||
visible === "all"
|
||||
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE'`
|
||||
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[])`;
|
||||
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND ${publishedPhotos}`
|
||||
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
|
||||
const [total, files, named, sharpest, roster] = await Promise.all([
|
||||
db.cloudFile.count({ where }),
|
||||
db.cloudFile.findMany({
|
||||
@@ -566,25 +596,25 @@ export async function registerArchiveViewerRoutes(
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN people p ON p.id = g.person_id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ANY(${ids}::uuid[]) AND cf.status = 'DONE'
|
||||
GROUP BY p.id
|
||||
ORDER BY count(DISTINCT f.photo_id) DESC, p.name`,
|
||||
db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>`
|
||||
SELECT DISTINCT ON (g.person_id) g.person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ANY(${ids}::uuid[]) AND cf.status = 'DONE'
|
||||
ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`,
|
||||
folder.eventId
|
||||
shown.eventId
|
||||
? db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; here: number; in_game: number }[]>`
|
||||
SELECT p.id, p.name, p.club, p.number,
|
||||
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ${folderId}::uuid)::int AS here,
|
||||
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ANY(${ids}::uuid[]))::int AS here,
|
||||
count(DISTINCT cf.photo_id)::int AS in_game
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
|
||||
JOIN people p ON p.id = g.person_id
|
||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${rosterScope}
|
||||
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${folder.eventId}::uuid
|
||||
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${shown.eventId}::uuid
|
||||
GROUP BY p.id, p.name, p.club, p.number
|
||||
ORDER BY p.name`
|
||||
: Promise.resolve([]),
|
||||
@@ -603,16 +633,16 @@ export async function registerArchiveViewerRoutes(
|
||||
);
|
||||
const base = folder.source.baseUrl.replace(/\/+$/, "");
|
||||
return {
|
||||
id: folder.id,
|
||||
title: folder.event ? eventName(folder.event) : folder.path.split("/").pop(),
|
||||
section: describeFolder(folder.path).section,
|
||||
id: shown.id,
|
||||
title: shown.event ? eventName(shown.event) : shown.path.split("/").pop(),
|
||||
section: null,
|
||||
/** A game's two sides (an event has no away side). */
|
||||
home: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.home : null,
|
||||
away: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.away || null : null,
|
||||
homeShort: folder.event?.homeShort ?? null,
|
||||
awayShort: folder.event?.awayShort ?? null,
|
||||
competition: folder.event?.competition ?? null,
|
||||
startsAt: folder.event?.startsAt ?? null,
|
||||
home: shown.event && shown.matchedBy !== "FOLDER" ? shown.event.home : null,
|
||||
away: shown.event && shown.matchedBy !== "FOLDER" ? shown.event.away || null : null,
|
||||
homeShort: shown.event?.homeShort ?? null,
|
||||
awayShort: shown.event?.awayShort ?? null,
|
||||
competition: shown.event?.competition ?? null,
|
||||
startsAt: shown.event?.startsAt ?? null,
|
||||
/** The folder on the cloud (opens for those it is shared with). */
|
||||
cloudUrl: onCloud ? `${base}/f/${folder.fileId}` : null,
|
||||
total,
|
||||
@@ -644,6 +674,8 @@ export async function registerArchiveViewerRoutes(
|
||||
if (!file?.photo) throw notFound("photo_not_found");
|
||||
const visible = await visibleFolders(v);
|
||||
if (visible !== "all" && !visible.includes(file.folderId)) throw notFound("photo_not_found");
|
||||
const listed = await db.cloudFolder.findFirst({ where: { id: file.folderId, published: true }, select: { id: true } });
|
||||
if (!listed) throw notFound("photo_not_found");
|
||||
const faces = await facesOfPhotos(db, [file.photo]);
|
||||
return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] };
|
||||
});
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The autopilot's finishing "look": colour, local contrast, sharpening and noise reduction, on top of the measured
|
||||
* white balance and tone (docs/photo-editing-rules.md §4). Fixed values, not measured per photo, so a match looks
|
||||
* like one set. Measured on the agencies (October 2026):
|
||||
*
|
||||
* - kolektiff images (EHF/IHF handball, 600 photos of 2025-26): saturated, punchy kits (HSV saturation 0.47),
|
||||
* pure blacks, neutral whites, shadows a touch cool (blue-magenta) in every photographer's work.
|
||||
* - Getty Images and AFP (Paris 2024, 1093 action photos): the same cool shadows and neutral whites, more natural
|
||||
* colour (0.40-0.43).
|
||||
*
|
||||
* "agency" follows kolektiff, "natural" Getty. Both stay inside the ethics rules: toning for clear reproduction,
|
||||
* no vignette or background darkening, nothing local.
|
||||
*/
|
||||
|
||||
export type Look = "agency" | "natural" | "none";
|
||||
|
||||
const BASE: Record<Exclude<Look, "none">, Record<string, number>> = {
|
||||
agency: {
|
||||
"color.vibrance": 18,
|
||||
"color.saturation": 4,
|
||||
"effects.clarity": 8,
|
||||
"effects.texture": 6,
|
||||
"grading.shadows.hue": 245,
|
||||
"grading.shadows.sat": 8,
|
||||
"grading.balance": -10,
|
||||
},
|
||||
natural: {
|
||||
"color.vibrance": 8,
|
||||
"effects.clarity": 4,
|
||||
"effects.texture": 4,
|
||||
"grading.shadows.hue": 245,
|
||||
"grading.shadows.sat": 4,
|
||||
},
|
||||
};
|
||||
|
||||
/** Capture sharpening for both looks (Lightroom-like amount, radius, detail; masking keeps flat skin and floor smooth). */
|
||||
const SHARPEN = { "detail.sharpenAmount": 40, "detail.sharpenRadius": 1, "detail.sharpenDetail": 25, "detail.sharpenMasking": 35 };
|
||||
|
||||
/** Noise reduction by ISO: none in good light, more in dim arenas (sports halls run ISO 3200-12800). */
|
||||
export function noiseReduction(iso: number | null | undefined): Record<string, number> {
|
||||
const out: Record<string, number> = { "detail.nrColor": 25 };
|
||||
if (!iso || iso < 1600) return out;
|
||||
out["detail.nrLuminance"] = iso < 3200 ? 8 : iso < 6400 ? 15 : iso < 12800 ? 22 : 30;
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The look's values for one photo (empty for "none"). */
|
||||
export function lookValues(look: Look, iso?: number | null): Record<string, number> {
|
||||
if (look === "none") return {};
|
||||
return { ...BASE[look], ...SHARPEN, ...noiseReduction(iso) };
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { sequenceWeights } from "./sequence.js";
|
||||
import { bestOf, groupBursts } from "./bursts.js";
|
||||
import { curate, matchMinutes } from "./curate.js";
|
||||
import { type LearntStyle, learntStyle, TONE_KEYS, WB_KEYS } from "./learning.js";
|
||||
import { lookValues } from "./look.js";
|
||||
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
/** A burst is decided once no new frame of it has arrived for this long. */
|
||||
@@ -25,12 +26,16 @@ const BURST_SETTLE_MS = 15_000;
|
||||
/** Straightening beyond this is more likely a creative tilt than a crooked horizon: left alone. */
|
||||
const MAX_LEVEL = 5;
|
||||
const MIN_LEVEL = 0.3;
|
||||
/** A crop this close to the whole frame (width) is not worth making: the photo stays as shot (agencies send a third uncropped). */
|
||||
const KEEP_WHOLE = 0.92;
|
||||
|
||||
export interface AutopilotRecord {
|
||||
score: number;
|
||||
reason: string | null;
|
||||
subject: Box | null;
|
||||
crop: Box | null;
|
||||
/** The whole-body frame, when the crop is tight: the second pick of a burst gets it (variety). */
|
||||
wide?: Box | null;
|
||||
angle: number;
|
||||
/** What it had learnt from corrections and added to its own edit. */
|
||||
style?: LearntStyle | null;
|
||||
@@ -111,6 +116,8 @@ export class AutopilotService {
|
||||
const v = (auto.values[k] ?? 0) * settings.toneStrength + (style?.offsets[k] ?? 0);
|
||||
if (v) values[k] = Math.round(v * 100) / 100;
|
||||
}
|
||||
// The finishing look (colour, local contrast, sharpening, noise by ISO): never over what was measured.
|
||||
for (const [k, v] of Object.entries(lookValues(settings.look, photo.iso))) if (values[k] === undefined) values[k] = v;
|
||||
if (Object.keys(values).length) ops.push({ command: "develop.set", params: { values } } as EditCommand);
|
||||
if (settings.level && auto.angle !== null && Math.abs(auto.angle) >= MIN_LEVEL && Math.abs(auto.angle) <= MAX_LEVEL) angle = auto.angle;
|
||||
}
|
||||
@@ -121,14 +128,18 @@ export class AutopilotService {
|
||||
const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null;
|
||||
const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
|
||||
const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null);
|
||||
const composition = detections ? compose(detections, aspect, { minWidth: minCropWidth(W, H, settings.minLongEdge), focus }) : null;
|
||||
const minWidth = minCropWidth(W, H, settings.minLongEdge);
|
||||
const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing }) : null;
|
||||
const wideComposition = detections && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full" }) : null;
|
||||
let crop: Box | null = null;
|
||||
if (settings.crop && composition) {
|
||||
// Photographers who always tighten the autopilot's crop get it tighter (never cutting into the subject).
|
||||
const rect = style?.cropFactor ? tighter(composition.rect, composition.subject, style.cropFactor) : composition.rect;
|
||||
crop = constrainRotated(rect, angle, W, H);
|
||||
// Almost the whole frame: leave the photo as shot.
|
||||
if (rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, angle, W, H);
|
||||
}
|
||||
else if (angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null;
|
||||
if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand);
|
||||
|
||||
// Someone already edited it (on the desktop app without a network, before it was uploaded): their edit
|
||||
@@ -147,6 +158,7 @@ export class AutopilotService {
|
||||
reason: composition?.reason ?? null,
|
||||
subject: composition?.subject ?? null,
|
||||
crop,
|
||||
wide,
|
||||
angle,
|
||||
style: style && (Object.keys(style.offsets).length || style.cropFactor) ? style : null,
|
||||
};
|
||||
@@ -200,11 +212,14 @@ export class AutopilotService {
|
||||
broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } });
|
||||
picked += toFlag.length;
|
||||
}
|
||||
// Variety: the second pick gets a slightly tighter frame than the first.
|
||||
// Variety: the second pick gets the other framing. A tight first pick: the wider, whole-body frame (the
|
||||
// context the agencies mix in); otherwise a slightly tighter one.
|
||||
const second = best[1];
|
||||
const secondEdited = second ? await db.photoEdit.count({ where: { photoId: second.id, NOT: { clientId: "autopilot" } } }) : 0;
|
||||
if (second?.rec?.crop && second.rec.subject && settings.crop && !secondEdited) {
|
||||
const rect = constrainRotated(tighter(second.rec.crop, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
const crop2 = second?.rec?.crop;
|
||||
const wider = crop2 && second.rec?.wide && (second.rec.wide.x1 - second.rec.wide.x0) / (crop2.x1 - crop2.x0) > 1.12 ? second.rec.wide : null;
|
||||
if (crop2 && second.rec?.subject && settings.crop && !secondEdited) {
|
||||
const rect = wider ?? constrainRotated(tighter(crop2, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
await develop
|
||||
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
|
||||
* crowd and the stands). Legs may be cut; heads and the ball may not.
|
||||
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
|
||||
* - "tight" framing (the agencies' handball look: kolektiff images, measured on 600 photos of 2025-26): the
|
||||
* subject fills the height, cut mid-shin or mid-thigh, the face big (about a seventh of the frame) near the top.
|
||||
* "full" keeps whole bodies when they fit (Peter's usual two thirds of the frame).
|
||||
*
|
||||
* Boxes are fractions of the upright photo (0..1, y down).
|
||||
* When the camera wrote a focus point, the person under it is the subject; sharpness still frames everyone else.
|
||||
@@ -79,7 +82,12 @@ export const TUNING = {
|
||||
const JOINTS = [0.17, 0.53, 0.74, 0.95];
|
||||
const JOINT_BAND = 0.035;
|
||||
|
||||
/** Tight framing: the subject's tallest body about this many crop heights (a little cut at the bottom). */
|
||||
export const TIGHT = { fillAt: 1.05, wFill: 2.2, chestAt: 0.34, headMax: 0.2 };
|
||||
|
||||
export interface ComposeOptions {
|
||||
/** "full": whole bodies when they fit (default); "tight": the agencies' close framing, legs cut mid-limb. */
|
||||
framing?: "full" | "tight";
|
||||
/** Narrowest crop allowed, as a fraction of the photo's width (from the delivery's minimum resolution). */
|
||||
minWidth?: number;
|
||||
/** Where the camera focused. The person there is the subject; the rest of the crop still follows the model. */
|
||||
@@ -100,7 +108,7 @@ const atEdge = (b: Box) => b.x0 < 0.01 || b.x1 > 0.99;
|
||||
const sharp = (p: Detection) => p.sharpness ?? 1;
|
||||
|
||||
/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */
|
||||
export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box; reason: Composition["reason"]; people: Detection[] } | null {
|
||||
export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
||||
const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT);
|
||||
if (!people.length) return null;
|
||||
// The main subject: the person the camera focused on, when that point lands on someone. Otherwise in focus
|
||||
@@ -119,7 +127,7 @@ export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box
|
||||
const contest = people.filter((p) => p === main || (h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)));
|
||||
if (!contest.includes(main)) contest.push(main);
|
||||
const box = contest.reduce<Box>((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 });
|
||||
return { box, reason: "ball", people: contest };
|
||||
return { box, reason: "ball", people: contest, ball };
|
||||
}
|
||||
|
||||
// No ball: the subject and the sharp people standing with them (a duel, a celebration, a line-up).
|
||||
@@ -162,13 +170,24 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null
|
||||
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
|
||||
const found = findSubject(d, opts.focus);
|
||||
if (!found) return null;
|
||||
const { box: s, reason, people: inSubject } = found;
|
||||
const { box: s, reason, people: inSubject, ball } = found;
|
||||
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
|
||||
const tallest = Math.max(...inSubject.map(h));
|
||||
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
|
||||
const headroom = 0.04 * tallest;
|
||||
// Whole bodies, feet included; only when that can't fit, down to the waist.
|
||||
const minWidth = opts.minWidth ?? 0;
|
||||
if (opts.framing === "tight") {
|
||||
// The ball (and the hands on it) is never cut: the bottom edge stays below it.
|
||||
const keep = (y: number) => Math.min(s.y1, Math.max(y, ball ? ball.y1 + 0.01 : 0));
|
||||
// Mid-shin, mid-thigh, or whole: the cost (fill, head, joints) chooses; the waist only when nothing else fits.
|
||||
const tries = [keep(s.y0 + 0.86 * tallest), keep(s.y0 + 0.64 * tallest), s.y1]
|
||||
.map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, true))
|
||||
.filter((c): c is Composition & { cost: number } => !!c);
|
||||
const best = tries.reduce<(Composition & { cost: number }) | null>((a, b) => (!a || b.cost < a.cost ? b : a), null);
|
||||
if (best) return { rect: best.rect, subject: best.subject, reason: best.reason, people: best.people };
|
||||
return frame(s, ratio, keep(s.y0 + 0.55 * tallest), headroom, tallest, others, inSubject, reason, minWidth, true);
|
||||
}
|
||||
// Whole bodies, feet included; only when that can't fit, down to the waist.
|
||||
return frame(s, ratio, s.y1, headroom, tallest, others, inSubject, reason, minWidth) ?? frame(s, ratio, s.y0 + 0.55 * tallest, headroom, tallest, others, inSubject, reason, minWidth);
|
||||
}
|
||||
|
||||
@@ -178,7 +197,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400):
|
||||
return Math.min(1, Math.max(0.35, minLongEdge / long) * (width >= height ? 1 : height / width));
|
||||
}
|
||||
|
||||
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number): Composition | null {
|
||||
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false): (Composition & { cost: number }) | null {
|
||||
const mainSharp = Math.max(...inSubject.map(sharp));
|
||||
let best: { rect: Box; cost: number } | null = null;
|
||||
for (let k = 0.35; k <= 1.0001; k += 0.025) {
|
||||
@@ -200,16 +219,16 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
const y0 = Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
|
||||
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
|
||||
if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject) + jointCost(r, inSubject, others, mainSharp);
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight) + jointCost(r, inSubject, others, mainSharp);
|
||||
if (!best || c < best.cost) best = { rect: r, cost: c };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!best) return null;
|
||||
return { rect: best.rect, subject: s, reason, people: inSubject.length };
|
||||
return { rect: best.rect, subject: s, reason, people: inSubject.length, cost: best.cost };
|
||||
}
|
||||
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[]): number {
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false): number {
|
||||
let c = 0;
|
||||
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
|
||||
for (const p of others) {
|
||||
@@ -220,21 +239,26 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
|
||||
const size = Math.min(1, h(p) / tallest);
|
||||
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
|
||||
}
|
||||
// Peter's usual crop is two thirds of the frame; bigger only when the subject needs it.
|
||||
const k = Math.max(ch, w(r) / ratio);
|
||||
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
|
||||
// The subject fills a good part of the height (people tall in the frame).
|
||||
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
||||
if (tight) {
|
||||
// The agencies' framing: the subject as tall as the crop (or a little taller, legs cut mid-limb).
|
||||
c += TIGHT.wFill * Math.abs(tallest / ch - TIGHT.fillAt);
|
||||
} else {
|
||||
// Peter's usual crop is two thirds of the frame; bigger only when the subject needs it.
|
||||
const k = Math.max(ch, w(r) / ratio);
|
||||
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
|
||||
// The subject fills a good part of the height (people tall in the frame).
|
||||
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
||||
}
|
||||
// Centred across.
|
||||
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
|
||||
// Heads a little below the top: not touching it, not floating in empty space.
|
||||
const head = (s.y0 - r.y0) / ch;
|
||||
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - TUNING.headMax));
|
||||
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - (tight ? TIGHT.headMax : TUNING.headMax)));
|
||||
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
|
||||
// the middle with a strip of grass below.
|
||||
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
|
||||
c += TUNING.wChest * Math.abs(chest - TUNING.chestAt);
|
||||
c += TUNING.wChest * Math.abs(chest - (tight ? TIGHT.chestAt : TUNING.chestAt));
|
||||
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
|
||||
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
|
||||
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
|
||||
|
||||
@@ -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,9 @@ 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 { galleryAssignments } from "../src/archive/gallery.js";
|
||||
import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryRoot, isExhibition, isInitials, isTeam, knownVersus, 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 +30,65 @@ 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"]);
|
||||
// A sponsor after the slash is the same club, not the away team. "Avanca / Bioria" was Avanca.
|
||||
expect(parseFolder("/Liga/04.11.23 Avanca / Bioria")).toMatchObject({ home: "Avanca / Bioria", away: "", single: true, day: "2023-11-04" });
|
||||
expect(parseFolder("/FPA/Fotos/2024_2025/PO01/20240913 - Avanca / Bioria")).toBeNull();
|
||||
expect(parseFolder("/Liga/04.11.23 Sporting CP / Betclic")).toMatchObject({ home: "Sporting CP / Betclic", away: "", single: true });
|
||||
const clubs = [
|
||||
{ name: "Avanca", abbreviation: null, slug: "avanca" },
|
||||
{ name: "SL Benfica", abbreviation: "SLB", slug: "benfica" },
|
||||
{ name: "FC Porto", abbreviation: "FCP", slug: "porto" },
|
||||
{ name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" },
|
||||
];
|
||||
expect(canonicalTeam("Avanca / Bioria", clubs)).toBe("Avanca");
|
||||
expect(canonicalTeam("Bioria / Avanca", clubs)).toBe("Avanca");
|
||||
expect(canonicalTeam("Sporting CP / Betclic", clubs)).toBe("Sporting CP");
|
||||
expect(canonicalTeam("ALMADA AC / EXT. GIL EANES", clubs)).toBe("ALMADA AC / EXT. GIL EANES");
|
||||
expect(knownVersus("Avanca / Bioria", clubs)).toBeNull();
|
||||
expect(knownVersus("Benfica / Porto", clubs)).toEqual({ home: "SL Benfica", away: "FC Porto" });
|
||||
const match = teamMatcher(clubs);
|
||||
expect(directorySides("Avanca / Bioria", (n) => match.knownName(n))).toEqual(["Avanca / Bioria"]);
|
||||
expect(directorySides("Benfica / Porto", (n) => match.knownName(n))).toEqual(["Benfica", "Porto"]);
|
||||
for (const name of ["Avanca / Bioria", "Bioria / Avanca", "Sporting CP / Betclic", "Benfica / Porto", "ALMADA AC / EXT. GIL EANES"])
|
||||
expect(match(name)).toBe(canonicalTeam(name, clubs));
|
||||
});
|
||||
|
||||
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",
|
||||
@@ -143,6 +203,45 @@ describe("archive folder names", () => {
|
||||
expect(describeFolder(`${session.replace("20241118 - Sessão", "20260306 - Sessao")}/Grupos`).people).toEqual([]);
|
||||
});
|
||||
|
||||
it("puts a game's parts and a session's athletes in one gallery", () => {
|
||||
const game = "/FPA/Fotos/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP";
|
||||
for (const part of ["1P", "2P", "Aquecimento", "Cerimónia", "1 - Pre-Match", "2 - 1st Half", "WARM UP", "GAME", "FLASH", "P1"]) {
|
||||
expect(galleryRoot(`${game}/${part}`)).toBe(game);
|
||||
expect(galleryRoot(`${game}/${part}/selecionadas`)).toBe(game);
|
||||
}
|
||||
const session = "/FPA/Fotos/2023_2024/Seleções Nacionais/Seleção Nacional A Feminina/20231008 - Sessao SNAF";
|
||||
expect(galleryRoot(`${session}/7 - Bebiana Sabino`)).toBe(session);
|
||||
expect(galleryRoot(`${session}/Equipa Técnica/Ana Teixeira`)).toBe(session);
|
||||
expect(galleryRoot("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio/Diogo Rema")).toBe(
|
||||
"/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio",
|
||||
);
|
||||
// A game filed inside another folder stays its own gallery.
|
||||
const nest = "/FPA/Fotos/2023_2024/Eventos/20240608 - Colégio Gaia x Vermoim";
|
||||
expect(galleryRoot(`${nest}/20240509 - Portugal x Bosnia`)).toBe(`${nest}/20240509 - Portugal x Bosnia`);
|
||||
expect(galleryRoot("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC")).toBe("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC");
|
||||
// A shelf that is not two clubs does not swallow the days under it, nor does a final without two clubs.
|
||||
expect(galleryRoot("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1")).toBe("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1");
|
||||
expect(galleryRoot("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1")).toBe("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1");
|
||||
// The same game copied under another name, when that copy is itself a game, stays separate.
|
||||
expect(galleryRoot("/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO")).toBe(
|
||||
"/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO",
|
||||
);
|
||||
// The duplicate mirror is not a session just because the shelf says "sessão".
|
||||
const mirror = "/FPA/Fotos/SESSÃO ESTÚDIO SNAF (2020 a 2022) - Equipamento Select/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP";
|
||||
expect(galleryRoot(`${mirror}/1P`)).toBe(mirror);
|
||||
const gameId = "game";
|
||||
const partId = "part";
|
||||
const nestedId = "nested";
|
||||
const assigned = galleryAssignments([
|
||||
{ id: gameId, path: game },
|
||||
{ id: partId, path: `${game}/1P` },
|
||||
{ id: nestedId, path: `${nest}/20240509 - Portugal x Bosnia` },
|
||||
]);
|
||||
expect(assigned.get(partId)).toBe(gameId);
|
||||
expect(assigned.get(gameId)).toBe(gameId);
|
||||
expect(assigned.get(nestedId)).toBe(nestedId);
|
||||
});
|
||||
|
||||
it("names what is not a game after the folders above when its own name says little", () => {
|
||||
expect(describeFolder("/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2/Cerimónia")).toMatchObject({
|
||||
occasion: "/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2",
|
||||
@@ -224,6 +323,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 +374,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 +669,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 +792,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;
|
||||
|
||||
@@ -187,7 +187,8 @@ describe("autopilot", () => {
|
||||
ingestFrom: new Date("2026-10-11T12:00:00Z"),
|
||||
ingestUntil: new Date("2026-10-11T18:00:00Z"),
|
||||
iptcTemplate: {},
|
||||
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2 } }),
|
||||
// The original settings (half tone, white balance as shot, no look, whole bodies); the agency defaults have a test of their own.
|
||||
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2, toneStrength: 0.5, whiteBalance: false, look: "none", framing: "full" } }),
|
||||
},
|
||||
});
|
||||
return { orgId: org!.id, userId: user.id, eventId: event.id };
|
||||
@@ -297,6 +298,18 @@ describe("autopilot", () => {
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE");
|
||||
});
|
||||
|
||||
it("edits the agencies' way by default: neutral whites, fuller tone, the finishing look", async () => {
|
||||
const { orgId, userId, eventId } = await setup();
|
||||
await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true } } });
|
||||
const id = await shot(orgId, userId, eventId, 0, 300);
|
||||
await ctx.db.photo.update({ where: { id }, data: { iso: 6400 } });
|
||||
await runQueue();
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } });
|
||||
const values = (edits[0]!.command as { params: { values: Record<string, number> } }).params.values;
|
||||
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 40, "detail.nrLuminance": 22 });
|
||||
expect(Object.keys(values).some((k) => k.startsWith("vignette."))).toBe(false);
|
||||
});
|
||||
|
||||
it("leaves events without autopilot alone", async () => {
|
||||
const { orgId, userId, eventId } = await setup(false);
|
||||
await shot(orgId, userId, eventId, 0, 100);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -84,3 +84,29 @@ describe("automatic crop", () => {
|
||||
expect(((c.rect.x1 - c.rect.x0) * 3000) / ((c.rect.y1 - c.rect.y0) * 2000)).toBeCloseTo(0.8, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tight framing (the agencies' handball look)", () => {
|
||||
it("fills the height with the player, cutting the legs mid-limb, never at a joint or below the ball", () => {
|
||||
const p = { ...person(0.42, 0.1, 0.56, 0.9), sharpness: 1 };
|
||||
const ball = { x0: 0.5, y0: 0.35, x1: 0.54, y1: 0.41, score: 0.8 };
|
||||
const full = compose({ ...frame, people: [p], balls: [ball] })!;
|
||||
const tight = compose({ ...frame, people: [p], balls: [ball] }, null, { framing: "tight" })!;
|
||||
const hT = tight.rect.y1 - tight.rect.y0;
|
||||
expect(hT).toBeLessThan(full.rect.y1 - full.rect.y0);
|
||||
// The player about as tall as the crop: feet out, head in.
|
||||
expect(tight.rect.y1).toBeLessThan(p.y1);
|
||||
expect(tight.rect.y0).toBeLessThanOrEqual(p.y0);
|
||||
expect(tight.rect.y1).toBeGreaterThan(ball.y1);
|
||||
const at = (tight.rect.y1 - p.y0) / (p.y1 - p.y0);
|
||||
for (const j of [0.53, 0.74, 0.95]) expect(Math.abs(at - j)).toBeGreaterThanOrEqual(0.035);
|
||||
// Same shape as the photo.
|
||||
expect(((tight.rect.x1 - tight.rect.x0) * 3000) / (hT * 2000)).toBeCloseTo(1.5, 2);
|
||||
});
|
||||
|
||||
it("keeps a ball held low inside the crop", () => {
|
||||
const p = { ...person(0.42, 0.1, 0.56, 0.9), sharpness: 1 };
|
||||
const ball = { x0: 0.5, y0: 0.7, x1: 0.54, y1: 0.76, score: 0.8 };
|
||||
const tight = compose({ ...frame, people: [p], balls: [ball] }, null, { framing: "tight" })!;
|
||||
expect(tight.rect.y1).toBeGreaterThan(ball.y1);
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
@@ -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") =>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { lookValues, noiseReduction } from "../src/autopilot/look.js";
|
||||
|
||||
describe("autopilot look", () => {
|
||||
it("gives the agency look punchier colour than the natural one, and nothing for none", () => {
|
||||
const agency = lookValues("agency", 400);
|
||||
const natural = lookValues("natural", 400);
|
||||
expect(agency["color.vibrance"]!).toBeGreaterThan(natural["color.vibrance"]!);
|
||||
expect(agency["detail.sharpenAmount"]).toBe(40);
|
||||
expect(lookValues("none", 6400)).toEqual({});
|
||||
// Never a vignette: the ethics rules forbid darkening the background.
|
||||
expect(Object.keys(agency).some((k) => k.startsWith("vignette."))).toBe(false);
|
||||
});
|
||||
|
||||
it("reduces noise more as the ISO climbs", () => {
|
||||
expect(noiseReduction(800)["detail.nrLuminance"]).toBeUndefined();
|
||||
expect(noiseReduction(3200)["detail.nrLuminance"]!).toBeLessThan(noiseReduction(12800)["detail.nrLuminance"]!);
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
@@ -301,6 +303,15 @@ export const t = {
|
||||
tone: "Tom",
|
||||
whiteBalance: "Equilíbrio de brancos",
|
||||
toneStrength: (n: number) => `Intensidade do tom: ${n}%`,
|
||||
framing: "Enquadramento",
|
||||
framingTight: "Apertado (estilo agência)",
|
||||
framingFull: "Corpo inteiro",
|
||||
framingHelp: "Apertado: o jogador ocupa a altura, cortado a meio da perna, a cara grande; a segunda escolhida de cada sequência leva o enquadramento largo, de corpo inteiro. Fotos já bem enquadradas ficam como foram tiradas.",
|
||||
look: "Acabamento",
|
||||
lookAgency: "Agência (cores fortes)",
|
||||
lookNatural: "Natural",
|
||||
lookNone: "Nenhum",
|
||||
lookHelp: "Cor, contraste local, nitidez e redução de ruído conforme o ISO, iguais em todas as fotos do jogo. Nunca escurece o fundo nem mexe numa zona só.",
|
||||
picksPerBurst: "Escolher por sequência",
|
||||
noPicks: "Não escolher",
|
||||
minLongEdge: "Resolução mínima do recorte",
|
||||
@@ -504,6 +515,12 @@ export const t = {
|
||||
diskNeeded: (n: string) => ` · as fotos por indexar vão ocupar cerca de ${n}`,
|
||||
diskShort: (min: string) => `Não chega: aumenta o disco do servidor. A indexação pára sozinha quando ficarem menos de ${min} livres.`,
|
||||
diskPaused: (min: string) => `Indexação em pausa: o disco tem menos de ${min} livres. Aumenta o disco e continua sozinha.`,
|
||||
siteFolders: "Pastas no site",
|
||||
siteFoldersHelp: "Por defeito entram todas. Tira o visto a uma pasta para ela deixar de aparecer no site, mesmo que a cloud a partilhe. Vale também para as pastas que estão dentro.",
|
||||
siteFoldersSearch: "Procurar pasta…",
|
||||
siteFoldersEmpty: "Ainda não há pastas indexadas.",
|
||||
siteFoldersLoading: "A carregar…",
|
||||
siteFoldersPhotos: (n: number) => `${n.toLocaleString("pt-PT")} fotos`,
|
||||
},
|
||||
metadataPage: {
|
||||
iptc: "Legendas",
|
||||
|
||||
@@ -58,6 +58,21 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta
|
||||
<span className="text-faint">{L.toneStrength(Math.round(s.toneStrength * 100))}</span>
|
||||
<input type="range" min={0} max={100} value={Math.round(s.toneStrength * 100)} disabled={!s.enabled || !s.tone || !props.canEdit} className="w-full" onChange={(e) => setS({ ...s, toneStrength: Number(e.target.value) / 100 })} onPointerUp={() => void save(s)} />
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2" title={L.framingHelp}>
|
||||
<span>{L.framing}</span>
|
||||
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !s.crop || !props.canEdit} value={s.framing} onChange={(e) => void save({ ...s, framing: e.target.value as AutopilotSettings["framing"] })}>
|
||||
<option value="tight">{L.framingTight}</option>
|
||||
<option value="full">{L.framingFull}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2" title={L.lookHelp}>
|
||||
<span>{L.look}</span>
|
||||
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.look} onChange={(e) => void save({ ...s, look: e.target.value as AutopilotSettings["look"] })}>
|
||||
<option value="agency">{L.lookAgency}</option>
|
||||
<option value="natural">{L.lookNatural}</option>
|
||||
<option value="none">{L.lookNone}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.picksPerBurst}</span>
|
||||
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.picksPerBurst} onChange={(e) => void save({ ...s, picksPerBurst: Number(e.target.value) })}>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { t } from "../i18n.js";
|
||||
import { teamDisplayName } from "../library/EventForm.js";
|
||||
import { openExternal } from "../platform.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
import { SiteFolders } from "./SiteFolders.js";
|
||||
|
||||
const A = t.archive;
|
||||
const VIEWER_BASE = EVENTS_URL;
|
||||
@@ -22,6 +23,7 @@ export function ArchivePage() {
|
||||
const { api, organization, role } = useAuth();
|
||||
const orgId = organization?.id ?? "";
|
||||
const isAdmin = role !== null && hasRole(role, "ADMIN");
|
||||
const canEdit = role !== null && hasRole(role, "EDITOR");
|
||||
const [sources, setSources] = useState<CloudSource[] | null>(null);
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
const [storage, setStorage] = useState<ArchiveStorage | null>(null);
|
||||
@@ -72,6 +74,7 @@ export function ArchivePage() {
|
||||
))}
|
||||
{isAdmin ? <ConnectForm api={api} orgId={orgId} onConnected={(s) => setSources((list) => [...(list ?? []), s])} /> : <p className="text-[12px] text-faint">{A.adminOnly}</p>}
|
||||
{current && current.status !== "LOGIN" && <Galleries key={current.id} api={api} source={current} />}
|
||||
{current && current.status !== "LOGIN" && canEdit && <SiteFolders key={`${current.id}-site`} api={api} source={current} />}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
import { ApiError, type ApiClient, type CloudSource, type CloudTreeFolder } from "@photoreport/sdk";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
const A = t.archive;
|
||||
const errorText = (code: string | null) => (code ? (A.errors[code] ?? code) : null);
|
||||
const errorOf = (err: unknown) => errorText(err instanceof ApiError ? err.code : null) ?? t.unexpectedError;
|
||||
|
||||
interface Node {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
published: boolean;
|
||||
photoCount: number;
|
||||
children: Node[];
|
||||
}
|
||||
|
||||
/** Folders under a source root, nested by path. */
|
||||
function treeOf(folders: CloudTreeFolder[]): Node[] {
|
||||
const byPath = new Map<string, Node>();
|
||||
const roots: Node[] = [];
|
||||
const sorted = [...folders].sort((a, b) => a.path.localeCompare(b.path, "pt"));
|
||||
for (const folder of sorted) {
|
||||
const path = folder.path.replace(/^\/+|\/+$/g, "");
|
||||
if (!path) continue;
|
||||
const name = path.split("/").pop() ?? path;
|
||||
const node: Node = { id: folder.id, name, path, published: folder.published, photoCount: folder.photoCount, children: [] };
|
||||
byPath.set(path, node);
|
||||
const parentPath = path.split("/").slice(0, -1).join("/");
|
||||
const parent = parentPath ? byPath.get(parentPath) : undefined;
|
||||
if (parent) parent.children.push(node);
|
||||
else roots.push(node);
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
function filterTree(nodes: Node[], query: string): Node[] {
|
||||
const needle = query.trim().toLocaleLowerCase("pt");
|
||||
if (!needle) return nodes;
|
||||
const walk = (node: Node): Node | null => {
|
||||
const children = node.children.flatMap((child) => {
|
||||
const kept = walk(child);
|
||||
return kept ? [kept] : [];
|
||||
});
|
||||
if (node.name.toLocaleLowerCase("pt").includes(needle) || children.length) return { ...node, children };
|
||||
return null;
|
||||
};
|
||||
return nodes.flatMap((node) => {
|
||||
const kept = walk(node);
|
||||
return kept ? [kept] : [];
|
||||
});
|
||||
}
|
||||
|
||||
type Box = "on" | "off" | "mixed";
|
||||
|
||||
function boxOf(node: Node): Box {
|
||||
if (!node.published) return "off";
|
||||
const hidden = (current: Node): boolean => current.children.some((child) => !child.published || hidden(child));
|
||||
return hidden(node) ? "mixed" : "on";
|
||||
}
|
||||
|
||||
function Branch({
|
||||
node,
|
||||
depth,
|
||||
expanded,
|
||||
busy,
|
||||
onToggle,
|
||||
onCheck,
|
||||
}: {
|
||||
node: Node;
|
||||
depth: number;
|
||||
expanded: Set<string>;
|
||||
busy: string | null;
|
||||
onToggle: (path: string) => void;
|
||||
onCheck: (node: Node) => void;
|
||||
}) {
|
||||
const box = boxOf(node);
|
||||
const open = expanded.has(node.path);
|
||||
return (
|
||||
<li>
|
||||
<div className="flex items-center gap-1 py-0.5" style={{ paddingLeft: depth * 16 }}>
|
||||
<button
|
||||
type="button"
|
||||
className="h-5 w-5 text-[11px] text-muted"
|
||||
aria-label={open ? "Fechar" : "Abrir"}
|
||||
onClick={() => node.children.length && onToggle(node.path)}
|
||||
>
|
||||
{node.children.length ? (open ? "−" : "+") : ""}
|
||||
</button>
|
||||
<Check box={box} disabled={busy === node.id} label={node.name} onChange={() => onCheck(node)} />
|
||||
<span className="truncate text-[13px] text-ink">{node.name}</span>
|
||||
{node.photoCount > 0 && <span className="shrink-0 text-[11px] text-faint">{A.siteFoldersPhotos(node.photoCount)}</span>}
|
||||
</div>
|
||||
{open && node.children.length > 0 && (
|
||||
<ul>
|
||||
{node.children.map((child) => (
|
||||
<Branch key={child.id} node={child} depth={depth + 1} expanded={expanded} busy={busy} onToggle={onToggle} onCheck={onCheck} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function Check({ box, disabled, label, onChange }: { box: Box; disabled: boolean; label: string; onChange: () => void }) {
|
||||
const [el, setEl] = useState<HTMLInputElement | null>(null);
|
||||
useEffect(() => {
|
||||
if (el) el.indeterminate = box === "mixed";
|
||||
}, [el, box]);
|
||||
return (
|
||||
<input
|
||||
ref={setEl}
|
||||
type="checkbox"
|
||||
className="h-3.5 w-3.5"
|
||||
checked={box === "on"}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
onChange={onChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Which indexed folders appear on the public archive site. This stays in the app: the site itself has no tree.
|
||||
* Everything starts published. Unchecking a folder hides it and the folders inside it.
|
||||
*/
|
||||
export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSource }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [rows, setRows] = useState<CloudTreeFolder[] | null>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || rows) return;
|
||||
let live = true;
|
||||
api.cloudFolderTree(source.id).then(
|
||||
(body) => live && setRows(body.folders),
|
||||
(err) => live && setError(errorOf(err)),
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [api, source.id, open, rows]);
|
||||
|
||||
const tree = useMemo(() => filterTree(treeOf(rows ?? []), query), [rows, query]);
|
||||
const shown = query.trim() ? new Set(collect(tree)) : expanded;
|
||||
|
||||
const toggle = (path: string) => {
|
||||
setExpanded((cur) => {
|
||||
const next = new Set(cur);
|
||||
if (next.has(path)) next.delete(path);
|
||||
else next.add(path);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const check = (node: Node) => {
|
||||
const published = boxOf(node) !== "on";
|
||||
setBusy(node.id);
|
||||
setError(null);
|
||||
api.setCloudFolderPublished(node.id, published).then(
|
||||
() => {
|
||||
setRows((cur) =>
|
||||
(cur ?? []).map((folder) =>
|
||||
folder.path === node.path || folder.path.startsWith(`${node.path}/`) ? { ...folder, published } : folder,
|
||||
),
|
||||
);
|
||||
setBusy(null);
|
||||
},
|
||||
(err) => {
|
||||
setError(errorOf(err));
|
||||
setBusy(null);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<button type="button" onClick={() => setOpen((value) => !value)} className="text-left">
|
||||
{open ? "−" : "+"} {A.siteFolders}
|
||||
</button>
|
||||
</div>
|
||||
{open && (
|
||||
<div className="space-y-2 px-4 py-3">
|
||||
<p className="max-w-3xl text-[12px] text-muted">{A.siteFoldersHelp}</p>
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={A.siteFoldersSearch}
|
||||
className="h-8 w-full max-w-sm border border-black bg-cell px-2 text-[13px] text-ink"
|
||||
/>
|
||||
{error && <p className="text-[12px] text-danger">{error}</p>}
|
||||
{!rows && !error && <p className="text-[12px] text-faint">{A.siteFoldersLoading}</p>}
|
||||
{rows && tree.length === 0 && <p className="text-[12px] text-faint">{A.siteFoldersEmpty}</p>}
|
||||
{rows && tree.length > 0 && (
|
||||
<ul className="max-h-[28rem] overflow-auto">
|
||||
{tree.map((node) => (
|
||||
<Branch key={node.id} node={node} depth={0} expanded={shown} busy={busy} onToggle={toggle} onCheck={check} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function collect(nodes: Node[]): string[] {
|
||||
return nodes.flatMap((node) => [node.path, ...collect(node.children)]);
|
||||
}
|
||||
@@ -192,11 +192,27 @@ export function ArchiveView({ info, start }: { info: ArchiveInfo; start?: View }
|
||||
}}
|
||||
onExpired={expired}
|
||||
onChanged={() => setMeTick((n) => n + 1)}
|
||||
onOpenPerson={(id) => go({ kind: "person", id })}
|
||||
/>
|
||||
) : tab === "review" && !me ? (
|
||||
<div className="arq-wrap arq-body" />
|
||||
) : tab === "review" ? (
|
||||
<div className="arq-wrap arq-body">
|
||||
<div className="arq-lock">
|
||||
<Icon name="lock" size={48} />
|
||||
<h1 className="arq-disp" style={{ margin: 0 }}>
|
||||
Só para quem pode editar
|
||||
</h1>
|
||||
<p className="arq-muted" style={{ maxWidth: 520, margin: 0 }}>
|
||||
Rever rostos é para quem tem permissão de edição nas pastas destas fotos. Se achas que devias ter, pede a quem gere o arquivo.
|
||||
</p>
|
||||
<button type="button" className="arq-btn" onClick={() => openTab("galleries")}>
|
||||
Voltar às galerias
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<Browse sourceId={info.id} token={token} tab={tab === "review" ? "galleries" : tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} />
|
||||
<Browse sourceId={info.id} token={token} tab={tab} onTab={openTab} onExpired={expired} onGallery={(id) => go({ kind: "gallery", id })} onPerson={(id) => go({ kind: "person", id })} canReview={!!me?.canReview} />
|
||||
)}
|
||||
</main>
|
||||
|
||||
|
||||
@@ -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";
|
||||
@@ -21,7 +21,10 @@ export function Browse({
|
||||
onExpired,
|
||||
onGallery,
|
||||
onPerson,
|
||||
canReview = false,
|
||||
}: {
|
||||
/** The viewer edits on the cloud: sees the suggestions waiting for confirmation. */
|
||||
canReview?: boolean;
|
||||
sourceId: string;
|
||||
token: string;
|
||||
tab: Tab;
|
||||
@@ -37,6 +40,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 +90,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;
|
||||
@@ -278,6 +294,7 @@ export function Browse({
|
||||
|
||||
{tab === "people" && (
|
||||
<>
|
||||
<h1 className="arq-disp arq-h1">Pessoas</h1>
|
||||
{people && people.clubs.length > 1 && (
|
||||
<div className="arq-club-pills" role="group" aria-label="Filtrar por equipa">
|
||||
<button type="button" className="arq-pill" aria-pressed={!club} onClick={() => setClub(null)}>
|
||||
@@ -331,8 +348,10 @@ export function Browse({
|
||||
<strong>{p.name}</strong>
|
||||
{p.club && <span className="arq-sm">{p.club}</span>}
|
||||
<span className="arq-badges">
|
||||
<span className="arq-badge ok">{p.photos} identificadas</span>
|
||||
{p.probable > 0 && <span className="arq-badge maybe">{p.probable} prováveis</span>}
|
||||
<span className="arq-badge ok">
|
||||
{p.photos} {p.photos === 1 ? "confirmada" : "confirmadas"}
|
||||
</span>
|
||||
{canReview && p.probable > 0 && <span className="arq-badge maybe">{p.probable} por confirmar</span>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
@@ -357,20 +376,37 @@ export function Browse({
|
||||
Equipas <small>{teams ? shownTeams.length : ""}</small>
|
||||
</h2>
|
||||
<div className="arq-panel">
|
||||
<p className="arq-muted" style={{ margin: "0 0 12px" }}>
|
||||
Cada equipa aparece uma vez, mesmo com vários nomes nas pastas. Abre os jogos da equipa ou as pessoas identificadas dela.
|
||||
</p>
|
||||
{!teams && !failed && <Loading />}
|
||||
{teams && shownTeams.length === 0 && <p className="arq-empty">Nenhuma equipa com esse nome.</p>}
|
||||
<div className="arq-teams">
|
||||
{shownTeams.slice(0, teamsShown).map((t) => (
|
||||
<button key={t.name} type="button" className="arq-teamcard" onClick={() => pickTeam(t.name)}>
|
||||
<span className="arq-crest">{initials(t.name)}</span>
|
||||
<span>
|
||||
<strong>{t.name}</strong>
|
||||
<small>
|
||||
{t.galleries} {t.galleries === 1 ? "jogo" : "jogos"}
|
||||
</small>
|
||||
</span>
|
||||
<Icon name="next" size={18} />
|
||||
</button>
|
||||
<div key={t.name} className="arq-teamcard-wrap">
|
||||
<button type="button" className="arq-teamcard" onClick={() => pickTeam(t.name)}>
|
||||
<span className="arq-crest">{initials(t.name)}</span>
|
||||
<span>
|
||||
<strong>{t.name}</strong>
|
||||
<small>
|
||||
{t.galleries} {t.galleries === 1 ? "jogo" : "jogos"}
|
||||
</small>
|
||||
</span>
|
||||
<Icon name="next" size={18} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="arq-teamcard-people"
|
||||
onClick={() => {
|
||||
setClub(t.name);
|
||||
setQ("");
|
||||
onTab("people");
|
||||
}}
|
||||
>
|
||||
<Icon name="people" size={16} />
|
||||
Pessoas
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{shownTeams.length > teamsShown && (
|
||||
|
||||
@@ -195,6 +195,19 @@ export function Gallery({
|
||||
<Icon name="check" size={18} />
|
||||
{picked ? "Cancelar seleção" : "Selecionar fotos"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="arq-btn ghost on-hero"
|
||||
onClick={() =>
|
||||
void navigator.clipboard?.writeText(window.location.href).then(
|
||||
() => setNote("Ligação copiada. Quem a abrir precisa de ter acesso a esta galeria."),
|
||||
() => setNote(window.location.href),
|
||||
)
|
||||
}
|
||||
>
|
||||
<Icon name="link" size={18} />
|
||||
Copiar ligação
|
||||
</button>
|
||||
</div>
|
||||
{note && <p className="arq-hero-note">{note}</p>}
|
||||
{g.cloudUrl && (
|
||||
@@ -323,6 +336,29 @@ export function Gallery({
|
||||
onPerson={onPerson}
|
||||
review={me?.canReview ? { sourceId, onDone: () => forget(`/v1/archive/${sourceId}/`) } : undefined}
|
||||
onDownload={(photoId) => save({ photoIds: [photoId] }, "one")}
|
||||
selected={!!picked?.has(photos[index]!.id)}
|
||||
onSelect={(photoId) => {
|
||||
const next = new Set(picked ?? []);
|
||||
if (next.has(photoId)) next.delete(photoId);
|
||||
else if (next.size < MAX_PICKED) next.add(photoId);
|
||||
setPicked(next);
|
||||
}}
|
||||
extra={() =>
|
||||
isGame ? (
|
||||
<>
|
||||
<span className="arq-label">Jogo</span>
|
||||
<span>
|
||||
{g.home} vs {g.away}
|
||||
{g.startsAt ? ` · ${shortDay.format(new Date(g.startsAt))}` : ""}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="arq-label">Galeria</span>
|
||||
<span>{g.title}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -19,6 +19,8 @@ export function Lightbox({
|
||||
extra,
|
||||
review,
|
||||
onDownload,
|
||||
selected,
|
||||
onSelect,
|
||||
}: {
|
||||
photos: ArchivePhoto[];
|
||||
index: number;
|
||||
@@ -33,6 +35,9 @@ export function Lightbox({
|
||||
extra?: (p: ArchivePhoto) => ReactNode;
|
||||
/** Saves this photo at web size. */
|
||||
onDownload?: (photoId: string) => void;
|
||||
/** This photo is in the gallery's selection (for a download), and the way to add or take it out. */
|
||||
selected?: boolean;
|
||||
onSelect?: (photoId: string) => void;
|
||||
}) {
|
||||
const current = photos[index]!;
|
||||
const [showFaces, setShowFaces] = useState(true);
|
||||
@@ -101,8 +106,14 @@ export function Lightbox({
|
||||
{index + 1} / {photos.length}
|
||||
</strong>
|
||||
<span className="arq-grow" />
|
||||
{onSelect && (
|
||||
<button type="button" className={`arq-btn ${selected ? "accent" : "ghost"}`} aria-pressed={!!selected} aria-label={selected ? "Tirar da seleção" : "Selecionar"} onClick={() => onSelect(current.id)}>
|
||||
<Icon name="check" size={18} />
|
||||
<span className="arq-hide-sm">{selected ? "Tirar da seleção" : "Selecionar"}</span>
|
||||
</button>
|
||||
)}
|
||||
{onDownload && (
|
||||
<button type="button" className="arq-btn accent" onClick={() => onDownload(current.id)}>
|
||||
<button type="button" className="arq-btn accent" aria-label="Descarregar" onClick={() => onDownload(current.id)}>
|
||||
<Icon name="download" size={18} />
|
||||
<span className="arq-hide-sm">Descarregar</span>
|
||||
</button>
|
||||
@@ -148,6 +159,14 @@ export function Lightbox({
|
||||
)}
|
||||
</div>
|
||||
<aside className="arq-info">
|
||||
<span className="arq-lb-nav">
|
||||
<button type="button" className="arq-btn ghost" disabled={index === 0} onClick={() => onIndex(index - 1)}>
|
||||
← Anterior
|
||||
</button>
|
||||
<button type="button" className="arq-btn ghost" disabled={index >= photos.length - 1} onClick={() => onIndex(index + 1)}>
|
||||
Seguinte →
|
||||
</button>
|
||||
</span>
|
||||
{current.level && (
|
||||
<span>
|
||||
<span className={`arq-badge ${current.level === "confirmed" ? "ok" : current.level === "probable" ? "maybe" : "sim"}`}>{LEVEL[current.level]}</span>
|
||||
|
||||
@@ -144,7 +144,7 @@ export function PhotosOf({
|
||||
</section>
|
||||
<div className="arq-wrap arq-body">
|
||||
<div className="arq-split" style={{ flexDirection: "row-reverse", flexWrap: "wrap" }}>
|
||||
{who && view.kind === "person" && me?.canReview && <Editor sourceId={sourceId} token={token} person={who} onReview={() => onReview(who.id)} onExpired={onExpired} />}
|
||||
{who && view.kind === "person" && me?.canReview && <Editor sourceId={sourceId} token={token} person={who} waiting={counts.probable} onReview={() => onReview(who.id)} onExpired={onExpired} />}
|
||||
<div style={{ flex: "999 1 560px", minWidth: 0, display: "flex", flexDirection: "column", gap: 16 }}>
|
||||
<div className="arq-pills scroll" role="group" aria-label="Mostrar">
|
||||
<button type="button" className="arq-pill" aria-pressed={only === null} onClick={() => setOnly(null)}>
|
||||
@@ -225,7 +225,7 @@ const ACTION: Record<string, string> = {
|
||||
* and (whoever edits the whole archive) taking back every suggestion, dropping a wrong reference photo, or
|
||||
* turning their recognition off, with the names already given or not.
|
||||
*/
|
||||
function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: string; token: string; person: { id: string; name: string }; onReview: () => void; onExpired: () => void }) {
|
||||
function Editor({ sourceId, token, person, waiting, onReview, onExpired }: { sourceId: string; token: string; person: { id: string; name: string }; waiting: number; onReview: () => void; onExpired: () => void }) {
|
||||
const [h, setH] = useState<PersonHistory | null>(null);
|
||||
const [asking, setAsking] = useState(false);
|
||||
const [removeConfirmed, setRemoveConfirmed] = useState(false);
|
||||
@@ -260,7 +260,22 @@ function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: st
|
||||
if (!h) return null;
|
||||
const off = h.recognitionOff;
|
||||
const base = `/v1/archive/${sourceId}/people/${person.id}`;
|
||||
const reenable = () => void run(`${base}/recognition`, { method: "POST", body: JSON.stringify({ enabled: true }) }, "Reconhecimento ligado. Precisa de uma foto de referência ou de um rosto confirmado para voltar a sugerir.");
|
||||
return (
|
||||
<>
|
||||
{off && (
|
||||
<div className="arq-offbanner" role="status" style={{ flexBasis: "100%" }}>
|
||||
<strong>
|
||||
Reconhecimento facial desativado para {person.name}
|
||||
{off.by ? ` (por ${off.by})` : ""}. Não aparece em sugestões; só se identifica à mão.
|
||||
</strong>
|
||||
{h.canManage && (
|
||||
<button type="button" className="arq-btn" disabled={busy} onClick={reenable}>
|
||||
Reativar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<aside className="arq-editor" aria-labelledby="arq-h-rec">
|
||||
<div className="arq-box">
|
||||
<h2 id="arq-h-rec" className="arq-disp">
|
||||
@@ -272,7 +287,7 @@ function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: st
|
||||
</span>
|
||||
{!off && (
|
||||
<button type="button" className="arq-btn" onClick={onReview}>
|
||||
Rever os rostos de {person.name}
|
||||
{waiting > 0 ? `Rever ${waiting} ${waiting === 1 ? "sugestão" : "sugestões"}` : `Rever os rostos de ${person.name}`}
|
||||
</button>
|
||||
)}
|
||||
{h.canManage && (
|
||||
@@ -288,8 +303,9 @@ function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: st
|
||||
</button>
|
||||
)}
|
||||
<div className="arq-danger">
|
||||
<span className="arq-label">Zona de cuidado</span>
|
||||
{off ? (
|
||||
<button type="button" className="arq-btn" disabled={busy} onClick={() => void run(`${base}/recognition`, { method: "POST", body: JSON.stringify({ enabled: true }) }, "Reconhecimento ligado. Precisa de uma foto de referência ou de um rosto confirmado para voltar a sugerir.")}>
|
||||
<button type="button" className="arq-btn" disabled={busy} onClick={reenable}>
|
||||
Ligar o reconhecimento outra vez
|
||||
</button>
|
||||
) : (
|
||||
@@ -353,5 +369,6 @@ function Editor({ sourceId, token, person, onReview, onExpired }: { sourceId: st
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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][] = [
|
||||
@@ -19,14 +19,17 @@ type Action = "confirm" | "reject" | "ignore" | "undo";
|
||||
* event). Confirm the suggestion, say "não é", mark a false positive, name an unnamed face, undo. Selected cards
|
||||
* take the same action at once. Keys on a focused card: C confirm, N não é, F false positive.
|
||||
*/
|
||||
export function Review({ sourceId, token, me, person, onPerson, onExpired, onChanged }: { sourceId: string; token: string; me: Me; person: string | null; onPerson: (id: string | null) => void; onExpired: () => void; onChanged: () => void }) {
|
||||
export function Review({ sourceId, token, me, person, onPerson, onExpired, onChanged, onOpenPerson }: { sourceId: string; token: string; me: Me; person: string | null; onPerson: (id: string | null) => void; onExpired: () => void; onChanged: () => void; onOpenPerson?: (id: string) => void }) {
|
||||
const [status, setStatus] = useState<ReviewStatus>("suggested");
|
||||
const [data, setData] = useState<ReviewResult | null>(null);
|
||||
const [busy, setBusy] = useState<Set<string>>(new Set());
|
||||
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];
|
||||
|
||||
@@ -111,6 +115,26 @@ export function Review({ sourceId, token, me, person, onPerson, onExpired, onCha
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="arq-shortcuts" style={{ margin: 0 }}>
|
||||
Atalhos: <kbd>C</kbd> confirmar · <kbd>N</kbd> não é · <kbd>F</kbd> falso positivo · clica numa cara para a selecionar
|
||||
</p>
|
||||
|
||||
{chosen && (
|
||||
<div className="arq-chosen">
|
||||
<PersonFace p={{ reference: chosen.reference, face: null, name: chosen.name }} size={64} />
|
||||
<div style={{ flex: "1 1 200px", display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
<strong style={{ fontSize: 20 }}>{chosen.name}</strong>
|
||||
<span className="arq-muted">
|
||||
{[chosen.club, chosen.number ? `#${chosen.number}` : null, `${chosen.waiting} por rever`].filter(Boolean).join(" · ")}
|
||||
</span>
|
||||
</div>
|
||||
{onOpenPerson && (
|
||||
<button type="button" className="arq-btn ghost" onClick={() => onOpenPerson(chosen.id)}>
|
||||
Opções de reconhecimento
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="arq-alert" role="alert">
|
||||
@@ -154,9 +178,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 +233,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 +327,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 +344,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 +387,22 @@ function Card({
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{open !== null && faces[open] && (
|
||||
<div className="arq-rlightbox" 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 {
|
||||
|
||||
@@ -1188,6 +1188,84 @@
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.arq-teamcard-wrap {
|
||||
position: relative;
|
||||
display: flex;
|
||||
}
|
||||
.arq-teamcard-wrap .arq-teamcard {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-right: 120px;
|
||||
}
|
||||
.arq-teamcard-wrap .arq-teamcard > svg {
|
||||
display: none;
|
||||
}
|
||||
.arq-teamcard-people {
|
||||
position: absolute;
|
||||
right: 14px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-height: 36px;
|
||||
padding: 0 12px;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
background: var(--chip);
|
||||
color: var(--chip-ink);
|
||||
font-weight: 700;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.arq-teamcard-people:hover {
|
||||
box-shadow: inset 0 0 0 1px currentColor;
|
||||
}
|
||||
.arq-h1 {
|
||||
margin: 0 0 4px;
|
||||
font-size: clamp(32px, 5vw, 48px);
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
.arq-shortcuts {
|
||||
font-size: 13px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.arq-shortcuts kbd {
|
||||
display: inline-block;
|
||||
min-width: 20px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 5px;
|
||||
background: var(--chip);
|
||||
color: var(--chip-ink);
|
||||
font: 700 12px/18px inherit;
|
||||
text-align: center;
|
||||
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
.arq-offbanner {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 14px 18px;
|
||||
border-radius: var(--r);
|
||||
background: #fff4c2;
|
||||
color: #4a3b00;
|
||||
}
|
||||
.arq-offbanner strong {
|
||||
flex: 1 1 260px;
|
||||
}
|
||||
.arq-lock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 64px 16px;
|
||||
text-align: center;
|
||||
}
|
||||
.arq-lock svg {
|
||||
opacity: 0.6;
|
||||
}
|
||||
.arq-teamcard:hover {
|
||||
box-shadow: 0 0 0 2px var(--ink);
|
||||
}
|
||||
@@ -1448,6 +1526,16 @@
|
||||
gap: 14px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.arq-lb-nav {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.arq-lb-nav .arq-btn {
|
||||
flex: 1;
|
||||
color: #ffffff;
|
||||
min-height: 40px;
|
||||
padding: 0 12px;
|
||||
}
|
||||
.arq-lightbox .arq-label {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
@@ -1627,6 +1715,58 @@
|
||||
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);
|
||||
}
|
||||
/* The review cards' photo viewer (not the gallery's large view, .arq-lightbox) */
|
||||
.arq-rlightbox {
|
||||
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;
|
||||
@@ -2056,3 +2196,22 @@
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Review: the person being reviewed */
|
||||
.arq-chosen {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 14px 16px;
|
||||
border-radius: var(--r);
|
||||
background: var(--card);
|
||||
box-shadow: 0 0 0 1px var(--line);
|
||||
}
|
||||
.arq-danger .arq-label {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.06em;
|
||||
text-transform: uppercase;
|
||||
color: #b42318;
|
||||
}
|
||||
@@ -95,6 +95,8 @@ const PATHS = {
|
||||
check: "M5 12l5 5 9-10",
|
||||
ban: "M12 20a8 8 0 100-16 8 8 0 000 16zM6.5 6.5l11 11",
|
||||
review: "M4 8V5h3M17 5h3v3M20 16v3h-3M7 19H4v-3M9 10h.01M15 10h.01M9 15c2 1.5 4 1.5 6 0",
|
||||
lock: "M6 11h12v9H6zM8 11V8a4 4 0 018 0v3",
|
||||
link: "M10 14a4 4 0 005.7 0l3-3a4 4 0 00-5.7-5.7l-1 1M14 10a4 4 0 00-5.7 0l-3 3a4 4 0 005.7 5.7l1-1",
|
||||
} as const;
|
||||
|
||||
export function Icon({ name, size = 20 }: { name: keyof typeof PATHS; size?: number }) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -24,12 +24,18 @@ Following the AP and NPPA codes:
|
||||
or a point on nobody, the subject is the person in focus, not the biggest one. With a ball in play, the ball and
|
||||
everyone contesting it come along. Without one, the subject and the sharp people with them (a duel, a
|
||||
celebration, a line-up).
|
||||
- **Shape:** the photo's own aspect unless the event or the editor chose another. Peter's usual crop is about two
|
||||
thirds of the frame; larger only when the subject needs it.
|
||||
- **Shape:** the photo's own aspect unless the event or the editor chose another (never turned vertical).
|
||||
- **Framing** (per event):
|
||||
- **"tight"** (default) is the agencies' handball framing, measured on kolektiff images (600 EHF/IHF photos of
|
||||
2025-26). The subject is about as tall as the crop, the legs are cut mid-shin or mid-thigh, and the face is
|
||||
big (a median face of 14% of the frame height) near the top. Whole bodies are kept only when that frames
|
||||
better.
|
||||
- **"full"** keeps whole bodies when they fit: Peter's usual crop, about two thirds of the frame.
|
||||
- **Never cut:** heads, faces, hands holding the ball, the ball itself.
|
||||
- **Limbs:** if a body has to be cut, cut mid-limb (mid-thigh, mid-shin, mid-forearm), never at a joint (ankle,
|
||||
knee, hip, wrist, elbow, neck). The engine estimates joints from the body box and avoids crop edges there.
|
||||
- **Feet:** keep whole bodies when they fit; otherwise cut above the knee rather than at the ankle.
|
||||
- **Feet:** with "full", keep whole bodies when they fit; otherwise cut above the knee rather than at the ankle.
|
||||
With "tight", cut mid-shin or mid-thigh, never below the ball.
|
||||
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
|
||||
background people don't count.
|
||||
- **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.
|
||||
@@ -42,6 +48,8 @@ Following the AP and NPPA codes:
|
||||
edge of the original (configurable per organisation; agencies often ask for more).
|
||||
- **Not too much:** if the only crop that works is tighter than the resolution allows, keep the wider frame. A good
|
||||
photo uncropped beats a bad crop.
|
||||
- **Not for nothing:** a crop of more than 92% of the width is not made: the photo stays as shot. The agencies
|
||||
send a fifth to a half of their photos uncropped (Getty, AFP, Paris 2024).
|
||||
|
||||
## 3. Bursts (sequences)
|
||||
|
||||
@@ -56,8 +64,9 @@ A camera at 10–30 frames per second sends several photos of the same moment.
|
||||
is the only picture of that moment.
|
||||
- **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never
|
||||
rejected or deleted automatically).
|
||||
- **Variety:** when two frames of a burst are kept, the second gets a slightly different crop (tighter or wider) so
|
||||
the client has a choice.
|
||||
- **Variety:** when two frames of a burst are kept, the second gets the other framing so the client has a choice.
|
||||
After a tight first pick, the second gets the wider, whole-body frame with context, as Getty mixes in.
|
||||
Otherwise the second is slightly tighter.
|
||||
- **Saturation:** an event can cap how many picks one burst, or one minute of play, may produce, so a long attack
|
||||
doesn't flood the delivery.
|
||||
|
||||
@@ -67,12 +76,26 @@ Per event (and an organisation default), off unless switched on. When on, every
|
||||
the local FTP of the desktop app or auto-ingest is, in order:
|
||||
|
||||
1. analysed (people, ball, focus);
|
||||
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop.
|
||||
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop,
|
||||
and the finishing look.
|
||||
The level reads the advertising boards, stands, posts and railings, never the pitch markings (lines on grass),
|
||||
which perspective tilts; when those lines disagree the photo is left as it is;
|
||||
3. scored within its burst; when the burst ends, its best frames are flagged as picks;
|
||||
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target.
|
||||
|
||||
**Look** (per event, `apps/api/src/autopilot/look.ts`): fixed values on top of the measured tone, the same for
|
||||
every photo of a match. They never go over a measured control.
|
||||
|
||||
- **"agency"** (default): kolektiff's punchy kits. Vibrance +18, saturation +4, clarity +8, texture +6, and
|
||||
shadows a touch blue-magenta. Every agency measured has that last trait: Getty, AFP and kolektiff all do it.
|
||||
- **"natural"**: Getty's more natural colour.
|
||||
- **"none"**: no look.
|
||||
- **Both looks** add capture sharpening (40, radius 1, masking 35), colour noise reduction, and luminance noise
|
||||
reduction by ISO (from ISO 1600). There is never a vignette or a local change (§1).
|
||||
|
||||
Defaults follow the agencies: white balance on (neutral whites) and 75% of the automatic tone (full range,
|
||||
pure blacks).
|
||||
|
||||
Uploads made by hand in the browser are not touched. Anything the autopilot did can be undone, changed or reset
|
||||
in Revelar.
|
||||
|
||||
|
||||
@@ -20,6 +20,13 @@ log() { printf '[%s] boot %s: %s\n' "$(date -u +%FT%TZ)" "$SERVICE" "$*"; }
|
||||
[[ -n "${TMPDIR:-}" ]] && mkdir -p "$TMPDIR" && chmod 700 "$TMPDIR"
|
||||
export PATH="$HOME/.cargo/bin:/usr/local/bin:$PATH"
|
||||
|
||||
# Observed 2026-10-19: a concurrent second run of this script raced `pm2 startOrReload` against a PM2 daemon
|
||||
# that had just been spawned (empty process list) and lost the "is it already running" check, launching a
|
||||
# duplicate photoreport-api that crash-looped forever on EADDRINUSE. Serialize with deploy.sh via the same lock
|
||||
# so a boot racing a webhook-triggered deploy can't do the same thing.
|
||||
exec 9>/run/photoreport-pm2.lock
|
||||
flock 9
|
||||
|
||||
cd "$REPO_DIR"
|
||||
SHA="$(git rev-parse HEAD)"
|
||||
|
||||
|
||||
@@ -60,7 +60,11 @@ deploy_api() {
|
||||
log "WARNING: no Rust toolchain: face analysis and edited renders stay off"
|
||||
fi
|
||||
bash infra/faces/download-models.sh "${MODELS_DIR:-/srv/photoreport-data/models}" || log "WARNING: face models could not be downloaded"
|
||||
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
|
||||
# Same lock as boot.sh: a reboot racing this deploy's pm2 call against a freshly-spawned, still-empty PM2
|
||||
# daemon duplicated photoreport-api on 2026-10-19 (crash-looped on EADDRINUSE forever). Serialize instead.
|
||||
( exec 9>/run/photoreport-pm2.lock; flock 9
|
||||
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
|
||||
)
|
||||
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
|
||||
# The process list PM2 restores after a reboot follows every deploy (photoreport-boot.service starts it too).
|
||||
pm2 save --force >/dev/null
|
||||
@@ -120,7 +124,9 @@ deploy_site() {
|
||||
# from apps/site/.env (that's Next's own, separate env loading) — source it here, same gap
|
||||
# class as the prisma CLI fix above, so a host's API_URL override actually reaches pm2.
|
||||
if [[ -f apps/site/.env ]]; then set -a; source apps/site/.env; set +a; fi
|
||||
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
|
||||
( exec 9>/run/photoreport-pm2.lock; flock 9
|
||||
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
|
||||
)
|
||||
local i
|
||||
for ((i = 1; i <= HEALTH_TRIES; i++)); do
|
||||
if curl -fsS --max-time 3 -o /dev/null "http://127.0.0.1:${SITE_PORT:-3100}/"; then pm2 save --force >/dev/null; return 0; fi
|
||||
|
||||
@@ -30,9 +30,17 @@ export const AutopilotSettings = z.object({
|
||||
crop: z.boolean().default(true),
|
||||
level: z.boolean().default(true),
|
||||
tone: z.boolean().default(true),
|
||||
/** How much of the automatic tone to apply (news photos want minimal toning). */
|
||||
toneStrength: z.number().min(0).max(1).default(0.5),
|
||||
whiteBalance: z.boolean().default(false),
|
||||
/** How much of the automatic tone to apply (agencies deliver full-range, contrasty photos: pure blacks, bright whites). */
|
||||
toneStrength: z.number().min(0).max(1).default(0.75),
|
||||
/** Neutral whites (white kits, the floor's lines), as the agencies deliver. */
|
||||
whiteBalance: z.boolean().default(true),
|
||||
/**
|
||||
* Crop framing: "tight", the agencies' close handball framing (subject fills the height, legs cut mid-limb, the
|
||||
* second pick of a burst gets the wider, whole-body frame); "full", whole bodies when they fit.
|
||||
*/
|
||||
framing: z.enum(["tight", "full"]).default("tight"),
|
||||
/** Finishing look (apps/api/src/autopilot/look.ts): "agency" punchy kits, "natural" Getty-like, "none". */
|
||||
look: z.enum(["agency", "natural", "none"]).default("agency"),
|
||||
/** Crop shape (width, height); null: the photo's own. */
|
||||
aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null),
|
||||
/** The crop keeps at least this many pixels on its long edge of the original. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
||||
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
|
||||
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
|
||||
|
||||
/**
|
||||
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
|
||||
@@ -808,6 +808,16 @@ export class ApiClient {
|
||||
return this.request<Pick<CloudFolderSummary, "id" | "matchedBy" | "event">>("PUT", `/v1/cloud-folders/${folderId}/event`, target);
|
||||
}
|
||||
|
||||
/** The folders an editor chooses to show on the public site. Not used by the site itself. */
|
||||
cloudFolderTree(sourceId: string) {
|
||||
return this.request<{ folders: CloudTreeFolder[] }>("GET", `/v1/cloud-sources/${sourceId}/tree`);
|
||||
}
|
||||
|
||||
/** Publishes or hides a folder and everything inside it. */
|
||||
setCloudFolderPublished(folderId: string, published: boolean) {
|
||||
return this.request<{ published: boolean; updated: number }>("PUT", `/v1/cloud-folders/${folderId}/published`, { published });
|
||||
}
|
||||
|
||||
// ---- delivery --------------------------------------------------------------------------------------
|
||||
|
||||
listDeliveryTargets(orgId: string) {
|
||||
|
||||
@@ -461,6 +461,15 @@ export interface ArchiveStorage {
|
||||
paused: boolean;
|
||||
}
|
||||
|
||||
/** One folder in the app's publish tree. The public site never sees this list. */
|
||||
export interface CloudTreeFolder {
|
||||
id: string;
|
||||
/** From the source's root, without a leading slash. */
|
||||
path: string;
|
||||
published: boolean;
|
||||
photoCount: number;
|
||||
}
|
||||
|
||||
export interface CloudFolderSummary {
|
||||
id: string;
|
||||
/** From the source's root. */
|
||||
|
||||
Reference in new issue
Block a user