diff --git a/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql b/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql new file mode 100644 index 0000000..4331149 --- /dev/null +++ b/apps/api/prisma/migrations/20261021230000_ehf_provider/migration.sql @@ -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'; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 464d082..1883c80 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1261,6 +1261,7 @@ enum SportsProvider { FPF // resultados.fpf.pt (football below the Liga: teams, fixtures, line-ups per match) FPA // ws.fpa.pt (handball: teams and fixtures) 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 { diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index bafa42a..d9fb249 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -56,6 +56,8 @@ export interface ArchiveDeps { ligaSeason?: (season: string) => Promise; /** The FPA's national games of a season (slow: run in the background, the galleries matched again after). */ fpaSeason?: (season: string) => Promise; + /** EHF club competitions of a season (Champions League, European League, European Cup), read when a gallery names one. */ + ehfSeason?: (season: string) => Promise; /** Brings the squads of a game's teams into the event (names for faces and codes). */ syncSquads?: (eventId: string) => Promise; fetchImpl?: typeof fetch; @@ -736,6 +738,13 @@ export class ArchiveService { this.seasonsAsked.add(`FPA|${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({ where: { // Never a game still to be played. diff --git a/apps/api/src/sports/ehf.test.ts b/apps/api/src/sports/ehf.test.ts new file mode 100644 index 0000000..42d1a01 --- /dev/null +++ b/apps/api/src/sports/ehf.test.ts @@ -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(`
`)).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 () => `
`, 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); + }); +}); diff --git a/apps/api/src/sports/providers.ts b/apps/api/src/sports/providers.ts index 6f2d916..0307810 100644 --- a/apps/api/src/sports/providers.ts +++ b/apps/api/src/sports/providers.ts @@ -912,3 +912,214 @@ export class UefaProvider { 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 = { + 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 { + 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(); + 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): Promise { + 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): Promise { + 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 }; + } +} diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 22759ff..2ac2878 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -23,6 +23,8 @@ import { type PlayerData, ProviderHttpError, type TeamData, + EHF_COMPETITIONS, + EhfProvider, UEFA_COMPETITIONS, UEFA_PITCH_OFFICIALS, UefaProvider, @@ -31,7 +33,7 @@ import { /** * 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 * the official headshot as reference) and into events (pick the match, the form fills itself). */ @@ -39,11 +41,13 @@ 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"]; +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. */ export const REFEREES = "Arbitragem"; /** UEFA match sheets read per refresh (past matches without one yet): squads grow from them. */ 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; /** 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"]; @@ -61,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. */ const PEOPLE_OFFICIALS = [...UEFA_PITCH_OFFICIALS, "TABLE_OFFICIAL"]; -const SPORT: Record = { LIGA: "futebol", FPF: "futebol", FPA: "andebol", UEFA: "futebol" }; +const SPORT: Record = { LIGA: "futebol", FPF: "futebol", FPA: "andebol", UEFA: "futebol", EHF: "andebol" }; export interface SportsDeps { db: Db; @@ -74,6 +78,8 @@ export interface SportsDeps { uefaDelayMs?: number; /** Pause between FPA pages. */ fpaDelayMs?: number; + /** Pause between EHF pages and match sheets. */ + ehfDelayMs?: number; } export interface RefreshResult { @@ -89,9 +95,11 @@ export class SportsService { readonly fpa: FpaProvider; readonly fpf: FpfProvider; readonly uefa: UefaProvider; + readonly ehf: EhfProvider; constructor(private readonly deps: SportsDeps) { this.uefa = new UefaProvider(deps.fetch); + this.ehf = new EhfProvider(deps.fetch, deps.ehfDelayMs ?? 200); this.liga = new LigaProvider(deps.fetch); this.fpa = new FpaProvider(deps.fetch, deps.fpaDelayMs ?? 800); this.fpf = new FpfProvider(deps.fetch, deps.fpfDelayMs ?? 800); @@ -114,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 } }); 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 { @@ -138,6 +152,7 @@ export class SportsService { 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 === "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(); return total; } @@ -152,7 +167,9 @@ export class SportsService { ? await this.refreshFpa(now) : c.provider === "UEFA" ? 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(); return r; } @@ -741,6 +758,78 @@ export class SportsService { 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 { + 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(); + 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 { + 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. */ async addFpfCompetition(ref: string, now = new Date()): Promise { const parsed = FpfProvider.parseRef(ref); @@ -760,11 +849,11 @@ export class SportsService { const fixtures = await db.sportsFixture.findMany({ where: { 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) }, }, take: 10, - include: { competition: { select: { provider: true } } }, + include: { competition: { select: { provider: true, externalId: true } } }, }); let read = 0; for (const f of fixtures) { @@ -773,6 +862,11 @@ export class SportsService { if ((await this.readUefaSheet(f, now)).read) read++; 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); if (!home.length && !away.length) continue; await this.savePlayers(f.homeTeamId, f.season, home, "lineup"); @@ -780,7 +874,7 @@ export class SportsService { await db.sportsFixture.update({ where: { id: f.id }, data: { lineupAt: now } }); read++; } 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(); diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 2e1ee4f..d31c1b4 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -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. // 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 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 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). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 21ee6cd..43d6575 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -290,6 +290,11 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati kept beside it. - **FPF** (`resultados.fpf.pt`, HTML): competitions are added by link. It gives teams and fixtures, and squads from each match sheet, read from 1 h before to 2 h after kick-off. +- **EHF** (the JSON `ehfcl`, `ehfel` and `ehfec.eurohandball.com` read; not a documented API): men's and women's + 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 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