Files
photoreport/apps/api/src/delivery/zerozero.ts
T
sparkandClaude Opus 5.5 8a78398fdf
ci / rust (pull_request) Successful in 3m47s
ci / typescript (pull_request) Failing after 7m20s
Take a replaced zerozero image back again: skip only the "synced-" placeholder, not every id that is not digits.
d204db4 skipped any id that is not all digits, which also skipped real ids the desk can answer (main's CI has been
red since, on the delivery test that checks a replaced photo's old image is taken back). Only the placeholder that
`upload` returns when the desk already had the file is skipped now, with a test of its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01SC7s5gwdivkoBXbRGxbnAo
2026-10-20 14:49:51 +00:00

343 lines
16 KiB
TypeScript

import { TransportError } from "./transports.js";
/**
* fotos.zerozero.pt, the photo desk of zerozero.pt: photographers upload a match's photos to the match's page, with
* their name as the author. Its own API (the one its web app reads):
*
* - Login is zerozero.pt's OAuth: `/api/auth/login` gives the authorize URL on www.zerozero.pt; signing in there
* (`ax_login.php`, username or email and password) and opening it again comes back to `/api/auth/callback`, which
* leaves the desk's own session cookie. All of it is cookies, kept here in a small jar.
* - Games: `/api/content/games/<id>` and `/api/content/upcoming` (every game of the coming days, with teams and
* Lisbon time).
* - Upload: tus 1.0 at `/api/upload?match_id=<id>`, metadata `match_id`, `artist` (the author shown with the photo)
* and the file name. The image's id is the upload's id; `DELETE /api/images/<id>` takes it back.
*/
export const ZEROZERO_URL = "https://fotos.zerozero.pt";
const LOGIN_SITE = "https://www.zerozero.pt";
const CHUNK = 5 * 1024 * 1024;
const TIMEOUT_MS = 60_000;
export interface ZerozeroGame {
id: string;
/** Lisbon wall time, "2026-10-15 17:45:00". */
date: string;
home: string;
away: string;
competition: string | null;
}
interface Cookie {
name: string;
value: string;
/** Host the cookie belongs to; with a leading dot, its subdomains too. */
domain: string;
}
/** Just enough of a cookie jar for one login: domain matching, no paths, no expiry (the session is short). */
export class CookieJar {
private readonly cookies = new Map<string, Cookie>();
store(url: string, headers: Headers): void {
const host = new URL(url).hostname;
const raw = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : splitSetCookie(headers.get("set-cookie"));
for (const line of raw) {
const [pair, ...attrs] = line.split(";");
const eq = pair!.indexOf("=");
if (eq <= 0) continue;
const name = pair!.slice(0, eq).trim();
const value = pair!.slice(eq + 1).trim();
const domainAttr = attrs.map((a) => a.trim()).find((a) => /^domain=/i.test(a));
const domain = domainAttr ? `.${domainAttr.slice(7).replace(/^\./, "").toLowerCase()}` : host;
const expired = attrs.some((a) => /^max-age=(0|-)/i.test(a.trim())) || (!value && attrs.some((a) => /^expires=/i.test(a.trim())));
const key = `${domain}|${name}`;
if (expired) this.cookies.delete(key);
else this.cookies.set(key, { name, value, domain });
}
}
header(url: string): string {
const host = new URL(url).hostname;
return [...this.cookies.values()]
.filter((c) => c.domain === host || (c.domain.startsWith(".") && (host === c.domain.slice(1) || host.endsWith(c.domain))))
.map((c) => `${c.name}=${c.value}`)
.join("; ");
}
clear(): void {
this.cookies.clear();
}
}
/** Set-Cookie lines folded into one header (when Headers.getSetCookie is missing): split on commas between cookies. */
function splitSetCookie(v: string | null): string[] {
if (!v) return [];
return v.split(/,(?=\s*[^;,=\s]+=)/).map((s) => s.trim());
}
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
/** `fetch` hides the socket error on `cause`. Keep the code (ETIMEDOUT, ECONNRESET, …) in the delivery error. */
export function fetchFailure(err: unknown): string {
const error = err as { message?: string; cause?: { code?: string; message?: string; errors?: { code?: string }[] } };
const message = error?.message || "fetch failed";
const cause = error?.cause;
const codes = new Set<string>();
if (cause?.code) codes.add(cause.code);
for (const item of cause?.errors ?? []) if (item.code) codes.add(item.code);
const extra = [...codes];
if (!extra.length && cause?.message && cause.message !== message) extra.push(cause.message);
return extra.length ? `${message} (${extra.join(", ")})` : message;
}
export class ZerozeroClient {
private readonly jar = new CookieJar();
private account: { role: string; name: string | null } | null = null;
private loggingIn: Promise<{ role: string; name: string | null }> | null = null;
private readonly games = new Map<string, ZerozeroGame>();
constructor(
private readonly credentials: { username: string; password: string },
private readonly fetchImpl: typeof fetch = fetch,
private readonly base = ZEROZERO_URL,
private readonly loginSite = LOGIN_SITE,
) {}
/** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */
private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> {
let current = url;
let options = init;
for (let i = 0; i <= hops; i++) {
const headers = new Headers(options.headers);
const cookie = this.jar.header(current);
if (cookie) headers.set("cookie", cookie);
if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)");
let res: Response;
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (err) {
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
this.jar.store(current, res.headers);
const location = res.headers.get("location");
if (res.status >= 300 && res.status < 400 && location) {
current = new URL(location, current).toString();
// A redirect after a POST is a GET (303, and in practice 301/302 too).
options = { method: "GET" };
continue;
}
return { res, url: current };
}
throw new TransportError("zerozero: too many redirects", false);
}
private async json<T>(path: string, init: RequestInit = {}, retry = true): Promise<T> {
await this.login();
const { res } = await this.request(`${this.base}/api${path}`, init);
if (res.status === 401 && retry) {
this.account = null;
this.jar.clear();
return this.json<T>(path, init, false);
}
if (!res.ok) throw new TransportError(`zerozero ${path}: ${res.status}`, res.status >= 500 || res.status === 429);
return (await res.json()) as T;
}
/** Signs in (once; again when the session has gone). Returns the account's role and its photographer name. */
async login(): Promise<{ role: string; name: string | null }> {
if (this.account) return this.account;
this.loggingIn ??= this.signIn().finally(() => {
this.loggingIn = null;
});
return this.loggingIn;
}
private async signIn(): Promise<{ role: string; name: string | null }> {
const me = async () => {
const { res } = await this.request(`${this.base}/api/auth/me`);
if (res.status === 401) return null;
if (!res.ok) throw new TransportError(`zerozero: account check ${res.status}`, res.status >= 500);
const body = (await res.json()) as { role?: string; photographer_name?: string | null };
return { role: body.role ?? "", name: body.photographer_name ?? null };
};
const authorize = async () => {
const { res } = await this.request(`${this.base}/api/auth/login`);
if (!res.ok) throw new TransportError(`zerozero: login ${res.status}`, res.status >= 500);
const { authURL } = (await res.json()) as { authURL?: string };
if (!authURL) throw new TransportError("zerozero: no login address", false);
return this.request(authURL);
};
// Opening the authorize page with a zerozero.pt session goes straight back to the desk.
let landed = await authorize();
if (new URL(landed.url).origin !== new URL(this.base).origin) {
const form = new FormData();
form.set("login_username", this.credentials.username);
form.set("login_password", this.credentials.password);
form.set("go", "1");
const { res } = await this.request(`${this.loginSite}/ax_login.php`, { method: "POST", body: form, headers: { "x-requested-with": "XMLHttpRequest", referer: landed.url } });
if (!res.ok) throw new TransportError(`zerozero: sign-in ${res.status}`, res.status >= 500);
const text = await res.text();
let body: { status?: unknown; msg?: unknown } = {};
try {
body = JSON.parse(text) as typeof body;
} catch {
throw new TransportError("zerozero: unexpected sign-in answer", true);
}
if (!body.status) throw new TransportError(`zerozero: ${typeof body.msg === "string" && body.msg ? body.msg : "sign-in refused"}`, false);
landed = await authorize();
if (new URL(landed.url).origin !== new URL(this.base).origin) throw new TransportError("zerozero: signed in, but the photo desk did not accept the account", false);
}
const account = await me();
if (!account) throw new TransportError("zerozero: signed in, but no session on the photo desk", false);
if (account.role !== "photographer" && account.role !== "admin") throw new TransportError(`zerozero: the account is not a photographer (${account.role || "no role"})`, false);
this.account = account;
return account;
}
/** A game by id (cached). */
async game(id: string): Promise<ZerozeroGame> {
const cached = this.games.get(id);
if (cached) return cached;
const raw = await this.json<Record<string, unknown>>(`/content/games/${encodeURIComponent(id)}`).catch((err: unknown) => {
if (err instanceof TransportError && /: 404$/.test(err.message)) throw new TransportError(`zerozero: game ${id} not found`, false);
throw err;
});
const game = toGame(raw);
if (!game) throw new TransportError(`zerozero: game ${id} not found`, false);
this.games.set(id, game);
return game;
}
private upcomingCache: { at: number; games: ZerozeroGame[] } | null = null;
/** The games of the coming days (and today's), as the desk lists them (a few thousand; kept 10 minutes). */
async upcoming(): Promise<ZerozeroGame[]> {
if (this.upcomingCache && Date.now() - this.upcomingCache.at < 10 * 60_000) return this.upcomingCache.games;
const rows = await this.json<unknown[]>("/content/upcoming");
const games = (Array.isArray(rows) ? rows : []).map((r) => toGame(r as Record<string, unknown>)).filter((g): g is ZerozeroGame => !!g);
this.upcomingCache = { at: Date.now(), games };
for (const g of games) this.games.set(g.id, g);
return games;
}
/** Uploads one photo to a game (tus, in chunks). Returns the image's id on the desk. */
async upload(gameId: string, fileName: string, data: Buffer, artist: string): Promise<string> {
const type = /\.png$/i.test(fileName) ? "image/png" : "image/jpeg";
const meta = { filename: fileName, filetype: type, name: fileName, type, match_id: gameId, artist };
const metadata = Object.entries(meta)
.map(([k, v]) => `${k} ${b64(v)}`)
.join(",");
const create = async (retry: boolean): Promise<string> => {
await this.login();
const { res } = await this.request(`${this.base}/api/upload?${new URLSearchParams({ match_id: gameId })}`, {
method: "POST",
headers: { "tus-resumable": "1.0.0", "upload-length": String(data.length), "upload-metadata": metadata },
});
if (res.status === 401 && retry) {
this.account = null;
this.jar.clear();
return create(false);
}
const location = res.headers.get("location");
if (res.status !== 201 || !location) throw new TransportError(`zerozero upload: ${res.status}`, res.status >= 500 || res.status === 429);
return new URL(location, this.base).toString();
};
const url = await create(true);
let offset = 0;
while (offset < data.length) {
const chunk = data.subarray(offset, Math.min(data.length, offset + CHUNK));
const { res } = await this.request(url, {
method: "PATCH",
headers: { "tus-resumable": "1.0.0", "upload-offset": String(offset), "content-type": "application/offset+octet-stream" },
body: new Uint8Array(chunk),
});
if (res.status !== 204) {
const detail = (await res.text().catch(() => "")).replace(/\s+/g, " ").slice(0, 180);
// The desk already has this file (a previous attempt landed). Not a failure.
if (res.status === 422 && /j[aá] foi enviada/i.test(detail)) return `synced-${fileName}`;
throw new TransportError(`zerozero upload: ${res.status} at ${offset} bytes${detail ? `: ${detail}` : ""}`, res.status >= 500 || res.status === 409 || res.status === 429);
}
const next = Number(res.headers.get("upload-offset"));
offset = Number.isFinite(next) && next > offset ? next : offset + chunk.length;
}
return new URL(url).pathname.split("/").filter(Boolean).pop()!;
}
/** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */
async remove(imageId: string): Promise<void> {
// "synced-<file name>" (from `upload`, when the desk already had the file) is not a real image id: there was
// never anything of ours to take back, and the desk answers a bare DELETE on it with 400, not 404.
if (imageId.startsWith("synced-")) return;
await this.json(`/images/${encodeURIComponent(imageId)}`, { method: "DELETE" }).catch((err: unknown) => {
if (err instanceof TransportError && /: (403|404)$/.test(err.message)) return;
throw err;
});
}
}
function toGame(r: Record<string, unknown> | null | undefined): ZerozeroGame | null {
if (!r) return null;
const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null);
const id = s(r.id);
const date = s(r.date);
const home = s(r.home_team_name);
const away = s(r.away_team_name);
if (!id || !date || !home || !away) return null;
return { id, date, home, away, competition: s(r.edition_name) };
}
/** A game's id from what someone pastes: the number, or a link like fotos.zerozero.pt/edicoes/219039/12627747. */
export function zerozeroGameId(input: string): string | null {
const t = input.trim();
if (/^\d{4,12}$/.test(t)) return t;
try {
const u = new URL(t);
if (!/(^|\.)zerozero\.pt$/.test(u.hostname)) return null;
const fromQuery = u.searchParams.get("id") ?? u.searchParams.get("match_id");
if (fromQuery && /^\d+$/.test(fromQuery)) return fromQuery;
const parts = u.pathname.split("/").filter(Boolean);
const last = parts[parts.length - 1];
if (last && /^\d{4,12}$/.test(last)) return last;
// zerozero.pt/jogo/<date>-<home>-<away>/<id>
const num = parts.reverse().find((p) => /^\d{4,12}$/.test(p));
return num ?? null;
} catch {
return null;
}
}
const STOP = new Set(["fc", "sc", "cf", "cd", "ud", "sad", "ac", "ad", "gd", "cs", "sl", "sport", "clube", "club", "futebol", "football", "afc", "the", "de", "da", "do", "e", "fk", "sk"]);
export const words = (name: string) =>
name
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.split(" ")
.filter((w) => w.length > 1 && !STOP.has(w));
/** Whether two names are the same team ("Torreense" / "SC Torreense", "Sporting CP" / "Sporting"). */
export function sameTeam(a: string, b: string): boolean {
return sameWords(words(a), words(b));
}
/** `sameTeam` on names already split into `words` (to compare one name with many teams). */
export function sameWords(wa: string[], wb: string[]): boolean {
if (!wa.length || !wb.length) return false;
const [short, long] = wa.length <= wb.length ? [wa, wb] : [wb, wa];
return short.every((w) => long.some((x) => x === w || (w.length >= 4 && (x.startsWith(w) || w.startsWith(x)))));
}
/**
* The desk's game for an event: same teams (home and away) starting within three hours of the event (Lisbon
* time); with several, the closest in time.
*/
export function matchGame(games: ZerozeroGame[], event: { home: string; away: string; startsAt: Date }, toUtc: (lisbon: string) => Date): ZerozeroGame | null {
const at = event.startsAt.getTime();
const near = games
.map((g) => ({ g, gap: Math.abs(toUtc(g.date).getTime() - at) }))
.filter((x) => x.gap <= 3 * 3600_000 && sameTeam(x.g.home, event.home) && sameTeam(x.g.away, event.away))
.sort((a, b) => a.gap - b.gap);
return near[0]?.g ?? null;
}