Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c77135e7a | ||
|
|
cf2e466549 | ||
|
|
06179738c4 | ||
|
|
899b45fbbd | ||
|
|
4aac2815ce | ||
|
|
37211014c7 | ||
|
|
ce306a7642 | ||
|
|
58660f08e8 | ||
|
|
cbe11712b8 | ||
|
|
7d77c51f57 | ||
|
|
7280d20742 | ||
|
|
c864a48ce7 | ||
|
|
cbe19e0373 | ||
|
|
ed0adce3b7 | ||
|
|
6135ed9000 | ||
|
|
3ff5df3942 |
No files matched your search
@@ -0,0 +1,2 @@
|
|||||||
|
-- Photos read before the season squads can be sent through face analysis again, newest first, once.
|
||||||
|
ALTER TABLE "photos" ADD COLUMN "faces_pass" INTEGER NOT NULL DEFAULT 0;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- European handball (EHF club competitions) is its own source, beside the FPA's national games.
|
||||||
|
ALTER TYPE "SportsProvider" ADD VALUE IF NOT EXISTS 'EHF';
|
||||||
@@ -401,6 +401,8 @@ model Photo {
|
|||||||
embeddedIptc Json? @map("embedded_iptc")
|
embeddedIptc Json? @map("embedded_iptc")
|
||||||
/// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED.
|
/// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED.
|
||||||
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
facesStatus FacesStatus @default(NONE) @map("faces_status")
|
||||||
|
/// Which squad-aware reread this photo has been sent through. 0: read before the season squads.
|
||||||
|
facesPass Int @default(0) @map("faces_pass")
|
||||||
/// When the event was asked to the front of the face queue. Null waits behind every boosted photo.
|
/// When the event was asked to the front of the face queue. Null waits behind every boosted photo.
|
||||||
facesBoostedAt DateTime? @map("faces_boosted_at")
|
facesBoostedAt DateTime? @map("faces_boosted_at")
|
||||||
/// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo.
|
/// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo.
|
||||||
@@ -1259,6 +1261,7 @@ enum SportsProvider {
|
|||||||
FPF // resultados.fpf.pt (football below the Liga: teams, fixtures, line-ups per match)
|
FPF // resultados.fpf.pt (football below the Liga: teams, fixtures, line-ups per match)
|
||||||
FPA // ws.fpa.pt (handball: teams and fixtures)
|
FPA // ws.fpa.pt (handball: teams and fixtures)
|
||||||
UEFA // match.uefa.com (club competitions: fixtures, referee teams, line-ups with numbers and headshots)
|
UEFA // match.uefa.com (club competitions: fixtures, referee teams, line-ups with numbers and headshots)
|
||||||
|
EHF // ehfcl/ehfel/ehfec.eurohandball.com (club handball: fixtures, match-sheet squads and staff)
|
||||||
}
|
}
|
||||||
|
|
||||||
model SportsCompetition {
|
model SportsCompetition {
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { boxInCrop, cropOfSettings } from "../faces/frame.js";
|
|||||||
import { cosine, inFocus, THRESHOLDS } from "../faces/math.js";
|
import { cosine, inFocus, THRESHOLDS } from "../faces/math.js";
|
||||||
import { notFound } from "../lib/errors.js";
|
import { notFound } from "../lib/errors.js";
|
||||||
import type { UrlSigner } from "../storage/storage.js";
|
import type { UrlSigner } from "../storage/storage.js";
|
||||||
import { publishedPhotos } from "./gallery.js";
|
import { gallerySeasons, publishedPhotos } from "./gallery.js";
|
||||||
import { isNationalSide } from "./match.js";
|
import { isNationalSide } from "./match.js";
|
||||||
import type { Viewer } from "./viewer.js";
|
import type { Viewer } from "./viewer.js";
|
||||||
import { videoFaceCrop, videoScope } from "./video-faces.js";
|
import { videoFaceCrop, videoScope } from "./video-faces.js";
|
||||||
@@ -30,7 +30,37 @@ interface Deps {
|
|||||||
const SourceParams = z.object({ sourceId: z.uuid() });
|
const SourceParams = z.object({ sourceId: z.uuid() });
|
||||||
const PersonParams = SourceParams.extend({ personId: z.uuid() });
|
const PersonParams = SourceParams.extend({ personId: z.uuid() });
|
||||||
const FaceParams = SourceParams.extend({ faceId: z.uuid() });
|
const FaceParams = SourceParams.extend({ faceId: z.uuid() });
|
||||||
const PeopleQuery = z.object({ q: z.string().trim().max(80).optional(), club: z.string().trim().max(120).optional() });
|
const PeopleQuery = z.object({
|
||||||
|
q: z.string().trim().max(80).optional(),
|
||||||
|
club: z.string().trim().max(120).optional(),
|
||||||
|
season: z.string().trim().max(16).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** "2025/26", "2025/2026" or "20252026" → 2025. Null when it is not a season, so the list stays everyone. */
|
||||||
|
export function seasonYear(raw: string | null | undefined): number | null {
|
||||||
|
const s = (raw ?? "").trim();
|
||||||
|
if (!s) return null;
|
||||||
|
const slash = /^(\d{4})\s*\/\s*(\d{2}|\d{4})$/.exec(s);
|
||||||
|
if (slash) {
|
||||||
|
const start = Number(slash[1]);
|
||||||
|
const end = Number(slash[2]);
|
||||||
|
if (slash[2]!.length === 4) return end === start + 1 ? start : null;
|
||||||
|
if (end === (start + 1) % 100) return start;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const compact = /^(\d{4})(\d{4})$/.exec(s.replace(/\s/g, ""));
|
||||||
|
if (compact && Number(compact[2]) === Number(compact[1]) + 1) return Number(compact[1]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The event's season, July to June in Lisbon, when a year was asked for. */
|
||||||
|
function inSeason(year: number | null): Prisma.Sql {
|
||||||
|
if (year == null) return Prisma.sql`TRUE`;
|
||||||
|
return Prisma.sql`(
|
||||||
|
extract(year FROM e.starts_at AT TIME ZONE 'Europe/Lisbon')::int
|
||||||
|
- CASE WHEN extract(month FROM e.starts_at AT TIME ZONE 'Europe/Lisbon') >= 7 THEN 0 ELSE 1 END
|
||||||
|
) = ${year}`;
|
||||||
|
}
|
||||||
const PhotosQuery = z.object({ level: z.enum(["all", "confirmed"]).default("all"), limit: z.coerce.number().int().min(1).max(600).default(300) });
|
const PhotosQuery = z.object({ level: z.enum(["all", "confirmed"]).default("all"), limit: z.coerce.number().int().min(1).max(600).default(300) });
|
||||||
|
|
||||||
/** How club names are compared: lowercase, no accents, single spaces. */
|
/** How club names are compared: lowercase, no accents, single spaces. */
|
||||||
@@ -137,13 +167,15 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
|||||||
const v = viewerOf(req, sourceId);
|
const v = viewerOf(req, sourceId);
|
||||||
const query = PeopleQuery.parse(req.query);
|
const query = PeopleQuery.parse(req.query);
|
||||||
const visible = await visibleFolders(v);
|
const visible = await visibleFolders(v);
|
||||||
if (visible !== "all" && !visible.length) return { people: [], clubs: [] };
|
if (visible !== "all" && !visible.length) return { people: [], clubs: [], seasons: [] };
|
||||||
const scope = visible === "all"
|
const scope = visible === "all"
|
||||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
|
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${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}`;
|
: 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"
|
const folderLimit = visible === "all"
|
||||||
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published`
|
? 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[])`;
|
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published AND cf.id = ANY(${visible}::uuid[])`;
|
||||||
|
const year = seasonYear(query.season);
|
||||||
|
const seasonSql = inSeason(year);
|
||||||
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; off: boolean; confirmed: bigint; probable: bigint }[]>`
|
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; off: boolean; confirmed: bigint; probable: bigint }[]>`
|
||||||
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, p.recognition_off_at IS NOT NULL AS off,
|
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference, p.recognition_off_at IS NOT NULL AS off,
|
||||||
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
|
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
|
||||||
@@ -152,7 +184,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
|||||||
JOIN faces f ON f.group_id = g.id
|
JOIN faces f ON f.group_id = g.id
|
||||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id
|
JOIN cloud_files cf ON cf.photo_id = f.photo_id
|
||||||
JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id)
|
JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id)
|
||||||
WHERE g.ignored_at IS NULL AND ${scope}
|
JOIN events e ON e.id = g.event_id
|
||||||
|
WHERE g.ignored_at IS NULL AND ${scope} AND ${seasonSql}
|
||||||
GROUP BY p.id`;
|
GROUP BY p.id`;
|
||||||
const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
|
||||||
// "Juntar nomes": other names of a club count as the club.
|
// "Juntar nomes": other names of a club count as the club.
|
||||||
@@ -170,7 +203,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
|||||||
FROM faces f
|
FROM faces f
|
||||||
JOIN face_groups g ON g.id = f.group_id
|
JOIN face_groups g ON g.id = f.group_id
|
||||||
JOIN cloud_files cf ON cf.photo_id = f.photo_id
|
JOIN cloud_files cf ON cf.photo_id = f.photo_id
|
||||||
WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope}
|
JOIN events e ON e.id = g.event_id
|
||||||
|
WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope} AND ${seasonSql}
|
||||||
ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC`
|
ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC`
|
||||||
: [];
|
: [];
|
||||||
const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
|
const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
|
||||||
@@ -188,11 +222,11 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
|||||||
FROM (
|
FROM (
|
||||||
SELECT e.id AS event_id, e.home AS name
|
SELECT e.id AS event_id, e.home AS name
|
||||||
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
||||||
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> ''
|
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.home) <> '' AND ${seasonSql}
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT e.id, e.away
|
SELECT e.id, e.away
|
||||||
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
FROM cloud_folders cf JOIN events e ON e.id = cf.event_id
|
||||||
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> ''
|
WHERE ${folderLimit} AND cf.photo_count > 0 AND cf.matched_by IS DISTINCT FROM 'FOLDER' AND btrim(e.away) <> '' AND ${seasonSql}
|
||||||
) sides
|
) sides
|
||||||
GROUP BY btrim(name)`;
|
GROUP BY btrim(name)`;
|
||||||
const clubs = new Map<string, { name: string; people: number; games: number; also: Set<string> }>();
|
const clubs = new Map<string, { name: string; people: number; games: number; also: Set<string> }>();
|
||||||
@@ -224,6 +258,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
|
|||||||
clubs: [...clubs.values()]
|
clubs: [...clubs.values()]
|
||||||
.sort((a, b) => b.people - a.people || b.games - a.games || a.name.localeCompare(b.name))
|
.sort((a, b) => b.people - a.people || b.games - a.games || a.name.localeCompare(b.name))
|
||||||
.map(({ name, people, also }) => ({ name, people, kind: clubKind(name), ...(also.size && { also: [...also].sort() }) })),
|
.map(({ name, people, also }) => ({ name, people, kind: clubKind(name), ...(also.size && { also: [...also].sort() }) })),
|
||||||
|
seasons: await gallerySeasons(db, v.s, visible),
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { seasonYear } from "./people.js";
|
||||||
|
|
||||||
|
describe("seasonYear", () => {
|
||||||
|
it("reads a season label and leaves anything else as every season", () => {
|
||||||
|
expect(seasonYear("2025/26")).toBe(2025);
|
||||||
|
expect(seasonYear("1999/00")).toBe(1999);
|
||||||
|
expect(seasonYear("2025/2026")).toBe(2025);
|
||||||
|
expect(seasonYear("20252026")).toBe(2025);
|
||||||
|
expect(seasonYear("")).toBeNull();
|
||||||
|
expect(seasonYear("2025/27")).toBeNull();
|
||||||
|
expect(seasonYear(undefined)).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -56,6 +56,8 @@ export interface ArchiveDeps {
|
|||||||
ligaSeason?: (season: string) => Promise<number>;
|
ligaSeason?: (season: string) => Promise<number>;
|
||||||
/** The FPA's national games of a season (slow: run in the background, the galleries matched again after). */
|
/** The FPA's national games of a season (slow: run in the background, the galleries matched again after). */
|
||||||
fpaSeason?: (season: string) => Promise<number>;
|
fpaSeason?: (season: string) => Promise<number>;
|
||||||
|
/** EHF club competitions of a season (Champions League, European League, European Cup), read when a gallery names one. */
|
||||||
|
ehfSeason?: (season: string) => Promise<number>;
|
||||||
/** Brings the squads of a game's teams into the event (names for faces and codes). */
|
/** Brings the squads of a game's teams into the event (names for faces and codes). */
|
||||||
syncSquads?: (eventId: string) => Promise<unknown>;
|
syncSquads?: (eventId: string) => Promise<unknown>;
|
||||||
fetchImpl?: typeof fetch;
|
fetchImpl?: typeof fetch;
|
||||||
@@ -326,7 +328,9 @@ export class ArchiveService {
|
|||||||
}
|
}
|
||||||
let folder = known
|
let folder = known
|
||||||
? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } })
|
? await db.cloudFolder.update({ where: { id: known.id }, data: { path: self.path, parentId: parent?.id ?? null, seenAt: new Date() } })
|
||||||
: await db.cloudFolder.create({ data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null } });
|
: await db.cloudFolder.create({
|
||||||
|
data: { sourceId: source.id, fileId: self.fileId, path: self.path, parentId: parent?.id ?? null, ...(parent && !parent.published ? { published: false } : {}) },
|
||||||
|
});
|
||||||
|
|
||||||
const dirs = children.filter((c) => c.isDir);
|
const dirs = children.filter((c) => c.isDir);
|
||||||
const images = children.filter((c) => !c.isDir && IMAGE.test(c.name));
|
const images = children.filter((c) => !c.isDir && IMAGE.test(c.name));
|
||||||
@@ -734,6 +738,13 @@ export class ArchiveService {
|
|||||||
this.seasonsAsked.add(`FPA|${season}`);
|
this.seasonsAsked.add(`FPA|${season}`);
|
||||||
this.fpaSeasonInBackground(season);
|
this.fpaSeasonInBackground(season);
|
||||||
}
|
}
|
||||||
|
// An EHF folder ("EHF Champions League/…/20261021 - RK Partizan AdmiralBet x FC Porto") needs that season's
|
||||||
|
// calendar before it can be the official game. One read, then this folder and the ones after it can match.
|
||||||
|
const ehf = game.parents.some((p) => /^ehf\b/i.test(p.trim()));
|
||||||
|
if (season && ehf && this.deps.ehfSeason && !this.seasonsAsked.has(`EHF|${season}`)) {
|
||||||
|
this.seasonsAsked.add(`EHF|${season}`);
|
||||||
|
await this.deps.ehfSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: ehf season not read"));
|
||||||
|
}
|
||||||
const fixtures = await this.deps.db.sportsFixture.findMany({
|
const fixtures = await this.deps.db.sportsFixture.findMany({
|
||||||
where: {
|
where: {
|
||||||
// Never a game still to be played.
|
// Never a game still to be played.
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { isTeamLineup, teamOfLineup, uniqueShirtNumbers, type LineupFace, type SquadSlot } from "./lineup.js";
|
||||||
|
|
||||||
|
const row = (y: number, n: number): LineupFace[] =>
|
||||||
|
Array.from({ length: n }, (_, i) => ({ x0: 0.05 + i * 0.11, x1: 0.14 + i * 0.11, y0: y, y1: y + 0.08 }));
|
||||||
|
|
||||||
|
const sporting: SquadSlot[] = [
|
||||||
|
["8", "a"],
|
||||||
|
["3", "b"],
|
||||||
|
["13", "c"],
|
||||||
|
["5", "d"],
|
||||||
|
["19", "e"],
|
||||||
|
["7", "f"],
|
||||||
|
["22", "g"],
|
||||||
|
["24", "h"],
|
||||||
|
].map(([number, personId]) => ({ teamId: "sporting", personId: personId!, number: number! }));
|
||||||
|
|
||||||
|
const other: SquadSlot[] = ["8", "9", "10", "11"].map((number, i) => ({ teamId: "other", personId: `o${i}`, number }));
|
||||||
|
|
||||||
|
describe("isTeamLineup", () => {
|
||||||
|
it("accepts two rows of a team across the frame", () => {
|
||||||
|
expect(isTeamLineup([...row(0.2, 8), ...row(0.55, 8)])).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a handful of faces and a tight group", () => {
|
||||||
|
expect(isTeamLineup(row(0.2, 4))).toBe(false);
|
||||||
|
const huddle = row(0.2, 8).map((f) => ({ ...f, x0: f.x0 * 0.2, x1: f.x1 * 0.2 }));
|
||||||
|
expect(isTeamLineup(huddle)).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("uniqueShirtNumbers", () => {
|
||||||
|
it("keeps one face per number and drops a number read on two neighbours", () => {
|
||||||
|
const kept = uniqueShirtNumbers([
|
||||||
|
{ faceId: "1", number: "13", score: 0.9 },
|
||||||
|
{ faceId: "2", number: "19", score: 0.91 },
|
||||||
|
{ faceId: "3", number: "19", score: 0.8 },
|
||||||
|
{ faceId: "4", number: "7", score: 0.95 },
|
||||||
|
{ faceId: "5", number: "7", score: 0.7 },
|
||||||
|
]);
|
||||||
|
expect(kept.map((r) => r.faceId)).toEqual(["1", "4"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("teamOfLineup", () => {
|
||||||
|
it("picks the squad that owns the numbers", () => {
|
||||||
|
const reads = ["8", "3", "13", "5", "19", "7", "22", "24"].map((number, i) => ({ faceId: String(i), number, score: 0.9 }));
|
||||||
|
const found = teamOfLineup(reads, [...sporting, ...other]);
|
||||||
|
expect(found?.teamId).toBe("sporting");
|
||||||
|
expect(found?.claims).toHaveLength(8);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("names nobody when the numbers fit both clubs", () => {
|
||||||
|
const reads = ["8", "9", "10", "11"].map((number, i) => ({ faceId: String(i), number, score: 0.9 }));
|
||||||
|
const both = reads.map((r, i) => ({ teamId: i < 2 ? "a" : "b", personId: `p${r.number}`, number: r.number }));
|
||||||
|
const mirrored = reads.map((r) => ({ teamId: "a", personId: `a${r.number}`, number: r.number })).concat(
|
||||||
|
reads.map((r) => ({ teamId: "b", personId: `b${r.number}`, number: r.number })),
|
||||||
|
);
|
||||||
|
expect(teamOfLineup(reads, mirrored)).toBeNull();
|
||||||
|
expect(both).toHaveLength(4);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/** A team lined up for the photograph: enough faces, about the same size, in one to three rows, across the frame. */
|
||||||
|
export const LINEUP_MIN_FACES = 8;
|
||||||
|
|
||||||
|
export interface LineupFace {
|
||||||
|
y0: number;
|
||||||
|
y1: number;
|
||||||
|
x0: number;
|
||||||
|
x1: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTeamLineup(faces: LineupFace[]): boolean {
|
||||||
|
if (faces.length < LINEUP_MIN_FACES) return false;
|
||||||
|
const heights = faces.map((f) => f.y1 - f.y0).filter((h) => h > 0);
|
||||||
|
if (heights.length < LINEUP_MIN_FACES) return false;
|
||||||
|
const mid = [...heights].sort((a, b) => a - b)[heights.length >> 1]!;
|
||||||
|
const similar = heights.filter((h) => h >= mid * 0.4 && h <= mid * 2.5).length;
|
||||||
|
if (similar < LINEUP_MIN_FACES) return false;
|
||||||
|
const span = Math.max(...faces.map((f) => f.x1)) - Math.min(...faces.map((f) => f.x0));
|
||||||
|
if (span < 0.55) return false;
|
||||||
|
const rows = rowCount(faces, mid);
|
||||||
|
return rows >= 1 && rows <= 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rows from the gaps between face centres. A team sits in one row or two, sometimes three. */
|
||||||
|
function rowCount(faces: LineupFace[], faceHeight: number): number {
|
||||||
|
const centres = faces.map((f) => (f.y0 + f.y1) / 2).sort((a, b) => a - b);
|
||||||
|
let rows = 1;
|
||||||
|
for (let i = 1; i < centres.length; i++) {
|
||||||
|
if (centres[i]! - centres[i - 1]! > faceHeight * 0.8) rows++;
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NumberRead {
|
||||||
|
faceId: string;
|
||||||
|
number: string;
|
||||||
|
score: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One shirt number belongs to one face. A second face with the same number is the neighbour's shirt
|
||||||
|
* inside a wide crop: neither is kept, unless one reading is clearly stronger.
|
||||||
|
*/
|
||||||
|
export function uniqueShirtNumbers(reads: NumberRead[], minScore = 0.7): NumberRead[] {
|
||||||
|
const byNumber = new Map<string, NumberRead[]>();
|
||||||
|
for (const read of reads) {
|
||||||
|
if (!read.number || read.score < minScore) continue;
|
||||||
|
byNumber.set(read.number, [...(byNumber.get(read.number) ?? []), read]);
|
||||||
|
}
|
||||||
|
const out: NumberRead[] = [];
|
||||||
|
for (const list of byNumber.values()) {
|
||||||
|
const sorted = [...list].sort((a, b) => b.score - a.score);
|
||||||
|
const best = sorted[0];
|
||||||
|
if (!best) continue;
|
||||||
|
const next = sorted[1];
|
||||||
|
if (!next || best.score - next.score >= 0.15) out.push(best);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SquadSlot {
|
||||||
|
teamId: string;
|
||||||
|
personId: string;
|
||||||
|
number: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LineupClaim {
|
||||||
|
faceId: string;
|
||||||
|
personId: string;
|
||||||
|
number: string;
|
||||||
|
score: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Which club this photograph is. The squad that contains the most of the numbers read, at least four,
|
||||||
|
* at least half of the readings, and at least two more than the other club.
|
||||||
|
*/
|
||||||
|
export function teamOfLineup(reads: NumberRead[], slots: SquadSlot[]): { teamId: string; claims: LineupClaim[] } | null {
|
||||||
|
const byTeam = new Map<string, SquadSlot[]>();
|
||||||
|
for (const slot of slots) byTeam.set(slot.teamId, [...(byTeam.get(slot.teamId) ?? []), slot]);
|
||||||
|
let best: { teamId: string; claims: LineupClaim[] } | null = null;
|
||||||
|
let second = 0;
|
||||||
|
for (const [teamId, teamSlots] of byTeam) {
|
||||||
|
const claims: LineupClaim[] = [];
|
||||||
|
const used = new Set<string>();
|
||||||
|
for (const read of reads) {
|
||||||
|
const hit = teamSlots.filter((s) => s.number === read.number);
|
||||||
|
if (hit.length !== 1) continue;
|
||||||
|
const personId = hit[0]!.personId;
|
||||||
|
if (used.has(personId)) continue;
|
||||||
|
used.add(personId);
|
||||||
|
claims.push({ faceId: read.faceId, personId, number: read.number, score: read.score });
|
||||||
|
}
|
||||||
|
const count = claims.length;
|
||||||
|
if (!best || count > best.claims.length) {
|
||||||
|
second = best?.claims.length ?? 0;
|
||||||
|
best = { teamId, claims };
|
||||||
|
} else if (count > second) second = count;
|
||||||
|
}
|
||||||
|
if (!best || best.claims.length < 4) return null;
|
||||||
|
if (best.claims.length * 2 < reads.length) return null;
|
||||||
|
if (best.claims.length < second + 2) return null;
|
||||||
|
return best;
|
||||||
|
}
|
||||||
@@ -8,9 +8,9 @@ import type { IngestLogger } from "../ingest/service.js";
|
|||||||
import { waitUntil } from "../lib/idle.js";
|
import { waitUntil } from "../lib/idle.js";
|
||||||
import type { Broadcaster } from "../realtime.js";
|
import type { Broadcaster } from "../realtime.js";
|
||||||
import type { LocalStorage } from "../storage/storage.js";
|
import type { LocalStorage } from "../storage/storage.js";
|
||||||
|
import { normLabel } from "../jersey/service.js";
|
||||||
import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox } from "../jersey/crop.js";
|
import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox } from "../jersey/crop.js";
|
||||||
import type { JerseyReading } from "../jersey/model.js";
|
import type { JerseyReading } from "../jersey/model.js";
|
||||||
import { normLabel } from "../jersey/service.js";
|
|
||||||
|
|
||||||
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
|
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
|
||||||
const STRONG_SUGGESTION = 0.85;
|
const STRONG_SUGGESTION = 0.85;
|
||||||
@@ -19,7 +19,9 @@ export { eventSport, normSport } from "./sport.js";
|
|||||||
|
|
||||||
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
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 { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
|
||||||
|
import { isTeamLineup, teamOfLineup, uniqueShirtNumbers, type SquadSlot } from "./lineup.js";
|
||||||
import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext } from "./numbers.js";
|
import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext } from "./numbers.js";
|
||||||
|
import { samePlayer } from "../sports/identity.js";
|
||||||
import { eventSport, normSport } from "./sport.js";
|
import { eventSport, normSport } from "./sport.js";
|
||||||
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js";
|
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js";
|
||||||
import type { FaceEngine } from "./process.js";
|
import type { FaceEngine } from "./process.js";
|
||||||
@@ -30,6 +32,10 @@ import { tmpdir } from "node:os";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { extractFrames, type VideoTools } from "../archive/video.js";
|
import { extractFrames, type VideoTools } from "../archive/video.js";
|
||||||
|
|
||||||
|
/** Photos read before the season squads. Each worker start, after the register, sends another batch back. */
|
||||||
|
const SQUAD_FACE_PASS = 1;
|
||||||
|
const SQUAD_FACE_BATCH = 30_000;
|
||||||
|
|
||||||
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
|
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
|
||||||
const MIN_FACE_SIDE = 0.012;
|
const MIN_FACE_SIDE = 0.012;
|
||||||
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
|
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
|
||||||
@@ -98,8 +104,8 @@ export class FaceService {
|
|||||||
const recent = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at >= now() - ${RECENT_FACES}`, Prisma.sql`taken_at DESC`);
|
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;
|
left -= recent.length;
|
||||||
if (left <= 0) return [...boosted, ...recent];
|
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.
|
// The older archive, only once that month is clear, still newest game first.
|
||||||
const rest = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at < now() - ${RECENT_FACES}`, Prisma.sql`created_at DESC`);
|
const rest = await this.claimWhere(left, Prisma.sql`faces_boosted_at IS NULL AND taken_at < now() - ${RECENT_FACES}`, Prisma.sql`taken_at DESC`);
|
||||||
return [...boosted, ...recent, ...rest];
|
return [...boosted, ...recent, ...rest];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,6 +144,25 @@ export class FaceService {
|
|||||||
return r.count;
|
return r.count;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Photographs already read, sent through face analysis again so the season's squad can name them.
|
||||||
|
* Newest first, one batch per start: the next start continues with the next batch. A confirmed face
|
||||||
|
* stays on its group when the new reading still matches it.
|
||||||
|
*/
|
||||||
|
async requeueForSquad(): Promise<number> {
|
||||||
|
return Number(
|
||||||
|
await this.deps.db.$executeRaw`
|
||||||
|
UPDATE photos SET faces_status = 'PENDING', faces_pass = ${SQUAD_FACE_PASS}, updated_at = now()
|
||||||
|
WHERE id IN (
|
||||||
|
SELECT id FROM photos
|
||||||
|
WHERE faces_status = 'DONE' AND status = 'READY' AND faces_pass < ${SQUAD_FACE_PASS}
|
||||||
|
AND organization_id IN (SELECT id FROM organizations WHERE biometrics_enabled)
|
||||||
|
ORDER BY taken_at DESC NULLS LAST
|
||||||
|
LIMIT ${SQUAD_FACE_BATCH}
|
||||||
|
)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Photos whose analysis failed, a few at a time, once they have been quiet for a few hours. Recent games first.
|
* 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.
|
* A photo that fails again waits before the next try, so one bad file does not sit at the front forever.
|
||||||
@@ -229,7 +254,7 @@ export class FaceService {
|
|||||||
return small && chest ? kitColour(small, chest) : null;
|
return small && chest ? kitColour(small, chest) : null;
|
||||||
});
|
});
|
||||||
await db.$transaction(async (tx) => {
|
await db.$transaction(async (tx) => {
|
||||||
await tx.face.deleteMany({ where: { photoId } });
|
await releasePhotoFaces(tx, photoId);
|
||||||
for (const [i, f] of faces.entries()) {
|
for (const [i, f] of faces.entries()) {
|
||||||
const n = numbers.get(i);
|
const n = numbers.get(i);
|
||||||
await tx.face.create({
|
await tx.face.create({
|
||||||
@@ -622,6 +647,130 @@ export class FaceService {
|
|||||||
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
|
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (ctx && !ctx.national && ctx.teamIds.length) await this.nameLineupPhotos(eventId, ctx, notThem, off);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A team lined up for the photograph: each clear shirt number belongs to one player of that squad.
|
||||||
|
* Those faces are suggested from the number. A group that already spans other photographs keeps a
|
||||||
|
* different name the face itself was sure of.
|
||||||
|
*/
|
||||||
|
private async nameLineupPhotos(eventId: string, ctx: NumberContext, rejected: Map<string, Set<string>>, off: Set<string>): Promise<void> {
|
||||||
|
const { db } = this.deps;
|
||||||
|
const slots = await this.lineupSlots(ctx);
|
||||||
|
if (slots.length < 4) return;
|
||||||
|
const faces = await db.face.findMany({
|
||||||
|
where: { photo: { eventId }, groupId: { not: null } },
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
photoId: true,
|
||||||
|
groupId: true,
|
||||||
|
x0: true,
|
||||||
|
y0: true,
|
||||||
|
x1: true,
|
||||||
|
y1: true,
|
||||||
|
jerseyNumber: true,
|
||||||
|
jerseyScore: true,
|
||||||
|
group: { select: { personId: true, suggestedPersonId: true, suggestionScore: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const byPhoto = new Map<string, typeof faces>();
|
||||||
|
for (const face of faces) byPhoto.set(face.photoId, [...(byPhoto.get(face.photoId) ?? []), face]);
|
||||||
|
for (const [photoId, lined] of byPhoto) {
|
||||||
|
if (!isTeamLineup(lined)) continue;
|
||||||
|
const reads = uniqueShirtNumbers(
|
||||||
|
lined
|
||||||
|
.filter((f) => f.groupId && !f.group?.personId)
|
||||||
|
.map((f) => ({ faceId: f.id, number: normLabel(f.jerseyNumber) ?? "", score: f.jerseyScore ?? 0 })),
|
||||||
|
);
|
||||||
|
const found = teamOfLineup(reads, slots);
|
||||||
|
if (!found) continue;
|
||||||
|
const faceOf = new Map(lined.map((f) => [f.id, f]));
|
||||||
|
for (const claim of found.claims) {
|
||||||
|
const face = faceOf.get(claim.faceId);
|
||||||
|
const groupId = face?.groupId;
|
||||||
|
if (!face || !groupId || face.group?.personId) continue;
|
||||||
|
if (rejected.get(groupId)?.has(claim.personId) || off.has(claim.personId)) continue;
|
||||||
|
const siblings = faces.filter((f) => f.groupId === groupId);
|
||||||
|
const onlyHere = siblings.every((f) => f.photoId === photoId);
|
||||||
|
const clash = siblings.some((f) => {
|
||||||
|
const n = normLabel(f.jerseyNumber);
|
||||||
|
return !!n && (f.jerseyScore ?? 0) >= 0.7 && n !== claim.number;
|
||||||
|
});
|
||||||
|
if (clash) continue;
|
||||||
|
const current = face.group?.suggestedPersonId ?? null;
|
||||||
|
if (!onlyHere && current && current !== claim.personId) continue;
|
||||||
|
const score = Math.round(Math.min(0.95, Math.max(0.75, claim.score)) * 1000) / 1000;
|
||||||
|
if (current === claim.personId && (face.group?.suggestionScore ?? 0) >= score) continue;
|
||||||
|
await db.faceGroup.update({ where: { id: groupId }, data: { suggestedPersonId: claim.personId, suggestionScore: score } });
|
||||||
|
face.group = { personId: null, suggestedPersonId: claim.personId, suggestionScore: score };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Squad players of the two clubs, as people, with the shirt number of this season. */
|
||||||
|
private async lineupSlots(ctx: NumberContext): Promise<SquadSlot[]> {
|
||||||
|
const { db } = this.deps;
|
||||||
|
const squad = await db.sportsPlayer.findMany({
|
||||||
|
where: { teamId: { in: ctx.teamIds }, season: ctx.season, goneAt: null, number: { not: null } },
|
||||||
|
select: { id: true, teamId: true, number: true, externalId: true, name: true, fullName: true, birthDate: true },
|
||||||
|
});
|
||||||
|
if (!squad.length) return [];
|
||||||
|
const externalIds = [...new Set(squad.map((s) => s.externalId).filter((id): id is string => !!id))];
|
||||||
|
const births = squad.filter((s): s is typeof s & { birthDate: string; fullName: string } => !!s.birthDate && !!s.fullName);
|
||||||
|
const mates = await db.sportsPlayer.findMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ id: { in: squad.map((s) => s.id) } },
|
||||||
|
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
|
||||||
|
...births.map((s) => ({ birthDate: s.birthDate, fullName: s.fullName })),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
select: { id: true, externalId: true, teamId: true, name: true, fullName: true, birthDate: true },
|
||||||
|
});
|
||||||
|
const people = await db.person.findMany({
|
||||||
|
where: { organizationId: ctx.organizationId, recognitionOffAt: null, sportsPlayerId: { in: mates.map((m) => m.id) } },
|
||||||
|
select: { id: true, sportsPlayerId: true },
|
||||||
|
});
|
||||||
|
const personByPlayer = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
|
||||||
|
const slots: SquadSlot[] = [];
|
||||||
|
for (const row of squad) {
|
||||||
|
const number = normLabel(row.number);
|
||||||
|
if (!number) continue;
|
||||||
|
const ids = new Set<string>();
|
||||||
|
for (const mate of mates) {
|
||||||
|
const personId = personByPlayer.get(mate.id);
|
||||||
|
if (personId && samePlayer(mate, row)) ids.add(personId);
|
||||||
|
}
|
||||||
|
if (ids.size === 1) slots.push({ teamId: row.teamId, personId: [...ids][0]!, number });
|
||||||
|
}
|
||||||
|
return slots;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recent team photographs, newest first. A restart names a few of them from the shirt numbers
|
||||||
|
* and leaves the rest of the archive for the next time that game is read.
|
||||||
|
*/
|
||||||
|
async refreshLineupEvents(stopped: () => boolean): Promise<number> {
|
||||||
|
const rows = await this.deps.db.$queryRaw<{ event_id: string }[]>`
|
||||||
|
SELECT event_id FROM (
|
||||||
|
SELECT p.event_id, max(p.taken_at) AS taken
|
||||||
|
FROM photos p
|
||||||
|
JOIN faces f ON f.photo_id = p.id
|
||||||
|
WHERE p.event_id IS NOT NULL
|
||||||
|
GROUP BY p.id, p.event_id
|
||||||
|
HAVING count(f.id) >= 8
|
||||||
|
) lineups
|
||||||
|
GROUP BY event_id
|
||||||
|
ORDER BY max(taken) DESC
|
||||||
|
LIMIT 24`;
|
||||||
|
let n = 0;
|
||||||
|
for (const row of rows) {
|
||||||
|
if (stopped()) break;
|
||||||
|
await this.refreshSuggestions(row.event_id);
|
||||||
|
n++;
|
||||||
|
}
|
||||||
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The number most of a group's faces read (clearly), if it is a clear majority. */
|
/** The number most of a group's faces read (clearly), if it is a clear majority. */
|
||||||
@@ -1186,6 +1335,38 @@ export async function dropOffRosterSuggestions(db: Db, refresh?: (eventId: strin
|
|||||||
return n;
|
return n;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type FaceTx = Pick<Db, "face" | "faceGroup" | "videoFace">;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Takes this photo's faces out of their groups before they are read again. A confirmed group keeps its
|
||||||
|
* centroid, so the new reading rejoins it when it is still the same person. An empty group nobody named goes.
|
||||||
|
*/
|
||||||
|
async function releasePhotoFaces(tx: FaceTx, photoId: string): Promise<void> {
|
||||||
|
const previous = await tx.face.findMany({ where: { photoId }, select: { groupId: true } });
|
||||||
|
await tx.face.deleteMany({ where: { photoId } });
|
||||||
|
const groupIds = [...new Set(previous.map((face) => face.groupId).filter((id): id is string => !!id))];
|
||||||
|
for (const groupId of groupIds) {
|
||||||
|
const group = await tx.faceGroup.findUnique({ where: { id: groupId }, select: { id: true, personId: true } });
|
||||||
|
if (!group) continue;
|
||||||
|
const left = await tx.face.findMany({ where: { groupId }, select: { embedding: true } });
|
||||||
|
const videos = await tx.videoFace.count({ where: { groupId } });
|
||||||
|
if (left.length === 0 && videos === 0) {
|
||||||
|
if (group.personId) await tx.faceGroup.update({ where: { id: groupId }, data: { size: 1 } });
|
||||||
|
else await tx.faceGroup.delete({ where: { id: groupId } });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (left.length === 0) {
|
||||||
|
await tx.faceGroup.update({ where: { id: groupId }, data: { size: videos } });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const centroid = mergeMeans(left.filter((face) => face.embedding.length > 0).map((face) => ({ mean: face.embedding, count: 1 })));
|
||||||
|
await tx.faceGroup.update({
|
||||||
|
where: { id: groupId },
|
||||||
|
data: { size: left.length + videos, ...(centroid.length > 0 ? { centroid } : {}) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Keeps `processes` face engines busy. */
|
/** Keeps `processes` face engines busy. */
|
||||||
export class FaceWorker {
|
export class FaceWorker {
|
||||||
private inFlight = 0;
|
private inFlight = 0;
|
||||||
@@ -1222,6 +1403,12 @@ export class FaceWorker {
|
|||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
void this.service.requeueStale();
|
void this.service.requeueStale();
|
||||||
|
void this.service
|
||||||
|
.refreshLineupEvents(() => this.stopped)
|
||||||
|
.then((n) => {
|
||||||
|
if (n) this.opts.log.info({ events: n }, "faces: lineup photographs named from shirt numbers");
|
||||||
|
})
|
||||||
|
.catch((err) => this.opts.log.warn({ err }, "faces: lineup photographs not named"));
|
||||||
let missedAt = 0;
|
let missedAt = 0;
|
||||||
let failedAt = 0;
|
let failedAt = 0;
|
||||||
let videosCheckedAt = Date.now();
|
let videosCheckedAt = Date.now();
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ function busyQueue() {
|
|||||||
requeueFailed: async () => 0,
|
requeueFailed: async () => 0,
|
||||||
requeueVideos: async () => 0,
|
requeueVideos: async () => 0,
|
||||||
requeueStale: async () => 0,
|
requeueStale: async () => 0,
|
||||||
|
refreshLineupEvents: async () => 0,
|
||||||
claimReferences: async () => [],
|
claimReferences: async () => [],
|
||||||
processReference: async () => {},
|
processReference: async () => {},
|
||||||
claim: async (limit: number) => Array.from({ length: Math.max(0, limit) }, (_, i) => `p${i}`),
|
claim: async (limit: number) => Array.from({ length: Math.max(0, limit) }, (_, i) => `p${i}`),
|
||||||
|
|||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { type Fetch, EHF_COMPETITIONS, EhfProvider, ehfFixture, ehfMatchesIds, ehfSeasonSlug, ehfSheet } from "./providers.js";
|
||||||
|
|
||||||
|
const partizan = {
|
||||||
|
matchID: "202711020101012",
|
||||||
|
venue: {
|
||||||
|
place: { cityName: "Belgrade", hallName: "Hala Aleksandar Nikolic" },
|
||||||
|
date: { utc: "2026-10-21T16:45:00Z", hasTime: true },
|
||||||
|
},
|
||||||
|
comp: { round: { name: "Group Phase" }, group: { name: "A" } },
|
||||||
|
homeTeam: { team: { id: "partizan", name: "RK Partizan AdmiralBet" }, score: { goals: null } },
|
||||||
|
guestTeam: { team: { id: "porto", name: "FC Porto" }, score: { goals: 28 } },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("EHF matches", () => {
|
||||||
|
it("reads the season slug and the ids the site's page carries", () => {
|
||||||
|
expect(ehfSeasonSlug("20262027")).toBe("2026-27");
|
||||||
|
expect(ehfSeasonSlug("2026")).toBeNull();
|
||||||
|
expect(ehfMatchesIds(`<div data-competition-id="abc" data-currentcontentid="138649">`)).toEqual({ competitionId: "abc", contentId: "138649" });
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the kick-off, the hall and a finished score, and drops a match with no time", () => {
|
||||||
|
const fixture = ehfFixture(partizan, "cl-men", "20262027");
|
||||||
|
expect(fixture).toMatchObject({
|
||||||
|
externalId: "202711020101012",
|
||||||
|
season: "20262027",
|
||||||
|
home: { name: "RK Partizan AdmiralBet" },
|
||||||
|
away: { name: "FC Porto" },
|
||||||
|
startsAt: new Date("2026-10-21T16:45:00Z"),
|
||||||
|
round: "Group Phase A",
|
||||||
|
venue: "Hala Aleksandar Nikolic, Belgrade",
|
||||||
|
homeScore: null,
|
||||||
|
awayScore: 28,
|
||||||
|
});
|
||||||
|
expect(ehfFixture({ ...partizan, venue: { date: {} } }, "cl-men", "20262027")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("takes the nominated players and the bench staff, and ignores a birth date the sheet left empty", () => {
|
||||||
|
const sheet = ehfSheet({
|
||||||
|
matchDetails: {
|
||||||
|
details: {
|
||||||
|
homeTeam: {
|
||||||
|
players: [
|
||||||
|
{
|
||||||
|
id: "p1",
|
||||||
|
shirtNumber: "1",
|
||||||
|
playingPosition: "Goalkeeper",
|
||||||
|
person: { firstName: "Luka", lastName: "Krivokapić", dateOfBirth: "2002-02-07T00:00:00Z", nationAbbreviation: "SRB" },
|
||||||
|
newPhoto: { w512: "https://res.ehf.eu/p1.jpg" },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
officials: [
|
||||||
|
{ id: "c1", shirtNumber: "A", person: { firstName: "Marko", lastName: "Isakovic", dateOfBirth: "0001-01-01T00:00:00" } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
guestTeam: { players: [], officials: [] },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(sheet?.home).toEqual([
|
||||||
|
{
|
||||||
|
externalId: "p1",
|
||||||
|
number: "1",
|
||||||
|
name: "Luka Krivokapić",
|
||||||
|
fullName: "Luka Krivokapić",
|
||||||
|
position: "Guarda-redes",
|
||||||
|
photoUrl: "https://res.ehf.eu/p1.jpg",
|
||||||
|
birthDate: "2002-02-07",
|
||||||
|
nationality: "SRB",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
externalId: "c1",
|
||||||
|
number: "A",
|
||||||
|
name: "Marko Isakovic",
|
||||||
|
fullName: "Marko Isakovic",
|
||||||
|
position: "Equipa técnica",
|
||||||
|
photoUrl: null,
|
||||||
|
birthDate: null,
|
||||||
|
nationality: null,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(ehfSheet({ matchDetails: { details: { homeTeam: { players: [] }, guestTeam: { players: [] } } } })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("walks past the page around today and stops when a page adds nothing", async () => {
|
||||||
|
const seen: string[] = [];
|
||||||
|
const fetch: Fetch = async (url) => {
|
||||||
|
seen.push(url);
|
||||||
|
const json = url.includes("GetInitMatches")
|
||||||
|
? { matches: [partizan], hasPastMatches: true, hasFutureMatches: false }
|
||||||
|
: url.includes("futureMatches=false")
|
||||||
|
? {
|
||||||
|
matches: [
|
||||||
|
{
|
||||||
|
...partizan,
|
||||||
|
matchID: "older",
|
||||||
|
venue: { ...partizan.venue, date: { utc: "2026-09-17T18:45:00Z", hasTime: true } },
|
||||||
|
homeTeam: { team: { id: "porto", name: "FC Porto" }, score: { goals: 30 } },
|
||||||
|
guestTeam: { team: { id: "partizan", name: "RK Partizan" }, score: { goals: 27 } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
hasPastMatches: true,
|
||||||
|
hasFutureMatches: false,
|
||||||
|
}
|
||||||
|
: { matches: [], hasPastMatches: false, hasFutureMatches: false };
|
||||||
|
return { ok: true, status: 200, json: async () => json, text: async () => `<div data-competition-id="abc" data-currentcontentid="9">`, arrayBuffer: async () => new ArrayBuffer(0) };
|
||||||
|
};
|
||||||
|
const fixtures = await new EhfProvider(fetch, 0).matches(EHF_COMPETITIONS[0], "20262027", true);
|
||||||
|
expect(fixtures.map((f) => f.externalId).sort()).toEqual(["202711020101012", "older"]);
|
||||||
|
expect(seen.some((u) => u.includes("/men/2026-27/matches/"))).toBe(true);
|
||||||
|
expect(seen.filter((u) => u.includes("GetMatches")).length).toBe(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -131,12 +131,59 @@ export const LIGA_COMPETITIONS = [
|
|||||||
|
|
||||||
const foldComp = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
const foldComp = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||||
|
|
||||||
|
/** The domestic club competitions: first division, second division, league cup. Not the cups of other countries. */
|
||||||
|
const CLUB_TIERS = new Set(["Liga 1", "Liga 2", "Taça"]);
|
||||||
|
|
||||||
|
export interface LigaClubCompetition {
|
||||||
|
externalId: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LigaClubSeason {
|
||||||
|
id: string;
|
||||||
|
competitions: LigaClubCompetition[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seasons the federation still lists, each with the club competitions of that year.
|
||||||
|
* The slug changes with the sponsor (Liga NOS, Liga Sagres, Betclic). A numeric id is a foreign competition.
|
||||||
|
*/
|
||||||
|
export function clubSeasons(payload: unknown): LigaClubSeason[] {
|
||||||
|
if (!Array.isArray(payload)) return [];
|
||||||
|
const out: LigaClubSeason[] = [];
|
||||||
|
for (const row of payload) {
|
||||||
|
if (!row || typeof row !== "object") continue;
|
||||||
|
const id = str((row as { id?: unknown }).id)?.replace(/\D/g, "") ?? "";
|
||||||
|
if (!/^\d{8}$/.test(id)) continue;
|
||||||
|
const comps = (row as { competitions?: unknown }).competitions;
|
||||||
|
if (!Array.isArray(comps)) continue;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const competitions: LigaClubCompetition[] = [];
|
||||||
|
for (const c of comps) {
|
||||||
|
if (!c || typeof c !== "object") continue;
|
||||||
|
const tier = str((c as { competition?: unknown }).competition);
|
||||||
|
if (!tier || !CLUB_TIERS.has(tier)) continue;
|
||||||
|
const externalId = str((c as { externalId?: unknown }).externalId);
|
||||||
|
if (!externalId || /^\d+$/.test(externalId) || seen.has(externalId)) continue;
|
||||||
|
seen.add(externalId);
|
||||||
|
competitions.push({ externalId, name: str((c as { name?: unknown }).name) ?? externalId });
|
||||||
|
}
|
||||||
|
if (competitions.length) out.push({ id, competitions });
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
export class LigaProvider {
|
export class LigaProvider {
|
||||||
static readonly BASE = "https://www.ligaportugal.pt/api/v1";
|
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" };
|
private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" };
|
||||||
|
|
||||||
constructor(private readonly fetcher: Fetch) {}
|
constructor(private readonly fetcher: Fetch) {}
|
||||||
|
|
||||||
|
/** Every season the federation still publishes, with that year's club competitions. */
|
||||||
|
async seasons(): Promise<LigaClubSeason[]> {
|
||||||
|
return clubSeasons(await this.api("seasons", {}));
|
||||||
|
}
|
||||||
|
|
||||||
private async api(path: string, params: Record<string, string>): Promise<unknown> {
|
private async api(path: string, params: Record<string, string>): Promise<unknown> {
|
||||||
const u = new URL(`${LigaProvider.BASE}/${path}`);
|
const u = new URL(`${LigaProvider.BASE}/${path}`);
|
||||||
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
|
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
|
||||||
@@ -865,3 +912,214 @@ export class UefaProvider {
|
|||||||
return parseUefaLineups(data);
|
return parseUefaLineups(data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- EHF (the JSON ehfcl/ehfel/ehfec.eurohandball.com reads; not a documented API) -------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EHF club competitions the archive files under Competições Internacionais. The id is ours (the site's competition
|
||||||
|
* id changes with the season). The page for that season names the id the site's own API expects.
|
||||||
|
*/
|
||||||
|
export const EHF_COMPETITIONS = [
|
||||||
|
{ externalId: "cl-men", name: "EHF Champions League", gender: "M", site: "https://ehfcl.eurohandball.com", path: "men" },
|
||||||
|
{ externalId: "cl-women", name: "EHF Champions League Women", gender: "F", site: "https://ehfcl.eurohandball.com", path: "women" },
|
||||||
|
{ externalId: "el-men", name: "EHF European League", gender: "M", site: "https://ehfel.eurohandball.com", path: "men" },
|
||||||
|
{ externalId: "el-women", name: "EHF European League Women", gender: "F", site: "https://ehfel.eurohandball.com", path: "women" },
|
||||||
|
{ externalId: "ec-men", name: "EHF European Cup", gender: "M", site: "https://ehfec.eurohandball.com", path: "men" },
|
||||||
|
{ externalId: "ec-women", name: "EHF European Cup Women", gender: "F", site: "https://ehfec.eurohandball.com", path: "women" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export type EhfCompetition = (typeof EHF_COMPETITIONS)[number];
|
||||||
|
|
||||||
|
/** Our season "20262027" is the site's "2026-27". */
|
||||||
|
export function ehfSeasonSlug(season: string): string | null {
|
||||||
|
const start = season.slice(0, 4);
|
||||||
|
const end = season.slice(4);
|
||||||
|
if (!/^20\d{2}$/.test(start) || !/^20\d{2}$/.test(end) || Number(end) !== Number(start) + 1) return null;
|
||||||
|
return `${start}-${end.slice(2)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Competition and content ids from a season's matches page. */
|
||||||
|
export function ehfMatchesIds(html: string): { competitionId: string; contentId: string } | null {
|
||||||
|
const competitionId = /data-competition-id="([^"]+)"/.exec(html)?.[1];
|
||||||
|
const contentId = /data-currentcontentid="([^"]+)"/.exec(html)?.[1];
|
||||||
|
return competitionId && contentId ? { competitionId, contentId } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const EHF_POSITIONS: Record<string, string> = {
|
||||||
|
Goalkeeper: "Guarda-redes",
|
||||||
|
"Left Wing": "Extremo esquerdo",
|
||||||
|
"Right Wing": "Extremo direito",
|
||||||
|
"Left Back": "Lateral esquerdo",
|
||||||
|
"Right Back": "Lateral direito",
|
||||||
|
"Centre Back": "Central",
|
||||||
|
"Line Player": "Pivô",
|
||||||
|
"Field Player": "Jogador",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** One match from the EHF matches API, in our season ("20262027"), or null when it has no teams or no kick-off. */
|
||||||
|
export function ehfFixture(row: unknown, competition: string, season: string): FixtureData | null {
|
||||||
|
const m = obj(row);
|
||||||
|
const id = str(m.matchID);
|
||||||
|
const home = ehfTeam(obj(m.homeTeam));
|
||||||
|
const away = ehfTeam(obj(m.guestTeam));
|
||||||
|
const when = obj(obj(m.venue).date);
|
||||||
|
const utc = str(when.utc);
|
||||||
|
if (!id || !home || !away || !utc) return null;
|
||||||
|
const at = new Date(utc);
|
||||||
|
if (Number.isNaN(at.getTime())) return null;
|
||||||
|
const place = obj(obj(m.venue).place);
|
||||||
|
const hall = str(place.hallName);
|
||||||
|
const city = str(place.cityName);
|
||||||
|
const comp = obj(m.comp);
|
||||||
|
const round = str(obj(comp.round).name) ?? str(obj(comp.phase).name);
|
||||||
|
const group = str(obj(comp.group).name);
|
||||||
|
const goals = (side: Json) => {
|
||||||
|
const n = obj(side.score).goals;
|
||||||
|
return typeof n === "number" ? n : null;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
externalId: id,
|
||||||
|
competition,
|
||||||
|
season,
|
||||||
|
home,
|
||||||
|
away,
|
||||||
|
startsAt: at,
|
||||||
|
timeKnown: when.hasTime !== false,
|
||||||
|
round: round && group ? `${round} ${group}` : round,
|
||||||
|
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
|
||||||
|
homeScore: goals(obj(m.homeTeam)),
|
||||||
|
awayScore: goals(obj(m.guestTeam)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function ehfTeam(side: Json): TeamData | null {
|
||||||
|
const t = obj(side.team);
|
||||||
|
const externalId = str(t.id);
|
||||||
|
const name = str(t.name);
|
||||||
|
if (!externalId || !name) return null;
|
||||||
|
return { externalId, name, abbreviation: str(t.shortName) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The match sheet: the nominated players and the bench staff (letters A, B, …). The EHF page does not say which
|
||||||
|
* letter is the coach. Null when the sheet is not published yet.
|
||||||
|
*/
|
||||||
|
export function ehfSheet(data: unknown): { home: PlayerData[]; away: PlayerData[] } | null {
|
||||||
|
const details = obj(obj(obj(data).matchDetails).details);
|
||||||
|
const home = ehfSide(obj(details.homeTeam));
|
||||||
|
const away = ehfSide(obj(details.guestTeam));
|
||||||
|
if (!home.length && !away.length) return null;
|
||||||
|
return { home, away };
|
||||||
|
}
|
||||||
|
|
||||||
|
function ehfSide(side: Json): PlayerData[] {
|
||||||
|
const players = (Array.isArray(side.players) ? side.players : []).flatMap((row) => {
|
||||||
|
const p = ehfMember(obj(row), false);
|
||||||
|
return p ? [p] : [];
|
||||||
|
});
|
||||||
|
const staff = (Array.isArray(side.officials) ? side.officials : []).flatMap((row) => {
|
||||||
|
const p = ehfMember(obj(row), true);
|
||||||
|
return p ? [p] : [];
|
||||||
|
});
|
||||||
|
return [...players, ...staff];
|
||||||
|
}
|
||||||
|
|
||||||
|
function ehfMember(entry: Json, staff: boolean): PlayerData | null {
|
||||||
|
const person = obj(entry.person);
|
||||||
|
const name = [str(person.firstName), str(person.lastName)].filter(Boolean).join(" ");
|
||||||
|
if (!name) return null;
|
||||||
|
const born = str(person.dateOfBirth);
|
||||||
|
const year = born ? Number(born.slice(0, 4)) : 0;
|
||||||
|
const photo = obj(entry.newPhoto);
|
||||||
|
const photoUrl = [str(photo.w512), str(photo.w360), str(photo.w180)].find((u) => u?.startsWith("https://")) ?? null;
|
||||||
|
const position = str(entry.playingPosition);
|
||||||
|
return {
|
||||||
|
externalId: str(entry.id),
|
||||||
|
number: str(entry.shirtNumber),
|
||||||
|
name,
|
||||||
|
fullName: name,
|
||||||
|
position: staff ? "Equipa técnica" : position ? (EHF_POSITIONS[position] ?? position) : null,
|
||||||
|
photoUrl,
|
||||||
|
birthDate: year >= 1900 && born ? born.slice(0, 10) : null,
|
||||||
|
nationality: str(person.nationAbbreviation),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface EhfPage {
|
||||||
|
matches: unknown[];
|
||||||
|
hasPastMatches?: boolean;
|
||||||
|
hasFutureMatches?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class EhfProvider {
|
||||||
|
constructor(
|
||||||
|
private readonly fetcher: Fetch,
|
||||||
|
private readonly delayMs = 200,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** A season's matches. `full` walks every page; otherwise the page the site opens on (around today). */
|
||||||
|
async matches(comp: EhfCompetition, season: string, full: boolean): Promise<FixtureData[]> {
|
||||||
|
const slug = ehfSeasonSlug(season);
|
||||||
|
if (!slug) return [];
|
||||||
|
const html = await get(this.fetcher, `${comp.site}/${comp.path}/${slug}/matches/`, { accept: "text/html" }, "text");
|
||||||
|
const ids = ehfMatchesIds(typeof html === "string" ? html : "");
|
||||||
|
if (!ids) throw new Error(`ehf: ${comp.name} ${slug} has no competition id`);
|
||||||
|
const byId = new Map<string, FixtureData>();
|
||||||
|
const add = (rows: unknown[]) => {
|
||||||
|
for (const row of rows) {
|
||||||
|
const fixture = ehfFixture(row, comp.externalId, season);
|
||||||
|
if (fixture) byId.set(fixture.externalId, fixture);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const init = await this.matchesPage(comp.site, "/umbraco/api/competitionmatchesapi/GetInitMatches", ids);
|
||||||
|
add(init.matches);
|
||||||
|
if (full) await this.walk(comp, season, ids, byId);
|
||||||
|
return [...byId.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The match sheet, or null when the EHF has not published the players yet. */
|
||||||
|
async sheet(site: string, matchId: string): Promise<{ home: PlayerData[]; away: PlayerData[] } | null> {
|
||||||
|
const data = await get(
|
||||||
|
this.fetcher,
|
||||||
|
`${site}/umbraco/api/matchdetailapi/GetMatchDetails?matchId=${encodeURIComponent(matchId)}`,
|
||||||
|
{ accept: "application/json" },
|
||||||
|
"json",
|
||||||
|
);
|
||||||
|
return ehfSheet(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async walk(comp: EhfCompetition, season: string, ids: { competitionId: string; contentId: string }, byId: Map<string, FixtureData>): Promise<void> {
|
||||||
|
const edge = (future: boolean) => {
|
||||||
|
const rows = [...byId.values()].sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime());
|
||||||
|
return future ? rows[rows.length - 1] : rows[0];
|
||||||
|
};
|
||||||
|
for (const future of [false, true]) {
|
||||||
|
for (let page = 0; page < 40; page++) {
|
||||||
|
const from = edge(future);
|
||||||
|
if (!from) break;
|
||||||
|
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
|
||||||
|
const body = await this.matchesPage(comp.site, "/umbraco/api/competitionmatchesapi/GetMatches", {
|
||||||
|
...ids,
|
||||||
|
matchId: from.externalId,
|
||||||
|
futureMatches: future ? "true" : "false",
|
||||||
|
});
|
||||||
|
let added = 0;
|
||||||
|
for (const row of body.matches) {
|
||||||
|
const fixture = ehfFixture(row, comp.externalId, season);
|
||||||
|
if (fixture && !byId.has(fixture.externalId)) {
|
||||||
|
byId.set(fixture.externalId, fixture);
|
||||||
|
added++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const more = future ? body.hasFutureMatches : body.hasPastMatches;
|
||||||
|
if (!added || !more) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async matchesPage(site: string, path: string, params: Record<string, string>): Promise<EhfPage> {
|
||||||
|
const q = new URLSearchParams(params);
|
||||||
|
const data = obj(await get(this.fetcher, `${site}${path}?${q}`, { accept: "application/json" }, "json"));
|
||||||
|
return { matches: Array.isArray(data.matches) ? data.matches : [], hasPastMatches: data.hasPastMatches === true, hasFutureMatches: data.hasFutureMatches === true };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { clubSeasons } from "./providers.js";
|
||||||
|
|
||||||
|
describe("clubSeasons", () => {
|
||||||
|
it("keeps the two divisions and the league cup, under the name of that year", () => {
|
||||||
|
const seasons = clubSeasons([
|
||||||
|
{
|
||||||
|
id: "20262027",
|
||||||
|
competitions: [
|
||||||
|
{ externalId: "ligaportugalbetclic", name: "Liga Portugal Betclic", competition: "Liga 1" },
|
||||||
|
{ externalId: "ligaportugalmeusuper", name: "Liga Portugal Meu Super", competition: "Liga 2" },
|
||||||
|
{ externalId: "allianzcup", name: "Allianz Cup", competition: "Taça" },
|
||||||
|
{ externalId: "218549", name: "Taça de Portugal", competition: "" },
|
||||||
|
{ externalId: "219487", name: "UEFA Champions League", competition: "" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "20172018",
|
||||||
|
competitions: [
|
||||||
|
{ externalId: "liganos", name: "Liga NOS", competition: "Liga 1" },
|
||||||
|
{ externalId: "ledmanligapro", name: "LEDMAN LigaPro", competition: "Liga 2" },
|
||||||
|
{ externalId: "taçactt", name: "Taça CTT", competition: "Taça" },
|
||||||
|
{ externalId: "taçactt", name: "Taça CTT", competition: "Taça" },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(seasons.map((s) => s.id)).toEqual(["20262027", "20172018"]);
|
||||||
|
expect(seasons[0]?.competitions.map((c) => c.externalId)).toEqual(["ligaportugalbetclic", "ligaportugalmeusuper", "allianzcup"]);
|
||||||
|
expect(seasons[1]?.competitions.map((c) => c.externalId)).toEqual(["liganos", "ledmanligapro", "taçactt"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+152
-40
@@ -17,11 +17,14 @@ import {
|
|||||||
FpaProvider,
|
FpaProvider,
|
||||||
FpfProvider,
|
FpfProvider,
|
||||||
LIGA_COMPETITIONS,
|
LIGA_COMPETITIONS,
|
||||||
|
type LigaClubCompetition,
|
||||||
LigaProvider,
|
LigaProvider,
|
||||||
type OfficialData,
|
type OfficialData,
|
||||||
type PlayerData,
|
type PlayerData,
|
||||||
ProviderHttpError,
|
ProviderHttpError,
|
||||||
type TeamData,
|
type TeamData,
|
||||||
|
EHF_COMPETITIONS,
|
||||||
|
EhfProvider,
|
||||||
UEFA_COMPETITIONS,
|
UEFA_COMPETITIONS,
|
||||||
UEFA_PITCH_OFFICIALS,
|
UEFA_PITCH_OFFICIALS,
|
||||||
UefaProvider,
|
UefaProvider,
|
||||||
@@ -30,7 +33,7 @@ import {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Sports data (the old app's "code replacements" system, rebuilt): competitions, teams, squads and fixtures read
|
* Sports data (the old app's "code replacements" system, rebuilt): competitions, teams, squads and fixtures read
|
||||||
* from Liga Portugal, FPF, FPA and UEFA every few hours, shared by every organisation. Organisations turn them into
|
* from Liga Portugal, FPF, FPA, UEFA and the EHF every few hours, shared by every organisation. Organisations turn them into
|
||||||
* their code list (`\b9\` → "Pavlidis"), into people (names, clubs and numbers for faces and jersey numbers, with
|
* their code list (`\b9\` → "Pavlidis"), into people (names, clubs and numbers for faces and jersey numbers, with
|
||||||
* the official headshot as reference) and into events (pick the match, the form fills itself).
|
* the official headshot as reference) and into events (pick the match, the form fills itself).
|
||||||
*/
|
*/
|
||||||
@@ -38,11 +41,13 @@ import {
|
|||||||
export const REFRESH_EVERY_MS = 6 * 3600_000;
|
export const REFRESH_EVERY_MS = 6 * 3600_000;
|
||||||
/** FPF line-ups appear on the match sheet around kick-off: read them from 1 h before to 2 h after. */
|
/** FPF line-ups appear on the match sheet around kick-off: read them from 1 h before to 2 h after. */
|
||||||
const LINEUP_WINDOW = { before: 3600_000, after: 2 * 3600_000 };
|
const LINEUP_WINDOW = { before: 3600_000, after: 2 * 3600_000 };
|
||||||
const HEADSHOT_HOSTS = ["www.ligaportugal.pt", "ligaportugal.pt", "img.uefa.com", "si.fpa.pt"];
|
const HEADSHOT_HOSTS = ["www.ligaportugal.pt", "ligaportugal.pt", "img.uefa.com", "si.fpa.pt", "res.ehf.eu"];
|
||||||
/** The "club" of referees made people from a match's referee team. */
|
/** The "club" of referees made people from a match's referee team. */
|
||||||
export const REFEREES = "Arbitragem";
|
export const REFEREES = "Arbitragem";
|
||||||
/** UEFA match sheets read per refresh (past matches without one yet): squads grow from them. */
|
/** UEFA match sheets read per refresh (past matches without one yet): squads grow from them. */
|
||||||
const UEFA_SHEETS_PER_REFRESH = 80;
|
const UEFA_SHEETS_PER_REFRESH = 80;
|
||||||
|
/** Match sheets read per EHF competition per refresh (the newest still unread). */
|
||||||
|
const EHF_SHEETS_PER_REFRESH = 20;
|
||||||
const HEADSHOT_MAX_BYTES = 8 * 1024 * 1024;
|
const HEADSHOT_MAX_BYTES = 8 * 1024 * 1024;
|
||||||
/** Handball competitions whose squads are read from the match reports: the senior national leagues and cups. */
|
/** Handball competitions whose squads are read from the match reports: the senior national leagues and cups. */
|
||||||
export const FPA_SQUAD_COMPETITIONS = ["PO01", "PO01A", "PO09", "PO09A", "PO20", "PO23"];
|
export const FPA_SQUAD_COMPETITIONS = ["PO01", "PO01A", "PO09", "PO09A", "PO20", "PO23"];
|
||||||
@@ -60,7 +65,7 @@ const FPA_REFEREES_TEAM = { externalId: "ARBITRAGEM", name: REFEREES };
|
|||||||
/** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */
|
/** Officials of the game who become people of an event (faces to name): on the pitch, and at the table. */
|
||||||
const PEOPLE_OFFICIALS = [...UEFA_PITCH_OFFICIALS, "TABLE_OFFICIAL"];
|
const PEOPLE_OFFICIALS = [...UEFA_PITCH_OFFICIALS, "TABLE_OFFICIAL"];
|
||||||
|
|
||||||
const SPORT: Record<SportsProvider, string> = { LIGA: "futebol", FPF: "futebol", FPA: "andebol", UEFA: "futebol" };
|
const SPORT: Record<SportsProvider, string> = { LIGA: "futebol", FPF: "futebol", FPA: "andebol", UEFA: "futebol", EHF: "andebol" };
|
||||||
|
|
||||||
export interface SportsDeps {
|
export interface SportsDeps {
|
||||||
db: Db;
|
db: Db;
|
||||||
@@ -73,6 +78,8 @@ export interface SportsDeps {
|
|||||||
uefaDelayMs?: number;
|
uefaDelayMs?: number;
|
||||||
/** Pause between FPA pages. */
|
/** Pause between FPA pages. */
|
||||||
fpaDelayMs?: number;
|
fpaDelayMs?: number;
|
||||||
|
/** Pause between EHF pages and match sheets. */
|
||||||
|
ehfDelayMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RefreshResult {
|
export interface RefreshResult {
|
||||||
@@ -88,9 +95,11 @@ export class SportsService {
|
|||||||
readonly fpa: FpaProvider;
|
readonly fpa: FpaProvider;
|
||||||
readonly fpf: FpfProvider;
|
readonly fpf: FpfProvider;
|
||||||
readonly uefa: UefaProvider;
|
readonly uefa: UefaProvider;
|
||||||
|
readonly ehf: EhfProvider;
|
||||||
|
|
||||||
constructor(private readonly deps: SportsDeps) {
|
constructor(private readonly deps: SportsDeps) {
|
||||||
this.uefa = new UefaProvider(deps.fetch);
|
this.uefa = new UefaProvider(deps.fetch);
|
||||||
|
this.ehf = new EhfProvider(deps.fetch, deps.ehfDelayMs ?? 200);
|
||||||
this.liga = new LigaProvider(deps.fetch);
|
this.liga = new LigaProvider(deps.fetch);
|
||||||
this.fpa = new FpaProvider(deps.fetch, deps.fpaDelayMs ?? 800);
|
this.fpa = new FpaProvider(deps.fetch, deps.fpaDelayMs ?? 800);
|
||||||
this.fpf = new FpfProvider(deps.fetch, deps.fpfDelayMs ?? 800);
|
this.fpf = new FpfProvider(deps.fetch, deps.fpfDelayMs ?? 800);
|
||||||
@@ -113,6 +122,12 @@ export class SportsService {
|
|||||||
await this.deps.db.sportsCompetition.create({ data: { provider: "UEFA", externalId: c.externalId, sport: c.sport, name: c.name, gender: c.gender, season } });
|
await this.deps.db.sportsCompetition.create({ data: { provider: "UEFA", externalId: c.externalId, sport: c.sport, name: c.name, gender: c.gender, season } });
|
||||||
else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } });
|
else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } });
|
||||||
}
|
}
|
||||||
|
for (const c of EHF_COMPETITIONS) {
|
||||||
|
const existing = await this.deps.db.sportsCompetition.findUnique({ where: { provider_externalId: { provider: "EHF", externalId: c.externalId } } });
|
||||||
|
if (!existing)
|
||||||
|
await this.deps.db.sportsCompetition.create({ data: { provider: "EHF", externalId: c.externalId, sport: "andebol", name: c.name, gender: c.gender, season } });
|
||||||
|
else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private due(c: SportsCompetition, now: Date): boolean {
|
private due(c: SportsCompetition, now: Date): boolean {
|
||||||
@@ -137,6 +152,7 @@ export class SportsService {
|
|||||||
if (fpa.length === 0 || fpa.some((c) => this.due(c, now))) add(await this.refreshFpa(now));
|
if (fpa.length === 0 || fpa.some((c) => this.due(c, now))) add(await this.refreshFpa(now));
|
||||||
for (const c of all.filter((c) => c.provider === "FPF" && this.due(c, now))) add(await this.refreshFpf(c, now));
|
for (const c of all.filter((c) => c.provider === "FPF" && this.due(c, now))) add(await this.refreshFpf(c, now));
|
||||||
for (const c of all.filter((c) => c.provider === "UEFA" && this.due(c, now))) add(await this.refreshUefa(c, now));
|
for (const c of all.filter((c) => c.provider === "UEFA" && this.due(c, now))) add(await this.refreshUefa(c, now));
|
||||||
|
for (const c of all.filter((c) => c.provider === "EHF" && this.due(c, now))) add(await this.refreshEhf(c, now));
|
||||||
if (total.players || total.teams) await this.regenerateCodeLists();
|
if (total.players || total.teams) await this.regenerateCodeLists();
|
||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
@@ -151,7 +167,9 @@ export class SportsService {
|
|||||||
? await this.refreshFpa(now)
|
? await this.refreshFpa(now)
|
||||||
: c.provider === "UEFA"
|
: c.provider === "UEFA"
|
||||||
? await this.refreshUefa(c, now)
|
? await this.refreshUefa(c, now)
|
||||||
: await this.refreshFpf(c, now);
|
: c.provider === "EHF"
|
||||||
|
? await this.refreshEhf(c, now)
|
||||||
|
: await this.refreshFpf(c, now);
|
||||||
if (r.players || r.teams) await this.regenerateCodeLists();
|
if (r.players || r.teams) await this.regenerateCodeLists();
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -227,7 +245,11 @@ export class SportsService {
|
|||||||
changed += await this.savePlayers(t.id, t.season, await this.liga.squad(t.external_id, t.season), "api");
|
changed += await this.savePlayers(t.id, t.season, await this.liga.squad(t.external_id, t.season), "api");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.squadClaimed.delete(key);
|
this.squadClaimed.delete(key);
|
||||||
this.deps.log.warn({ err, team: t.id, season: t.season }, "sports: liga squad not read");
|
// Liga 400s team/squad until it publishes a team's list for that season (newly promoted or still
|
||||||
|
// pre-season): expected, not an outage, so it is kept out of the error hub and read again later.
|
||||||
|
if (err instanceof ProviderHttpError && err.status === 400)
|
||||||
|
this.deps.log.info({ err, team: t.id, season: t.season }, "sports: liga squad not published yet for this team");
|
||||||
|
else this.deps.log.warn({ err, team: t.id, season: t.season }, "sports: liga squad not read");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (changed) this.deps.log.info({ season, changed }, "sports: liga squads imported");
|
if (changed) this.deps.log.info({ season, changed }, "sports: liga squads imported");
|
||||||
@@ -236,77 +258,89 @@ export class SportsService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Every Liga club and every player the federation still publishes, season by season, newest first.
|
* Every Liga club and every player the federation still publishes, season by season, newest first.
|
||||||
* A photo of a club five years ago then has that season's squad, including players who have since moved.
|
* The list is the seasons endpoint, so an older name of the same league (Liga NOS, Liga Sagres) is read too.
|
||||||
* Stops at the first past season that lists no teams. The current season being empty (pre-season) does not stop it.
|
* One competition missing in a year does not stop the older years. `stopped` is checked between requests.
|
||||||
* `stopped` is checked between requests so a shutdown leaves within one call.
|
|
||||||
*/
|
*/
|
||||||
async backfillLigaRegister(stopped: () => boolean): Promise<number> {
|
async backfillLigaRegister(stopped: () => boolean): Promise<number> {
|
||||||
await this.ensureCatalog();
|
await this.ensureCatalog();
|
||||||
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } });
|
let seasons: { id: string; competitions: LigaClubCompetition[] }[];
|
||||||
let season = seasonOf(new Date());
|
try {
|
||||||
|
seasons = await this.liga.seasons();
|
||||||
|
} catch (err) {
|
||||||
|
this.deps.log.warn({ err }, "sports: liga seasons not read");
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
let saved = 0;
|
let saved = 0;
|
||||||
for (let year = 0; year < 25 && !stopped(); year++) {
|
for (const season of seasons) {
|
||||||
let sawTeams = false;
|
if (stopped()) return saved;
|
||||||
let failed = 0;
|
for (const comp of season.competitions) {
|
||||||
for (const c of comps) {
|
|
||||||
if (stopped()) return saved;
|
if (stopped()) return saved;
|
||||||
const key = `${c.externalId}:${season}`;
|
const key = `${comp.externalId}:${season.id}`;
|
||||||
if (this.registerDone.has(key)) {
|
if (this.registerDone.has(key)) continue;
|
||||||
sawTeams = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let teams: TeamData[];
|
let teams: TeamData[];
|
||||||
try {
|
try {
|
||||||
teams = await this.liga.teams(c.externalId, season);
|
teams = await this.liga.teams(comp.externalId, season.id);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected");
|
const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected");
|
||||||
if (missing) {
|
if (missing) {
|
||||||
this.registerDone.add(key);
|
this.registerDone.add(key);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
failed++;
|
// Liga 400s competition/teams until it opens that season (a future season, not yet scheduled).
|
||||||
this.deps.log.warn({ err, competition: c.externalId, season }, "sports: liga teams not read");
|
if (err instanceof ProviderHttpError && err.status === 400)
|
||||||
|
this.deps.log.info({ err, competition: comp.externalId, season: season.id }, "sports: liga teams not published yet for this competition");
|
||||||
|
else this.deps.log.warn({ err, competition: comp.externalId, season: season.id }, "sports: liga teams not read");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!teams.length) {
|
if (!teams.length) {
|
||||||
this.registerDone.add(key);
|
this.registerDone.add(key);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
sawTeams = true;
|
const competitionId = await this.ligaCompetitionId(comp, season.id);
|
||||||
let complete = true;
|
let complete = true;
|
||||||
for (const t of teams) {
|
for (const t of teams) {
|
||||||
if (stopped()) return saved;
|
if (stopped()) return saved;
|
||||||
const teamId = await this.upsertTeam("LIGA", t);
|
const teamId = await this.upsertTeam("LIGA", t);
|
||||||
await this.deps.db.sportsCompetitionTeam.upsert({
|
await this.deps.db.sportsCompetitionTeam.upsert({
|
||||||
where: { competitionId_teamId_season: { competitionId: c.id, teamId, season } },
|
where: { competitionId_teamId_season: { competitionId, teamId, season: season.id } },
|
||||||
create: { competitionId: c.id, teamId, season },
|
create: { competitionId, teamId, season: season.id },
|
||||||
update: {},
|
update: {},
|
||||||
});
|
});
|
||||||
const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season } });
|
const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season: season.id } });
|
||||||
if (have > 0) continue;
|
if (have > 0) continue;
|
||||||
const claim = `${teamId}:${season}`;
|
const claim = `${teamId}:${season.id}`;
|
||||||
if (this.squadClaimed.has(claim)) continue;
|
if (this.squadClaimed.has(claim)) continue;
|
||||||
this.squadClaimed.add(claim);
|
this.squadClaimed.add(claim);
|
||||||
try {
|
try {
|
||||||
saved += await this.savePlayers(teamId, season, await this.liga.squad(t.externalId, season), "api");
|
saved += await this.savePlayers(teamId, season.id, await this.liga.squad(t.externalId, season.id), "api");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
complete = false;
|
complete = false;
|
||||||
this.squadClaimed.delete(claim);
|
this.squadClaimed.delete(claim);
|
||||||
this.deps.log.warn({ err, team: t.name, season }, "sports: liga squad not read");
|
if (err instanceof ProviderHttpError && err.status === 400)
|
||||||
|
this.deps.log.info({ err, team: t.name, season: season.id }, "sports: liga squad not published yet for this team");
|
||||||
|
else this.deps.log.warn({ err, team: t.name, season: season.id }, "sports: liga squad not read");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (complete) this.registerDone.add(key);
|
if (complete) this.registerDone.add(key);
|
||||||
}
|
}
|
||||||
if (failed === comps.length && comps.length) break;
|
|
||||||
if (year > 0 && !sawTeams) break;
|
|
||||||
const start = Number(season.slice(0, 4)) - 1;
|
|
||||||
if (!Number.isFinite(start) || start < 2000) break;
|
|
||||||
season = `${start}${start + 1}`;
|
|
||||||
}
|
}
|
||||||
if (saved) this.deps.log.info({ saved }, "sports: liga register imported");
|
if (saved) this.deps.log.info({ saved }, "sports: liga register imported");
|
||||||
return saved;
|
return saved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The competition row for a season's club league. A historical sponsor stays out of the six-hour refresh. */
|
||||||
|
private async ligaCompetitionId(comp: LigaClubCompetition, season: string): Promise<string> {
|
||||||
|
const existing = await this.deps.db.sportsCompetition.findUnique({
|
||||||
|
where: { provider_externalId: { provider: "LIGA", externalId: comp.externalId } },
|
||||||
|
});
|
||||||
|
if (existing) return existing.id;
|
||||||
|
const modern = LIGA_COMPETITIONS.some((c) => c.externalId === comp.externalId);
|
||||||
|
const row = await this.deps.db.sportsCompetition.create({
|
||||||
|
data: { provider: "LIGA", externalId: comp.externalId, sport: "futebol", name: comp.name, gender: "M", season, active: modern },
|
||||||
|
});
|
||||||
|
return row.id;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A whole past FPA season (the archive's folders of other seasons): the federation's national games of every
|
* A whole past FPA season (the archive's folders of other seasons): the federation's national games of every
|
||||||
* level, club by club. It starts from the clubs of today's agenda and follows every club met in those games, so
|
* level, club by club. It starts from the clubs of today's agenda and follows every club met in those games, so
|
||||||
@@ -724,6 +758,78 @@ export class SportsService {
|
|||||||
return { read: true, changed };
|
return { read: true, changed };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An EHF club competition: its matches (the whole season the first time, then the page around today) and the
|
||||||
|
* match sheets already published (players, shirt numbers, photos, and the bench staff).
|
||||||
|
*/
|
||||||
|
async refreshEhf(c: SportsCompetition, now = new Date()): Promise<RefreshResult> {
|
||||||
|
const { db, log } = this.deps;
|
||||||
|
const result: RefreshResult = { competitions: 1, teams: 0, players: 0, fixtures: 0, errors: [] };
|
||||||
|
const spec = EHF_COMPETITIONS.find((x) => x.externalId === c.externalId);
|
||||||
|
if (!spec) return result;
|
||||||
|
try {
|
||||||
|
const teams = new Set<string>();
|
||||||
|
for (const f of await this.ehf.matches(spec, c.season, !c.lastIngestAt)) {
|
||||||
|
result.fixtures += await this.saveFixture(c, "EHF", f, "andebol");
|
||||||
|
teams.add(f.home.externalId).add(f.away.externalId);
|
||||||
|
}
|
||||||
|
const rows = await db.sportsTeam.findMany({ where: { provider: "EHF", externalId: { in: [...teams] } }, select: { id: true } });
|
||||||
|
for (const t of rows) {
|
||||||
|
await db.sportsCompetitionTeam.upsert({
|
||||||
|
where: { competitionId_teamId_season: { competitionId: c.id, teamId: t.id, season: c.season } },
|
||||||
|
create: { competitionId: c.id, teamId: t.id, season: c.season },
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
result.teams = rows.length;
|
||||||
|
const played = (
|
||||||
|
await db.sportsFixture.findMany({
|
||||||
|
where: { competitionId: c.id, season: c.season, lineupAt: null, startsAt: { lt: now } },
|
||||||
|
orderBy: { startsAt: "desc" },
|
||||||
|
take: EHF_SHEETS_PER_REFRESH,
|
||||||
|
})
|
||||||
|
).reverse();
|
||||||
|
for (const [i, f] of played.entries()) {
|
||||||
|
if (i) await new Promise((r) => setTimeout(r, this.deps.ehfDelayMs ?? 200));
|
||||||
|
try {
|
||||||
|
result.players += (await this.readEhfSheet(spec.site, f, now)).changed;
|
||||||
|
} catch (err) {
|
||||||
|
result.errors.push(`${c.name} ${f.externalId}: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const fixtures = await db.sportsFixture.count({ where: { competitionId: c.id, season: c.season } });
|
||||||
|
await db.sportsCompetition.update({ where: { id: c.id }, data: { lastIngestAt: now, lastError: null, counts: { teams: result.teams, players: result.players, fixtures } } });
|
||||||
|
} catch (err) {
|
||||||
|
result.errors.push(`${c.name}: ${(err as Error).message}`);
|
||||||
|
await db.sportsCompetition.update({ where: { id: c.id }, data: { lastIngestAt: now, lastError: (err as Error).message } });
|
||||||
|
}
|
||||||
|
if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: ehf refresh had errors");
|
||||||
|
log.info({ competition: c.name, ...result, errors: result.errors.length }, "sports: ehf refreshed");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One EHF match sheet into both squads. Unpublished sheets are left to be read again. */
|
||||||
|
private async readEhfSheet(
|
||||||
|
site: string,
|
||||||
|
f: { id: string; externalId: string; season: string; homeTeamId: string; awayTeamId: string },
|
||||||
|
now: Date,
|
||||||
|
): Promise<{ read: boolean; changed: number }> {
|
||||||
|
const sheet = await this.ehf.sheet(site, f.externalId);
|
||||||
|
if (!sheet) return { read: false, changed: 0 };
|
||||||
|
const changed = (await this.savePlayers(f.homeTeamId, f.season, sheet.home, "lineup")) + (await this.savePlayers(f.awayTeamId, f.season, sheet.away, "lineup"));
|
||||||
|
await this.deps.db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } });
|
||||||
|
return { read: true, changed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The EHF season a gallery folder names: its six competitions, once. Returns how many fixtures were written. */
|
||||||
|
async importEhfSeason(season: string): Promise<number> {
|
||||||
|
await this.ensureCatalog();
|
||||||
|
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "EHF", active: true, season } });
|
||||||
|
let n = 0;
|
||||||
|
for (const c of comps) n += (await this.refreshEhf(c)).fixtures;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
/** An FPF competition (any division or district) by its resultados.fpf.pt link. */
|
/** An FPF competition (any division or district) by its resultados.fpf.pt link. */
|
||||||
async addFpfCompetition(ref: string, now = new Date()): Promise<SportsCompetition> {
|
async addFpfCompetition(ref: string, now = new Date()): Promise<SportsCompetition> {
|
||||||
const parsed = FpfProvider.parseRef(ref);
|
const parsed = FpfProvider.parseRef(ref);
|
||||||
@@ -743,11 +849,11 @@ export class SportsService {
|
|||||||
const fixtures = await db.sportsFixture.findMany({
|
const fixtures = await db.sportsFixture.findMany({
|
||||||
where: {
|
where: {
|
||||||
lineupAt: null,
|
lineupAt: null,
|
||||||
competition: { provider: { in: ["FPF", "UEFA"] }, active: true },
|
competition: { provider: { in: ["FPF", "UEFA", "EHF"] }, active: true },
|
||||||
startsAt: { gte: new Date(now.getTime() - LINEUP_WINDOW.after), lte: new Date(now.getTime() + LINEUP_WINDOW.before) },
|
startsAt: { gte: new Date(now.getTime() - LINEUP_WINDOW.after), lte: new Date(now.getTime() + LINEUP_WINDOW.before) },
|
||||||
},
|
},
|
||||||
take: 10,
|
take: 10,
|
||||||
include: { competition: { select: { provider: true } } },
|
include: { competition: { select: { provider: true, externalId: true } } },
|
||||||
});
|
});
|
||||||
let read = 0;
|
let read = 0;
|
||||||
for (const f of fixtures) {
|
for (const f of fixtures) {
|
||||||
@@ -756,6 +862,11 @@ export class SportsService {
|
|||||||
if ((await this.readUefaSheet(f, now)).read) read++;
|
if ((await this.readUefaSheet(f, now)).read) read++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if (f.competition.provider === "EHF") {
|
||||||
|
const spec = EHF_COMPETITIONS.find((c) => c.externalId === f.competition.externalId);
|
||||||
|
if (spec && (await this.readEhfSheet(spec.site, f, now)).read) read++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const { home, away } = await this.fpf.lineups(f.externalId);
|
const { home, away } = await this.fpf.lineups(f.externalId);
|
||||||
if (!home.length && !away.length) continue;
|
if (!home.length && !away.length) continue;
|
||||||
await this.savePlayers(f.homeTeamId, f.season, home, "lineup");
|
await this.savePlayers(f.homeTeamId, f.season, home, "lineup");
|
||||||
@@ -763,7 +874,7 @@ export class SportsService {
|
|||||||
await db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } });
|
await db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } });
|
||||||
read++;
|
read++;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.warn({ err, fixture: f.id }, "sports: fpf line-up failed");
|
log.warn({ err, fixture: f.id }, "sports: line-up failed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (read) await this.regenerateCodeLists();
|
if (read) await this.regenerateCodeLists();
|
||||||
@@ -1322,7 +1433,7 @@ export class SportsWorker {
|
|||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly service: SportsService,
|
private readonly service: SportsService,
|
||||||
private readonly opts: { log: IngestLogger; lineupEveryMs?: number; refreshCheckMs?: number },
|
private readonly opts: { log: IngestLogger; lineupEveryMs?: number; refreshCheckMs?: number; afterRegister?: () => Promise<void> },
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
@@ -1352,11 +1463,12 @@ export class SportsWorker {
|
|||||||
private async fillRegister(): Promise<void> {
|
private async fillRegister(): Promise<void> {
|
||||||
this.filling = true;
|
this.filling = true;
|
||||||
try {
|
try {
|
||||||
await this.service.backfillLigaRegister(() => this.stopped);
|
const saved = await this.service.backfillLigaRegister(() => this.stopped);
|
||||||
while (!this.stopped) {
|
while (!this.stopped && saved >= 0) {
|
||||||
const n = await this.service.linkStoredSquads(24);
|
const n = await this.service.linkStoredSquads(24);
|
||||||
if (!n) break;
|
if (!n) break;
|
||||||
}
|
}
|
||||||
|
if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.opts.log.warn({ err }, "sports: register not filled");
|
this.opts.log.warn({ err }, "sports: register not filled");
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
+15
-4
@@ -106,7 +106,7 @@ const sportsService = new SportsService({ db, storage, log, fetch });
|
|||||||
// Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud.
|
// Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud.
|
||||||
// A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share.
|
// A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share.
|
||||||
const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir());
|
const videoTools = findVideoTools({ ffmpeg: config.FFMPEG_BIN, ffprobe: config.FFPROBE_BIN }, homedir());
|
||||||
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools });
|
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), ehfSeason: (season) => sportsService.importEhfSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS), storage, videoTools });
|
||||||
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure(), videos: config.ARCHIVE_VIDEO_CONCURRENCY });
|
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure(), videos: config.ARCHIVE_VIDEO_CONCURRENCY });
|
||||||
const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) });
|
const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) });
|
||||||
// Every arrival goes on to the destinations that take all of them (one's own backup of the originals).
|
// Every arrival goes on to the destinations that take all of them (one's own backup of the originals).
|
||||||
@@ -133,8 +133,11 @@ const faceEngine =
|
|||||||
: undefined;
|
: undefined;
|
||||||
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
|
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
|
||||||
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
|
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
|
||||||
const faces = faceEngine
|
const faceService = faceEngine
|
||||||
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), {
|
? new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS })
|
||||||
|
: undefined;
|
||||||
|
const faces = faceService
|
||||||
|
? new FaceWorker(faceService, {
|
||||||
concurrency: () => faceEngine?.size ?? 1,
|
concurrency: () => faceEngine?.size ?? 1,
|
||||||
intervalMs: 1000,
|
intervalMs: 1000,
|
||||||
log,
|
log,
|
||||||
@@ -149,7 +152,15 @@ const autopilot = new AutopilotWorker(
|
|||||||
{ concurrency: capacity.autopilot, intervalMs: 200, log },
|
{ concurrency: capacity.autopilot, intervalMs: 200, log },
|
||||||
);
|
);
|
||||||
|
|
||||||
const sports = config.SPORTS_SYNC === "on" ? new SportsWorker(sportsService, { log }) : undefined;
|
const sports = config.SPORTS_SYNC === "on"
|
||||||
|
? new SportsWorker(sportsService, {
|
||||||
|
log,
|
||||||
|
afterRegister: async () => {
|
||||||
|
const n = await faceService?.requeueForSquad();
|
||||||
|
if (n) log.info({ photos: n }, "faces: read photographs queued again, newest first");
|
||||||
|
},
|
||||||
|
})
|
||||||
|
: undefined;
|
||||||
|
|
||||||
scanner.start();
|
scanner.start();
|
||||||
if (secrets) archive.start();
|
if (secrets) archive.start();
|
||||||
|
|||||||
@@ -308,6 +308,11 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
|
|||||||
},
|
},
|
||||||
]);
|
]);
|
||||||
if (u.pathname.includes("/calendar/")) return json([]);
|
if (u.pathname.includes("/calendar/")) return json([]);
|
||||||
|
// EHF club competitions: the season pages exist but list no matches yet.
|
||||||
|
if (u.host.endsWith(".eurohandball.com")) {
|
||||||
|
if (u.pathname.endsWith("/matches/")) return bytes(Buffer.from(`<div data-competition-id="ehf" data-currentcontentid="1"></div>`, "utf8"));
|
||||||
|
if (u.pathname.startsWith("/umbraco/api/competitionmatchesapi/")) return json({ matches: [], hasPastMatches: false, hasFutureMatches: false });
|
||||||
|
}
|
||||||
if (u.host === "www.ligaportugal.pt" && u.pathname.endsWith(".png"))
|
if (u.host === "www.ligaportugal.pt" && u.pathname.endsWith(".png"))
|
||||||
return { ok: true, status: 200, json: async () => ({}), text: async () => "", arrayBuffer: async () => state.png.buffer.slice(state.png.byteOffset, state.png.byteOffset + state.png.byteLength) as ArrayBuffer };
|
return { ok: true, status: 200, json: async () => ({}), text: async () => "", arrayBuffer: async () => state.png.buffer.slice(state.png.byteOffset, state.png.byteOffset + state.png.byteLength) as ArrayBuffer };
|
||||||
return { ok: false, status: 404, json: async () => ({}), text: async () => "", arrayBuffer: async () => new ArrayBuffer(0) };
|
return { ok: false, status: 404, json: async () => ({}), text: async () => "", arrayBuffer: async () => new ArrayBuffer(0) };
|
||||||
@@ -352,6 +357,12 @@ describe("sports data service", () => {
|
|||||||
expect(comps.map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
expect(comps.map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
||||||
["LIGA", "allianzcup", "20262027"],
|
["LIGA", "allianzcup", "20262027"],
|
||||||
["FPA", "PO09", "20262027"],
|
["FPA", "PO09", "20262027"],
|
||||||
|
["EHF", "cl-men", "20262027"],
|
||||||
|
["EHF", "cl-women", "20262027"],
|
||||||
|
["EHF", "ec-men", "20262027"],
|
||||||
|
["EHF", "ec-women", "20262027"],
|
||||||
|
["EHF", "el-men", "20262027"],
|
||||||
|
["EHF", "el-women", "20262027"],
|
||||||
["LIGA", "ligaportugalbetclic", "20262027"],
|
["LIGA", "ligaportugalbetclic", "20262027"],
|
||||||
["LIGA", "ligaportugalmeusuper", "20262027"],
|
["LIGA", "ligaportugalmeusuper", "20262027"],
|
||||||
["UEFA", "1", "20262027"],
|
["UEFA", "1", "20262027"],
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import userEvent from "@testing-library/user-event";
|
|||||||
import { describe, expect, it, vi } from "vitest";
|
import { describe, expect, it, vi } from "vitest";
|
||||||
import { App } from "./App.js";
|
import { App } from "./App.js";
|
||||||
|
|
||||||
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live" }));
|
vi.mock("./library/realtime.js", () => ({ useLibraryLive: () => "live", onSocketLive: () => () => {} }));
|
||||||
|
|
||||||
const ME: Me = {
|
const ME: Me = {
|
||||||
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
|
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
|
||||||
|
|||||||
@@ -643,7 +643,9 @@ export const t = {
|
|||||||
diskShort: (min: string) => `Não chega: aumenta o disco do servidor. A indexação pára sozinha quando ficarem menos de ${min} livres.`,
|
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.`,
|
diskPaused: (min: string) => `Indexação em pausa: o disco tem menos de ${min} livres. Aumenta o disco e continua sozinha.`,
|
||||||
siteFolders: "Pastas no site",
|
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.",
|
siteFoldersHelp: "Por defeito entram todas. Tira o visto a uma pasta para ela deixar de aparecer no site, mesmo que a cloud a partilhe. As que já estão dentro, e as que forem lidas depois, ficam na mesma.",
|
||||||
|
siteFoldersMore: (left: number) => `Mostrar mais (${left})`,
|
||||||
|
siteFoldersHidden: (n: number) => (n === 1 ? "1 pasta fora do site" : `${n} pastas fora do site`),
|
||||||
siteFoldersSearch: "Procurar pasta…",
|
siteFoldersSearch: "Procurar pasta…",
|
||||||
siteFoldersEmpty: "Ainda não há pastas indexadas.",
|
siteFoldersEmpty: "Ainda não há pastas indexadas.",
|
||||||
siteFoldersLoading: "A carregar…",
|
siteFoldersLoading: "A carregar…",
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import { type FtpStatus, type IncomingFile, type Invoke, useLocalFtp } from "./L
|
|||||||
import type { UploadStatus } from "./uploads.js";
|
import type { UploadStatus } from "./uploads.js";
|
||||||
import { localPhotos } from "../offline/local.js";
|
import { localPhotos } from "../offline/local.js";
|
||||||
|
|
||||||
|
// The feed sends through the signed-in client (offline queue flush, local autopilot). Nothing here signs in, and
|
||||||
|
// the target has no organization, so a bare client is enough.
|
||||||
|
vi.mock("../auth.js", () => ({ useAuth: () => ({ api: {} }) }));
|
||||||
|
|
||||||
const status = (running: boolean): FtpStatus => ({
|
const status = (running: boolean): FtpStatus => ({
|
||||||
running,
|
running,
|
||||||
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
|
settings: { port: 2121, users: [{ name: "1dx", password: "1dx" }], ingest: "~/Desktop/ingest", workFolder: "~/Desktop/{year}/{date} - {event}", autoStart: false, uploadOriginals: false },
|
||||||
|
|||||||
@@ -73,8 +73,8 @@ export function ArchivePage() {
|
|||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
{isAdmin ? <ConnectForm api={api} orgId={orgId} onConnected={(s) => setSources((list) => [...(list ?? []), s])} /> : <p className="text-[12px] text-faint">{A.adminOnly}</p>}
|
{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} />}
|
{current && current.status !== "LOGIN" && canEdit && <SiteFolders key={`${current.id}-site`} api={api} source={current} />}
|
||||||
|
{current && current.status !== "LOGIN" && <Galleries key={current.id} api={api} source={current} />}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useEffect, useMemo, useState } from "react";
|
|||||||
import { t } from "../i18n.js";
|
import { t } from "../i18n.js";
|
||||||
|
|
||||||
const A = t.archive;
|
const A = t.archive;
|
||||||
|
const ROOTS_PAGE = 100;
|
||||||
const errorText = (code: string | null) => (code ? (A.errors[code] ?? code) : null);
|
const errorText = (code: string | null) => (code ? (A.errors[code] ?? code) : null);
|
||||||
const errorOf = (err: unknown) => errorText(err instanceof ApiError ? err.code : null) ?? t.unexpectedError;
|
const errorOf = (err: unknown) => errorText(err instanceof ApiError ? err.code : null) ?? t.unexpectedError;
|
||||||
|
|
||||||
@@ -125,7 +126,8 @@ function Check({ box, disabled, label, onChange }: { box: Box; disabled: boolean
|
|||||||
* Everything starts published. Unchecking a folder hides it and the folders inside it.
|
* Everything starts published. Unchecking a folder hides it and the folders inside it.
|
||||||
*/
|
*/
|
||||||
export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSource }) {
|
export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSource }) {
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(true);
|
||||||
|
const [rootLimit, setRootLimit] = useState(ROOTS_PAGE);
|
||||||
const [rows, setRows] = useState<CloudTreeFolder[] | null>(null);
|
const [rows, setRows] = useState<CloudTreeFolder[] | null>(null);
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
const [expanded, setExpanded] = useState<Set<string>>(new Set());
|
||||||
@@ -145,6 +147,8 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour
|
|||||||
}, [api, source.id, open, rows]);
|
}, [api, source.id, open, rows]);
|
||||||
|
|
||||||
const tree = useMemo(() => filterTree(treeOf(rows ?? []), query), [rows, query]);
|
const tree = useMemo(() => filterTree(treeOf(rows ?? []), query), [rows, query]);
|
||||||
|
const visible = tree.slice(0, rootLimit);
|
||||||
|
const hidden = (rows ?? []).filter((row) => !row.published).length;
|
||||||
const shown = query.trim() ? new Set(collect(tree)) : expanded;
|
const shown = query.trim() ? new Set(collect(tree)) : expanded;
|
||||||
|
|
||||||
const toggle = (path: string) => {
|
const toggle = (path: string) => {
|
||||||
@@ -186,6 +190,7 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour
|
|||||||
{open && (
|
{open && (
|
||||||
<div className="space-y-2 px-4 py-3">
|
<div className="space-y-2 px-4 py-3">
|
||||||
<p className="max-w-3xl text-[12px] text-muted">{A.siteFoldersHelp}</p>
|
<p className="max-w-3xl text-[12px] text-muted">{A.siteFoldersHelp}</p>
|
||||||
|
{hidden > 0 && <p className="text-[12px] text-faint">{A.siteFoldersHidden(hidden)}</p>}
|
||||||
<input
|
<input
|
||||||
value={query}
|
value={query}
|
||||||
onChange={(event) => setQuery(event.target.value)}
|
onChange={(event) => setQuery(event.target.value)}
|
||||||
@@ -197,11 +202,16 @@ export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSour
|
|||||||
{rows && tree.length === 0 && <p className="text-[12px] text-faint">{A.siteFoldersEmpty}</p>}
|
{rows && tree.length === 0 && <p className="text-[12px] text-faint">{A.siteFoldersEmpty}</p>}
|
||||||
{rows && tree.length > 0 && (
|
{rows && tree.length > 0 && (
|
||||||
<ul className="max-h-[28rem] overflow-auto">
|
<ul className="max-h-[28rem] overflow-auto">
|
||||||
{tree.map((node) => (
|
{visible.map((node) => (
|
||||||
<Branch key={node.id} node={node} depth={0} expanded={shown} busy={busy} onToggle={toggle} onCheck={check} />
|
<Branch key={node.id} node={node} depth={0} expanded={shown} busy={busy} onToggle={toggle} onCheck={check} />
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
)}
|
)}
|
||||||
|
{visible.length < tree.length && (
|
||||||
|
<button type="button" className="h-8 border border-line px-3 text-[12px] text-ink" onClick={() => setRootLimit((n) => n + ROOTS_PAGE)}>
|
||||||
|
{A.siteFoldersMore(tree.length - visible.length)}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -71,6 +71,8 @@ export function Browse({
|
|||||||
const [joinInto, setJoinInto] = useState("");
|
const [joinInto, setJoinInto] = useState("");
|
||||||
const [joinNote, setJoinNote] = useState<string | null>(null);
|
const [joinNote, setJoinNote] = useState<string | null>(null);
|
||||||
const [peopleTick, setPeopleTick] = useState(0);
|
const [peopleTick, setPeopleTick] = useState(0);
|
||||||
|
/** People stay everyone until a season is chosen. Separate from the gallery filter. */
|
||||||
|
const [peopleSeason, setPeopleSeason] = useState<string | null>(null);
|
||||||
|
|
||||||
const guard = useCallback(
|
const guard = useCallback(
|
||||||
(err: unknown) => {
|
(err: unknown) => {
|
||||||
@@ -132,12 +134,15 @@ export function Browse({
|
|||||||
}).catch((err) => !cancel && guard(err));
|
}).catch((err) => !cancel && guard(err));
|
||||||
cached<Directory>(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([]));
|
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));
|
if (tab === "people") {
|
||||||
|
const peopleUrl = peopleSeason ? `/v1/archive/${sourceId}/people?season=${encodeURIComponent(peopleSeason)}` : `/v1/archive/${sourceId}/people`;
|
||||||
|
cached<PeopleList>(peopleUrl, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err));
|
||||||
|
}
|
||||||
return () => {
|
return () => {
|
||||||
cancel = true;
|
cancel = true;
|
||||||
clearTimeout(retry);
|
clearTimeout(retry);
|
||||||
};
|
};
|
||||||
}, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick]);
|
}, [tab, sourceId, token, guard, attempt, teamsTry, peopleTick, peopleSeason]);
|
||||||
|
|
||||||
/** Joins (or parts) club names, then reads people and teams again. */
|
/** Joins (or parts) club names, then reads people and teams again. */
|
||||||
const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => {
|
const joinClubs = (path: "merge" | "unmerge", body: unknown, done: string) => {
|
||||||
@@ -209,6 +214,7 @@ export function Browse({
|
|||||||
let emptyPeople = "";
|
let emptyPeople = "";
|
||||||
if (people && shownPeople.length === 0) {
|
if (people && shownPeople.length === 0) {
|
||||||
if (club && !people.people.some((p) => clubNames?.has(fold(p.club ?? "")))) emptyPeople = "Ainda não há pessoas identificadas desta equipa.";
|
if (club && !people.people.some((p) => clubNames?.has(fold(p.club ?? "")))) emptyPeople = "Ainda não há pessoas identificadas desta equipa.";
|
||||||
|
else if (peopleSeason && !people.people.length) emptyPeople = "Ainda não há pessoas identificadas nesta época.";
|
||||||
else if (people.people.length) emptyPeople = "Ninguém com esse nome.";
|
else if (people.people.length) emptyPeople = "Ninguém com esse nome.";
|
||||||
else emptyPeople = "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela.";
|
else emptyPeople = "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela.";
|
||||||
}
|
}
|
||||||
@@ -475,7 +481,30 @@ export function Browse({
|
|||||||
|
|
||||||
{tab === "people" && (
|
{tab === "people" && (
|
||||||
<>
|
<>
|
||||||
<h1 className="arq-disp arq-h1">Pessoas</h1>
|
<div className="arq-people-head">
|
||||||
|
<h1 className="arq-disp arq-h1">Pessoas</h1>
|
||||||
|
{!!people?.seasons?.length && (
|
||||||
|
<label className="arq-filter">
|
||||||
|
<span>Época</span>
|
||||||
|
<select
|
||||||
|
className="arq-select"
|
||||||
|
aria-label="Época"
|
||||||
|
value={peopleSeason ?? ""}
|
||||||
|
onChange={(e) => {
|
||||||
|
setPeopleSeason(e.target.value || null);
|
||||||
|
setPeopleShown(PEOPLE_STEP);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Todas</option>
|
||||||
|
{people.seasons.map((s) => (
|
||||||
|
<option key={s} value={s}>
|
||||||
|
{s}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
{people && people.clubs.length > 1 && (
|
{people && people.clubs.length > 1 && (
|
||||||
<div className="arq-club-pills" role="group" aria-label="Filtrar por equipa">
|
<div className="arq-club-pills" role="group" aria-label="Filtrar por equipa">
|
||||||
<button type="button" className="arq-pill" aria-pressed={!club} onClick={() => setClub(null)}>
|
<button type="button" className="arq-pill" aria-pressed={!club} onClick={() => setClub(null)}>
|
||||||
|
|||||||
@@ -188,6 +188,8 @@ export interface Directory {
|
|||||||
export interface PeopleList {
|
export interface PeopleList {
|
||||||
people: PersonCard[];
|
people: PersonCard[];
|
||||||
clubs: { name: string; people: number; kind?: "national" | "club" | "other"; also?: string[] }[];
|
clubs: { name: string; people: number; kind?: "national" | "club" | "other"; also?: string[] }[];
|
||||||
|
/** Seasons the galleries span, newest first. Missing on an older API. */
|
||||||
|
seasons?: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PhotosOfResult {
|
export interface PhotosOfResult {
|
||||||
|
|||||||
@@ -1227,6 +1227,13 @@
|
|||||||
line-height: 1;
|
line-height: 1;
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
}
|
}
|
||||||
|
.arq-people-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
.arq-shortcuts {
|
.arq-shortcuts {
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
|
|||||||
+18
-6
@@ -185,9 +185,10 @@ it when files must be served from more than one host.
|
|||||||
|
|
||||||
Only for organizations whose owner switched it on with a recorded legal basis (biometric data, GDPR art. 9).
|
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 reads the last 30 days first (when the photo
|
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.
|
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
|
also newest game first. Once the season squads have been read, photographs already analysed go back through the
|
||||||
archive that has been waiting. The worker starts a few face processes and adds more while the CPU stays under
|
queue (`photos.faces_pass`), thirty thousand per worker start, newest first, so the squad of that year can name
|
||||||
|
them. A confirmed face keeps its group, and the new reading rejoins it when it is still the same person. The worker starts a few face processes and adds more while the CPU stays under
|
||||||
about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is
|
about 99%, stopping sooner when memory (the model) runs short. 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
|
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
|
improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the
|
||||||
@@ -240,6 +241,9 @@ number for that event's context:
|
|||||||
already have a face. A player who has since moved is included when that season's list has them (the same
|
already have a face. A player who has since moved is included when that season's list has them (the same
|
||||||
federation id, or the same birth date and full name), with the shirt number of that season. A face none of
|
federation id, or the same birth date and full name), with the shirt number of that season. A face none of
|
||||||
them explains stays unnamed. It is never someone who was not at either club that season.
|
them explains stays unnamed. It is never someone who was not at either club that season.
|
||||||
|
A photograph of one team lined up (the faces across the frame, in one to three rows) is read as a set:
|
||||||
|
each clear shirt number belongs to one player of the squad the numbers fit, and that face is suggested
|
||||||
|
as that player. Confirming the photograph is what teaches the other photographs of the game.
|
||||||
A session, a training day or a studio day of a national team (FPA: SNAF, SNAM, M18, and the same team under
|
A session, a training day or a studio day of a national team (FPA: SNAF, SNAM, M18, and the same team under
|
||||||
its long name) uses that team only: people already confirmed there this season, and the athletes the session
|
its long name) uses that team only: people already confirmed there this season, and the athletes the session
|
||||||
folders name. There is no match number. A gala or a press day names no team: the face alone, against everyone
|
folders name. There is no match number. A gala or a press day names no team: the face alone, against everyone
|
||||||
@@ -265,9 +269,12 @@ hand-drawn boxes.
|
|||||||
`apps/api/src/sports` rebuilds the old app's code-replacement system. The worker reads public federation data
|
`apps/api/src/sports` rebuilds the old app's code-replacement system. The worker reads public federation data
|
||||||
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
|
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
|
||||||
|
|
||||||
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup. Gives teams, squads (numbers,
|
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh.
|
||||||
positions, official headshots) and the season's fixtures. On start the worker walks every season the federation
|
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. On start the worker reads
|
||||||
still publishes, club by club, so a past season keeps the squad and the shirt numbers of that year.
|
every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro),
|
||||||
|
so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest
|
||||||
|
photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list
|
||||||
|
is everyone; a season narrows it to the people in that season's photographs.
|
||||||
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
|
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
|
||||||
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
|
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
|
||||||
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
|
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
|
||||||
@@ -283,6 +290,11 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
|||||||
kept beside it.
|
kept beside it.
|
||||||
- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads
|
- **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads
|
||||||
from each match sheet, read from 1 h before to 2 h after kick-off.
|
from each match sheet, read from 1 h before to 2 h after kick-off.
|
||||||
|
- **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's
|
||||||
|
Champions League, European League and European Cup. Fixtures with venue, and squads from the match sheet once
|
||||||
|
it is published: the nominated players (number, position, photo) and the bench staff (letters A, B, …; the sheet
|
||||||
|
does not say which letter is the coach). A gallery filed under an EHF competition is matched to that game.
|
||||||
|
Beach handball stays a folder. Asked sparingly and cached.
|
||||||
- **UEFA** (`match.uefa.com/v5`, the JSON uefa.com itself reads; not a documented API): Champions League, Europa
|
- **UEFA** (`match.uefa.com/v5`, the JSON uefa.com itself reads; not a documented API): Champions League, Europa
|
||||||
League, Conference League, Women's Champions League and Futsal Champions League. Fixtures with venue and the
|
League, Conference League, Women's Champions League and Futsal Champions League. Fixtures with venue and the
|
||||||
referee team; squads (numbers, positions, headshots, coaches) built from the match sheets of matches already
|
referee team; squads (numbers, positions, headshots, coaches) built from the match sheets of matches already
|
||||||
|
|||||||
@@ -32,6 +32,12 @@ never reaches PhotoReport. A revoked app password puts the source back to LOGIN
|
|||||||
downloaded as before; deliveries and the 100% view read from the mount too.
|
downloaded as before; deliveries and the 100% view read from the mount too.
|
||||||
- The editor's 100% view (`GET /v1/photos/:id/original`) and deliveries read the original from the cloud.
|
- The editor's 100% view (`GET /v1/photos/:id/original`) and deliveries read the original from the cloud.
|
||||||
|
|
||||||
|
## Which folders are on the site
|
||||||
|
|
||||||
|
App → Arquivo → "Pastas no site", above the galleries. Every folder starts on the site. Unchecking one hides that
|
||||||
|
folder and everything inside it, including folders the next scan finds there. Checking it again publishes them.
|
||||||
|
The public site only lists photos whose folder is still published.
|
||||||
|
|
||||||
## Matching galleries to games
|
## Matching galleries to games
|
||||||
|
|
||||||
`archive/match.ts` reads the place and name of each folder with images:
|
`archive/match.ts` reads the place and name of each folder with images:
|
||||||
|
|||||||
Reference in new issue
Block a user