Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0121f950b5 | ||
|
|
7a02cce000 | ||
|
|
c9e4e4af53 | ||
|
|
7a71ff1d10 | ||
|
|
bdbb5c364a | ||
|
|
6d4bb4f19e | ||
|
|
7c0e92b5ae | ||
|
|
ae47a3f703 | ||
|
|
a661742733 | ||
|
|
b2de0d4215 | ||
|
|
2e6be068f5 | ||
|
|
8daa66573d | ||
|
|
53fa7e110c |
No files matched your search
@@ -292,7 +292,7 @@ export class AutopilotService {
|
||||
const edited = await db.photoEdit.count({ where: { photoId: framePick.id, NOT: { clientId: "autopilot" } } });
|
||||
if (edited) continue;
|
||||
const rect = constrainRotated(planned, framePick.rec?.angle ?? 0, framePick.width ?? 3, framePick.height ?? 2);
|
||||
const aspect = settings.aspect ?? [framePick.width ?? 3, framePick.height ?? 2];
|
||||
const aspect = photoAspect(framePick.width, framePick.height);
|
||||
await develop
|
||||
.append(framePick.id, framePick.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
@@ -310,7 +310,7 @@ export class AutopilotService {
|
||||
if (crop2 && second.rec?.subject && settings.crop && !secondEdited) {
|
||||
// The planned crop already keeps the hands and the feet. Shrinking it again cuts them.
|
||||
const rect = wider ?? constrainRotated(crop2, second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
const aspect = settings.aspect ?? [second.width ?? 3, second.height ?? 2];
|
||||
const aspect = photoAspect(second.width, second.height);
|
||||
await develop
|
||||
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
@@ -533,6 +533,14 @@ function subjectFocus(d: { people: { x0: number; y0: number; x1: number; y1: num
|
||||
return values.length ? Math.max(...values) : 0;
|
||||
}
|
||||
|
||||
/** The photograph's own pixel size, so the crop lock is that format and not another. */
|
||||
function photoAspect(width: number | null | undefined, height: number | null | undefined): [number, number] {
|
||||
if (width && height && width > 0 && height > 0) {
|
||||
return [Math.round(width), Math.round(height)];
|
||||
}
|
||||
return [3, 2];
|
||||
}
|
||||
|
||||
/** A tighter plan keeps the crop and the structure scaled to that crop, so the halo does not grow with the tighter frame. */
|
||||
function cropOps(photoId: string, key: string, rect: Box, angle: number, aspect: readonly number[], detail: Record<string, number>): { opId: string; command: EditCommand }[] {
|
||||
const ops: { opId: string; command: EditCommand }[] = [];
|
||||
|
||||
@@ -46,6 +46,33 @@ export function constrainRotated(r: Box, angle: number, w: number, h: number): B
|
||||
return { x0: 0.5 - (rw * k) / 2, y0: 0.5 - (rh * k) / 2, x1: 0.5 + (rw * k) / 2, y1: 0.5 + (rh * k) / 2 };
|
||||
}
|
||||
|
||||
/**
|
||||
* The crop on the photo's own aspect. In frame fractions that is a square: width and height match.
|
||||
* The horizontal centre stays, so the crop can still sit anywhere across the frame.
|
||||
*/
|
||||
export function keepPhotoAspect(rect: Box): Box {
|
||||
const width = rect.x1 - rect.x0;
|
||||
const height = rect.y1 - rect.y0;
|
||||
if (width <= 0 || height <= 0) return rect;
|
||||
let side = width;
|
||||
if (side > 1) side = 1;
|
||||
let x0 = (rect.x0 + rect.x1) / 2 - side / 2;
|
||||
let y0 = (rect.y0 + rect.y1) / 2 - side / 2;
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (x0 + side > 1) x0 = 1 - side;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (y0 + side > 1) y0 = 1 - side;
|
||||
const room = Math.min(side, 1 - x0, 1 - y0);
|
||||
if (room < side) {
|
||||
const cx = x0 + side / 2;
|
||||
const cy = y0 + side / 2;
|
||||
side = room;
|
||||
x0 = Math.min(Math.max(0, cx - side / 2), 1 - side);
|
||||
y0 = Math.min(Math.max(0, cy - side / 2), 1 - side);
|
||||
}
|
||||
return { x0, y0, x1: x0 + side, y1: y0 + side };
|
||||
}
|
||||
|
||||
/** `r` shrunk by `factor` about the subject's centre, keeping the subject inside and the crop on the photo. */
|
||||
export function tighter(r: Box, subject: Box, factor: number): Box {
|
||||
const w = (r.x1 - r.x0) * factor;
|
||||
@@ -105,8 +132,13 @@ export function frameOnSubject(base: Box, subject: Box, intent: { cut?: number |
|
||||
|
||||
/** Expand `r` by `factor` (>1) about the subject's centre, without leaving the photo. */
|
||||
function looser(r: Box, subject: Box, factor: number): Box {
|
||||
const w = Math.min(1, (r.x1 - r.x0) * factor);
|
||||
const h = Math.min(1, (r.y1 - r.y0) * factor);
|
||||
let w = (r.x1 - r.x0) * factor;
|
||||
let h = (r.y1 - r.y0) * factor;
|
||||
if (w > 1 || h > 1) {
|
||||
const fit = Math.min(1 / w, 1 / h);
|
||||
w = w * fit;
|
||||
h = h * fit;
|
||||
}
|
||||
const cx = (subject.x0 + subject.x1) / 2;
|
||||
const cy = (r.y0 + r.y1) / 2;
|
||||
const x0 = Math.min(Math.max(0, cx - w / 2), 1 - w);
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { keepPhotoAspect } from "./geometry.js";
|
||||
import { planFrame, type PlanSettings } from "./planFrame.js";
|
||||
|
||||
const settings: PlanSettings = {
|
||||
crop: true,
|
||||
tone: false,
|
||||
whiteBalance: false,
|
||||
level: false,
|
||||
toneStrength: 0.75,
|
||||
look: "none",
|
||||
framing: "full",
|
||||
aspect: [4, 5],
|
||||
minLongEdge: 800,
|
||||
};
|
||||
|
||||
describe("keepPhotoAspect", () => {
|
||||
it("keeps the horizontal place and the photograph's aspect", () => {
|
||||
const crop = keepPhotoAspect({ x0: 0.2, y0: 0.1, x1: 0.7, y1: 0.95 });
|
||||
expect(crop.x1 - crop.x0).toBeCloseTo(crop.y1 - crop.y0, 5);
|
||||
expect((crop.x0 + crop.x1) / 2).toBeCloseTo(0.45, 5);
|
||||
});
|
||||
});
|
||||
|
||||
describe("planFrame", () => {
|
||||
it("does not turn the photograph into another format", () => {
|
||||
const planned = planFrame({
|
||||
detections: {
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
people: [{ x0: 0.4, y0: 0.15, x1: 0.62, y1: 0.92, score: 0.9, sharpness: 1 }],
|
||||
balls: [],
|
||||
},
|
||||
width: 6000,
|
||||
height: 4000,
|
||||
reportage: false,
|
||||
values: null,
|
||||
angle: 0,
|
||||
settings,
|
||||
});
|
||||
const crop = planned.ops.find((op) => op.command === "crop.set");
|
||||
expect(crop?.command).toBe("crop.set");
|
||||
if (!crop || crop.command !== "crop.set") return;
|
||||
const rect = crop.params.rect;
|
||||
const ratio = ((rect.x1 - rect.x0) * 6000) / ((rect.y1 - rect.y0) * 4000);
|
||||
expect(ratio).toBeCloseTo(6000 / 4000, 2);
|
||||
expect(crop.params.aspect).toEqual([6000, 4000]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EditCommand } from "@photoreport/contracts";
|
||||
import { type Box, type Detections, type FocusHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js";
|
||||
import { biasCrop, constrainRotated, frameOnSubject, tighter } from "./geometry.js";
|
||||
import { biasCrop, constrainRotated, frameOnSubject, keepPhotoAspect, tighter } from "./geometry.js";
|
||||
import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js";
|
||||
import type { CropBias } from "../autopilot/cropBias.js";
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface PlanSettings {
|
||||
toneStrength: number;
|
||||
look: Look;
|
||||
framing: "tight" | "full";
|
||||
/** Ignored. The autopilot keeps the photograph's own aspect and only moves the crop. */
|
||||
aspect: [number, number] | null;
|
||||
minLongEdge: number;
|
||||
}
|
||||
@@ -81,7 +82,8 @@ export function planFrame(input: {
|
||||
settings: PlanSettings;
|
||||
}): PlannedFrame {
|
||||
const { detections, settings, width: W, height: H, reportage } = input;
|
||||
const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null;
|
||||
// The photograph's own aspect. A preset (4:5, 16:9, a portrait of a landscape frame) is not used.
|
||||
const aspect = null;
|
||||
const minWidth = minCropWidth(W, H, settings.minLongEdge);
|
||||
const context = reportage ? "reportage" : "sport";
|
||||
const faces = input.faces ?? [];
|
||||
@@ -113,15 +115,21 @@ export function planFrame(input: {
|
||||
// A learnt crop must not slice a ball the frame had kept whole.
|
||||
const balls = detections?.balls ?? [];
|
||||
if (clipsBall(rect, balls)) rect = composition.rect;
|
||||
if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, angle, W, H);
|
||||
if (!clipsBall(rect, balls) && rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(keepPhotoAspect(rect), angle, W, H);
|
||||
}
|
||||
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null;
|
||||
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(keepPhotoAspect(wideComposition.rect), angle, W, H) : null;
|
||||
if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
const lockedPlans = plans
|
||||
? {
|
||||
half: plans.half ? keepPhotoAspect(plans.half) : null,
|
||||
threeQuarter: plans.threeQuarter ? keepPhotoAspect(plans.threeQuarter) : null,
|
||||
}
|
||||
: null;
|
||||
const ops: EditCommand[] = [];
|
||||
if (input.values) {
|
||||
const tuned = detailForCrop(input.values, crop, W, H);
|
||||
if (Object.keys(tuned).length) ops.push({ command: "develop.set", params: { values: tuned } });
|
||||
}
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } });
|
||||
return { ops, crop, wide, composition, plans };
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: [Math.max(1, Math.round(W)), Math.max(1, Math.round(H))] } });
|
||||
return { ops, crop, wide, composition, plans: lockedPlans };
|
||||
}
|
||||
@@ -8,6 +8,22 @@ import { createHash } from "node:crypto";
|
||||
*
|
||||
* Off without ERROR_REPORTING_TOKEN (the project's ingest key on the hub), or with ERROR_REPORTING_DISABLED=1.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Transient PostgreSQL connection errors during a restart, graceful shutdown, or network blip. Prisma surfaces
|
||||
* these as `PrismaClientKnownRequestError` wrapping the raw SQLSTATE (57P01/57P03) or its own P1001/P1017.
|
||||
* The pool reconnects on the next attempt, so these are not code bugs — reporting them only trips the Error
|
||||
* Loop with one-off incidents from every code path that touches the database during the brief outage.
|
||||
* Individual call sites that need to stop a batch or retry still check `isPostgresAdminShutdown` /
|
||||
* `isPrismaServerUnreachable` (lib/pg.ts); this filter keeps the hub quiet for the paths that just let the
|
||||
* error propagate to a generic log.error (BIT-32490 and 11 sibling clusters).
|
||||
*/
|
||||
function isTransientDatabaseError(err: unknown): boolean {
|
||||
if (!(err instanceof Error)) return false;
|
||||
const code = (err as { code?: unknown }).code;
|
||||
if (code === "P1001" || code === "P1017") return true;
|
||||
return /57P01|57P03|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection/i.test(err.message);
|
||||
}
|
||||
export type ReportLevel = "critical" | "error" | "warning" | "info";
|
||||
|
||||
export interface ReportEvent {
|
||||
@@ -93,6 +109,7 @@ export class ErrorReporter {
|
||||
}
|
||||
|
||||
reportError(err: unknown, component: string, context: Record<string, unknown> = {}, level: ReportLevel = "error"): void {
|
||||
if (isTransientDatabaseError(err)) return;
|
||||
const e = err instanceof Error ? err : new Error(typeof err === "string" ? err : JSON.stringify(err));
|
||||
const code = (e as { code?: unknown }).code;
|
||||
this.report({ level, message: `${e.name}: ${e.message}`, stack: e.stack, component, context: { error_type: e.constructor?.name ?? "Error", ...(code !== undefined && { error_code: String(code) }), ...context } });
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import * as cheerio from "cheerio";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fpfDate, fpfSeasonId, parseFpfDetailsFixtures, parseFpfLineups } from "./providers.js";
|
||||
|
||||
describe("FPF catalogue helpers", () => {
|
||||
it("maps the football season to FPF's seasonId", () => {
|
||||
expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106");
|
||||
expect(fpfSeasonId(new Date("2027-08-01T12:00:00Z"))).toBe("107");
|
||||
});
|
||||
|
||||
it("reads the kick-off when the day and time are stuck together", () => {
|
||||
const now = new Date("2026-11-20T12:00:00Z");
|
||||
expect(fpfDate("20 nov20:45", now)).toMatchObject({ timeKnown: true });
|
||||
expect(fpfDate("20 nov20:45", now)!.at.toISOString()).toBe("2026-11-20T20:45:00.000Z");
|
||||
});
|
||||
|
||||
it("reads Taça-style Details games without GetClassification links", () => {
|
||||
const html = `
|
||||
<h2>TAÇA DE PORTUGAL</h2>
|
||||
<div class="accordion-item">
|
||||
<div class="accordion-title">4.ª Eliminatória</div>
|
||||
<div class="accordion-content">
|
||||
<div class="game">
|
||||
<div class="home-team">Fc Porto Sad</div>
|
||||
<span class="game-schedule">20 nov<br />20:45</span>
|
||||
<div class="away-team">Usc Paredes</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estadio Do Dragao</small></div>
|
||||
<div class="game">
|
||||
<div class="home-team">Vencedor Jogo A x B</div>
|
||||
<span class="game-schedule">16 dez<br />15:00</span>
|
||||
<div class="away-team">Vencedor Jogo C x D</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Recinto A Indicar</small></div>
|
||||
<a class="game-link" href="/Match/GetMatchInformation?matchId=2687999">
|
||||
<div class="game">
|
||||
<div class="home-team">Sporting Cp Sad</div>
|
||||
<span class="game-schedule">21 nov<br />18:00</span>
|
||||
<div class="away-team">União D. Serra</div>
|
||||
</div>
|
||||
<div class="game-list-stadium"><small>Estádio José Alvalade</small></div>
|
||||
</a>
|
||||
</div>
|
||||
</div>`;
|
||||
const fixtures = parseFpfDetailsFixtures(cheerio.load(html), {
|
||||
competitionId: "25263",
|
||||
seasonId: "106",
|
||||
competitionName: "Taça de Portugal",
|
||||
now: new Date("2026-11-20T12:00:00Z"),
|
||||
});
|
||||
expect(fixtures).toHaveLength(2);
|
||||
expect(fixtures[0]).toMatchObject({
|
||||
home: { name: "Fc Porto Sad" },
|
||||
away: { name: "Usc Paredes" },
|
||||
timeKnown: true,
|
||||
round: "4.ª Eliminatória",
|
||||
venue: "Estadio Do Dragao",
|
||||
});
|
||||
expect(fixtures[0]!.startsAt.toISOString()).toBe("2026-11-20T20:45:00.000Z");
|
||||
expect(fixtures[0]!.externalId).toContain("25263-");
|
||||
expect(fixtures[1]).toMatchObject({
|
||||
externalId: "2687999",
|
||||
home: { name: "Sporting Cp Sad" },
|
||||
away: { name: "União D. Serra" },
|
||||
venue: "Estádio José Alvalade",
|
||||
});
|
||||
});
|
||||
|
||||
it("reads each side of a match sheet with the federation headshot", () => {
|
||||
const html = `
|
||||
<section>
|
||||
<div class="title-bar">Equipas Iniciais</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo">
|
||||
<img src="/Player/Logo/4487059">
|
||||
<span class="icons"><span class="icon icon-goal"><span>1</span></span></span>
|
||||
</div>
|
||||
<strong>1</strong> Duarte Jesus (GR)
|
||||
</div>
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4487058"></div>
|
||||
<strong>9</strong> Roger Almeida
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team away-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4478263"></div>
|
||||
<strong>33</strong> José Costa (GR)
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="title-bar">Suplentes</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4484537"></div>
|
||||
<strong>7</strong> Antonio Andrade
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team away-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4478262"></div>
|
||||
<strong>4</strong> Tiago Araujo
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section>
|
||||
<div class="title-bar">Treinadores</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4488001"></div>
|
||||
<span style="font-weight: bold">Treinador Principal</span>
|
||||
<span>Andre Henriques Anastacio</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="lineup-team home-team">
|
||||
<div class="player">
|
||||
<div class="photo"><img src="/Player/Logo/4488002"></div>
|
||||
<span style="font-weight: bold">Treinador Principal</span>
|
||||
<span>Rui Borges</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>`;
|
||||
const { home, away } = parseFpfLineups(html);
|
||||
expect(home.map((p) => p.name)).toEqual(["Duarte Jesus", "Roger Almeida", "Antonio Andrade", "Andre Henriques Anastacio"]);
|
||||
expect(home[0]).toMatchObject({
|
||||
number: "1",
|
||||
position: "Guarda-Redes",
|
||||
externalId: "4487059",
|
||||
photoUrl: "https://resultados.fpf.pt/Player/Logo/4487059",
|
||||
});
|
||||
expect(home[1]).toMatchObject({ number: "9", name: "Roger Almeida", position: null });
|
||||
expect(home[3]).toMatchObject({ number: null, position: "Treinador" });
|
||||
expect(away.map((p) => [p.number, p.name])).toEqual([
|
||||
["33", "José Costa"],
|
||||
["4", "Tiago Araujo"],
|
||||
[null, "Rui Borges"],
|
||||
]);
|
||||
expect(away[0]).toMatchObject({ position: "Guarda-Redes", photoUrl: "https://resultados.fpf.pt/Player/Logo/4478263" });
|
||||
});
|
||||
});
|
||||
@@ -894,11 +894,81 @@ function fpaFixture(r: Record<string, unknown>): FixtureData | null {
|
||||
|
||||
// --- FPF (resultados.fpf.pt, HTML) --------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Competitions we always follow. The Taça de Portugal is FPF's (not Liga Portugal's calendar). `externalId` is the
|
||||
* resultados.fpf.pt competitionId; the seasonId advances with {@link fpfSeasonId}.
|
||||
*/
|
||||
export const FPF_COMPETITIONS = [{ externalId: "25263", name: "Taça de Portugal", gender: "M" }] as const;
|
||||
|
||||
/** FPF's seasonId: 106 is 2026/27. Advances by one each July. */
|
||||
export function fpfSeasonId(now = new Date()): string {
|
||||
const start = Number(seasonOf(now).slice(0, 4));
|
||||
return String(106 + (start - 2026));
|
||||
}
|
||||
|
||||
const MONTHS: Record<string, number> = { jan: 1, fev: 2, mar: 3, abr: 4, mai: 5, jun: 6, jul: 7, ago: 8, set: 9, out: 10, nov: 11, dez: 12 };
|
||||
|
||||
/** "Vencedor Jogo …" on a later round: not a real club yet. */
|
||||
function isFpfUndecidedSide(name: string): boolean {
|
||||
return /^vencedor\b/i.test(name.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Games listed on the competition Details page (accordion rounds). Some rounds wrap each game in a match link;
|
||||
* others (e.g. Taça 4.ª eliminatória) only print the teams and kick-off — then the id is derived from the kick-off
|
||||
* and the two clubs so a re-read stays stable.
|
||||
*/
|
||||
export function parseFpfDetailsFixtures(
|
||||
$: cheerio.CheerioAPI,
|
||||
opts: { competitionId: string; seasonId: string; competitionName: string; now?: Date },
|
||||
): FixtureData[] {
|
||||
const now = opts.now ?? new Date();
|
||||
const out: FixtureData[] = [];
|
||||
const items = $(".accordion-item");
|
||||
const roots = items.length ? items.toArray() : [$.root().get(0)!].filter(Boolean);
|
||||
for (const item of roots) {
|
||||
const root = $(item);
|
||||
const roundLabel = root.find(".accordion-title").first().text().replace(/\s+/g, " ").trim() || null;
|
||||
root.find(".game").each((_, gameEl) => {
|
||||
const game = $(gameEl);
|
||||
const homeName = game.find(".home-team").first().text().replace(/\s+/g, " ").trim();
|
||||
const awayName = game.find(".away-team").first().text().replace(/\s+/g, " ").trim();
|
||||
if (!homeName || !awayName) return;
|
||||
if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return;
|
||||
const when = fpfDate(game.find(".game-schedule").text(), now);
|
||||
if (!when) return;
|
||||
const parentLink = game.closest("a.game-link");
|
||||
const matchId = parentLink.length ? /matchId=(\d+)/i.exec(parentLink.attr("href") ?? "")?.[1] ?? null : null;
|
||||
const stadiumText = parentLink.length
|
||||
? parentLink.find(".game-list-stadium small").first().text().trim()
|
||||
: game.nextAll(".game-list-stadium").first().find("small").text().trim();
|
||||
const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text());
|
||||
const home = { externalId: slugify(homeName), name: homeName };
|
||||
const away = { externalId: slugify(awayName), name: awayName };
|
||||
const stamp = when.at.toISOString().slice(0, 16).replace(/[-:T]/g, "");
|
||||
out.push({
|
||||
externalId: matchId ?? `${opts.competitionId}-${stamp}-${home.externalId}-${away.externalId}`,
|
||||
competition: opts.competitionId,
|
||||
competitionName: opts.competitionName,
|
||||
season: opts.seasonId,
|
||||
home,
|
||||
away,
|
||||
startsAt: when.at,
|
||||
timeKnown: when.timeKnown,
|
||||
round: roundLabel,
|
||||
...fpfPlace(stadiumText),
|
||||
homeScore: score ? Number(score[1]) : null,
|
||||
awayScore: score ? Number(score[2]) : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** "12 out 15:00" (no year on the site): the year that puts it nearest to `now`. */
|
||||
export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean } | null {
|
||||
const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D+(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase());
|
||||
// Cheerio's .text() on "20 nov<br />20:45" can yield "20 nov20:45" with no space before the time.
|
||||
const m = /(\d{1,2})\s*(?:de\s+)?([a-zç]{3})[a-zç]*\.?(?:\s+(\d{4}))?(?:\D*(\d{1,2}:\d{2}))?/i.exec(text.toLowerCase().replace(/\s+/g, " ").trim());
|
||||
if (!m) return null;
|
||||
const month = MONTHS[m[2]!.slice(0, 3)];
|
||||
if (!month) return null;
|
||||
@@ -948,6 +1018,14 @@ export class FpfProvider {
|
||||
for (const m of ($.html().match(/GetClassificationAndMatchesByFixture\?fixtureId=(\d+)/g) ?? [])) rounds.add(m.replace(/\D/g, ""));
|
||||
const teams = new Map<string, TeamData>();
|
||||
const fixtures: FixtureData[] = [];
|
||||
const seen = new Set<string>();
|
||||
const addFixture = (f: FixtureData) => {
|
||||
if (seen.has(f.externalId)) return;
|
||||
seen.add(f.externalId);
|
||||
teams.set(f.home.externalId, f.home);
|
||||
teams.set(f.away.externalId, f.away);
|
||||
fixtures.push(f);
|
||||
};
|
||||
let n = 0;
|
||||
for (const round of rounds) {
|
||||
n++;
|
||||
@@ -959,14 +1037,13 @@ export class FpfProvider {
|
||||
const homeName = game.find(".home-team").text().trim();
|
||||
const awayName = game.find(".away-team").text().trim();
|
||||
if (!matchId || !homeName || !awayName) return;
|
||||
if (isFpfUndecidedSide(homeName) || isFpfUndecidedSide(awayName)) return;
|
||||
const home = { externalId: slugify(homeName), name: homeName };
|
||||
const away = { externalId: slugify(awayName), name: awayName };
|
||||
teams.set(home.externalId, home);
|
||||
teams.set(away.externalId, away);
|
||||
const when = fpfDate(game.find(".game-schedule").text(), now);
|
||||
if (!when) return;
|
||||
const score = /(\d+)\s*-\s*(\d+)/.exec(game.find(".score span").first().text());
|
||||
fixtures.push({
|
||||
addFixture({
|
||||
externalId: matchId,
|
||||
competition: competitionId,
|
||||
competitionName: name,
|
||||
@@ -976,31 +1053,122 @@ export class FpfProvider {
|
||||
startsAt: when.at,
|
||||
timeKnown: when.timeKnown,
|
||||
round: roundLabel,
|
||||
...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()),
|
||||
...fpfPlace(r(link).find(".game-list-stadium small").first().text().trim() || r(link).next(".game-list-stadium").find("small").text().trim()),
|
||||
homeScore: score ? Number(score[1]) : null,
|
||||
awayScore: score ? Number(score[2]) : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
// Cups such as the Taça de Portugal list rounds on the Details page (accordion) and often omit the
|
||||
// GetClassificationAndMatchesByFixture links the older divisions use. Read those games too.
|
||||
for (const f of parseFpfDetailsFixtures($, { competitionId, seasonId, competitionName: name, now })) {
|
||||
addFixture(f);
|
||||
}
|
||||
return { name, teams: [...teams.values()], fixtures };
|
||||
}
|
||||
|
||||
/** Line-ups from the match sheet ("Equipas Iniciais", "Suplentes"): starters and substitutes per side. */
|
||||
/** Line-ups from the match sheet: numbers, names and the federation headshot (`/Player/Logo/{id}`). */
|
||||
async lineups(matchId: string): Promise<{ home: PlayerData[]; away: PlayerData[] }> {
|
||||
const $ = await this.page(`/Match/GetMatchInformation?matchId=${matchId}`);
|
||||
const parsed = parseFpfLineups($);
|
||||
if (parsed.home.length || parsed.away.length) return parsed;
|
||||
return parseFpfLineups($("body").text());
|
||||
}
|
||||
}
|
||||
|
||||
export function parseFpfLineups(text: string): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const FPF_PLAYER_PHOTO = "https://resultados.fpf.pt";
|
||||
|
||||
/** The headshot on a match sheet. The id is the player's federation id. */
|
||||
function fpfPlayerPhoto(src: string | undefined): { externalId: string | null; photoUrl: string | null } {
|
||||
const id = /\/Player\/Logo\/(\d+)/.exec(src ?? "")?.[1] ?? null;
|
||||
if (!id) return { externalId: null, photoUrl: null };
|
||||
return { externalId: id, photoUrl: `${FPF_PLAYER_PHOTO}/Player/Logo/${id}` };
|
||||
}
|
||||
|
||||
function fpfCardPlayer($: cheerio.CheerioAPI, el: unknown): PlayerData | null {
|
||||
const card = $(el as never);
|
||||
const photo = fpfPlayerPhoto(card.find("img").first().attr("src"));
|
||||
const strong = card.find("strong").first().text().replace(/\s+/g, "").trim();
|
||||
const hasNumber = /^\d{1,3}$/.test(strong);
|
||||
if (hasNumber) {
|
||||
// Goal and card icons sit in `.photo` and their counts would stick to the name.
|
||||
card.find(".photo").remove();
|
||||
card.find("strong").first().remove();
|
||||
const raw = card.text().replace(/\s+/g, " ").trim();
|
||||
const name = raw.replace(/\s*\(GR\)\s*$/i, "").replace(/\s*\(C\)\s*$/i, "").trim();
|
||||
if (!name || name.length >= 80) return null;
|
||||
let position: string | null = null;
|
||||
if (/\(GR\)/i.test(raw)) position = "Guarda-Redes";
|
||||
return { externalId: photo.externalId, number: strong, name, position, photoUrl: photo.photoUrl };
|
||||
}
|
||||
const spans = card
|
||||
.find("span")
|
||||
.toArray()
|
||||
.map((span) => $(span).text().replace(/\s+/g, " ").trim())
|
||||
.filter((text) => text && !/^\d+$/.test(text));
|
||||
const role = spans[0] ?? "";
|
||||
const name = spans[1] ?? "";
|
||||
if (!name || name.length >= 80) return null;
|
||||
let position = role || "Equipa técnica";
|
||||
if (/treinador principal/i.test(role)) position = "Treinador";
|
||||
return { externalId: photo.externalId, number: null, name, position, photoUrl: photo.photoUrl };
|
||||
}
|
||||
|
||||
/** One column (home or away) of a named block on the match sheet. */
|
||||
function fpfColumn($: cheerio.CheerioAPI, title: string, side: "home-team" | "away-team"): PlayerData[] {
|
||||
const out: PlayerData[] = [];
|
||||
$("section").each((_, section) => {
|
||||
const heading = $(section).find(".title-bar").first().text().replace(/\s+/g, " ").trim();
|
||||
if (heading !== title) return;
|
||||
const root = $(section);
|
||||
let column = root.find(`.lineup-team.${side}`).first();
|
||||
// The coach block marks both columns `home-team`. The second column is the away coach.
|
||||
if (!column.length && side === "away-team") {
|
||||
const both = root.find(".lineup-team");
|
||||
if (both.length > 1) column = both.eq(1);
|
||||
}
|
||||
column.find(".player").each((__, el) => {
|
||||
const player = fpfCardPlayer($, el);
|
||||
if (player) out.push(player);
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseFpfLineupDom($: cheerio.CheerioAPI): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const titles = ["Equipas Iniciais", "Suplentes", "Treinadores"];
|
||||
const home: PlayerData[] = [];
|
||||
const away: PlayerData[] = [];
|
||||
for (const title of titles) {
|
||||
home.push(...fpfColumn($, title, "home-team"));
|
||||
away.push(...fpfColumn($, title, "away-team"));
|
||||
}
|
||||
return { home, away };
|
||||
}
|
||||
|
||||
/**
|
||||
* Match sheet. HTML keeps each side, the shirt number and the headshot. Plain text (no `lineup-team`) is the
|
||||
* older fallback: eleven starters a side, then the bench split in half. That path has no photos.
|
||||
*/
|
||||
export function parseFpfLineups(input: string | cheerio.CheerioAPI): { home: PlayerData[]; away: PlayerData[] } {
|
||||
if (typeof input !== "string") return parseFpfLineupDom(input);
|
||||
if (input.includes("lineup-team")) return parseFpfLineupDom(cheerio.load(input));
|
||||
return parseFpfLineupsText(input);
|
||||
}
|
||||
|
||||
function parseFpfLineupsText(text: string): { home: PlayerData[]; away: PlayerData[] } {
|
||||
const block = (from: string, to: string) => {
|
||||
const a = text.indexOf(from);
|
||||
if (a === -1) return [];
|
||||
const b = text.indexOf(to, a);
|
||||
const slice = b === -1 ? text.slice(a) : text.slice(a, b);
|
||||
const out: PlayerData[] = [];
|
||||
for (const m of (b === -1 ? text.slice(a) : text.slice(a, b)).matchAll(/^\s*(\d{1,3})\s+(.+?)\s*$/gm)) {
|
||||
for (const m of slice.matchAll(/^\s*(\d{1,3})\s+(.+?)\s*$/gm)) {
|
||||
const name = m[2]!.replace(/\s*\(GR\)\s*$/i, "").replace(/\s*\(C\)\s*$/i, "").trim();
|
||||
if (name && name.length < 80) out.push({ number: m[1]!, name, position: /\(GR\)/i.test(m[2]!) ? "Guarda-Redes" : null });
|
||||
if (!name || name.length >= 80) continue;
|
||||
let position: string | null = null;
|
||||
if (/\(GR\)/i.test(m[2]!)) position = "Guarda-Redes";
|
||||
out.push({ number: m[1]!, name, position });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
@@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
import { SportsService } from "./service.js";
|
||||
|
||||
type Level = "info" | "warn";
|
||||
type LogCall = { level: Level; msg: string };
|
||||
type LogCall = { level: Level; msg: string; obj: unknown };
|
||||
|
||||
const makeLog = (): { info: (obj: unknown, msg: string) => void; warn: (obj: unknown, msg: string) => void; error: () => void; debug: () => void; calls: LogCall[] } => {
|
||||
const calls: LogCall[] = [];
|
||||
return {
|
||||
calls,
|
||||
info: (_obj, msg) => calls.push({ level: "info", msg }),
|
||||
warn: (_obj, msg) => calls.push({ level: "warn", msg }),
|
||||
info: (obj, msg) => calls.push({ level: "info", msg, obj }),
|
||||
warn: (obj, msg) => calls.push({ level: "warn", msg, obj }),
|
||||
error: () => {},
|
||||
debug: () => {},
|
||||
};
|
||||
@@ -39,6 +39,9 @@ const p57p01 = () =>
|
||||
const p1017 = () =>
|
||||
Object.assign(new Error("Invalid `prisma.person.findFirst()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
|
||||
|
||||
const p1017findUnique = () =>
|
||||
Object.assign(new Error("Invalid `prisma.person.findUnique()` invocation:\n\nServer has closed the connection."), { code: "P1017" });
|
||||
|
||||
const ligaTeam = (id: string, externalId: string) => ({
|
||||
id,
|
||||
provider: "LIGA",
|
||||
@@ -232,6 +235,42 @@ describe("syncEventSquads downgrades a P1017 server-closed connection that exhau
|
||||
});
|
||||
});
|
||||
|
||||
describe("syncEventSquads downgrades a P1017 from person.findUnique in linkSquadPerson (BIT-32481)", () => {
|
||||
it("logs at info and returns zeros when the first person.findUnique is P1017 on both attempts", async () => {
|
||||
// The error loop reported P1017 ("Server has closed the connection.") from linkSquadPerson →
|
||||
// person.findUnique (the organizationId_sportsPlayerId lookup, the first DB call in the method). This is the
|
||||
// same catch path as BIT-32475 (retryOnConnectionClosed retries once, then isPrismaConnectionClosed downgrades
|
||||
// to info), but from the findUnique call rather than findFirst. This test proves that coverage.
|
||||
const fpaTeam = {
|
||||
id: "t-fpa",
|
||||
provider: "FPA",
|
||||
externalId: "fpa-1",
|
||||
name: "Team FPA",
|
||||
abbreviation: "FPA",
|
||||
logoUrl: null,
|
||||
};
|
||||
const db = {
|
||||
event: { findUnique: async () => makeEvent({ homeTeam: fpaTeam, awayTeam: null }) },
|
||||
sportsPlayer: {
|
||||
findFirst: async () => ({ season: "2026" }),
|
||||
findMany: async () => [{ id: "pl-1", name: "Player 1", externalId: "lic-1", number: "1", photoUrl: null, season: "2026" }],
|
||||
findUnique: async () => null,
|
||||
},
|
||||
person: {
|
||||
// Throws on every call, so the retryOnConnectionClosed retry also fails with P1017.
|
||||
findUnique: async () => { throw p1017findUnique(); },
|
||||
findFirst: async () => null,
|
||||
},
|
||||
};
|
||||
const service = new SportsService(makeDeps(db));
|
||||
const out = await service.syncEventSquads("evt-1");
|
||||
expect(out).toEqual({ created: 0, updated: 0, headshots: 0 });
|
||||
const log = (service as unknown as { deps: { log: { calls: LogCall[] } } }).deps.log;
|
||||
expect(log.calls.some((c) => c.level === "info" && /database connection closed/.test(c.msg))).toBe(true);
|
||||
expect(log.calls.some((c) => c.level === "warn")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("linkStoredSquads downgrades a 57P01 admin-terminated connection (BIT-32471)", () => {
|
||||
it("logs at info and returns 0 when the raw query is terminated mid-flight (57P01)", async () => {
|
||||
const db = {
|
||||
@@ -255,3 +294,27 @@ describe("linkStoredSquads downgrades a 57P01 admin-terminated connection (BIT-3
|
||||
expect(log.calls.some((c) => c.level === "info" && /database connection terminated/.test(c.msg))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveHeadshot swallows a network-level fetch failure (BIT-31961)", () => {
|
||||
it("returns false and logs a warn without a bare Error when the headshot URL is unreachable, so the bare undici TypeError does not reach the hub fingerprint", async () => {
|
||||
const log = makeLog();
|
||||
const db = {
|
||||
person: { update: async () => { throw new Error("must not be reached on a network failure"); } },
|
||||
};
|
||||
const storage = { referenceKey: () => "key", write: async () => { throw new Error("must not be reached on a network failure"); } };
|
||||
const deps = { db, log, fetch: (async () => { throw new TypeError("fetch failed"); }) as never, storage: storage as never, signer: null as never };
|
||||
const service = new SportsService(deps as unknown as ConstructorParameters<typeof SportsService>[0]);
|
||||
const saveHeadshot = (service as unknown as { saveHeadshot: (orgId: string, personId: string, src: string) => Promise<boolean> }).saveHeadshot.bind(service);
|
||||
|
||||
await expect(saveHeadshot("org-1", "person-1", "https://www.ligaportugal.pt/headshot.jpg")).resolves.toBe(false);
|
||||
|
||||
const warn = log.calls.find((c) => c.level === "warn" && /headshot download unavailable/.test(c.msg));
|
||||
expect(warn).toBeTruthy();
|
||||
// The warn must not carry the bare undici TypeError as `err`: pino's logHooks fingerprints any warn that has an
|
||||
// Error `err`, and a bare `TypeError: fetch failed` has no frame in our code, so it would collapse into the
|
||||
// same ERRSIG as every other unwrapped fetch site (BIT-31961). The reason is logged as a plain string instead.
|
||||
expect(warn!.obj && typeof warn!.obj === "object" && "err" in (warn!.obj as Record<string, unknown>)).toBe(false);
|
||||
expect((warn!.obj as { reason?: string }).reason).toBe("fetch failed");
|
||||
expect(log.calls.some((c) => c.level === "info" && /must not be reached/.test(c.msg))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,8 @@ import {
|
||||
fpaShortName,
|
||||
lisbonTime,
|
||||
FpfProvider,
|
||||
FPF_COMPETITIONS,
|
||||
fpfSeasonId,
|
||||
LIGA_COMPETITIONS,
|
||||
type LigaClubCompetition,
|
||||
LigaProvider,
|
||||
@@ -63,7 +65,27 @@ import {
|
||||
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. */
|
||||
const LINEUP_WINDOW = { before: 3600_000, after: 2 * 3600_000 };
|
||||
const HEADSHOT_HOSTS = ["www.ligaportugal.pt", "ligaportugal.pt", "img.uefa.com", "si.fpa.pt", "res.ehf.eu"];
|
||||
|
||||
/**
|
||||
* Season the squad is stored under. FPF's own id (`106`) stays on the competition, because that is what
|
||||
* resultados.fpf.pt expects. Players share the football season (`20262027`) with Liga, so a cup tie against
|
||||
* a Liga club sees that club's headshots.
|
||||
*/
|
||||
function squadSeason(provider: string | null | undefined, fixtureSeason: string | null | undefined, startsAt: Date): string {
|
||||
if (provider === "FPF") return seasonOf(startsAt);
|
||||
if (fixtureSeason) return fixtureSeason;
|
||||
return seasonOf(startsAt);
|
||||
}
|
||||
const HEADSHOT_HOSTS = [
|
||||
"www.ligaportugal.pt",
|
||||
"ligaportugal.pt",
|
||||
"img.uefa.com",
|
||||
"si.fpa.pt",
|
||||
"res.ehf.eu",
|
||||
"resultados.fpf.pt",
|
||||
"fpf360cdnprd.blob.core.windows.net",
|
||||
"app2030-prd-images.fpf.pt",
|
||||
];
|
||||
/** The "club" of referees made people from a match's referee team. */
|
||||
export const REFEREES = "Arbitragem";
|
||||
/** UEFA match sheets read per refresh (past matches without one yet): squads grow from them. */
|
||||
@@ -158,6 +180,16 @@ export class SportsService {
|
||||
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 } });
|
||||
}
|
||||
const fpfSeason = fpfSeasonId(now);
|
||||
for (const c of FPF_COMPETITIONS) {
|
||||
const existing = await this.deps.db.sportsCompetition.findUnique({ where: { provider_externalId: { provider: "FPF", externalId: c.externalId } } });
|
||||
if (!existing)
|
||||
await this.deps.db.sportsCompetition.create({
|
||||
data: { provider: "FPF", externalId: c.externalId, sport: "futebol", name: c.name, gender: c.gender, season: fpfSeason },
|
||||
});
|
||||
else if (existing.season !== fpfSeason)
|
||||
await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season: fpfSeason, lastIngestAt: null } });
|
||||
}
|
||||
}
|
||||
|
||||
private due(c: SportsCompetition, now: Date): boolean {
|
||||
@@ -1226,10 +1258,13 @@ export class SportsService {
|
||||
if (spec && (await this.readEhfSheet(spec.site, f, now)).read) read++;
|
||||
continue;
|
||||
}
|
||||
// A cup game listed before FPF assigns a matchId cannot be read. The next refresh replaces that id.
|
||||
if (!/^\d+$/.test(f.externalId)) continue;
|
||||
const { home, away } = await this.fpf.lineups(f.externalId);
|
||||
if (!home.length && !away.length) continue;
|
||||
await this.savePlayers(f.homeTeamId, f.season, home, "lineup");
|
||||
await this.savePlayers(f.awayTeamId, f.season, away, "lineup");
|
||||
const season = squadSeason("FPF", f.season, f.startsAt);
|
||||
await this.savePlayers(f.homeTeamId, season, home, "lineup");
|
||||
await this.savePlayers(f.awayTeamId, season, away, "lineup");
|
||||
await db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } });
|
||||
read++;
|
||||
} catch (err) {
|
||||
@@ -1326,8 +1361,9 @@ export class SportsService {
|
||||
const home = await this.deps.db.sportsTeam.findUnique({ where: { id: homeTeamId }, select: { venue: true, city: true } });
|
||||
place = { venue: place.venue ?? home?.venue ?? null, city: place.city ?? home?.city ?? null };
|
||||
}
|
||||
const season = squadSeason(provider, f.season, f.startsAt);
|
||||
const data = {
|
||||
season: f.season,
|
||||
season,
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
startsAt: f.startsAt,
|
||||
@@ -1338,6 +1374,32 @@ export class SportsService {
|
||||
awayScore: f.awayScore ?? null,
|
||||
...(f.officials?.length ? { officials: f.officials as unknown as object } : {}),
|
||||
};
|
||||
// The Taça lists a game before FPF assigns a matchId. When the id appears, keep the same fixture (the event
|
||||
// already points at it) instead of inserting a second row the line-up reader never sees.
|
||||
if (provider === "FPF" && /^\d+$/.test(f.externalId)) {
|
||||
const prior = await this.deps.db.sportsFixture.findFirst({
|
||||
where: {
|
||||
competitionId: c.id,
|
||||
startsAt: f.startsAt,
|
||||
homeTeamId,
|
||||
awayTeamId,
|
||||
NOT: { externalId: f.externalId },
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (prior) {
|
||||
await this.deps.db.sportsFixture.update({
|
||||
where: { id: prior.id },
|
||||
data: {
|
||||
externalId: f.externalId,
|
||||
...data,
|
||||
...(place.venue ? { venue: place.venue } : {}),
|
||||
...(place.city ? { city: place.city } : {}),
|
||||
},
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
// A sheet that does not name a hall must not wipe a venue we already stored (the youth article has none).
|
||||
await this.deps.db.sportsFixture.upsert({
|
||||
where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } },
|
||||
@@ -1367,7 +1429,7 @@ export class SportsService {
|
||||
const { db } = this.deps;
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true } } },
|
||||
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true, competition: { select: { provider: true } } } } },
|
||||
});
|
||||
if (!event) throw notFound("event_not_found");
|
||||
const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[];
|
||||
@@ -1387,7 +1449,7 @@ export class SportsService {
|
||||
["away", event.awayTeam],
|
||||
] as const) {
|
||||
if (!team) continue;
|
||||
const season = event.fixture?.season ?? seasonOf(event.startsAt);
|
||||
const season = squadSeason(event.fixture?.competition.provider, event.fixture?.season, event.startsAt);
|
||||
const players = await this.squad(team.id, season);
|
||||
const personOf = await this.peopleOf(event.organizationId, players);
|
||||
const faceOf = await this.facesOf([...personOf.values()]);
|
||||
@@ -1475,7 +1537,8 @@ export class SportsService {
|
||||
const result = { created: 0, updated: 0, headshots: 0 };
|
||||
const headshots: { personId: string; url: string }[] = [];
|
||||
// Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh.
|
||||
const season = event.fixture?.season ?? seasonOf(event.startsAt);
|
||||
// FPF fixtures keep the site's seasonId; the squad itself is the football season, same as Liga.
|
||||
const season = squadSeason(event.fixture?.competition.provider, event.fixture?.season, event.startsAt);
|
||||
for (const team of [event.homeTeam, event.awayTeam]) {
|
||||
if (team?.provider !== "LIGA") continue;
|
||||
try {
|
||||
@@ -2035,7 +2098,18 @@ export class SportsService {
|
||||
private async saveHeadshot(orgId: string, personId: string, src: string): Promise<boolean> {
|
||||
const u = new URL(src);
|
||||
if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false;
|
||||
const res = await this.deps.fetch(u.toString(), { signal: AbortSignal.timeout(20_000) });
|
||||
let res: { ok: boolean; status: number; json(): Promise<unknown>; text(): Promise<string>; arrayBuffer(): Promise<ArrayBuffer> };
|
||||
try {
|
||||
res = await this.deps.fetch(u.toString(), { signal: AbortSignal.timeout(20_000) });
|
||||
} catch (err) {
|
||||
// A network-level failure (DNS, connection reset, timeout) has no Response and surfaces as a bare undici
|
||||
// `TypeError: fetch failed` whose stack has no frame in our code, so it collapses into a single hub
|
||||
// fingerprint regardless of the call site (BIT-31961). A headshot that can't be downloaded is not worth
|
||||
// paging: log the reason without the bare Error object (so pino's logHooks does not fingerprint it) and
|
||||
// skip this URL — the next sync retries it.
|
||||
this.deps.log.warn({ personId, host: u.hostname, reason: err instanceof Error ? err.message : "fetch failed" }, "sports: headshot download unavailable");
|
||||
return false;
|
||||
}
|
||||
if (!res.ok) return false;
|
||||
const data = Buffer.from(await res.arrayBuffer());
|
||||
if (data.length > HEADSHOT_MAX_BYTES) return false;
|
||||
|
||||
@@ -90,6 +90,28 @@ describe("errors to errors.bitreport.pt", () => {
|
||||
]);
|
||||
expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" });
|
||||
});
|
||||
|
||||
it("does not report transient PostgreSQL shutdown/restart errors (57P01/57P03/P1001/P1017)", async () => {
|
||||
const hub = fakeHub();
|
||||
const reporter = reporterWith(hub.fetchImpl);
|
||||
const sink = new Writable({ write: (_c, _e, cb) => cb() });
|
||||
const log = pino({ level: "info", hooks: reporter.logHooks("api") }, sink);
|
||||
const mk = (msg: string, code?: string) => {
|
||||
const e = new Error(msg);
|
||||
if (code) (e as { code?: string }).code = code;
|
||||
return e;
|
||||
};
|
||||
log.error({ err: mk("Database error. Code: 57P03. Message: the database system is shutting down") }, "sports: query failed");
|
||||
log.error({ err: mk("Database error. Code: 57P01. Message: terminating connection due to administrator command") }, "archive: query failed");
|
||||
log.error({ err: mk("Can't reach database server at localhost:5432", "P1001") }, "db unreachable");
|
||||
log.error({ err: mk("Server has closed the connection.", "P1017") }, "connection closed");
|
||||
reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker");
|
||||
log.error({ err: new Error("render crashed") }, "real error");
|
||||
await reporter.flush();
|
||||
const events = hub.sent.flatMap((s) => s.events);
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]!.message).toContain("render crashed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser errors through the API", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CodeGeneratorSettings } from "@photoreport/contracts";
|
||||
import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { BLOCK_START, buildCodeLines, mergeGenerated, teamPrefix, toTsv } from "../src/sports/codegen.js";
|
||||
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { type Fetch, fpaEpochFor, fpaProva, fpaShortName, fpfDate, fpfSeasonId, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { SportsService } from "../src/sports/service.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
@@ -111,6 +111,7 @@ describe("federation data", () => {
|
||||
const now = new Date("2026-12-20T12:00:00Z");
|
||||
expect(fpfDate("10 jan 15:00", now)!.at.toISOString()).toBe("2027-01-10T15:00:00.000Z");
|
||||
expect(fpfDate("12 out", now)).toMatchObject({ timeKnown: false });
|
||||
expect(fpfSeasonId(new Date("2026-11-20T12:00:00Z"))).toBe("106");
|
||||
const sheet = ["Equipas Iniciais", ...Array.from({ length: 22 }, (_, i) => `${i + 1} Jogador ${i + 1}${i === 0 ? " (GR)" : ""}`), "Suplentes", "30 Suplente A", "31 Suplente B", "Treinadores"].join("\n");
|
||||
const { home, away } = parseFpfLineups(sheet);
|
||||
expect(home).toHaveLength(12);
|
||||
@@ -232,6 +233,7 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
|
||||
const u = new URL(url);
|
||||
const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body), arrayBuffer: async () => new ArrayBuffer(0) });
|
||||
const bytes = (b: Buffer) => ({ ok: true, status: 200, json: async () => ({}), text: async () => b.toString("latin1"), arrayBuffer: async () => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) as ArrayBuffer });
|
||||
if (u.host === "resultados.fpf.pt" && u.pathname === "/Competition/Details") return bytes(Buffer.from("<html><body><h2>TAÇA DE PORTUGAL</h2></body></html>", "utf8"));
|
||||
if (state.handball && u.host === "ws.fpa.pt" && u.pathname.includes("getJogosClubeEpocaEscalao"))
|
||||
return json(u.pathname.endsWith("/140/374/4") ? [fpaGame("323264", "2026-09-23", VITORIA, AGUAS, [33, 29]), fpaGame("323500", "2026-10-17", VITORIA, AGUAS, null)] : []);
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname.startsWith("/clube/id/")) return bytes(Buffer.from(CLUB_PAGE, "utf8"));
|
||||
@@ -372,7 +374,8 @@ describe("sports data service", () => {
|
||||
const r = await sports.refreshDue(now);
|
||||
expect(r.errors).toEqual([]);
|
||||
const comps = await ctx.db.sportsCompetition.findMany({ orderBy: { name: "asc" } });
|
||||
expect(comps.map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
||||
expect(comps.filter((c) => c.provider === "FPF").map((c) => [c.externalId, c.season])).toEqual([["25263", "106"]]);
|
||||
expect(comps.filter((c) => c.provider !== "FPF").map((c) => [c.provider, c.externalId, c.season])).toEqual([
|
||||
["LIGA", "allianzcup", "20262027"],
|
||||
["FPA", "PO09", "20262027"],
|
||||
["EHF", "cl-men", "20262027"],
|
||||
|
||||
@@ -341,8 +341,15 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
||||
existing FPA Nextcloud account and never sent on arrival. FPA licence or an older EHF club photo fills
|
||||
gaps. People and reference faces are created when the event syncs those teams (`POST …/squads/sync`), not on
|
||||
every sports refresh. Example match: Portugal–Switzerland `202811130101002`.
|
||||
- **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.
|
||||
- **FPF** (`resultados.fpf.pt`, HTML): the Taça de Portugal is seeded in the catalogue; other competitions are
|
||||
added by link. It gives teams and fixtures (Details page and round sheets). The competition row keeps the
|
||||
site's seasonId (`106`); the fixture and the squad use the football season (`20262027`), the same key as Liga,
|
||||
so a Liga club in the cup keeps its headshots. Squads come from each match sheet (starters, substitutes and
|
||||
the two head coaches), including the federation headshot (`Player/Logo/{id}` or the
|
||||
`fpf360cdnprd` photo host), read from 1 h before to 2 h after kick-off. A game published before it has a `matchId` is stored with a stable
|
||||
synthetic id; the next read that finds the real id updates that same fixture. The federation's Cloudflare
|
||||
challenge blocks datacentre IPs: when the worker cannot reach the site, fixtures and squads must be seeded
|
||||
another way until the IP is allowed or a proxy is set.
|
||||
- **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
|
||||
|
||||
@@ -32,7 +32,9 @@ Following the AP and NPPA codes:
|
||||
below the knee is on the floor: it does not frame the photo, even when it overlaps the player's legs and sits
|
||||
closer to the middle of the body. Football plays the ball on the ground, so the ball at the feet is the one
|
||||
that stays. A spare ball that nobody is playing never wins, in either sport.
|
||||
- **Shape:** the photo's own aspect unless the event or the editor chose another (never turned vertical).
|
||||
- **Shape:** the autopilot keeps the photograph's own aspect. The crop may move anywhere across the frame,
|
||||
including a tighter window, but it is not turned into another format. A square, a 4:5, a 16:9, or a portrait
|
||||
crop of a landscape frame is not an autopilot crop. An editor, by hand, may still choose another aspect.
|
||||
- **Context:** a generic event (no opponent, no fixture) is reportage. A match is sport, and a photo of that
|
||||
match with no ball in play is cropped as a person. Reportage does not use the handball cut.
|
||||
- **Framing** (per event, sport only):
|
||||
|
||||
@@ -45,7 +45,7 @@ export const AutopilotSettings = z.object({
|
||||
* "natural" Getty-like.
|
||||
*/
|
||||
look: z.enum(["agency", "natural", "none"]).default("none"),
|
||||
/** Crop shape (width, height); null: the photo's own. */
|
||||
/** Unused. The autopilot always keeps the photograph's own aspect. */
|
||||
aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null),
|
||||
/** The crop keeps at least this many pixels on its long edge of the original. */
|
||||
minLongEdge: z.number().int().min(800).max(12000).default(2400),
|
||||
|
||||
Reference in new issue
Block a user