feat(sports): EHF Euro Cup fixtures in the match picker (BIT-180) #181

Merged
spark merged 4 commits from task/BIT-180-eurocup-fixtures into main 2026-11-04 15:04:12 +00:00
14 changed files with 240 additions and 11 deletions

No files matched your search

@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "DeliveryKind" ADD VALUE 'SMUGMUG';
+2
View File
@@ -517,6 +517,8 @@ enum DeliveryKind {
ZEROZERO
/// A folder on one of the organisation's computers: the desktop app there saves the rendered files.
LOCAL
/// SmugMug guest upload link (https://site.smugmug.com/upload/{album}/{key}).
SMUGMUG
}
enum DeliveryStatus {
+3 -2
View File
@@ -20,7 +20,7 @@ const OrgParams = z.object({ orgId: z.uuid() });
const TargetParams = OrgParams.extend({ targetId: z.uuid() });
const ItemParams = OrgParams.extend({ itemId: z.uuid() });
const KIND = z.enum(["NEXTCLOUD", "SFTP", "FTP", "DROPBOX", "ZEROZERO", "LOCAL"]);
const KIND = z.enum(["NEXTCLOUD", "SFTP", "FTP", "DROPBOX", "ZEROZERO", "LOCAL", "SMUGMUG"]);
const ADDRESS: Record<z.infer<typeof KIND>, RegExp> = {
NEXTCLOUD: /^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)/,
SFTP: /^sftp:\/\/[^/\s]+$/,
@@ -29,6 +29,7 @@ const ADDRESS: Record<z.infer<typeof KIND>, RegExp> = {
ZEROZERO: /^https:\/\/fotos\.zerozero\.pt\/?$/,
// A folder on a computer (macOS/Linux, or Windows with a drive letter); the user is that computer's id.
LOCAL: /^(\/|[A-Za-z]:[\\/])/,
SMUGMUG: /^https:\/\/[a-z0-9-]+\.smugmug\.com\/upload\/[A-Za-z0-9_-]+\/[A-Za-z0-9]+\/?$/,
};
const TargetBase = z.object({
name: z.string().trim().min(1).max(80),
@@ -72,7 +73,7 @@ const TargetBase = z.object({
});
const checkAddress = (kind: z.infer<typeof KIND>, baseUrl: string, username: string) => {
if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`);
if (kind !== "DROPBOX" && !username) throw badRequest("username_required");
if (kind !== "DROPBOX" && kind !== "SMUGMUG" && !username) throw badRequest("username_required");
};
// Defaults only when creating: an update that leaves a field out keeps what is saved.
const TargetFields = TargetBase.extend({
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { SmugmugTransport, parseSmugUploadLink } from "./transports.js";
describe("parseSmugUploadLink", () => {
it("reads the album and the key from a guest upload link", () => {
expect(parseSmugUploadLink("https://ehfmedia.smugmug.com/upload/dwSRLJ/PORupload")).toEqual({
nickname: "ehfmedia",
albumKey: "dwSRLJ",
uploadKey: "PORupload",
});
expect(parseSmugUploadLink("https://ehfmedia.smugmug.com/gallery/x")).toBeNull();
});
});
describe("SmugmugTransport", () => {
it("posts the jpeg to the guest uploader with the album and the key", async () => {
const seen: { url: string; headers: Record<string, string> }[] = [];
const fetchImpl = (async (url: string, init?: RequestInit) => {
const headers: Record<string, string> = {};
new Headers(init?.headers).forEach((value, key) => {
headers[key] = value;
});
seen.push({ url: String(url), headers });
return new Response(JSON.stringify({ stat: "ok" }), { status: 200 });
}) as typeof fetch;
const transport = new SmugmugTransport(
{
kind: "SMUGMUG",
baseUrl: "https://ehfmedia.smugmug.com/upload/dwSRLJ/PORupload",
username: "ehfmedia",
secret: "PORupload",
},
fetchImpl,
);
await transport.upload("SNAM/photo.jpg", Buffer.from("jpeg"));
expect(seen[0]?.url).toBe("https://upload.smugmug.com/");
expect(seen[0]?.headers["x-smug-albumuri"]).toBe("/api/v2/album/dwSRLJ");
expect(seen[0]?.headers["x-smug-filename"]).toBe("photo.jpg");
expect(seen[0]?.headers["x-smug-guestuploadkey"]).toBe("PORupload");
expect(await transport.test()).toEqual({ account: "ehfmedia / dwSRLJ" });
});
});
+75 -1
View File
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { Client as FtpClient } from "basic-ftp";
import SftpClient from "ssh2-sftp-client";
@@ -44,7 +45,7 @@ export class TransportError extends Error {
}
}
export type TransportKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX" | "ZEROZERO";
export type TransportKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX" | "ZEROZERO" | "SMUGMUG";
export interface TransportConfig {
kind: TransportKind;
@@ -77,9 +78,82 @@ export function createTransport(config: TransportConfig, fetchImpl: typeof fetch
return new DropboxTransport(config, fetchImpl);
case "ZEROZERO":
return new ZerozeroTransport(new ZerozeroClient({ username: config.username, password: config.secret }, fetchImpl));
case "SMUGMUG":
return new SmugmugTransport(config, fetchImpl);
}
}
/**
* A SmugMug guest-upload link: `https://{site}.smugmug.com/upload/{albumKey}/{uploadKey}`.
* The key is the last path segment (it can change per game). No OAuth: the guest uploader posts the file.
*/
export function parseSmugUploadLink(url: string): { nickname: string; albumKey: string; uploadKey: string } | null {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return null;
}
if (parsed.protocol !== "https:" || !parsed.hostname.endsWith(".smugmug.com")) return null;
const parts = parsed.pathname.split("/").filter(Boolean);
if (parts[0] !== "upload" || !parts[1] || !parts[2]) return null;
if (!/^[A-Za-z0-9_-]+$/.test(parts[1]) || !/^[A-Za-z0-9]+$/.test(parts[2])) return null;
return { nickname: parsed.hostname.replace(/\.smugmug\.com$/, ""), albumKey: parts[1], uploadKey: parts[2] };
}
export class SmugmugTransport implements Transport {
constructor(
private readonly config: TransportConfig,
private readonly fetchImpl: typeof fetch,
) {}
async ensureFolder(): Promise<void> {}
async upload(remoteFile: string, data: Buffer): Promise<void> {
const link = parseSmugUploadLink(this.config.baseUrl);
if (!link) throw new TransportError("smugmug: the address must be an https upload link (/upload/album/key)", false);
const uploadKey = this.config.secret.trim() || link.uploadKey;
const fileName = remoteFile.split("/").filter(Boolean).pop() || "photo.jpg";
let res: Response;
try {
res = await this.fetchImpl("https://upload.smugmug.com/", {
method: "POST",
headers: {
"content-type": "image/jpeg",
"content-length": String(data.length),
"content-md5": createHash("md5").update(data).digest("base64"),
"x-smug-albumuri": `/api/v2/album/${link.albumKey}`,
"x-smug-filename": fileName,
"x-smug-responsetype": "JSON",
"x-smug-version": "v2",
"x-smug-guestuploadkey": uploadKey,
},
body: new Uint8Array(data),
signal: AbortSignal.timeout(120_000),
});
} catch (err) {
throw new TransportError(`smugmug: network error: ${(err as Error).message}`, true);
}
const text = await res.text().catch(() => "");
if (!res.ok || /"stat"\s*:\s*"fail"/i.test(text)) {
throw new TransportError(`smugmug upload ${res.status}: ${text.slice(0, 200)}`, res.status === 429 || res.status >= 500);
}
}
async remove(): Promise<void> {
throw new TransportError("smugmug: a guest upload cannot be taken back", false);
}
async test(): Promise<{ account?: string }> {
const link = parseSmugUploadLink(this.config.baseUrl);
if (!link) throw new TransportError("smugmug: the address must be an https upload link (/upload/album/key)", false);
if (!this.config.secret.trim() && !link.uploadKey) throw new TransportError("smugmug: missing upload key", false);
return { account: `${link.nickname} / ${link.albumKey}` };
}
async close(): Promise<void> {}
}
/** fotos.zerozero.pt: the folder is the game's id ("12627747/"), checked once; the file keeps its name. */
export class ZerozeroTransport implements Transport {
// One session cookie and one tus upload at a time. Parallel deliveries share this client and otherwise
+6
View File
@@ -374,6 +374,12 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
if (side) for (const id of await peopleConfirmedOnSide(db, event.organizationId, season, side)) ids.add(id);
if (!game) for (const id of await peopleNamedHere(db, eventId, event.organizationId)) ids.add(id);
if (game) for (const id of await officialsOf(db, eventId, event.organizationId)) ids.add(id);
// A training that points at the national teams (no fixture): the plantel, without becoming the match.
if (!game) {
const linked = await db.event.findUnique({ where: { id: eventId }, select: { homeTeamId: true, awayTeamId: true } });
const teamIds = [linked?.homeTeamId, linked?.awayTeamId].filter((t): t is string => !!t);
if (teamIds.length) for (const id of await peopleOnSquad(db, event.organizationId, teamIds, season)) ids.add(id);
}
// National match with linked plantéis (SNAM / SUI-M): same people-with-face query as club games.
let squad = 0;
if (game && isNationalEvent(event)) {
+9 -2
View File
@@ -1237,7 +1237,10 @@ export class EhfProvider {
* Men's EHF EURO Cup (national teams) on eurohandball.com — same GetMatchDetails shape as club sheets,
* with shirt numbers and res.ehf.eu headshots once the nominated 16 are published.
*/
async euroCupMenMatches(competitionId: string, contentId: string): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null }[]> {
async euroCupMenMatches(
competitionId: string,
contentId: string,
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1245,19 +1248,23 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
const place = obj(obj(m.venue).place);
const utc = str(obj(obj(m.venue).date).utc);
if (!matchId || !utc) continue;
const at = new Date(utc);
if (Number.isNaN(at.getTime())) continue;
const hall = str(place.hallName);
const city = str(place.cityName);
out.push({
matchId,
startsAt: at,
homeNation: str(obj(obj(m.homeTeam).team).nationAbbreviation) ?? str(obj(obj(m.homeTeam).team).countryAbbreviation),
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
});
}
return out;
+36 -2
View File
@@ -574,14 +574,41 @@ export class SportsService {
* Merges onto SNAM/SUI-M (and other nations in the group): keeps Portuguese CIPA as externalId when the name matches.
*/
private async applyEuroCupSheets(now: Date, season: string, result: RefreshResult): Promise<void> {
const { log } = this.deps;
let matches: { matchId: string; startsAt: Date }[];
const { db, log } = this.deps;
let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[];
try {
matches = await this.ehf.euroCupMenMatches(EHF_EURO_CUP_MEN.competitionId, EHF_EURO_CUP_MEN.contentId);
} catch (err) {
result.errors.push(`ehf euro cup: ${(err as Error).message}`);
return;
}
const listed = matches.filter((m) => nationToSnamTeam(m.homeNation, "snam") && nationToSnamTeam(m.awayNation, "snam"));
const comp = listed.length
? await db.sportsCompetition.upsert({
where: { provider_externalId: { provider: "FPA", externalId: "EURO-CUP-M" } },
create: { provider: "FPA", externalId: "EURO-CUP-M", sport: "andebol", name: "EHF Euro Cup", gender: "M", season },
update: { name: "EHF Euro Cup", season },
})
: null;
for (const m of listed) {
if (!comp) continue;
const homeExt = nationToSnamTeam(m.homeNation, "snam");
const awayExt = nationToSnamTeam(m.awayNation, "snam");
if (!homeExt || !awayExt) continue;
const homeSide = NATIONAL_SIDES.find((s) => s.externalId === homeExt);
const awaySide = NATIONAL_SIDES.find((s) => s.externalId === awayExt);
result.fixtures += await this.saveFixture(comp, "FPA", {
externalId: m.matchId,
competition: "EURO-CUP-M",
season,
home: { externalId: homeExt, name: homeSide?.name ?? m.homeNation ?? homeExt, abbreviation: homeSide?.abbreviation ?? m.homeNation },
away: { externalId: awayExt, name: awaySide?.name ?? m.awayNation ?? awayExt, abbreviation: awaySide?.abbreviation ?? m.awayNation },
startsAt: m.startsAt,
timeKnown: true,
round: "EHF Euro Cup",
venue: m.venue,
});
}
const due = matches.filter((m) => Math.abs(m.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
// Always include today's known kick-off window even if the standing list is empty (tests / cache).
if (!due.length) {
@@ -1790,6 +1817,8 @@ export class SportsWorker {
private ticking = false;
private filling = false;
private lastRefresh = 0;
/** Euro Cup fixtures and sheets, even when the FPA agenda itself is not due yet. */
private lastNational = 0;
constructor(
private readonly service: SportsService,
@@ -1808,6 +1837,11 @@ export class SportsWorker {
await this.service.importLigaSquads({ limit: 20 });
await this.service.linkStoredSquads(24);
}
// National fixtures (Euro Cup) land in the database on their own, so the picker already has them.
if (Date.now() - this.lastNational >= 60 * 60_000) {
this.lastNational = Date.now();
await this.service.syncNationalCallUps();
}
await this.service.pollLineups();
} catch (err) {
this.opts.log.warn({ err }, "sports: tick failed");
+7
View File
@@ -794,6 +794,13 @@ describe("sports data service", () => {
number: "3",
photoUrl: "https://res.ehf.eu/photo/meister.jpg",
});
const fixture = await ctx.db.sportsFixture.findFirst({
where: { externalId: "202811130101002" },
include: { homeTeam: true, awayTeam: true, competition: true },
});
expect(fixture?.competition.name).toBe("EHF Euro Cup");
expect(fixture?.homeTeam.name).toBe("Portugal");
expect(fixture?.awayTeam.name).toBe("Suíça");
});
});
+3 -1
View File
@@ -657,7 +657,9 @@ export const t = {
startsAt: "Início",
photographers: "Fotógrafos",
pickMatch: "Escolher o jogo",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os das últimas duas semanas). Preenche o evento e junta os plantéis às pessoas.",
pickMatchHelp: "Jogos da Liga Portugal, FPF, FPA, EHF Euro Cup (seleções) e UEFA (Champions, Liga Europa, Conference, Champions feminina e de futsal) dos próximos dias (ao pesquisar, também os das últimas duas semanas). Preenche o evento e junta os plantéis às pessoas. As fotos de 2 h antes até 4 h depois do apito vão para este evento.",
squadFromMatch: "Usar o plantel de um jogo",
squadFromMatchHelp: "Treino ou sessão: fica com os jogadores desse jogo, sem ser o jogo (legenda e hora são as tuas).",
searchMatch: "Equipa, competição ou pavilhão",
noMatches: "Nenhum jogo encontrado.",
linked: "Ligado ao jogo oficial",
+22
View File
@@ -67,6 +67,9 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [match, setMatch] = useState<SportsFixture | null>(null);
/** Generic event (a training): borrow this match's squads without becoming the match. */
const [squadMatch, setSquadMatch] = useState<SportsFixture | null>(null);
const [showSquad, setShowSquad] = useState(false);
const [kind, setKind] = useState<Kind>("match");
const [caption, setCaption] = useState("");
const fields: readonly (typeof FIELDS)[number][] = kind === "match" ? FIELDS : OTHER_FIELDS;
@@ -109,6 +112,10 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
homeShort: match.home.abbreviation,
awayShort: match.away.abbreviation,
}),
...(kind === "other" && squadMatch && {
homeTeamId: squadMatch.home.id,
awayTeamId: squadMatch.away.id,
}),
});
onCreated(event);
} catch (err) {
@@ -143,6 +150,21 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
))}
</div>
{kind === "match" && <FixturePicker api={api} match={match} onPick={pick} onClear={() => setMatch(null)} />}
{kind === "other" && (
<div className="border-b border-line px-4 py-3">
{!showSquad && !squadMatch ? (
<button type="button" className="text-[12px] text-accent hover:underline" onClick={() => setShowSquad(true)}>
{t.eventForm.squadFromMatch}
</button>
) : (
<>
<p className="mb-1 text-[11px] text-faint">{t.eventForm.squadFromMatch}</p>
<FixturePicker api={api} match={squadMatch} onPick={setSquadMatch} onClear={() => { setSquadMatch(null); setShowSquad(false); }} />
<p className="mt-1 text-[11px] text-faint">{t.eventForm.squadFromMatchHelp}</p>
</>
)}
</div>
)}
{kind === "other" && (
<AgendaPicker
api={api}
+29 -2
View File
@@ -97,6 +97,14 @@ const KINDS: Record<
secret: "Senha do zerozero.pt",
help: "A conta de fotógrafo do zerozero.pt. As fotos vão para a página do jogo, com o nome do fotógrafo como autor; o jogo é encontrado pelas equipas e pela hora do evento (ou escolhes ao enviar).",
},
SMUGMUG: {
label: "SmugMug (link de upload)",
address: "Link de upload",
placeholder: "https://ehfmedia.smugmug.com/upload/dwSRLJ/PORupload",
user: "",
secret: "Chave do link",
help: "Cola o link completo que a SmugMug dá (muda de jogo para jogo). A chave é o último bocado do link, por exemplo PORupload. O JPEG vai para essa galeria.",
},
};
const PRESETS = {
@@ -141,6 +149,18 @@ const PRESETS = {
jpegQuality: 90,
sharpen: false,
},
smugmug: {
label: "SmugMug SNAM",
kind: "SMUGMUG",
baseUrl: "https://ehfmedia.smugmug.com/upload/dwSRLJ/PORupload",
longEdge: 4000,
folder: "/",
fileName: "{originalName}",
jpegQuality: 90,
sharpen: false,
password: "PORupload",
username: "ehfmedia",
},
} as const;
/**
@@ -293,6 +313,8 @@ export function TargetForm({
longEdge: p.longEdge,
jpegQuality: "jpegQuality" in p ? p.jpegQuality : 100,
sharpen: "sharpen" in p ? p.sharpen : false,
...("password" in p ? { password: p.password } : {}),
...("username" in p ? { username: p.username } : {}),
name: v.name || p.label.replace(/ \(.*\)$/, ""),
})
}
@@ -324,6 +346,11 @@ export function TargetForm({
folderTemplate: "/{event}/",
username: "",
}),
...(kind === "SMUGMUG" && {
folderTemplate: "/",
fileNameTemplate: "{originalName}",
username: "ehfmedia",
}),
});
}}
>
@@ -394,8 +421,8 @@ export function TargetForm({
spellCheck: false,
})}
{v.kind !== "LOCAL" && (
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
{field("username", k.user, {
<div className={`grid gap-3 max-sm:grid-cols-1 ${v.kind === "SMUGMUG" ? "grid-cols-1" : "grid-cols-2"}`}>
{v.kind !== "SMUGMUG" && field("username", k.user, {
autoComplete: "off",
spellCheck: false,
})}
+3
View File
@@ -299,6 +299,9 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
per refresh; again after a week. Event sync still fills gaps via `portal.fpa.pt/associado/<CIPA>/` when a
boletim names someone the register has not yet brought. With biometrics on, photos become reference faces.
Names are first + last name ("Rui Lopes"), the full name kept beside it.
The sports worker (`SportsWorker`, about every 10 minutes, and national sheets at least hourly) writes
fixtures into `sports_fixtures` before anyone opens the form. Choosing a game reads that row: teams, venue,
kick-off and, once the sheet is in, the plantel. Men's EHF Euro Cup matches come from the same pass.
Each FPA refresh also upserts senior national sides (`SNAM`, `SNAF`, `SUI-M`, …) and merges the Men's EHF
EURO Cup match sheets from `www.eurohandball.com` (`GetStandingMatches` / `GetMatchDetails` — same shape as
club sheets, with shirt numbers and `res.ehf.eu` headshots for the nominated 16). Portuguese CIPAs from the
+1 -1
View File
@@ -243,7 +243,7 @@ export interface IptcIssue {
}
/** LOCAL: a folder on one of the organisation's computers (baseUrl: the folder; username: that computer's id). */
export type DeliveryKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX" | "ZEROZERO" | "LOCAL";
export type DeliveryKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX" | "ZEROZERO" | "LOCAL" | "SMUGMUG";
/** A game on fotos.zerozero.pt (date in Lisbon time, "2026-10-15 17:45:00"). */
export interface ZerozeroGame {