Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0e1664375 | ||
|
|
e74ca03f23 | ||
|
|
b4d3cedacc | ||
|
|
caeee877ba | ||
|
|
28291a5f96 | ||
|
|
eadb535d8f | ||
|
|
8c39c6eb34 | ||
|
|
c782c73abd | ||
|
|
6b2f060463 | ||
|
|
97265b8de2 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "SportsProvider" ADD VALUE 'UEFA';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "sports_fixtures" ADD COLUMN "officials" JSONB;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "DeliveryKind" ADD VALUE 'ZEROZERO';
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "events" ADD COLUMN "zerozero_game_id" TEXT;
|
||||
@@ -0,0 +1,5 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "DeliveryKind" ADD VALUE 'LOCAL';
|
||||
|
||||
-- AlterEnum
|
||||
ALTER TYPE "DeliveryStatus" ADD VALUE 'WAITING';
|
||||
@@ -255,6 +255,8 @@ model Event {
|
||||
fixtureId String? @map("fixture_id") @db.Uuid
|
||||
homeTeamId String? @map("home_team_id") @db.Uuid
|
||||
awayTeamId String? @map("away_team_id") @db.Uuid
|
||||
/// The match's page on fotos.zerozero.pt (game id), found from teams and time or chosen by hand.
|
||||
zerozeroGameId String? @map("zerozero_game_id")
|
||||
createdById String? @map("created_by_id") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
@@ -485,11 +487,16 @@ enum DeliveryKind {
|
||||
SFTP
|
||||
FTP
|
||||
DROPBOX
|
||||
ZEROZERO
|
||||
/// A folder on one of the organisation's computers: the desktop app there saves the rendered files.
|
||||
LOCAL
|
||||
}
|
||||
|
||||
enum DeliveryStatus {
|
||||
QUEUED
|
||||
RUNNING
|
||||
/// LOCAL: rendered and kept on the server until the computer's desktop app takes it.
|
||||
WAITING
|
||||
DONE
|
||||
FAILED
|
||||
}
|
||||
@@ -1182,6 +1189,7 @@ enum SportsProvider {
|
||||
LIGA // ligaportugal.pt API (football: teams, squads with numbers and headshots, fixtures)
|
||||
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)
|
||||
}
|
||||
|
||||
model SportsCompetition {
|
||||
@@ -1288,8 +1296,10 @@ model SportsFixture {
|
||||
venue String?
|
||||
homeScore Int? @map("home_score")
|
||||
awayScore Int? @map("away_score")
|
||||
/// FPF: when the line-ups were read from the match sheet.
|
||||
/// FPF and UEFA: when the line-ups were read from the match sheet.
|
||||
lineupAt DateTime? @map("lineup_at")
|
||||
/// The referee team ({name, role}[]), when the provider publishes it (UEFA).
|
||||
officials Json?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Db } from "../db.js";
|
||||
import { bestOf, groupBursts } from "./bursts.js";
|
||||
import { type Candidate, type WindowDecision, actionScore, curate, matchMinutes } from "./curate.js";
|
||||
import type { AutopilotRecord } from "./service.js";
|
||||
|
||||
interface PhotoRow {
|
||||
id: string;
|
||||
capturedAt: Date | null;
|
||||
createdAt: Date;
|
||||
cameraSerial: string | null;
|
||||
cameraModel: string | null;
|
||||
uploaderId: string | null;
|
||||
rating: number;
|
||||
flag: string;
|
||||
autopilot: unknown;
|
||||
}
|
||||
|
||||
export const CANDIDATE_SELECT = { id: true, capturedAt: true, createdAt: true, cameraSerial: true, cameraModel: true, uploaderId: true, rating: true, flag: true, autopilot: true } as const;
|
||||
|
||||
/**
|
||||
* One candidate per burst (its best frame), from the autopilot's analysis. Photos it never saw (autopilot off) are
|
||||
* ranked by the photographer's own marks instead: stars, and picks.
|
||||
*/
|
||||
export function candidatesOf(photos: PhotoRow[], burstGapMs: number, onlyDecided: boolean): Candidate[] {
|
||||
const frames = photos.map((p) => {
|
||||
const rec = p.autopilot as AutopilotRecord | null;
|
||||
const own = p.rating + (p.flag === "PICK" ? 1 : 0);
|
||||
return { ...p, rec, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score: rec ? rec.score : own > 0 ? own / 10 : 0 };
|
||||
});
|
||||
const out: Candidate[] = [];
|
||||
groupBursts(frames, burstGapMs).forEach((burst, i) => {
|
||||
if (onlyDecided && !burst.every((f) => f.rec?.decided)) return;
|
||||
const best = bestOf(burst, 1)[0];
|
||||
if (!best) return;
|
||||
const rec = best.rec;
|
||||
out.push({
|
||||
id: best.id,
|
||||
at: (best.capturedAt ?? best.createdAt).getTime(),
|
||||
burst: i,
|
||||
score: best.score ?? 0,
|
||||
reason: rec ? rec.reason : best.score ? "person" : null,
|
||||
people: rec?.people ?? null,
|
||||
subjectHeight: rec?.subject ? rec.subject.y1 - rec.subject.y0 : null,
|
||||
rating: best.rating,
|
||||
rejected: best.flag === "REJECT",
|
||||
});
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The best `count` photos of an event, spread over the match (for a one-off delivery after the match). */
|
||||
export async function bestOfEvent(db: Db, eventId: string, count: number): Promise<string[]> {
|
||||
const event = await db.event.findUniqueOrThrow({ where: { id: eventId }, select: { startsAt: true, sport: true } });
|
||||
const photos = await db.photo.findMany({ where: { eventId, status: "READY" }, select: CANDIDATE_SELECT });
|
||||
const candidates = candidatesOf(photos, 1500, false);
|
||||
if (!candidates.length) return [];
|
||||
const times = candidates.map((c) => c.at);
|
||||
// From kick-off (warm-up and line-ups are not game moments).
|
||||
const start = event.startsAt.getTime();
|
||||
const end = Math.max(...times, start + matchMinutes(event.sport) * 60_000);
|
||||
const decisions: WindowDecision[] = curate(candidates, [], { count, start, durationMs: Math.max(end - start, 10 * 60_000), now: Number.MAX_SAFE_INTEGER, settleMs: 0 });
|
||||
const chosen = new Set(decisions.flatMap((d) => d.chosen));
|
||||
// The windows' shares are rounded, and photos may cover only part of the match: the best of the rest fill the
|
||||
// gallery up to its size (never twins of a chosen frame).
|
||||
const rest = candidates.filter((c) => !chosen.has(c.id) && actionScore(c) > 0 && c.at >= start - 5 * 60_000).sort((a, b) => actionScore(b) - actionScore(a));
|
||||
const picked = candidates.filter((c) => chosen.has(c.id));
|
||||
for (const c of rest) {
|
||||
if (picked.length >= count) break;
|
||||
if (picked.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < 8_000)) continue;
|
||||
picked.push(c);
|
||||
}
|
||||
return picked.sort((a, b) => a.at - b.at).map((c) => c.id);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* "Only the best" (docs/photo-editing-rules.md §5): for clients that want a short gallery of the match, not every
|
||||
* usable frame. The match is cut into short windows, and each window may add its share of the gallery size, with
|
||||
* the share it did not use carried forward (half-time adds nothing, a busy spell may take a little more). Within a
|
||||
* window the frames with the most action win: the ball in play, a duel or a celebration, a subject big in the
|
||||
* frame and sharp; one frame per burst, and not two from the same few seconds. Anything well below the match's
|
||||
* typical frame is left out even when the window has room.
|
||||
*/
|
||||
|
||||
export interface Candidate {
|
||||
id: string;
|
||||
/** Capture time (ms). */
|
||||
at: number;
|
||||
/** The burst it belongs to (only one frame of a burst is chosen). */
|
||||
burst: number;
|
||||
/** Frame score from the autopilot (sharpness × size, within a burst). */
|
||||
score: number;
|
||||
/** ball, group, person, or null (nobody clear). */
|
||||
reason: string | null;
|
||||
/** People in the subject. */
|
||||
people: number | null;
|
||||
/** Height of the subject (0-1 of the frame). */
|
||||
subjectHeight: number | null;
|
||||
/** The photographer's stars (0-5); a rejected frame is never chosen. */
|
||||
rating: number;
|
||||
rejected: boolean;
|
||||
}
|
||||
|
||||
/** How much of a "game moment" a frame is, comparable across the match. 0: not a candidate. */
|
||||
export function actionScore(c: Candidate): number {
|
||||
if (c.rejected || c.score <= 0 || !c.reason) return 0;
|
||||
let s = c.score;
|
||||
if (c.reason === "ball") s *= 1.3;
|
||||
else if (c.reason === "group") s *= 1.1;
|
||||
if ((c.people ?? 1) >= 2) s *= 1.1;
|
||||
// Far away (a small figure in a big field) reads badly in a gallery.
|
||||
if (c.subjectHeight !== null && c.subjectHeight < 0.25) s *= 0.7;
|
||||
return s * (1 + 0.2 * Math.max(0, Math.min(5, c.rating)));
|
||||
}
|
||||
|
||||
export interface CurateOptions {
|
||||
/** Gallery size wanted for the whole match. */
|
||||
count: number;
|
||||
/** Kick-off (ms) and how long the match lasts (with the break). */
|
||||
start: number;
|
||||
durationMs: number;
|
||||
windowMs?: number;
|
||||
/** Frames this close in time are the same moment. */
|
||||
minGapMs?: number;
|
||||
/** A window is decided once it ended this long ago. */
|
||||
settleMs?: number;
|
||||
now: number;
|
||||
}
|
||||
|
||||
export interface WindowDecision {
|
||||
/** Window index from kick-off (−1: before kick-off, never chosen). */
|
||||
window: number;
|
||||
ids: string[];
|
||||
chosen: string[];
|
||||
}
|
||||
|
||||
const median = (xs: number[]) => {
|
||||
if (!xs.length) return 0;
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s[Math.floor(s.length / 2)]!;
|
||||
};
|
||||
|
||||
/**
|
||||
* Decides the windows that have closed and are not decided yet. `decided` holds the candidates already decided
|
||||
* (chosen or not), so earlier choices count against the gallery size.
|
||||
*/
|
||||
export function curate(candidates: Candidate[], decided: { id: string; chosen: boolean }[], opts: CurateOptions): WindowDecision[] {
|
||||
const windowMs = opts.windowMs ?? 5 * 60_000;
|
||||
const minGapMs = opts.minGapMs ?? 8_000;
|
||||
const settleMs = opts.settleMs ?? 60_000;
|
||||
const done = new Map(decided.map((d) => [d.id, d.chosen]));
|
||||
let chosenSoFar = [...done.values()].filter(Boolean).length;
|
||||
const cap = Math.round(opts.count * 1.1);
|
||||
const perWindow = (opts.count * windowMs) / opts.durationMs;
|
||||
// The match's typical frame, for the floor: half of the median of the frames with a subject.
|
||||
const scored = candidates.map((c) => ({ c, s: actionScore(c) }));
|
||||
const floor = scored.filter((x) => x.s > 0).length >= 10 ? 0.5 * median(scored.filter((x) => x.s > 0).map((x) => x.s)) : 0;
|
||||
|
||||
const byWindow = new Map<number, typeof scored>();
|
||||
for (const x of scored) {
|
||||
if (done.has(x.c.id)) continue;
|
||||
// Warm-up and line-ups (more than 5 minutes before kick-off) are not game moments.
|
||||
const w = x.c.at < opts.start - 5 * 60_000 ? -1 : Math.max(0, Math.floor((x.c.at - opts.start) / windowMs));
|
||||
byWindow.set(w, [...(byWindow.get(w) ?? []), x]);
|
||||
}
|
||||
const out: WindowDecision[] = [];
|
||||
for (const w of [...byWindow.keys()].sort((a, b) => a - b)) {
|
||||
const list = byWindow.get(w)!;
|
||||
if (w === -1) {
|
||||
out.push({ window: -1, ids: list.map((x) => x.c.id), chosen: [] });
|
||||
continue;
|
||||
}
|
||||
const end = opts.start + (w + 1) * windowMs;
|
||||
if (end + settleMs > opts.now) break;
|
||||
// The share up to the end of this window, minus what was already chosen; at most three windows' worth at once.
|
||||
const target = Math.min(cap, Math.round(perWindow * (w + 1)));
|
||||
const room = Math.max(0, Math.min(target - chosenSoFar, Math.ceil(3 * perWindow), cap - chosenSoFar));
|
||||
const ranked = list.filter((x) => x.s > 0 && x.s >= floor).sort((a, b) => b.s - a.s);
|
||||
const chosen: Candidate[] = [];
|
||||
for (const { c } of ranked) {
|
||||
if (chosen.length >= room) break;
|
||||
if (chosen.some((o) => o.burst === c.burst || Math.abs(o.at - c.at) < minGapMs)) continue;
|
||||
chosen.push(c);
|
||||
}
|
||||
chosenSoFar += chosen.length;
|
||||
out.push({ window: w, ids: list.map((x) => x.c.id), chosen: chosen.sort((a, b) => a.at - b.at).map((c) => c.id) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Typical length of a match with its break, by sport (minutes). */
|
||||
export function matchMinutes(sport: string | null | undefined): number {
|
||||
const s = (sport ?? "").toLowerCase();
|
||||
if (s.includes("andebol") || s.includes("handball")) return 80;
|
||||
if (s.includes("futsal")) return 90;
|
||||
if (s.includes("basquet") || s.includes("basket")) return 110;
|
||||
if (s.includes("voleibol") || s.includes("volley")) return 100;
|
||||
return 115;
|
||||
}
|
||||
@@ -3,13 +3,15 @@ import type { Db } from "../db.js";
|
||||
import type { DeliveryService } from "../delivery/service.js";
|
||||
import type { RenderEngine } from "../develop/engine.js";
|
||||
import type { DevelopService } from "../develop/service.js";
|
||||
import { type Box, compose, frameScore, minCropWidth } from "../composition/compose.js";
|
||||
import { type Box, compose, frameScore, minCropWidth, peopleIn } from "../composition/compose.js";
|
||||
import type { SubjectDetector } from "../composition/detect.js";
|
||||
import { constrainRotated, tighter } from "../composition/geometry.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { CANDIDATE_SELECT, candidatesOf } from "./best.js";
|
||||
import { bestOf, groupBursts } from "./bursts.js";
|
||||
import { curate, matchMinutes } from "./curate.js";
|
||||
import { type LearntStyle, learntStyle, TONE_KEYS, WB_KEYS } from "./learning.js";
|
||||
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
@@ -30,6 +32,11 @@ export interface AutopilotRecord {
|
||||
/** Set when the photo's burst was decided: whether it was picked. */
|
||||
decided?: boolean;
|
||||
picked?: boolean;
|
||||
/** People in the subject (a duel, a celebration). */
|
||||
people?: number;
|
||||
/** "Only the best": set when the photo's window was decided, and whether it went into the gallery. */
|
||||
curated?: boolean;
|
||||
chosen?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,6 +136,7 @@ export class AutopilotService {
|
||||
}
|
||||
const record: AutopilotRecord = {
|
||||
score: detections ? frameScore(detections, composition) : 0,
|
||||
people: detections && composition ? peopleIn(detections, composition.subject) : 0,
|
||||
reason: composition?.reason ?? null,
|
||||
subject: composition?.subject ?? null,
|
||||
crop,
|
||||
@@ -194,15 +202,71 @@ export class AutopilotService {
|
||||
for (const f of burst) {
|
||||
await db.photo.update({ where: { id: f.id }, data: { autopilot: { ...(f.rec ?? {}), decided: true, picked: pickedIds.has(f.id) } as object } });
|
||||
}
|
||||
if (settings.deliverTargetId && toFlag.length && this.deps.deliveries && event.createdById) {
|
||||
// "Only the best" delivers per window of the match instead (below), not every burst's picks.
|
||||
if (settings.selection === "bursts" && settings.deliverTargetId && toFlag.length && this.deps.deliveries && event.createdById) {
|
||||
await this.deps.deliveries
|
||||
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: toFlag, again: false, requestedById: event.createdById })
|
||||
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued"));
|
||||
}
|
||||
}
|
||||
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
|
||||
}
|
||||
// Windows close with time, not only when photos arrive: events in "only the best" with candidates waiting.
|
||||
const waiting = await db.$queryRaw<{ event_id: string }[]>`
|
||||
SELECT DISTINCT event_id FROM photos
|
||||
WHERE autopilot_status = 'DONE' AND event_id IS NOT NULL AND (autopilot->>'decided') = 'true' AND (autopilot->>'curated') IS NULL
|
||||
AND created_at > now() - interval '1 day'`;
|
||||
for (const { event_id: eventId } of waiting) {
|
||||
if (undecided.some((u) => u.event_id === eventId)) continue;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true } });
|
||||
const settings = AutopilotSettings.parse(event?.autopilot ?? {});
|
||||
if (settings.selection === "best") picked += await this.curateEvent(eventId, settings, now);
|
||||
}
|
||||
return picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Only the best": decides the match's windows that have closed, chooses their game moments (curate.ts) and
|
||||
* delivers them. Every decided burst's frames are marked, so a window is decided once.
|
||||
*/
|
||||
private async curateEvent(eventId: string, settings: AutopilotSettings, now: Date): Promise<number> {
|
||||
const { db, log } = this.deps;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { organizationId: true, startsAt: true, sport: true, createdById: true } });
|
||||
if (!event) return 0;
|
||||
const photos = await db.photo.findMany({ where: { eventId, autopilotStatus: "DONE" }, select: CANDIDATE_SELECT });
|
||||
const decided = photos
|
||||
.filter((p) => (p.autopilot as unknown as AutopilotRecord | null)?.curated)
|
||||
.map((p) => ({ id: p.id, chosen: !!(p.autopilot as unknown as AutopilotRecord).chosen }));
|
||||
const candidates = candidatesOf(photos, settings.burstGapSec * 1000, true);
|
||||
const decisions = curate(candidates, decided, { count: settings.bestCount, start: event.startsAt.getTime(), durationMs: matchMinutes(event.sport) * 60_000, now: now.getTime() });
|
||||
const records = new Map(photos.map((p) => [p.id, p.autopilot as unknown as AutopilotRecord | null]));
|
||||
// Frames that were not their burst's candidate are decided with it.
|
||||
const burstOf = new Map<string, string[]>();
|
||||
for (const burst of groupBursts(
|
||||
photos.map((p) => ({ ...p, camera: p.cameraSerial ?? p.cameraModel ?? p.uploaderId ?? "?", score: (p.autopilot as unknown as AutopilotRecord | null)?.score ?? null })),
|
||||
settings.burstGapSec * 1000,
|
||||
)) {
|
||||
for (const f of burst) burstOf.set(f.id, burst.map((x) => x.id));
|
||||
}
|
||||
let chosenCount = 0;
|
||||
for (const d of decisions) {
|
||||
const chosen = new Set(d.chosen);
|
||||
const ids = new Set(d.ids.flatMap((id) => burstOf.get(id) ?? [id]));
|
||||
for (const id of ids) {
|
||||
const rec = records.get(id);
|
||||
if (!rec || rec.curated) continue;
|
||||
await db.photo.update({ where: { id }, data: { autopilot: { ...rec, curated: true, chosen: chosen.has(id) } as object } });
|
||||
}
|
||||
chosenCount += chosen.size;
|
||||
if (chosen.size && settings.deliverTargetId && this.deps.deliveries && event.createdById) {
|
||||
await this.deps.deliveries
|
||||
.enqueue({ organizationId: event.organizationId, targetId: settings.deliverTargetId, photoIds: [...chosen], again: false, requestedById: event.createdById })
|
||||
.catch((err: unknown) => log.warn({ err }, "autopilot: delivery not queued"));
|
||||
}
|
||||
if (d.window >= 0) log.info({ eventId, window: d.window, candidates: d.ids.length, chosen: chosen.size }, "autopilot: best of the window");
|
||||
}
|
||||
return chosenCount;
|
||||
}
|
||||
}
|
||||
|
||||
/** Polls the autopilot queue and settles bursts. */
|
||||
|
||||
@@ -235,6 +235,11 @@ function jointCost(r: Box, subject: Detection[], others: Detection[], mainSharp:
|
||||
return c;
|
||||
}
|
||||
|
||||
/** People inside the subject box (a duel, a celebration: more than one). */
|
||||
export function peopleIn(d: Detections, subject: Box): number {
|
||||
return d.people.filter((p) => p.x0 >= subject.x0 - 1e-9 && p.x1 <= subject.x1 + 1e-9 && p.y0 >= subject.y0 - 1e-9 && p.y1 <= subject.y1 + 1e-9).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* How good a frame is, to pick the best of a burst (docs/photo-editing-rules.md §3): the subject in focus (no motion
|
||||
* blur), big enough, with the ball when there is one. Only meaningful between frames of the same burst.
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { DeliveryRequest } from "@photoreport/contracts";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { DeliveryBestRequest, DeliveryRequest } from "@photoreport/contracts";
|
||||
import { bestOfEvent } from "../autopilot/best.js";
|
||||
import { PathTemplateError, renderFileName, renderFolder, buildVars } from "@photoreport/metadata";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
@@ -17,12 +19,15 @@ 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"]);
|
||||
const KIND = z.enum(["NEXTCLOUD", "SFTP", "FTP", "DROPBOX", "ZEROZERO", "LOCAL"]);
|
||||
const ADDRESS: Record<z.infer<typeof KIND>, RegExp> = {
|
||||
NEXTCLOUD: /^(https:\/\/|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)/,
|
||||
SFTP: /^sftp:\/\/[^/\s]+$/,
|
||||
FTP: /^ftps?:\/\/[^/\s]+$/,
|
||||
DROPBOX: /^https:\/\//,
|
||||
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]:[\\/])/,
|
||||
};
|
||||
const TargetBase = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
@@ -31,8 +36,8 @@ const TargetBase = z.object({
|
||||
baseUrl: z.string().trim().max(300),
|
||||
/** DROPBOX: the app key (empty for a long-lived access token). */
|
||||
username: z.string().trim().max(120),
|
||||
/** Password, Nextcloud app password, SFTP private key (PEM) or Dropbox refresh token. Write-only. */
|
||||
password: z.string().min(1).max(8000),
|
||||
/** Password, Nextcloud app password, SFTP private key (PEM) or Dropbox refresh token. Write-only. LOCAL: none. */
|
||||
password: z.string().min(1).max(8000).optional(),
|
||||
folderTemplate: z.string().trim().min(1).max(400),
|
||||
fileNameTemplate: z.string().trim().min(1).max(200),
|
||||
longEdge: z.number().int().min(800).max(12000),
|
||||
@@ -60,10 +65,13 @@ const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optiona
|
||||
const ListQuery = z.object({
|
||||
targetId: z.uuid().optional(),
|
||||
eventId: z.uuid().optional(),
|
||||
status: z.enum(["QUEUED", "RUNNING", "DONE", "FAILED"]).optional(),
|
||||
status: z.enum(["QUEUED", "RUNNING", "WAITING", "DONE", "FAILED"]).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(500).default(200),
|
||||
});
|
||||
const ShareBody = z.object({ eventId: z.uuid() });
|
||||
const GameQuery = z.object({ eventId: z.uuid() });
|
||||
/** A link or an id from fotos.zerozero.pt; null: forget the choice (and look it up again). */
|
||||
const GameBody = z.object({ eventId: z.uuid(), game: z.string().trim().min(1).max(300).nullable() });
|
||||
|
||||
function publicTarget(t: DeliveryTarget) {
|
||||
const { secretEnc: _secret, ...rest } = t;
|
||||
@@ -118,7 +126,8 @@ export async function registerDeliveryRoutes(
|
||||
const example = checkTemplates(body.folderTemplate, body.fileNameTemplate);
|
||||
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
|
||||
const { password, ...fields } = body;
|
||||
const target = await db.deliveryTarget.create({ data: { ...fields, organizationId: orgId, secretEnc: seal(password) } });
|
||||
if (!password && body.kind !== "LOCAL") throw badRequest("password_required");
|
||||
const target = await db.deliveryTarget.create({ data: { ...fields, organizationId: orgId, secretEnc: seal(password ?? "") } });
|
||||
return reply.code(201).send({ ...publicTarget(target), example });
|
||||
});
|
||||
|
||||
@@ -185,6 +194,54 @@ export async function registerDeliveryRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
/** Only the best of an event (game moments, spread over the match): chosen here, then queued like any other. */
|
||||
app.post("/v1/orgs/:orgId/deliveries/best", { preHandler: authenticate }, async (req, reply) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
const body = DeliveryBestRequest.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
const event = await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } });
|
||||
if (!event) throw notFound("event_not_found");
|
||||
const chosen = await bestOfEvent(db, event.id, body.count);
|
||||
if (body.dryRun || !chosen.length) return { chosen, queued: [], skipped: [] };
|
||||
try {
|
||||
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: chosen, again: false, requestedById: currentUserId(req) });
|
||||
return reply.code(202).send({ chosen, queued: result.queued.map(toItemSummary), skipped: result.skipped });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
// --- a folder on a computer: the desktop app there takes the rendered files -------------------------------------
|
||||
|
||||
app.post("/v1/orgs/:orgId/deliveries/local/claim", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
const { machine } = z.object({ machine: z.string().trim().min(8).max(120) }).parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
return { items: await delivery.localClaim(orgId, machine) };
|
||||
});
|
||||
|
||||
app.get("/v1/orgs/:orgId/deliveries/:itemId/local-file", { preHandler: authenticate }, async (req, reply) => {
|
||||
const { orgId, itemId } = ItemParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
const file = await delivery.localFile(orgId, itemId);
|
||||
return reply.type("image/jpeg").send(createReadStream(file));
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/v1/orgs/:orgId/deliveries/:itemId/local-result", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId, itemId } = ItemParams.parse(req.params);
|
||||
const body = z.object({ ok: z.boolean(), path: z.string().max(2000).optional(), error: z.string().max(2000).optional() }).parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
return toItemSummary(await delivery.localResult(orgId, itemId, body));
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/v1/orgs/:orgId/deliveries", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
const q = ListQuery.parse(req.query);
|
||||
@@ -211,6 +268,29 @@ export async function registerDeliveryRoutes(
|
||||
return toItemSummary(await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId } }));
|
||||
});
|
||||
|
||||
/** ZeroZero: the event's game on the photo desk (chosen, or found by teams and time). */
|
||||
app.get("/v1/orgs/:orgId/delivery-targets/:targetId/zerozero-game", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId, targetId } = TargetParams.parse(req.params);
|
||||
const { eventId } = GameQuery.parse(req.query);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
return await delivery.zerozeroGame(orgId, targetId, eventId);
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
app.put("/v1/orgs/:orgId/delivery-targets/:targetId/zerozero-game", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId, targetId } = TargetParams.parse(req.params);
|
||||
const body = GameBody.parse(req.body);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
try {
|
||||
return await delivery.setZerozeroGame(orgId, targetId, body.eventId, body.game);
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
});
|
||||
|
||||
app.post("/v1/orgs/:orgId/delivery-targets/:targetId/share", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId, targetId } = TargetParams.parse(req.params);
|
||||
const { eventId } = ShareBody.parse(req.body);
|
||||
|
||||
@@ -10,7 +10,9 @@ import type { LocalStorage } from "../storage/storage.js";
|
||||
import type { RenderEngine, Settings } from "../develop/engine.js";
|
||||
import { type DeliveryEdit, renderDelivery } from "./render.js";
|
||||
import type { SecretBox } from "./secrets.js";
|
||||
import { type Transport, type TransportKind, createTransport, isTransient } from "./transports.js";
|
||||
import { lisbonTime } from "../sports/providers.js";
|
||||
import { type Transport, type TransportKind, ZerozeroTransport, createTransport, isTransient } from "./transports.js";
|
||||
import { type ZerozeroGame, matchGame, zerozeroGameId } from "./zerozero.js";
|
||||
|
||||
export const MAX_ATTEMPTS = 5;
|
||||
/** Running items older than this belonged to a worker that died; they go back in the queue. */
|
||||
@@ -43,6 +45,9 @@ export function deliveredName(photo: { originalName: string; fileName: string |
|
||||
return photo.fileName + (dot > 0 ? photo.originalName.slice(dot) : "");
|
||||
}
|
||||
|
||||
/** Where a file rendered for a computer's folder waits on the server. */
|
||||
export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`;
|
||||
|
||||
export class DeliveryRejected extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
@@ -98,7 +103,7 @@ export class DeliveryService {
|
||||
: new Set(
|
||||
(
|
||||
await db.deliveryItem.findMany({
|
||||
where: { targetId: target.id, photoId: { in: [...found] }, status: { in: ["QUEUED", "RUNNING", "DONE"] } },
|
||||
where: { targetId: target.id, photoId: { in: [...found] }, status: { in: ["QUEUED", "RUNNING", "WAITING", "DONE"] } },
|
||||
select: { photoId: true },
|
||||
})
|
||||
).map((i) => i.photoId),
|
||||
@@ -160,10 +165,11 @@ export class DeliveryService {
|
||||
}
|
||||
|
||||
/** One connection per target (and per version of its settings), reused between items. */
|
||||
private client(target: { id: string; kind: TransportKind; baseUrl: string; username: string; secretEnc: string; hostFingerprint: string | null; updatedAt: Date }): Transport {
|
||||
private client(target: { id: string; kind: TransportKind | "LOCAL"; baseUrl: string; username: string; secretEnc: string; hostFingerprint: string | null; updatedAt: Date }): Transport {
|
||||
const key = `${target.id}:${target.updatedAt.getTime()}`;
|
||||
let client = this.transports.get(key);
|
||||
if (!client) {
|
||||
if (target.kind === "LOCAL") throw new DeliveryRejected("local_target");
|
||||
if (!this.deps.secrets) throw new DeliveryRejected("delivery_secret_key_missing");
|
||||
for (const [k, old] of this.transports) {
|
||||
if (k.startsWith(`${target.id}:`)) {
|
||||
@@ -171,9 +177,10 @@ export class DeliveryService {
|
||||
this.transports.delete(k);
|
||||
}
|
||||
}
|
||||
const kind = target.kind;
|
||||
client = createTransport(
|
||||
{
|
||||
kind: target.kind,
|
||||
kind,
|
||||
baseUrl: target.baseUrl,
|
||||
username: target.username,
|
||||
secret: this.deps.secrets.open(target.secretEnc),
|
||||
@@ -195,6 +202,8 @@ export class DeliveryService {
|
||||
async testTarget(organizationId: string, targetId: string): Promise<{ ok: true; account?: string; fingerprint?: string }> {
|
||||
const target = await this.deps.db.deliveryTarget.findFirst({ where: { id: targetId, organizationId } });
|
||||
if (!target) throw new DeliveryRejected("target_not_found");
|
||||
// A computer's folder: the desktop app there checks it (the server cannot see it).
|
||||
if (target.kind === "LOCAL") return { ok: true, account: target.baseUrl };
|
||||
return { ok: true, ...(await this.client(target).test()) };
|
||||
}
|
||||
|
||||
@@ -214,17 +223,32 @@ export class DeliveryService {
|
||||
{ capturedAt: item.photo.capturedAt ?? undefined, players: item.photo.players, sequence: item.sequence, cameraModel: item.photo.cameraModel ?? undefined, cameraSerial: item.photo.cameraSerial ?? undefined },
|
||||
item.photo.uploader?.name,
|
||||
);
|
||||
const folder = renderFolder(item.target.folderTemplate, vars);
|
||||
let folder = renderFolder(item.target.folderTemplate, vars);
|
||||
if (item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
|
||||
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
|
||||
const fileName = renderFileName(item.target.fileNameTemplate, vars, deliveredName(item.photo));
|
||||
const iptc = await iptcForPhoto(db, item.photoId);
|
||||
const edit = await this.editFor(item.photoId, item.photo.developSeq);
|
||||
const data = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit);
|
||||
const rendered = await renderDelivery(storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit);
|
||||
const data = rendered;
|
||||
if (item.target.kind === "LOCAL") {
|
||||
// Kept here until the computer's desktop app takes it (localClaim → localFile → localResult).
|
||||
await storage.write(localKey(item.organizationId, item.id), data);
|
||||
const relative = (folder + fileName).replace(/^[/\\]+/, "");
|
||||
update = { status: "WAITING", remotePath: relative, byteSize: data.length, lastError: null };
|
||||
log.info({ itemId, remotePath: relative }, "delivery: rendered for a computer's folder");
|
||||
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: update });
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
const client = this.client(item.target);
|
||||
await client.ensureFolder(folder);
|
||||
await client.upload(folder + fileName, data);
|
||||
update = { status: "DONE", remotePath: folder + fileName, byteSize: data.length, lastError: null, finishedAt: new Date() };
|
||||
log.info({ itemId, remotePath: folder + fileName }, "delivery: uploaded");
|
||||
// The author as the service shows it: the photographer's name from the IPTC creator ("Peter Spark / PhotoReport.pt").
|
||||
const creator = typeof iptc?.values.creator === "string" ? iptc.values.creator.split(" / ")[0]!.trim() : "";
|
||||
const remote = await client.upload(folder + fileName, data, { author: creator || item.photo.uploader?.name || undefined });
|
||||
const remotePath = typeof remote === "string" ? remote : folder + fileName;
|
||||
update = { status: "DONE", remotePath, byteSize: data.length, lastError: null, finishedAt: new Date() };
|
||||
log.info({ itemId, remotePath }, "delivery: uploaded");
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const retry = !(err instanceof PathTemplateError || err instanceof DeliveryRejected) && isTransient(err);
|
||||
@@ -241,6 +265,101 @@ export class DeliveryService {
|
||||
return saved;
|
||||
}
|
||||
|
||||
private zerozero(target: Parameters<DeliveryService["client"]>[0]): ZerozeroTransport {
|
||||
const client = this.client(target);
|
||||
if (!(client instanceof ZerozeroTransport)) throw new DeliveryRejected("not_zerozero");
|
||||
return client;
|
||||
}
|
||||
|
||||
/** The event's game on fotos.zerozero.pt: the one chosen, else found by teams and time (and kept). */
|
||||
private async zerozeroGameId(target: Parameters<DeliveryService["client"]>[0], event: { id: string; home: string; away: string; startsAt: Date; zerozeroGameId: string | null } | null): Promise<string> {
|
||||
if (!event) throw new DeliveryRejected("zerozero_game_not_found");
|
||||
if (event.zerozeroGameId) return event.zerozeroGameId;
|
||||
const game = await this.findZerozeroGame(target, event);
|
||||
if (!game) throw new DeliveryRejected("zerozero_game_not_found");
|
||||
await this.deps.db.event.update({ where: { id: event.id }, data: { zerozeroGameId: game.id } });
|
||||
event.zerozeroGameId = game.id;
|
||||
return game.id;
|
||||
}
|
||||
|
||||
private async findZerozeroGame(target: Parameters<DeliveryService["client"]>[0], event: { home: string; away: string; startsAt: Date }): Promise<ZerozeroGame | null> {
|
||||
const games = await this.zerozero(target).client.upcoming();
|
||||
return matchGame(games, event, (d) => lisbonTime(d.slice(0, 10), d.slice(11, 16)).at);
|
||||
}
|
||||
|
||||
/** The event's game on a ZeroZero target, for the person sending: the chosen one, or the one found (not kept). */
|
||||
async zerozeroGame(organizationId: string, targetId: string, eventId: string): Promise<{ game: ZerozeroGame | null; chosen: boolean }> {
|
||||
const { db } = this.deps;
|
||||
const target = await db.deliveryTarget.findFirst({ where: { id: targetId, organizationId, kind: "ZEROZERO" } });
|
||||
const event = await db.event.findFirst({ where: { id: eventId, organizationId } });
|
||||
if (!target || !event) throw new DeliveryRejected("not_found");
|
||||
if (event.zerozeroGameId) return { game: await this.zerozero(target).client.game(event.zerozeroGameId), chosen: true };
|
||||
return { game: await this.findZerozeroGame(target, event), chosen: false };
|
||||
}
|
||||
|
||||
/** Chooses the event's game (a link or an id from fotos.zerozero.pt), checked on the desk; null forgets it. */
|
||||
async setZerozeroGame(organizationId: string, targetId: string, eventId: string, input: string | null): Promise<{ game: ZerozeroGame | null; chosen: boolean }> {
|
||||
const { db } = this.deps;
|
||||
const target = await db.deliveryTarget.findFirst({ where: { id: targetId, organizationId, kind: "ZEROZERO" } });
|
||||
const event = await db.event.findFirst({ where: { id: eventId, organizationId } });
|
||||
if (!target || !event) throw new DeliveryRejected("not_found");
|
||||
if (input === null) {
|
||||
await db.event.update({ where: { id: event.id }, data: { zerozeroGameId: null } });
|
||||
return { game: await this.findZerozeroGame(target, event), chosen: false };
|
||||
}
|
||||
const id = zerozeroGameId(input);
|
||||
if (!id) throw new DeliveryRejected("invalid_zerozero_game");
|
||||
const game = await this.zerozero(target).client.game(id);
|
||||
await db.event.update({ where: { id: event.id }, data: { zerozeroGameId: game.id } });
|
||||
return { game, chosen: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* The desktop app of a computer takes what is waiting for its folders: marked running (a crash puts them back in
|
||||
* the queue after 10 minutes, rendered again), with where each file goes under the folder.
|
||||
*/
|
||||
async localClaim(organizationId: string, machine: string, limit = 10): Promise<{ id: string; folder: string; path: string; byteSize: number | null }[]> {
|
||||
const { db } = this.deps;
|
||||
const waiting = await db.deliveryItem.findMany({
|
||||
where: { organizationId, status: "WAITING", target: { kind: "LOCAL", username: machine, disabledAt: null } },
|
||||
include: { target: { select: { baseUrl: true } } },
|
||||
orderBy: { sequence: "asc" },
|
||||
take: limit,
|
||||
});
|
||||
const out: { id: string; folder: string; path: string; byteSize: number | null }[] = [];
|
||||
for (const item of waiting) {
|
||||
const taken = await db.deliveryItem.updateMany({ where: { id: item.id, status: "WAITING" }, data: { status: "RUNNING", startedAt: new Date() } });
|
||||
if (taken.count) out.push({ id: item.id, folder: item.target.baseUrl, path: item.remotePath ?? "", byteSize: item.byteSize });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The rendered file of an item a computer took. */
|
||||
async localFile(organizationId: string, itemId: string): Promise<string> {
|
||||
const item = await this.deps.db.deliveryItem.findFirst({ where: { id: itemId, organizationId, status: { in: ["RUNNING", "WAITING"] }, target: { kind: "LOCAL" } } });
|
||||
if (!item) throw new DeliveryRejected("not_found");
|
||||
const key = localKey(organizationId, itemId);
|
||||
if (!(await this.deps.storage.exists(key))) throw new DeliveryRejected("not_found");
|
||||
return this.deps.storage.resolve(key);
|
||||
}
|
||||
|
||||
/** What the computer did with it: saved (where), or why not. */
|
||||
async localResult(organizationId: string, itemId: string, result: { ok: boolean; path?: string | undefined; error?: string | undefined }): Promise<DeliveryItem> {
|
||||
const { db, storage } = this.deps;
|
||||
const item = await db.deliveryItem.findFirst({ where: { id: itemId, organizationId, status: { in: ["RUNNING", "WAITING"] }, target: { kind: "LOCAL" } }, include: { target: true, event: true } });
|
||||
if (!item) throw new DeliveryRejected("not_found");
|
||||
const saved = await db.deliveryItem.update({
|
||||
where: { id: itemId },
|
||||
data: result.ok
|
||||
? { status: "DONE", remotePath: result.path ?? item.remotePath, lastError: null, finishedAt: new Date() }
|
||||
: { status: "FAILED", lastError: result.error?.slice(0, 500) ?? "not saved", finishedAt: new Date() },
|
||||
});
|
||||
await storage.remove(localKey(organizationId, itemId));
|
||||
if (saved.status === "FAILED") await this.deps.notifications?.notifyRole(saved.organizationId, "ADMIN", { type: "delivery_failed", key: `target:${item.targetId}`, payload: { target: item.target.name, event: item.event ? eventName(item.event) : null, error: saved.lastError } });
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
|
||||
/** Public link to the event's folder on the target (for the client or the press). */
|
||||
async shareEventFolder(organizationId: string, targetId: string, eventId: string): Promise<{ folder: string; url: string }> {
|
||||
const { db } = this.deps;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Readable } from "node:stream";
|
||||
import { Client as FtpClient } from "basic-ftp";
|
||||
import SftpClient from "ssh2-sftp-client";
|
||||
import { NextcloudClient, NextcloudError } from "./nextcloud.js";
|
||||
import { ZerozeroClient } from "./zerozero.js";
|
||||
|
||||
/**
|
||||
* Where deliveries go. Every kind does the same three things: make the folder, put the file (replacing one with the
|
||||
@@ -12,10 +13,18 @@ import { NextcloudClient, NextcloudError } from "./nextcloud.js";
|
||||
* remembered on first contact and checked from then on.
|
||||
* - FTP: plain or explicit TLS (`ftps://`), for older newsroom servers.
|
||||
* - DROPBOX: the Dropbox API, with a refresh token (app key + refresh token) or a long-lived access token.
|
||||
* - ZEROZERO: fotos.zerozero.pt, a match's page on zerozero.pt's photo desk (zerozero.ts). The "folder" is the
|
||||
* game's id, and the photo goes up with its author's name.
|
||||
*/
|
||||
export interface UploadMeta {
|
||||
/** The photographer, as the service shows the photo's author. */
|
||||
author?: string | undefined;
|
||||
}
|
||||
|
||||
export interface Transport {
|
||||
ensureFolder(folder: string): Promise<void>;
|
||||
upload(remoteFile: string, data: Buffer): Promise<void>;
|
||||
/** Returns where the photo ended up when the service names it (an id), else nothing. */
|
||||
upload(remoteFile: string, data: Buffer, meta?: UploadMeta): Promise<void | string>;
|
||||
/** Public read-only link to a folder; undefined when the service has none. */
|
||||
shareLink?(folder: string): Promise<string>;
|
||||
/** Connects and checks the credentials; SFTP also reports the host key fingerprint. */
|
||||
@@ -33,7 +42,7 @@ export class TransportError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type TransportKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX";
|
||||
export type TransportKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX" | "ZEROZERO";
|
||||
|
||||
export interface TransportConfig {
|
||||
kind: TransportKind;
|
||||
@@ -64,9 +73,35 @@ export function createTransport(config: TransportConfig, fetchImpl: typeof fetch
|
||||
return new FtpTransport(config);
|
||||
case "DROPBOX":
|
||||
return new DropboxTransport(config, fetchImpl);
|
||||
case "ZEROZERO":
|
||||
return new ZerozeroTransport(new ZerozeroClient({ username: config.username, password: config.secret }, fetchImpl));
|
||||
}
|
||||
}
|
||||
|
||||
/** fotos.zerozero.pt: the folder is the game's id ("12627747/"), checked once; the file keeps its name. */
|
||||
export class ZerozeroTransport implements Transport {
|
||||
constructor(readonly client: ZerozeroClient) {}
|
||||
async ensureFolder(folder: string) {
|
||||
const id = folder.replace(/\/+$/, "");
|
||||
if (!/^\d+$/.test(id)) throw new TransportError("zerozero: no game chosen for this event", false);
|
||||
await this.client.game(id);
|
||||
}
|
||||
async upload(remoteFile: string, data: Buffer, meta?: UploadMeta) {
|
||||
const slash = remoteFile.indexOf("/");
|
||||
const gameId = remoteFile.slice(0, slash);
|
||||
const fileName = remoteFile.slice(slash + 1);
|
||||
const account = await this.client.login();
|
||||
const author = meta?.author?.trim() || account.name || "PhotoReport";
|
||||
const imageId = await this.client.upload(gameId, fileName, data, author);
|
||||
return `${gameId}/${imageId}`;
|
||||
}
|
||||
async test() {
|
||||
const account = await this.client.login();
|
||||
return { account: account.name ?? account.role };
|
||||
}
|
||||
async close() {}
|
||||
}
|
||||
|
||||
class NextcloudTransport implements Transport {
|
||||
constructor(private readonly client: NextcloudClient) {}
|
||||
ensureFolder(folder: string) {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
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");
|
||||
|
||||
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: ${(err as Error).message}`, 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) throw new TransportError(`zerozero upload: ${res.status} at ${offset} bytes`, 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. */
|
||||
async remove(imageId: string): Promise<void> {
|
||||
await this.json(`/images/${encodeURIComponent(imageId)}`, { method: "DELETE" });
|
||||
}
|
||||
}
|
||||
|
||||
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"]);
|
||||
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 {
|
||||
const wa = words(a);
|
||||
const wb = words(b);
|
||||
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;
|
||||
}
|
||||
@@ -167,9 +167,13 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "INGESTER");
|
||||
const people = await db.person.findMany({ where: { organizationId: orgId }, orderBy: [{ club: "asc" }, { name: "asc" }] });
|
||||
// The full name from the squad ("Ana Sofia Osorio Sousa" for "Ana Sousa"), so people can be found by any of it.
|
||||
const ids = people.map((p) => p.sportsPlayerId).filter((id): id is string => !!id);
|
||||
const full = new Map((await db.sportsPlayer.findMany({ where: { id: { in: ids } }, select: { id: true, fullName: true } })).map((s) => [s.id, s.fullName]));
|
||||
return {
|
||||
people: people.map((p) => ({
|
||||
...personOut(p)!,
|
||||
fullName: (p.sportsPlayerId && full.get(p.sportsPlayerId)) || null,
|
||||
faceCount: p.faceCount,
|
||||
reference: p.referenceKey ? { status: p.referenceStatus, url: signer.personUrl(p.id) } : null,
|
||||
})),
|
||||
|
||||
@@ -9,6 +9,8 @@ import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox
|
||||
import type { JerseyReading } from "../jersey/model.js";
|
||||
import { normLabel } from "../jersey/service.js";
|
||||
|
||||
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
|
||||
const STRONG_SUGGESTION = 0.85;
|
||||
/** Below this the shirt-number reading is not used for suggestions. */
|
||||
export const JERSEY_MIN_SCORE = 0.7;
|
||||
export interface NumberVote {
|
||||
@@ -228,9 +230,18 @@ export class FaceService {
|
||||
if (ok && read && first.p.number && normLabel(first.p.number) !== read.number && read.votes >= 2) {
|
||||
// The face says one person, the shirt clearly says another number: still suggested, but as less sure.
|
||||
suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000;
|
||||
} else if (ok && read && normLabel(first.p.number) === read.number) {
|
||||
// Face and shirt agree on the same player: surer than either alone.
|
||||
suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000;
|
||||
} else if (!ok && read) {
|
||||
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones.
|
||||
const near = ranked.filter((r) => r.s >= match * 0.8 && normLabel(r.p.number) === read.number);
|
||||
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones,
|
||||
// and when two of them wear it (one per team), the kit colour.
|
||||
let near = ranked.filter((r) => r.s >= match * 0.8 && normLabel(r.p.number) === read.number);
|
||||
if (near.length > 1) {
|
||||
const team = await this.teamByKit(g.id, eventId);
|
||||
const onTeam = team ? await this.playersOfTeam(near.map((r) => r.p), team.teamId) : null;
|
||||
if (onTeam) near = near.filter((r) => onTeam.has(r.p.id));
|
||||
}
|
||||
if (near.length === 1) {
|
||||
suggestedPersonId = near[0]!.p.id;
|
||||
suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000;
|
||||
@@ -292,6 +303,13 @@ export class FaceService {
|
||||
return { personId: candidates[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
|
||||
}
|
||||
|
||||
/** Which of these people play for the team (by their squad entry). */
|
||||
private async playersOfTeam(people: { id: string; sportsPlayerId: string | null }[], teamId: string): Promise<Set<string>> {
|
||||
const ids = people.map((p) => p.sportsPlayerId).filter((x): x is string => !!x);
|
||||
const onTeam = new Set((await this.deps.db.sportsPlayer.findMany({ where: { id: { in: ids }, teamId }, select: { id: true } })).map((p) => p.id));
|
||||
return new Set(people.filter((p) => p.sportsPlayerId && onTeam.has(p.sportsPlayerId)).map((p) => p.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of the event's two teams a group plays for, by kit colour: each team's colour comes from the faces of its
|
||||
* players already confirmed in this event (goalkeepers left out: they wear their own colours). Null unless one team
|
||||
@@ -304,15 +322,25 @@ export class FaceService {
|
||||
const median = (cols: number[][]) => (cols.length ? [0, 1, 2].map((c) => cols.map((v) => v[c]!).sort((a, b) => a - b)[cols.length >> 1]!) : null);
|
||||
const mine = median((await db.face.findMany({ where: { groupId }, select: { kitColour: true } })).map((f) => f.kitColour).filter((k) => k.length === 3));
|
||||
if (!mine) return null;
|
||||
const confirmed = await db.face.findMany({
|
||||
where: { photo: { eventId }, group: { personId: { not: null } }, NOT: { kitColour: { isEmpty: true } } },
|
||||
select: { kitColour: true, group: { select: { person: { select: { sportsPlayerId: true } } } } },
|
||||
// Players confirmed here, and groups suggested with face and shirt agreeing (score 0.85 and up): learnt as the
|
||||
// match goes, before anyone confirms anything.
|
||||
const known = await db.face.findMany({
|
||||
where: {
|
||||
photo: { eventId },
|
||||
groupId: { not: groupId },
|
||||
NOT: { kitColour: { isEmpty: true } },
|
||||
OR: [{ group: { personId: { not: null } } }, { group: { suggestionScore: { gte: STRONG_SUGGESTION } } }],
|
||||
},
|
||||
select: { kitColour: true, group: { select: { personId: true, suggestedPersonId: true } } },
|
||||
});
|
||||
const ids = [...new Set(confirmed.map((f) => f.group?.person?.sportsPlayerId).filter((x): x is string => !!x))];
|
||||
const personIds = [...new Set(known.map((f) => f.group?.personId ?? f.group?.suggestedPersonId).filter((x): x is string => !!x))];
|
||||
const sportsOf = new Map((await db.person.findMany({ where: { id: { in: personIds } }, select: { id: true, sportsPlayerId: true } })).map((p) => [p.id, p.sportsPlayerId]));
|
||||
const confirmed = known.map((f) => ({ kitColour: f.kitColour, sportsPlayerId: sportsOf.get(f.group?.personId ?? f.group?.suggestedPersonId ?? "") ?? null }));
|
||||
const ids = [...new Set(confirmed.map((f) => f.sportsPlayerId).filter((x): x is string => !!x))];
|
||||
const players = new Map((await db.sportsPlayer.findMany({ where: { id: { in: ids } }, select: { id: true, teamId: true, position: true } })).map((p) => [p.id, p]));
|
||||
const byTeam = new Map<string, number[][]>();
|
||||
for (const f of confirmed) {
|
||||
const spId = f.group?.person?.sportsPlayerId;
|
||||
const spId = f.sportsPlayerId;
|
||||
const sp = spId ? players.get(spId) : undefined;
|
||||
if (!sp || /guarda|gr\b|goal/i.test(sp.position ?? "")) continue;
|
||||
byTeam.set(sp.teamId, [...(byTeam.get(sp.teamId) ?? []), f.kitColour]);
|
||||
|
||||
@@ -63,8 +63,12 @@ export function numberBoxes(face: Box, width: number, height: number): { region:
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The crop the model sees and people review: from the original, upright, at most 256 px on the long side. */
|
||||
export async function cropJpeg(original: string, box: Box, size = 256): Promise<Buffer> {
|
||||
/**
|
||||
* The crop the model sees and people review: from the stored photo (the original, or the 2048 px preview the desktop
|
||||
* app sends), upright, at its own resolution up to 512 px on the long side (never enlarged: a small number stays as
|
||||
* sharp as the photo has it; the model scales it itself).
|
||||
*/
|
||||
export async function cropJpeg(original: string, box: Box, size = 512): Promise<Buffer> {
|
||||
const img = sharp(original).rotate();
|
||||
const meta = await img.metadata();
|
||||
const w = meta.autoOrient?.width ?? meta.width ?? 1;
|
||||
@@ -73,7 +77,7 @@ export async function cropJpeg(original: string, box: Box, size = 256): Promise<
|
||||
const top = Math.round(box.y0 * h);
|
||||
const width = Math.max(1, Math.min(w - left, Math.round((box.x1 - box.x0) * w)));
|
||||
const height = Math.max(1, Math.min(h - top, Math.round((box.y1 - box.y0) * h)));
|
||||
return sharp(original).rotate().extract({ left, top, width, height }).resize({ width: size, height: size, fit: "inside" }).jpeg({ quality: 90 }).toBuffer();
|
||||
return sharp(original).rotate().extract({ left, top, width, height }).resize({ width: size, height: size, fit: "inside", withoutEnlargement: true }).jpeg({ quality: 92 }).toBuffer();
|
||||
}
|
||||
|
||||
/** A photo decoded once, small: enough to tell the colour of a kit. */
|
||||
|
||||
@@ -44,7 +44,7 @@ export class JerseyService {
|
||||
}
|
||||
|
||||
cropUrl(id: string): string {
|
||||
return `/v1/jersey/samples/${id}/crop?sig=${this.sig(id)}`;
|
||||
return `/v1/jersey/samples/${id}/crop?sig=${this.sig(id)}&v=2`;
|
||||
}
|
||||
|
||||
checkSig(id: string, sig: string): boolean {
|
||||
@@ -123,7 +123,8 @@ export class JerseyService {
|
||||
/** The crop, made from the original on first request and cached. */
|
||||
async cropFile(sample: JerseySample): Promise<string> {
|
||||
const { db, storage } = this.deps;
|
||||
const key = `${sample.organizationId}/jersey/${sample.id}.jpg`;
|
||||
// v2: up to 512 px (the first crops were cut down to 256 px and looked soft).
|
||||
const key = `${sample.organizationId}/jersey/${sample.id}-v2.jpg`;
|
||||
if (!(await storage.exists(key))) {
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: sample.photoId }, select: { storageKey: true } });
|
||||
await storage.write(key, await cropJpeg(storage.resolve(photo.storageKey), sample));
|
||||
|
||||
@@ -20,6 +20,8 @@ export interface TeamData {
|
||||
abbreviation?: string | null;
|
||||
logoUrl?: string | null;
|
||||
venue?: string | null;
|
||||
/** FPA: the club the team belongs to (its games and levels are listed per club). Not stored. */
|
||||
clubId?: string | null;
|
||||
}
|
||||
|
||||
export interface PlayerData {
|
||||
@@ -49,6 +51,17 @@ export interface FixtureData {
|
||||
venue?: string | null;
|
||||
homeScore?: number | null;
|
||||
awayScore?: number | null;
|
||||
/** The referee team (UEFA publishes it before the match). */
|
||||
officials?: OfficialData[] | null;
|
||||
}
|
||||
|
||||
export interface OfficialData {
|
||||
name: string;
|
||||
/** REFEREE, ASSISTANT_REFEREE_ONE, FOURTH_OFFICIAL, VIDEO_ASSISTANT_REFEREE, UEFA_DELEGATE, TABLE_OFFICIAL, DELEGATE... */
|
||||
role: string;
|
||||
/** FPA: licence number (CIPA) and full name, from the match report. */
|
||||
externalId?: string | null;
|
||||
fullName?: string | null;
|
||||
}
|
||||
|
||||
const TIMEOUT_MS = 20_000;
|
||||
@@ -197,17 +210,236 @@ function ligaTeam(t: unknown): TeamData | null {
|
||||
|
||||
// --- FPA (andebol) ------------------------------------------------------------------------------------------------
|
||||
|
||||
/** Officials' cards on the handball bench: "Oficial A" … "Oficial F" (B is usually the head coach). */
|
||||
const FPA_OFFICIAL = /^Oficial ([A-F])$/;
|
||||
/** The game's officials in the match report, as roles. */
|
||||
const FPA_GAME_OFFICIAL: [RegExp, string][] = [
|
||||
[/^Árbitro \d/, "REFEREE"],
|
||||
[/^Oficial (de )?Mesa/i, "TABLE_OFFICIAL"],
|
||||
[/^Delegado/i, "DELEGATE"],
|
||||
];
|
||||
|
||||
/**
|
||||
* The FPA's public pages, the same the portal links to: the agenda (JSON), a club's games of a season and level
|
||||
* (JSON), the match report ("Boletim do Jogo": every player with shirt number and licence number, the bench officials
|
||||
* with their letter, the referees), a match page (the referees, published before the match) and an athlete's page
|
||||
* (the licence photo). Asked for sparingly and cached in the database.
|
||||
*/
|
||||
export class FpaProvider {
|
||||
static readonly AGENDA = "https://ws.fpa.pt/index.php/getAgendaJogosFAP/";
|
||||
static readonly WS = "https://ws.fpa.pt/index.php";
|
||||
static readonly PORTAL = "https://portal.fpa.pt";
|
||||
static readonly BOLETIM = "https://si.fpa.pt/fap_sa/usrpck_print.print_boletim";
|
||||
private static readonly HTML = { accept: "text/html", "accept-language": "pt-PT,pt;q=0.9", "user-agent": "PhotoReport/2 (sports data)" };
|
||||
|
||||
constructor(private readonly fetcher: Fetch) {}
|
||||
constructor(
|
||||
private readonly fetcher: Fetch,
|
||||
private readonly delayMs = 800,
|
||||
) {}
|
||||
|
||||
/** The federation's whole agenda (national competitions, recent and upcoming). */
|
||||
private async pause() {
|
||||
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
|
||||
}
|
||||
|
||||
/** An HTML page in whatever charset it declares (the match report is windows-1252). */
|
||||
private async html(u: string): Promise<string> {
|
||||
const res = await this.fetcher(u, { headers: FpaProvider.HTML, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`${new URL(u).host} ${new URL(u).pathname} ${res.status}`);
|
||||
const bytes = Buffer.from(await res.arrayBuffer());
|
||||
await this.pause();
|
||||
const head = bytes.subarray(0, 2048).toString("latin1");
|
||||
const charset = /charset=["']?([\w-]+)/i.exec(head)?.[1]?.toLowerCase() ?? "utf-8";
|
||||
try {
|
||||
return new TextDecoder(charset).decode(bytes);
|
||||
} catch {
|
||||
return bytes.toString("utf8");
|
||||
}
|
||||
}
|
||||
|
||||
/** The federation's whole agenda (national competitions, upcoming). */
|
||||
async agenda(): Promise<FixtureData[]> {
|
||||
const rows = await get(this.fetcher, FpaProvider.AGENDA, { accept: "application/json" }, "json");
|
||||
if (!Array.isArray(rows)) throw new Error("fpa: unexpected agenda");
|
||||
return (rows as Record<string, unknown>[]).map(fpaFixture).filter((f): f is FixtureData => !!f);
|
||||
}
|
||||
|
||||
/** The portal's ids for a club's current season and its levels ("Seniores M" → 4), from the club page. */
|
||||
async clubTerms(clubId: string): Promise<{ season: string | null; levels: { id: string; name: string }[] }> {
|
||||
return parseFpaClubTerms(await this.html(`${FpaProvider.PORTAL}/clube/id/${encodeURIComponent(clubId)}/`));
|
||||
}
|
||||
|
||||
/** A club's games of a season and level (played and to play). */
|
||||
async clubGames(clubId: string, season: string, level: string): Promise<FixtureData[]> {
|
||||
const path = ["getJogosClubeEpocaEscalao", clubId, season, level].map(encodeURIComponent).join("/");
|
||||
const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json");
|
||||
await this.pause();
|
||||
if (!Array.isArray(rows)) return [];
|
||||
return (rows as Record<string, unknown>[]).map(fpaFixture).filter((f): f is FixtureData => !!f);
|
||||
}
|
||||
|
||||
/** The match report: empty until the game is played. */
|
||||
async boletim(gameId: string): Promise<FpaBoletim> {
|
||||
const q = new URLSearchParams({ p_sessao: "1", P_ID_PROVA_JOGO: gameId, p_layout: "P300632" });
|
||||
return parseFpaBoletim(await this.html(`${FpaProvider.BOLETIM}?${q}`));
|
||||
}
|
||||
|
||||
/** The referees named on the match page (published some days before the match). */
|
||||
async referees(gameId: string): Promise<OfficialData[]> {
|
||||
return (await this.matchPage(gameId)).officials;
|
||||
}
|
||||
|
||||
/** The match page: referees and table officials by name, and (once played) both teams with licence numbers. */
|
||||
async matchPage(gameId: string): Promise<FpaMatchPage> {
|
||||
return parseFpaMatchPage(await this.html(`${FpaProvider.PORTAL}/jogo/${encodeURIComponent(gameId)}/`));
|
||||
}
|
||||
|
||||
/** An athlete's licence photo (by licence number), if the federation has one. */
|
||||
async athletePhoto(cipa: string): Promise<string | null> {
|
||||
const html = await this.html(`${FpaProvider.PORTAL}/associado/${encodeURIComponent(cipa)}/`);
|
||||
return /https:\/\/si\.fpa\.pt\/blob\/obj_anexo\/FOTO_CIPA\/\d+_\d+\.(?:jpe?g|png)/i.exec(html)?.[0] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface FpaBoletim {
|
||||
/** Whether the report has the teams yet (it is filled in after the match). */
|
||||
available: boolean;
|
||||
home: PlayerData[];
|
||||
away: PlayerData[];
|
||||
referees: OfficialData[];
|
||||
}
|
||||
|
||||
/** "Emanuel Jose Oliveira Ribeiro" → "Emanuel Ribeiro" (as captions name players); the full name is kept too. */
|
||||
export function fpaShortName(full: string): string {
|
||||
const words = full.trim().split(/\s+/);
|
||||
return words.length <= 2 ? words.join(" ") : `${words[0]} ${words[words.length - 1]}`;
|
||||
}
|
||||
|
||||
const cellText = (s: string) => s.replace(/\s+/g, " ").trim();
|
||||
|
||||
/**
|
||||
* The "Boletim do Jogo": for each team (Equipa A at home, Equipa B away) the rows "Nº | CIPA | Nome | …" and
|
||||
* "Oficial A | Grau … | Nome | …"; then "Árbitro 1" with "Nome:" and "CIPA:" rows.
|
||||
*/
|
||||
export function parseFpaBoletim(html: string): FpaBoletim {
|
||||
const $ = cheerio.load(html);
|
||||
const rows: string[][] = [];
|
||||
$("tr").each((_, tr) => {
|
||||
if ($(tr).find("table").length) return;
|
||||
const cells = $(tr)
|
||||
.children("td,th")
|
||||
.map((_, td) => cellText($(td).text()))
|
||||
.get();
|
||||
if (cells.some(Boolean)) rows.push(cells);
|
||||
});
|
||||
const sides: Record<"home" | "away", { number: string | null; full: string; cipa: string | null; official?: string }[]> = { home: [], away: [] };
|
||||
const referees: OfficialData[] = [];
|
||||
let side: "home" | "away" | null = null;
|
||||
let referee: string | null = null;
|
||||
for (const r of rows) {
|
||||
const first = r[0] ?? "";
|
||||
if (/^Equipa A ::/.test(first)) side = "home";
|
||||
else if (/^Equipa B ::/.test(first)) side = "away";
|
||||
else if (FPA_GAME_OFFICIAL.some(([re]) => re.test(first))) {
|
||||
side = null;
|
||||
referee = FPA_GAME_OFFICIAL.find(([re]) => re.test(first))![1];
|
||||
} else if (/^(Observador|Director|Diretor|Cronometrista|Secret|Médico|Medico)/i.test(first)) {
|
||||
side = null;
|
||||
referee = null;
|
||||
} else if (first === "Nome:" && referee && r[1]) {
|
||||
referees.push({ name: fpaShortName(r[1]), fullName: r[1], role: referee, externalId: null });
|
||||
} else if (first === "CIPA:" && referee && /^\d{3,8}$/.test(r[1] ?? "") && referees.length) {
|
||||
referees[referees.length - 1]!.externalId = r[1]!;
|
||||
referee = null;
|
||||
} else if (side && /^\d{1,3}$/.test(first) && /^\d{3,8}$/.test(r[1] ?? "") && r[2]) {
|
||||
sides[side].push({ number: String(Number(first)), cipa: r[1]!, full: r[2] });
|
||||
} else if (side && FPA_OFFICIAL.test(first)) {
|
||||
const name = r.slice(1).find((c) => c && !/^(Grau|Trei)/i.test(c) && /[A-Za-zÀ-ÿ]{2,}\s+[A-Za-zÀ-ÿ]/.test(c));
|
||||
if (name) sides[side].push({ number: FPA_OFFICIAL.exec(first)![1]!, cipa: null, full: name, official: first });
|
||||
}
|
||||
}
|
||||
const toPlayers = (list: (typeof sides)["home"]): PlayerData[] => {
|
||||
const shortCount = new Map<string, number>();
|
||||
for (const p of list) shortCount.set(fpaShortName(p.full), (shortCount.get(fpaShortName(p.full)) ?? 0) + 1);
|
||||
return list.map((p) => {
|
||||
const short = fpaShortName(p.full);
|
||||
return {
|
||||
externalId: p.cipa,
|
||||
number: p.number,
|
||||
name: (shortCount.get(short) ?? 0) > 1 ? p.full : short,
|
||||
fullName: p.full,
|
||||
position: p.official ?? null,
|
||||
};
|
||||
});
|
||||
};
|
||||
const home = toPlayers(sides.home);
|
||||
const away = toPlayers(sides.away);
|
||||
return { available: home.length + away.length > 0, home, away, referees };
|
||||
}
|
||||
|
||||
export interface FpaMatchPage {
|
||||
/** Referees and table officials by name (no licence number on this page). */
|
||||
officials: OfficialData[];
|
||||
/** Licence numbers of each team's bench officials by card letter (the report gives their coaching grade instead). */
|
||||
benchCipa: { home: Map<string, string>; away: Map<string, string> };
|
||||
}
|
||||
|
||||
/**
|
||||
* The match page: rows "Árbitros | Name One, Name Two" and "Oficiais de Mesa | …" (shown in capitals by the site's
|
||||
* style); once played, a pane per team ("team-a", "team-b") with "Nº | Nº CIPA | Nome" rows, bench officials included.
|
||||
*/
|
||||
export function parseFpaMatchPage(html: string): FpaMatchPage {
|
||||
const $ = cheerio.load(html);
|
||||
const officials: OfficialData[] = [];
|
||||
const roles: [RegExp, string][] = [
|
||||
[/^árbitros$/i, "REFEREE"],
|
||||
[/^oficiais de mesa$/i, "TABLE_OFFICIAL"],
|
||||
];
|
||||
const done = new Set<string>();
|
||||
$("td,th").each((_, td) => {
|
||||
const label = cellText($(td).text());
|
||||
const role = roles.find(([re]) => re.test(label))?.[1];
|
||||
if (!role || done.has(role)) return;
|
||||
done.add(role);
|
||||
for (const name of cellText($(td).next().text()).split(/\s*,\s*/)) {
|
||||
if (/[A-Za-zÀ-ÿ]{2,}\s+[A-Za-zÀ-ÿ]/.test(name) && name.length < 80) officials.push({ name: name.trim(), role });
|
||||
}
|
||||
});
|
||||
const benchCipa = { home: new Map<string, string>(), away: new Map<string, string>() };
|
||||
for (const [pane, side] of [
|
||||
["team-a", "home"],
|
||||
["team-b", "away"],
|
||||
] as const) {
|
||||
$(`[data-pane="${pane}"] .module-table__row`).each((_, row) => {
|
||||
const letter = FPA_OFFICIAL.exec(cellText($(row).children().first().text()))?.[1];
|
||||
const cipa = cellText($(row).find('a[href*="/associado/"]').first().text());
|
||||
if (letter && /^\d{3,8}$/.test(cipa)) benchCipa[side].set(letter, cipa);
|
||||
});
|
||||
}
|
||||
return { officials, benchCipa };
|
||||
}
|
||||
|
||||
/** The referees and table officials named on the match page. */
|
||||
export function parseFpaReferees(html: string): OfficialData[] {
|
||||
return parseFpaMatchPage(html).officials;
|
||||
}
|
||||
|
||||
/** The club page carries its selectors as JSON: the first season is the current one. */
|
||||
export function parseFpaClubTerms(html: string): { season: string | null; levels: { id: string; name: string }[] } {
|
||||
const options = (id: string) => {
|
||||
const at = html.indexOf(`"id":"${id}"`);
|
||||
if (at === -1) return [];
|
||||
const open = html.indexOf("[", at);
|
||||
const close = html.indexOf("]", open);
|
||||
if (open === -1 || close === -1) return [];
|
||||
try {
|
||||
return (JSON.parse(html.slice(open, close + 1)) as { term_id?: unknown; name?: unknown }[])
|
||||
.map((o) => ({ id: str(o.term_id) ?? "", name: cellText(String(o.name ?? "")) }))
|
||||
.filter((o) => o.id);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
return { season: options("season")[0]?.id ?? null, levels: options("level") };
|
||||
}
|
||||
|
||||
/** "PO01 - Campeonato Betclic Masculino" → PO01 and its name; "PARTICULARES SELECOES NACIONAIS" has no code. */
|
||||
@@ -226,22 +458,22 @@ function fpaFixture(r: Record<string, unknown>): FixtureData | null {
|
||||
const awayId = str(r.EQUIPA_FORA_ID);
|
||||
if (!prova || !day || !id || !homeName || !awayName || !homeId || !awayId) return null;
|
||||
const { at, timeKnown } = lisbonTime(day, str(r.JOG_HORA));
|
||||
const goals = (v: unknown) => (v === null || v === undefined || v === "" ? null : Number(v));
|
||||
const goals = (v: unknown) => (v === null || v === undefined || v === "" || v === "null" || !Number.isFinite(Number(v)) ? null : Number(v));
|
||||
return {
|
||||
externalId: id,
|
||||
competition: prova.code,
|
||||
competitionName: prova.name,
|
||||
gender: str(r.PRO_SEXO),
|
||||
season: seasonOf(at),
|
||||
home: { externalId: homeId, name: homeName },
|
||||
away: { externalId: awayId, name: awayName },
|
||||
home: { externalId: homeId, name: homeName, clubId: str(r.CLUBE_CASA_ID) },
|
||||
away: { externalId: awayId, name: awayName, clubId: str(r.CLUBE_FORA_ID) },
|
||||
startsAt: at,
|
||||
timeKnown,
|
||||
round: str(r.FASE),
|
||||
matchNumber: str(r.JOG_NUM_JOGO),
|
||||
venue: str(r.LOCAL),
|
||||
homeScore: goals(r.GOLOS_CASA),
|
||||
awayScore: goals(r.GOLOS_FORA),
|
||||
homeScore: goals(r.GOLOS_CASA ?? r.JOG_GOLOS_CASA),
|
||||
awayScore: goals(r.GOLOS_FORA ?? r.JOG_GOLOS_FORA),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -358,3 +590,174 @@ export function parseFpfLineups(text: string): { home: PlayerData[]; away: Playe
|
||||
away: [...starters.slice(11, 22), ...subs.slice(half)],
|
||||
};
|
||||
}
|
||||
|
||||
// --- UEFA (match.uefa.com, the JSON the uefa.com site reads) ------------------------------------------------------
|
||||
|
||||
/**
|
||||
* UEFA's club competitions. Not a documented API: the same public JSON uefa.com itself reads, asked for sparingly
|
||||
* (a few pages every six hours, line-ups only around matches) and cached in the database. If it changes, events still
|
||||
* work: names are typed by hand, as for handball.
|
||||
*/
|
||||
export const UEFA_COMPETITIONS = [
|
||||
{ externalId: "1", name: "UEFA Champions League", sport: "futebol", gender: "M" },
|
||||
{ externalId: "14", name: "UEFA Europa League", sport: "futebol", gender: "M" },
|
||||
{ externalId: "2019", name: "UEFA Conference League", sport: "futebol", gender: "M" },
|
||||
{ externalId: "28", name: "UEFA Women's Champions League", sport: "futebol", gender: "F" },
|
||||
{ externalId: "27", name: "UEFA Futsal Champions League", sport: "futsal", gender: "M" },
|
||||
] as const;
|
||||
|
||||
/** Our season "20262027" is UEFA's seasonYear 2027 (the year it ends). */
|
||||
export const uefaSeasonYear = (season: string) => season.slice(4);
|
||||
|
||||
/** Roles of the referee team that are on the pitch (or at its side), so they show up in photos. */
|
||||
export const UEFA_PITCH_OFFICIALS = ["REFEREE", "ASSISTANT_REFEREE_ONE", "ASSISTANT_REFEREE_TWO", "FOURTH_OFFICIAL"];
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const obj = (v: unknown): Json => (v && typeof v === "object" ? (v as Json) : {});
|
||||
/** A UEFA name: a plain string, or translations ({EN, PT, ...}) directly or under `translations`. */
|
||||
function uefaName(v: unknown, ...keys: string[]): string | null {
|
||||
const o = obj(v);
|
||||
for (const k of keys) {
|
||||
const direct = str(o[k]);
|
||||
if (direct) return direct;
|
||||
const tr = obj(o[k]);
|
||||
const t = str(tr.PT) ?? str(tr.EN);
|
||||
if (t) return t;
|
||||
const nested = obj(obj(o.translations)[k]);
|
||||
const n = str(nested.EN) ?? str(nested.PT);
|
||||
if (n) return n;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function uefaTeam(v: unknown): TeamData | null {
|
||||
const t = obj(v);
|
||||
const id = str(t.id);
|
||||
const name = str(t.internationalName) ?? uefaName(t, "displayName", "name");
|
||||
if (!id || !name) return null;
|
||||
return { externalId: id, name, abbreviation: str(t.teamCode), logoUrl: url(t.mediumLogoUrl, t.logoUrl) };
|
||||
}
|
||||
|
||||
export function uefaFixture(m: Json, competitionId: string, season: string): FixtureData | null {
|
||||
const id = str(m.id);
|
||||
const home = uefaTeam(m.homeTeam);
|
||||
const away = uefaTeam(m.awayTeam);
|
||||
const ko = obj(m.kickOffTime);
|
||||
const when = str(ko.dateTime) ?? str(m.kickOffTime);
|
||||
if (!id || !home || !away || !when) return null;
|
||||
const at = new Date(when);
|
||||
if (Number.isNaN(at.getTime())) return null;
|
||||
const total = obj(obj(m.score).total);
|
||||
const goals = (v: unknown) => (typeof v === "number" ? v : null);
|
||||
const stadium = uefaName(m.stadium, "name");
|
||||
const city = uefaName(m.stadium, "city");
|
||||
const officials = (Array.isArray(m.referees) ? m.referees : [])
|
||||
.map((r) => {
|
||||
const o = obj(r);
|
||||
const name = uefaName(o.person, "name", "internationalName");
|
||||
const role = str(o.role);
|
||||
return name && role ? { name, role } : null;
|
||||
})
|
||||
.filter((o): o is OfficialData => !!o);
|
||||
return {
|
||||
externalId: id,
|
||||
competition: competitionId,
|
||||
season,
|
||||
home,
|
||||
away,
|
||||
startsAt: at,
|
||||
timeKnown: true,
|
||||
round: str(obj(m.matchday).longName) ?? str(obj(m.matchday).name) ?? str(obj(obj(m.round).metaData).name),
|
||||
venue: stadium ? (city ? `${stadium}, ${city}` : stadium) : null,
|
||||
homeScore: goals(total.home),
|
||||
awayScore: goals(total.away),
|
||||
officials,
|
||||
};
|
||||
}
|
||||
|
||||
const POSITIONS: Record<string, string> = { GOALKEEPER: "Guarda-Redes", DEFENDER: "Defesa", MIDFIELDER: "Médio", FORWARD: "Avançado" };
|
||||
|
||||
function uefaPlayer(entry: unknown): PlayerData | null {
|
||||
const e = obj(entry);
|
||||
const p = obj(e.player);
|
||||
const name = str(p.internationalName) ?? uefaName(p, "name", "shortName");
|
||||
if (!name) return null;
|
||||
const number = typeof e.jerseyNumber === "number" ? String(e.jerseyNumber) : (str(e.jerseyNumber) ?? str(p.clubJerseyNumber));
|
||||
const position = e.type === "GOALKEEPER" ? "Guarda-Redes" : (str(obj(obj(p.translations).fieldPosition).PT) ?? POSITIONS[str(p.fieldPosition) ?? ""] ?? null);
|
||||
return {
|
||||
externalId: str(p.id),
|
||||
number,
|
||||
name,
|
||||
fullName: uefaName(p, "name"),
|
||||
position,
|
||||
photoUrl: url(p.imageUrl),
|
||||
birthDate: str(p.birthDate),
|
||||
nationality: str(p.countryCode),
|
||||
};
|
||||
}
|
||||
|
||||
function uefaCoach(entry: unknown): PlayerData | null {
|
||||
const e = obj(entry);
|
||||
const name = uefaName(e.person, "name", "internationalName");
|
||||
if (!name) return null;
|
||||
const role = str(e.role);
|
||||
return { externalId: str(obj(e.person).id), number: null, name, position: role === "COACH" ? "Treinador" : "Equipa técnica", photoUrl: url(e.imageUrl) };
|
||||
}
|
||||
|
||||
export interface UefaLineup {
|
||||
available: boolean;
|
||||
home: PlayerData[];
|
||||
away: PlayerData[];
|
||||
}
|
||||
|
||||
/** One side of a match sheet: starters, bench and staff. */
|
||||
function uefaSide(v: unknown): PlayerData[] {
|
||||
const s = obj(v);
|
||||
const list = (k: string) => (Array.isArray(s[k]) ? (s[k] as unknown[]) : []);
|
||||
return [...list("field"), ...list("bench")].map(uefaPlayer).concat(list("coaches").map(uefaCoach)).filter((p): p is PlayerData => !!p);
|
||||
}
|
||||
|
||||
export function parseUefaLineups(data: unknown): UefaLineup {
|
||||
const d = obj(data);
|
||||
const home = uefaSide(d.homeTeam);
|
||||
const away = uefaSide(d.awayTeam);
|
||||
return { available: home.length + away.length > 0, home, away };
|
||||
}
|
||||
|
||||
export class UefaProvider {
|
||||
static readonly MATCHES = "https://match.uefa.com/v5/matches";
|
||||
static readonly PAGE = 100;
|
||||
|
||||
constructor(private readonly fetcher: Fetch) {}
|
||||
|
||||
/** Matches of a competition between two days (both included), every page. */
|
||||
async matches(competitionId: string, season: string, from: Date, to: Date): Promise<FixtureData[]> {
|
||||
const out: FixtureData[] = [];
|
||||
const day = (d: Date) => d.toISOString().slice(0, 10);
|
||||
for (let offset = 0; offset < 2000; offset += UefaProvider.PAGE) {
|
||||
const q = new URLSearchParams({
|
||||
competitionId,
|
||||
seasonYear: uefaSeasonYear(season),
|
||||
fromDate: day(from),
|
||||
toDate: day(to),
|
||||
limit: String(UefaProvider.PAGE),
|
||||
offset: String(offset),
|
||||
order: "ASC",
|
||||
});
|
||||
const rows = await get(this.fetcher, `${UefaProvider.MATCHES}?${q}`, { accept: "application/json" }, "json");
|
||||
if (!Array.isArray(rows)) throw new Error("uefa: unexpected matches");
|
||||
for (const r of rows) {
|
||||
const f = uefaFixture(obj(r), competitionId, season);
|
||||
if (f) out.push(f);
|
||||
}
|
||||
if (rows.length < UefaProvider.PAGE) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The match sheet (published about an hour before kick-off): numbers of starters and bench, and the coaches. */
|
||||
async lineups(matchId: string): Promise<UefaLineup> {
|
||||
const data = await get(this.fetcher, `${UefaProvider.MATCHES}/${encodeURIComponent(matchId)}/lineups`, { accept: "application/json" }, "json");
|
||||
return parseUefaLineups(data);
|
||||
}
|
||||
}
|
||||
+415
-45
@@ -2,7 +2,7 @@ import { CodeGeneratorSettings, type CodeLine } from "@photoreport/contracts";
|
||||
import { parseCodeList } from "@photoreport/metadata";
|
||||
import sharp from "sharp";
|
||||
import type { Db } from "../db.js";
|
||||
import type { SportsCompetition, SportsProvider } from "../generated/prisma/client.js";
|
||||
import type { SportsCompetition, SportsPlayer, SportsProvider } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
|
||||
import { badRequest, notFound } from "../lib/errors.js";
|
||||
@@ -15,14 +15,18 @@ import {
|
||||
FpfProvider,
|
||||
LIGA_COMPETITIONS,
|
||||
LigaProvider,
|
||||
type OfficialData,
|
||||
type PlayerData,
|
||||
type TeamData,
|
||||
UEFA_COMPETITIONS,
|
||||
UEFA_PITCH_OFFICIALS,
|
||||
UefaProvider,
|
||||
seasonOf,
|
||||
} from "./providers.js";
|
||||
|
||||
/**
|
||||
* Sports data (the old app's "code replacements" system, rebuilt): competitions, teams, squads and fixtures read
|
||||
* from Liga Portugal, FPF and FPA every few hours, shared by every organisation. Organisations turn them into
|
||||
* from Liga Portugal, FPF, FPA and UEFA 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).
|
||||
*/
|
||||
@@ -30,10 +34,31 @@ 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"];
|
||||
const HEADSHOT_HOSTS = ["www.ligaportugal.pt", "ligaportugal.pt", "img.uefa.com", "si.fpa.pt"];
|
||||
/** A face suggestion this sure counts as "probably them" in the squad's photo counts. */
|
||||
const LIKELY_SUGGESTION = 0.7;
|
||||
/** 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;
|
||||
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"];
|
||||
/** Teams started per refresh (their club page, games and last reports), and reports read for each. */
|
||||
const FPA_TEAMS_PER_REFRESH = 8;
|
||||
const FPA_REPORTS_PER_TEAM = 3;
|
||||
/** Reports of games already played read per refresh (filled in after the match, sometimes the next day). */
|
||||
const FPA_REPORTS_PER_REFRESH = 30;
|
||||
/** A team whose club page gave nothing is tried again after this long. */
|
||||
const FPA_RETRY_MS = 3 * 86400_000;
|
||||
/** Reports read before licence numbers were kept, read again per refresh until none are left. */
|
||||
const FPA_REREADS_PER_REFRESH = 40;
|
||||
/** The handball referees and table officials, kept as one "team" so their licence (and photo) is known by name. */
|
||||
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<SportsProvider, string> = { LIGA: "futebol", FPF: "futebol", FPA: "andebol" };
|
||||
const SPORT: Record<SportsProvider, string> = { LIGA: "futebol", FPF: "futebol", FPA: "andebol", UEFA: "futebol" };
|
||||
|
||||
export interface SportsDeps {
|
||||
db: Db;
|
||||
@@ -42,6 +67,10 @@ export interface SportsDeps {
|
||||
fetch: Fetch;
|
||||
/** Pause between FPF pages (be gentle with the site). */
|
||||
fpfDelayMs?: number;
|
||||
/** Pause between UEFA match sheets. */
|
||||
uefaDelayMs?: number;
|
||||
/** Pause between FPA pages. */
|
||||
fpaDelayMs?: number;
|
||||
}
|
||||
|
||||
export interface RefreshResult {
|
||||
@@ -56,10 +85,12 @@ export class SportsService {
|
||||
readonly liga: LigaProvider;
|
||||
readonly fpa: FpaProvider;
|
||||
readonly fpf: FpfProvider;
|
||||
readonly uefa: UefaProvider;
|
||||
|
||||
constructor(private readonly deps: SportsDeps) {
|
||||
this.uefa = new UefaProvider(deps.fetch);
|
||||
this.liga = new LigaProvider(deps.fetch);
|
||||
this.fpa = new FpaProvider(deps.fetch);
|
||||
this.fpa = new FpaProvider(deps.fetch, deps.fpaDelayMs ?? 800);
|
||||
this.fpf = new FpfProvider(deps.fetch, deps.fpfDelayMs ?? 800);
|
||||
}
|
||||
|
||||
@@ -74,6 +105,12 @@ export class SportsService {
|
||||
await this.deps.db.sportsCompetition.create({ data: { provider: "LIGA", externalId: c.externalId, sport: "futebol", name: c.name, gender: "M", season } });
|
||||
else if (existing.season < season) await this.deps.db.sportsCompetition.update({ where: { id: existing.id }, data: { season, lastIngestAt: null } });
|
||||
}
|
||||
for (const c of UEFA_COMPETITIONS) {
|
||||
const existing = await this.deps.db.sportsCompetition.findUnique({ where: { provider_externalId: { provider: "UEFA", externalId: c.externalId } } });
|
||||
if (!existing)
|
||||
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 } });
|
||||
}
|
||||
}
|
||||
|
||||
private due(c: SportsCompetition, now: Date): boolean {
|
||||
@@ -97,6 +134,7 @@ export class SportsService {
|
||||
const fpa = all.filter((c) => c.provider === "FPA");
|
||||
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));
|
||||
if (total.players || total.teams) await this.regenerateCodeLists();
|
||||
return total;
|
||||
}
|
||||
@@ -104,7 +142,14 @@ export class SportsService {
|
||||
async refreshCompetition(id: string, now = new Date()): Promise<RefreshResult> {
|
||||
const c = await this.deps.db.sportsCompetition.findUnique({ where: { id } });
|
||||
if (!c) throw notFound("competition_not_found");
|
||||
const r = c.provider === "LIGA" ? await this.refreshLiga([c], now) : c.provider === "FPA" ? await this.refreshFpa(now) : await this.refreshFpf(c, now);
|
||||
const r =
|
||||
c.provider === "LIGA"
|
||||
? await this.refreshLiga([c], now)
|
||||
: c.provider === "FPA"
|
||||
? await this.refreshFpa(now)
|
||||
: c.provider === "UEFA"
|
||||
? await this.refreshUefa(c, now)
|
||||
: await this.refreshFpf(c, now);
|
||||
if (r.players || r.teams) await this.regenerateCodeLists();
|
||||
return r;
|
||||
}
|
||||
@@ -216,10 +261,168 @@ export class SportsService {
|
||||
result.teams += k.teams.size;
|
||||
result.fixtures += k.fixtures;
|
||||
}
|
||||
await this.fpaSquads(fixtures, now, result);
|
||||
await this.fpaReferees(now, result);
|
||||
if (result.errors.length) log.warn({ errors: result.errors.slice(0, 10) }, "sports: fpa refresh had errors");
|
||||
log.info({ ...result, errors: result.errors.length }, "sports: fpa refreshed");
|
||||
return result;
|
||||
}
|
||||
|
||||
private readonly fpaTried = new Map<string, number>();
|
||||
/** Reports read again for licence numbers (once each: some list none). */
|
||||
private readonly fpaReread = new Set<string>();
|
||||
|
||||
private fpaCompetition(f: FixtureData): Promise<SportsCompetition> {
|
||||
return this.deps.db.sportsCompetition.upsert({
|
||||
where: { provider_externalId: { provider: "FPA", externalId: f.competition } },
|
||||
create: { provider: "FPA", externalId: f.competition, sport: "andebol", name: f.competitionName ?? f.competition, gender: f.gender ?? null, season: f.season },
|
||||
update: {},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handball squads from the match reports. Teams of the senior national competitions without a squad this season
|
||||
* start from their club's last games (a few each refresh); then every report of a game played is read once.
|
||||
*/
|
||||
private async fpaSquads(agenda: FixtureData[], now: Date, result: RefreshResult): Promise<void> {
|
||||
const { db } = this.deps;
|
||||
const season = seasonOf(now);
|
||||
const wanted = new Map<string, { team: TeamData; gender: string | null }>();
|
||||
for (const f of [...agenda].sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime())) {
|
||||
if (!FPA_SQUAD_COMPETITIONS.includes(f.competition)) continue;
|
||||
for (const t of [f.home, f.away]) if (t.clubId && !wanted.has(t.externalId)) wanted.set(t.externalId, { team: t, gender: f.gender ?? null });
|
||||
}
|
||||
const known = await db.sportsTeam.findMany({
|
||||
where: { provider: "FPA", externalId: { in: [...wanted.keys()] } },
|
||||
select: { externalId: true, _count: { select: { players: { where: { season } } } } },
|
||||
});
|
||||
const started = new Set(known.filter((t) => t._count.players > 0).map((t) => t.externalId));
|
||||
const terms = new Map<string, Awaited<ReturnType<FpaProvider["clubTerms"]>>>();
|
||||
let teams = 0;
|
||||
for (const [ext, { team, gender }] of wanted) {
|
||||
if (teams >= FPA_TEAMS_PER_REFRESH) break;
|
||||
const tried = this.fpaTried.get(`${ext}|${season}`);
|
||||
if (started.has(ext) || (tried && now.getTime() - tried < FPA_RETRY_MS)) continue;
|
||||
teams++;
|
||||
this.fpaTried.set(`${ext}|${season}`, now.getTime());
|
||||
try {
|
||||
const club = team.clubId!;
|
||||
let t = terms.get(club);
|
||||
if (!t) terms.set(club, (t = await this.fpa.clubTerms(club)));
|
||||
const level = t.levels.find((l) => l.name === (gender === "F" ? "Seniores F" : "Seniores M"));
|
||||
if (!t.season || !level) continue;
|
||||
const played = (await this.fpa.clubGames(club, t.season, level.id))
|
||||
.filter((g) => (g.home.externalId === ext || g.away.externalId === ext) && g.homeScore !== null && g.homeScore !== undefined && g.startsAt < now)
|
||||
.sort((a, b) => b.startsAt.getTime() - a.startsAt.getTime())
|
||||
.slice(0, FPA_REPORTS_PER_TEAM)
|
||||
.reverse();
|
||||
for (const g of played) {
|
||||
const c = await this.fpaCompetition(g);
|
||||
await this.saveFixture(c, "FPA", g);
|
||||
const row = await db.sportsFixture.findUniqueOrThrow({ where: { competitionId_externalId: { competitionId: c.id, externalId: g.externalId } } });
|
||||
if (!row.lineupAt) result.players += (await this.readFpaReport(row, now)).changed;
|
||||
}
|
||||
} catch (err) {
|
||||
result.errors.push(`fpa ${team.name}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
const pending = await db.sportsFixture.findMany({
|
||||
where: {
|
||||
lineupAt: null,
|
||||
competition: { provider: "FPA", externalId: { in: FPA_SQUAD_COMPETITIONS } },
|
||||
startsAt: { gte: new Date(now.getTime() - 30 * 86400_000), lt: new Date(now.getTime() - 3 * 3600_000) },
|
||||
},
|
||||
orderBy: { startsAt: "desc" },
|
||||
take: FPA_REPORTS_PER_REFRESH,
|
||||
});
|
||||
for (const f of pending.reverse()) {
|
||||
try {
|
||||
result.players += (await this.readFpaReport(f, now)).changed;
|
||||
} catch (err) {
|
||||
result.errors.push(`fpa report ${f.externalId}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
// Reports read before licence numbers were kept (their referees have none): once more, newest first.
|
||||
const read = await db.sportsFixture.findMany({
|
||||
where: {
|
||||
lineupAt: { not: null },
|
||||
competition: { provider: "FPA", externalId: { in: FPA_SQUAD_COMPETITIONS } },
|
||||
startsAt: { gte: new Date(now.getTime() - 90 * 86400_000) },
|
||||
},
|
||||
orderBy: { startsAt: "desc" },
|
||||
select: { id: true, externalId: true, season: true, homeTeamId: true, awayTeamId: true, officials: true },
|
||||
});
|
||||
const stale = read.filter((f) => !this.fpaReread.has(f.id) && !((f.officials as OfficialData[] | null) ?? []).some((o) => o.externalId)).slice(0, FPA_REREADS_PER_REFRESH);
|
||||
for (const f of stale) {
|
||||
this.fpaReread.add(f.id);
|
||||
try {
|
||||
result.players += (await this.readFpaReport(f, now)).changed;
|
||||
} catch (err) {
|
||||
result.errors.push(`fpa report ${f.externalId}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One match report into both squads (players with number and licence, the bench officials by letter). */
|
||||
private async readFpaReport(
|
||||
f: { id: string; externalId: string; season: string; homeTeamId: string; awayTeamId: string; officials?: unknown },
|
||||
now: Date,
|
||||
): Promise<{ read: boolean; changed: number }> {
|
||||
const report = await this.fpa.boletim(f.externalId);
|
||||
if (!report.available) return { read: false, changed: 0 };
|
||||
// The report gives the bench officials' coaching grade where the players have their licence: the match page has it.
|
||||
try {
|
||||
const page = await this.fpa.matchPage(f.externalId);
|
||||
for (const [list, cipa] of [
|
||||
[report.home, page.benchCipa.home],
|
||||
[report.away, page.benchCipa.away],
|
||||
] as const) {
|
||||
for (const p of list) if (!p.externalId && p.number && cipa.has(p.number)) p.externalId = cipa.get(p.number)!;
|
||||
}
|
||||
} catch (err) {
|
||||
this.deps.log.warn({ err, fixture: f.externalId }, "sports: fpa match page failed");
|
||||
}
|
||||
let changed = (await this.savePlayers(f.homeTeamId, f.season, report.home, "lineup")) + (await this.savePlayers(f.awayTeamId, f.season, report.away, "lineup"));
|
||||
const people = report.referees.filter((o) => o.externalId && PEOPLE_OFFICIALS.includes(o.role));
|
||||
if (people.length) {
|
||||
const team = await this.upsertTeam("FPA", FPA_REFEREES_TEAM, "andebol");
|
||||
changed += await this.savePlayers(
|
||||
team,
|
||||
f.season,
|
||||
people.map((o) => ({ externalId: o.externalId ?? null, name: o.name, fullName: o.fullName ?? null, number: null, position: o.role === "REFEREE" ? "Árbitro" : "Oficial de mesa" })),
|
||||
"lineup",
|
||||
);
|
||||
}
|
||||
// The report's list (with licence numbers) replaces the names the match page gave before the game.
|
||||
await this.deps.db.sportsFixture.update({
|
||||
where: { id: f.id },
|
||||
data: { lineupAt: now, ...(report.referees.length ? { officials: report.referees as unknown as object } : {}) },
|
||||
});
|
||||
return { read: true, changed };
|
||||
}
|
||||
|
||||
/** The referees of handball games someone is covering, from the match page (named some days before). */
|
||||
private async fpaReferees(now: Date, result: RefreshResult): Promise<void> {
|
||||
const { db } = this.deps;
|
||||
const fixtures = await db.sportsFixture.findMany({
|
||||
where: {
|
||||
events: { some: {} },
|
||||
competition: { provider: "FPA" },
|
||||
startsAt: { gte: new Date(now.getTime() - 86400_000), lte: new Date(now.getTime() + 7 * 86400_000) },
|
||||
},
|
||||
take: 20,
|
||||
});
|
||||
for (const f of fixtures) {
|
||||
if (((f.officials as OfficialData[] | null) ?? []).length) continue;
|
||||
try {
|
||||
const referees = await this.fpa.referees(f.externalId);
|
||||
if (referees.length) await db.sportsFixture.update({ where: { id: f.id }, data: { officials: referees as unknown as object } });
|
||||
} catch (err) {
|
||||
result.errors.push(`fpa referees ${f.externalId}: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async refreshFpf(c: SportsCompetition, now = new Date()): Promise<RefreshResult> {
|
||||
const { db } = this.deps;
|
||||
const result: RefreshResult = { competitions: 1, teams: 0, players: 0, fixtures: 0, errors: [] };
|
||||
@@ -246,6 +449,73 @@ export class SportsService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* A UEFA competition: its matches (the whole season the first time, then a month around today) with the referee
|
||||
* teams, and squads built from the match sheets already published (numbers, positions, headshots, coaches).
|
||||
*/
|
||||
async refreshUefa(c: SportsCompetition, now = new Date()): Promise<RefreshResult> {
|
||||
const { db, log } = this.deps;
|
||||
const result: RefreshResult = { competitions: 1, teams: 0, players: 0, fixtures: 0, errors: [] };
|
||||
const sport = c.sport;
|
||||
try {
|
||||
const startYear = Number(c.season.slice(0, 4));
|
||||
const from = c.lastIngestAt ? new Date(now.getTime() - 14 * 86400_000) : new Date(Date.UTC(startYear, 5, 1));
|
||||
const to = c.lastIngestAt ? new Date(now.getTime() + 35 * 86400_000) : new Date(Date.UTC(startYear + 1, 6, 31));
|
||||
const teams = new Set<string>();
|
||||
for (const f of await this.uefa.matches(c.externalId, c.season, from, to)) {
|
||||
result.fixtures += await this.saveFixture(c, "UEFA", f, sport);
|
||||
teams.add(f.home.externalId).add(f.away.externalId);
|
||||
}
|
||||
// Teams of the competition this season.
|
||||
const rows = await db.sportsTeam.findMany({ where: { provider: "UEFA", 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;
|
||||
// Squads from the match sheets of matches already played: the most recent ones first (the teams playing now,
|
||||
// not July's qualifiers), read oldest to newest so the latest number wins.
|
||||
const played = (
|
||||
await db.sportsFixture.findMany({
|
||||
where: { competitionId: c.id, season: c.season, lineupAt: null, startsAt: { lt: new Date(now.getTime() - 2 * 3600_000) } },
|
||||
orderBy: { startsAt: "desc" },
|
||||
take: UEFA_SHEETS_PER_REFRESH,
|
||||
})
|
||||
).reverse();
|
||||
for (const [i, f] of played.entries()) {
|
||||
if (i) await new Promise((r) => setTimeout(r, this.deps.uefaDelayMs ?? 500));
|
||||
try {
|
||||
result.players += (await this.readUefaSheet(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: uefa refresh had errors");
|
||||
log.info({ competition: c.name, ...result, errors: result.errors.length }, "sports: uefa refreshed");
|
||||
return result;
|
||||
}
|
||||
|
||||
/** One UEFA match sheet into both squads: whether it was published yet, and players added or changed. */
|
||||
private async readUefaSheet(
|
||||
f: { id: string; externalId: string; season: string; homeTeamId: string; awayTeamId: string },
|
||||
now: Date,
|
||||
): Promise<{ read: boolean; changed: number }> {
|
||||
const sheet = await this.uefa.lineups(f.externalId);
|
||||
if (!sheet.available) 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 };
|
||||
}
|
||||
|
||||
/** An FPF competition (any division or district) by its resultados.fpf.pt link. */
|
||||
async addFpfCompetition(ref: string, now = new Date()): Promise<SportsCompetition> {
|
||||
const parsed = FpfProvider.parseRef(ref);
|
||||
@@ -259,20 +529,25 @@ export class SportsService {
|
||||
return this.deps.db.sportsCompetition.findUniqueOrThrow({ where: { id: c.id } });
|
||||
}
|
||||
|
||||
/** FPF squads come from each match sheet around kick-off. */
|
||||
/** FPF and UEFA squads come from each match sheet around kick-off. */
|
||||
async pollLineups(now = new Date()): Promise<number> {
|
||||
const { db, log } = this.deps;
|
||||
const fixtures = await db.sportsFixture.findMany({
|
||||
where: {
|
||||
lineupAt: null,
|
||||
competition: { provider: "FPF", active: true },
|
||||
competition: { provider: { in: ["FPF", "UEFA"] }, 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 } } },
|
||||
});
|
||||
let read = 0;
|
||||
for (const f of fixtures) {
|
||||
try {
|
||||
if (f.competition.provider === "UEFA") {
|
||||
if ((await this.readUefaSheet(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");
|
||||
@@ -287,7 +562,7 @@ export class SportsService {
|
||||
return read;
|
||||
}
|
||||
|
||||
private async upsertTeam(provider: SportsProvider, t: TeamData): Promise<string> {
|
||||
private async upsertTeam(provider: SportsProvider, t: TeamData, sport = SPORT[provider]): Promise<string> {
|
||||
const data = {
|
||||
name: t.name,
|
||||
slug: slugify(t.name) || `team-${t.externalId}`,
|
||||
@@ -297,7 +572,7 @@ export class SportsService {
|
||||
};
|
||||
const team = await this.deps.db.sportsTeam.upsert({
|
||||
where: { provider_externalId: { provider, externalId: t.externalId } },
|
||||
create: { provider, externalId: t.externalId, sport: SPORT[provider], ...data },
|
||||
create: { provider, externalId: t.externalId, sport, ...data },
|
||||
update: data,
|
||||
select: { id: true },
|
||||
});
|
||||
@@ -326,7 +601,14 @@ export class SportsService {
|
||||
if (!old) {
|
||||
await db.sportsPlayer.create({ data: { teamId, season, name: p.name, source, ...data } });
|
||||
changed++;
|
||||
} else if (old.number !== p.number || old.goneAt || (p.photoUrl && old.photoUrl !== p.photoUrl) || (p.position && old.position !== p.position)) {
|
||||
} else if (
|
||||
old.number !== p.number ||
|
||||
old.goneAt ||
|
||||
(p.photoUrl && old.photoUrl !== p.photoUrl) ||
|
||||
(p.position && old.position !== p.position) ||
|
||||
(p.externalId && old.externalId !== p.externalId) ||
|
||||
(p.fullName && old.fullName !== p.fullName)
|
||||
) {
|
||||
await db.sportsPlayer.update({ where: { id: old.id }, data: { ...data, goneAt: null, ...(source === "api" ? { source } : {}) } });
|
||||
changed++;
|
||||
}
|
||||
@@ -341,9 +623,9 @@ export class SportsService {
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async saveFixture(c: SportsCompetition, provider: SportsProvider, f: FixtureData): Promise<number> {
|
||||
const homeTeamId = await this.upsertTeam(provider, f.home);
|
||||
const awayTeamId = await this.upsertTeam(provider, f.away);
|
||||
private async saveFixture(c: SportsCompetition, provider: SportsProvider, f: FixtureData, sport?: string): Promise<number> {
|
||||
const homeTeamId = await this.upsertTeam(provider, f.home, sport);
|
||||
const awayTeamId = await this.upsertTeam(provider, f.away, sport);
|
||||
const data = {
|
||||
season: f.season,
|
||||
homeTeamId,
|
||||
@@ -355,6 +637,7 @@ export class SportsService {
|
||||
venue: f.venue ?? null,
|
||||
homeScore: f.homeScore ?? null,
|
||||
awayScore: f.awayScore ?? null,
|
||||
...(f.officials?.length ? { officials: f.officials as unknown as object } : {}),
|
||||
};
|
||||
await this.deps.db.sportsFixture.upsert({
|
||||
where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } },
|
||||
@@ -371,7 +654,9 @@ export class SportsService {
|
||||
const latest = await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { updatedAt: "desc" }, select: { season: true } });
|
||||
if (!latest) return [];
|
||||
const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } });
|
||||
return players.sort((a, b) => (Number(a.number) || 999) - (Number(b.number) || 999) || a.name.localeCompare(b.name));
|
||||
// Shirt numbers, then the handball officials by letter (A, B, …), then those without either.
|
||||
const order = (n: string | null) => (n && /^\d+$/.test(n) ? Number(n) : n && /^[A-F]$/.test(n) ? 900 + n.charCodeAt(0) : 999);
|
||||
return players.sort((a, b) => order(a.number) - order(b.number) || a.name.localeCompare(b.name));
|
||||
}
|
||||
|
||||
/** Both teams of an event, with the person each player is in the organisation (for tagging by number). */
|
||||
@@ -380,6 +665,26 @@ export class SportsService {
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, include: { homeTeam: true, awayTeam: 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[] }[];
|
||||
// Photos of each person in this event: faces confirmed as them, and faces the system takes for them (a
|
||||
// suggestion of 70% or more, not confirmed yet). A photo counts once, as confirmed when it is both.
|
||||
const rows = await db.$queryRaw<{ person_id: string; photo_id: string; confirmed: boolean }[]>`
|
||||
SELECT DISTINCT COALESCE(g.person_id, g.suggested_person_id) AS person_id, f.photo_id, (g.person_id IS NOT NULL) AS confirmed
|
||||
FROM faces f
|
||||
JOIN face_groups g ON g.id = f.group_id
|
||||
JOIN photos ph ON ph.id = f.photo_id
|
||||
WHERE g.event_id = ${eventId}::uuid AND g.ignored_at IS NULL AND ph.event_id = ${eventId}::uuid
|
||||
AND (g.person_id IS NOT NULL OR g.suggestion_score >= ${LIKELY_SUGGESTION})`;
|
||||
const photosOf = new Map<string, { confirmed: Set<string>; likely: Set<string> }>();
|
||||
for (const r of rows) {
|
||||
const entry = photosOf.get(r.person_id) ?? { confirmed: new Set<string>(), likely: new Set<string>() };
|
||||
(r.confirmed ? entry.confirmed : entry.likely).add(r.photo_id);
|
||||
photosOf.set(r.person_id, entry);
|
||||
}
|
||||
const counts = (personId: string | null) => {
|
||||
const e = personId ? photosOf.get(personId) : undefined;
|
||||
if (!e) return { confirmed: 0, likely: 0 };
|
||||
return { confirmed: e.confirmed.size, likely: [...e.likely].filter((id) => !e.confirmed.has(id)).length };
|
||||
};
|
||||
for (const [side, team] of [
|
||||
["home", event.homeTeam],
|
||||
["away", event.awayTeam],
|
||||
@@ -402,6 +707,7 @@ export class SportsService {
|
||||
position: p.position,
|
||||
hasPhoto: !!p.photoUrl,
|
||||
personId: personOf.get(p.id) ?? null,
|
||||
photos: counts(personOf.get(p.id) ?? null),
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -430,7 +736,12 @@ export class SportsService {
|
||||
const { db, log } = this.deps;
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
include: { homeTeam: true, awayTeam: true, organization: { select: { biometricsEnabled: true, codeGenerator: true } } },
|
||||
include: {
|
||||
homeTeam: true,
|
||||
awayTeam: true,
|
||||
fixture: { select: { id: true, externalId: true, officials: true, competition: { select: { provider: true } } } },
|
||||
organization: { select: { biometricsEnabled: true, codeGenerator: true } },
|
||||
},
|
||||
});
|
||||
if (!event) throw notFound("event_not_found");
|
||||
const settings = CodeGeneratorSettings.parse(event.organization.codeGenerator ?? {});
|
||||
@@ -441,36 +752,42 @@ export class SportsService {
|
||||
if (!team) continue;
|
||||
const club = settings.teamNames[team.id] ?? team.name;
|
||||
for (const p of await this.squad(team.id)) {
|
||||
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
|
||||
let created = false;
|
||||
if (!person) {
|
||||
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
|
||||
if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName;
|
||||
else {
|
||||
// Same name in another club: the second one gets its team in brackets (people are unique by name).
|
||||
const name = byName ? `${p.name} (${team.abbreviation || club})` : p.name;
|
||||
const other = byName ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
|
||||
if (other?.sportsPlayerId && other.sportsPlayerId !== p.id) continue;
|
||||
if (other) person = other;
|
||||
else {
|
||||
try {
|
||||
person = await db.person.create({ data: { organizationId: orgId, name, club, number: p.number, sportsPlayerId: p.id } });
|
||||
created = true;
|
||||
} catch (err) {
|
||||
// Created meanwhile by another process: use that one.
|
||||
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||
person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
|
||||
if (!person) continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result);
|
||||
}
|
||||
}
|
||||
// The referee team on the pitch (UEFA publishes it, the FPA names it on the match page): people too, so their
|
||||
// faces can be named.
|
||||
let named = (event.fixture?.officials as OfficialData[] | null) ?? [];
|
||||
if (!named.length && event.fixture?.competition.provider === "FPA") {
|
||||
try {
|
||||
named = await this.fpa.referees(event.fixture.externalId);
|
||||
if (named.length) await db.sportsFixture.update({ where: { id: event.fixture.id }, data: { officials: named as unknown as object } });
|
||||
} catch (err) {
|
||||
log.warn({ err, fixture: event.fixture.id }, "sports: fpa referees failed");
|
||||
}
|
||||
}
|
||||
const officials = named.filter((o) => PEOPLE_OFFICIALS.includes(o.role));
|
||||
const refTeam = event.fixture?.competition.provider === "FPA" ? await db.sportsTeam.findUnique({ where: { provider_externalId: { provider: "FPA", externalId: FPA_REFEREES_TEAM.externalId } } }) : null;
|
||||
for (const o of officials) {
|
||||
// Handball: the referee as seen in earlier match reports (licence, full name, photo); by licence or by name.
|
||||
if (refTeam) {
|
||||
const known = await db.sportsPlayer.findMany({
|
||||
where: { teamId: refTeam.id, goneAt: null, OR: [...(o.externalId ? [{ externalId: o.externalId }] : []), { name: o.name }] },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
const one = known.find((k) => o.externalId && k.externalId === o.externalId) ?? (new Set(known.map((k) => k.externalId)).size === 1 ? known[0] : undefined);
|
||||
if (one) {
|
||||
await this.linkSquadPerson(orgId, refTeam, REFEREES, one, event.organization.biometricsEnabled, headshots, result);
|
||||
continue;
|
||||
}
|
||||
if (created) result.created++;
|
||||
else if (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id) {
|
||||
person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } });
|
||||
result.updated++;
|
||||
}
|
||||
if (p.photoUrl && !person.referenceKey) headshots.push({ personId: person.id, url: p.photoUrl });
|
||||
}
|
||||
const existing = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: o.name } } });
|
||||
if (existing) continue;
|
||||
try {
|
||||
await db.person.create({ data: { organizationId: orgId, name: o.name, club: REFEREES } });
|
||||
result.created++;
|
||||
} catch (err) {
|
||||
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||
}
|
||||
}
|
||||
if (event.organization.biometricsEnabled) {
|
||||
@@ -489,6 +806,59 @@ export class SportsService {
|
||||
return result;
|
||||
}
|
||||
|
||||
/** One squad entry as a person of the organisation (created, or kept in step), with its photo to use as reference. */
|
||||
private async linkSquadPerson(
|
||||
orgId: string,
|
||||
team: { provider: SportsProvider; name: string; abbreviation: string | null },
|
||||
club: string,
|
||||
p: SportsPlayer,
|
||||
biometrics: boolean,
|
||||
headshots: { personId: string; url: string }[],
|
||||
result: { created: number; updated: number },
|
||||
): Promise<void> {
|
||||
const { db, log } = this.deps;
|
||||
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
|
||||
let created = false;
|
||||
if (!person) {
|
||||
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
|
||||
if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName;
|
||||
else {
|
||||
// Same name in another club: the second one gets its team in brackets (people are unique by name).
|
||||
const name = byName ? `${p.name} (${team.abbreviation || club})` : p.name;
|
||||
const other = byName ? await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name } } }) : null;
|
||||
if (other?.sportsPlayerId && other.sportsPlayerId !== p.id) return;
|
||||
if (other) person = other;
|
||||
else {
|
||||
try {
|
||||
person = await db.person.create({ data: { organizationId: orgId, name, club, number: p.number, sportsPlayerId: p.id } });
|
||||
created = true;
|
||||
} catch (err) {
|
||||
// Created meanwhile by another process: use that one.
|
||||
if ((err as { code?: string }).code !== "P2002") throw err;
|
||||
person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
|
||||
if (!person) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (created) result.created++;
|
||||
else if (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id) {
|
||||
person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } });
|
||||
result.updated++;
|
||||
}
|
||||
let photo = p.photoUrl;
|
||||
// Handball: the licence photo, looked up for the people of this event only (one page each).
|
||||
if (!photo && !person.referenceKey && biometrics && team.provider === "FPA" && p.externalId && /^\d+$/.test(p.externalId)) {
|
||||
try {
|
||||
photo = await this.fpa.athletePhoto(p.externalId);
|
||||
if (photo) await db.sportsPlayer.update({ where: { id: p.id }, data: { photoUrl: photo } });
|
||||
} catch (err) {
|
||||
log.warn({ err, player: p.id }, "sports: fpa photo failed");
|
||||
}
|
||||
}
|
||||
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
@@ -5,6 +5,7 @@ import sharp from "sharp";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { AutopilotService } from "../src/autopilot/service.js";
|
||||
import { bestOf, groupBursts } from "../src/autopilot/bursts.js";
|
||||
import { type Candidate, actionScore, curate } from "../src/autopilot/curate.js";
|
||||
import { correctionOf, fold, learntStyle, recordCorrection, styleOf } from "../src/autopilot/learning.js";
|
||||
import type { Detections } from "../src/composition/compose.js";
|
||||
import type { SubjectDetector } from "../src/composition/detect.js";
|
||||
@@ -55,6 +56,58 @@ describe("bursts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("only the best", () => {
|
||||
const start = 1_800_000_000_000;
|
||||
const min = 60_000;
|
||||
let k = 0;
|
||||
const c = (at: number, score: number, extra: Partial<Candidate> = {}): Candidate => ({ id: `c${k++}`, at: start + at, burst: k, score, reason: "person", people: 1, subjectHeight: 0.5, rating: 0, rejected: false, ...extra });
|
||||
|
||||
it("prefers the ball, duels and big sharp subjects; never a rejected frame or an empty pitch", () => {
|
||||
const base = c(0, 2);
|
||||
expect(actionScore({ ...base, reason: "ball", people: 2 })).toBeGreaterThan(actionScore({ ...base, reason: "group", people: 2 }));
|
||||
expect(actionScore({ ...base, reason: "group", people: 2 })).toBeGreaterThan(actionScore(base));
|
||||
expect(actionScore({ ...base, subjectHeight: 0.1 })).toBeLessThan(actionScore(base));
|
||||
expect(actionScore({ ...base, rating: 4 })).toBeGreaterThan(actionScore({ ...base, reason: "ball" }));
|
||||
expect(actionScore({ ...base, rejected: true })).toBe(0);
|
||||
expect(actionScore({ ...base, reason: null })).toBe(0);
|
||||
});
|
||||
|
||||
it("spreads a gallery of the asked size over the match, carrying half-time forward, without twins", () => {
|
||||
// 90 minutes of play with a 15 minute break; a frame every 30 s, better ones now and then.
|
||||
const frames: Candidate[] = [];
|
||||
for (let t = -20 * min; t < 105 * min; t += 30_000) {
|
||||
if (t >= 45 * min && t < 60 * min) continue;
|
||||
frames.push(c(t, 1 + ((t / 30_000) % 7) / 3, t % (4 * min) === 0 ? { reason: "ball", people: 2 } : {}));
|
||||
}
|
||||
// A twin of a great frame, two seconds later in another burst.
|
||||
const great = c(20 * min, 9, { reason: "ball", people: 2 });
|
||||
const twin = c(20 * min + 2_000, 8.9, { reason: "ball", people: 2 });
|
||||
const rejected = c(30 * min, 20, { reason: "ball", rejected: true });
|
||||
frames.push(great, twin, rejected);
|
||||
const opts = { count: 30, start, durationMs: 105 * min, now: start + 200 * min };
|
||||
const all = curate(frames, [], opts).flatMap((d) => d.chosen);
|
||||
expect(all.length).toBeGreaterThanOrEqual(28);
|
||||
expect(all.length).toBeLessThanOrEqual(33);
|
||||
expect(all).toContain(great.id);
|
||||
expect(all).not.toContain(twin.id);
|
||||
expect(all).not.toContain(rejected.id);
|
||||
const at = new Map(frames.map((f) => [f.id, f.at - start]));
|
||||
// Nothing from the warm-up; both halves well represented.
|
||||
expect(all.every((id) => at.get(id)! >= -5 * min)).toBe(true);
|
||||
expect(all.filter((id) => at.get(id)! < 45 * min).length).toBeGreaterThanOrEqual(11);
|
||||
expect(all.filter((id) => at.get(id)! >= 60 * min).length).toBeGreaterThanOrEqual(11);
|
||||
|
||||
// Live, window by window, it comes to the same gallery size.
|
||||
const decided: { id: string; chosen: boolean }[] = [];
|
||||
for (let now = start - 20 * min; now <= start + 200 * min; now += min) {
|
||||
const seen = frames.filter((f) => f.at <= now);
|
||||
for (const d of curate(seen, decided, { ...opts, now })) for (const id of d.ids) decided.push({ id, chosen: d.chosen.includes(id) });
|
||||
}
|
||||
const live = decided.filter((d) => d.chosen).length;
|
||||
expect(Math.abs(live - all.length)).toBeLessThanOrEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("learning from corrections", () => {
|
||||
const set = (values: Record<string, number>) => ({ command: "develop.set" as const, params: { values } });
|
||||
const crop = (x0: number, x1: number) => ({ command: "crop.set" as const, params: { rect: { x0, y0: 0, x1, y1: 1 }, angle: 0, aspect: null } });
|
||||
@@ -181,6 +234,28 @@ describe("autopilot", () => {
|
||||
expect(await autopilot.decideBursts(new Date(Date.now() + 40_000))).toBe(0);
|
||||
});
|
||||
|
||||
it("only the best: chooses each window's game moments once the window has closed", async () => {
|
||||
const { eventId, orgId, userId } = await setup();
|
||||
const start = new Date(1_800_000_000_000);
|
||||
// A gallery of 23 over 115 minutes: one photo per 5-minute window, unused ones carried forward.
|
||||
await ctx.db.event.update({ where: { id: eventId }, data: { startsAt: start, sport: "futebol", autopilot: { enabled: true, picksPerBurst: 2, selection: "best", bestCount: 23 } } });
|
||||
const w0a = await shot(orgId, userId, eventId, 60_000, 900);
|
||||
const w0b = await shot(orgId, userId, eventId, 120_000, 300);
|
||||
const w2a = await shot(orgId, userId, eventId, 11 * 60_000, 800);
|
||||
const w2b = await shot(orgId, userId, eventId, 12 * 60_000, 700);
|
||||
const w2c = await shot(orgId, userId, eventId, 13 * 60_000, 100);
|
||||
await runQueue();
|
||||
// Window 0 has closed (and settled), window 2 not yet.
|
||||
await autopilot.decideBursts(new Date(start.getTime() + 7 * 60_000));
|
||||
const chosen = async () => Object.fromEntries((await ctx.db.photo.findMany({ where: { eventId } })).map((p) => [p.id, (p.autopilot as { curated?: boolean; chosen?: boolean }).curated ? !!(p.autopilot as { chosen?: boolean }).chosen : null]));
|
||||
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: null, [w2b]: null, [w2c]: null });
|
||||
// Window 2 also takes the share window 1 (no photos) did not use.
|
||||
await autopilot.decideBursts(new Date(start.getTime() + 17 * 60_000));
|
||||
expect(await chosen()).toEqual({ [w0a]: true, [w0b]: false, [w2a]: true, [w2b]: true, [w2c]: false });
|
||||
// The burst picks are still flagged for the photographer.
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: w2c } })).flag).toBe("PICK");
|
||||
});
|
||||
|
||||
it("never edits over a person's edit (made on the desktop app before the photo was uploaded)", async () => {
|
||||
const { orgId, userId, eventId } = await setup();
|
||||
const photoId = await shot(orgId, userId, eventId, 0, 300);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { closeRenderer } from "../src/delivery/render.js";
|
||||
import { SecretBox } from "../src/delivery/secrets.js";
|
||||
import { DeliveryService } from "../src/delivery/service.js";
|
||||
import { CookieJar, matchGame, sameTeam, zerozeroGameId } from "../src/delivery/zerozero.js";
|
||||
import { IngestService } from "../src/ingest/service.js";
|
||||
import { MemoryBroadcaster } from "../src/realtime.js";
|
||||
import { LocalStorage, UrlSigner } from "../src/storage/storage.js";
|
||||
@@ -65,11 +66,107 @@ class FakeNextcloud {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* fotos.zerozero.pt as its web app sees it: OAuth through www.zerozero.pt (ax_login.php), a session cookie on the
|
||||
* desk, the games list, and tus uploads.
|
||||
*/
|
||||
class FakeZerozero {
|
||||
logins = 0;
|
||||
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
|
||||
password = "zz-pass";
|
||||
|
||||
private cookie(init: RequestInit | undefined, name: string) {
|
||||
const c = new Headers(init?.headers).get("cookie") ?? "";
|
||||
return c.split(/;\s*/).some((p) => p.startsWith(`${name}=`));
|
||||
}
|
||||
|
||||
handles(input: RequestInfo | URL) {
|
||||
return /zerozero\.pt$/.test(new URL(String(input)).hostname);
|
||||
}
|
||||
|
||||
fetch: typeof fetch = async (input, init) => {
|
||||
const url = new URL(String(input));
|
||||
const method = init?.method ?? "GET";
|
||||
const redirect = (to: string, setCookie?: string) => new Response(null, { status: 302, headers: { location: to, ...(setCookie ? { "set-cookie": setCookie } : {}) } });
|
||||
if (url.hostname === "www.zerozero.pt") {
|
||||
if (url.pathname === "/oauth.php") {
|
||||
if (this.cookie(init, "zzuser")) return redirect(`https://fotos.zerozero.pt/api/auth/callback?code=c1&state=${url.searchParams.get("state")}`);
|
||||
return new Response("<form id=zz-login-form>", { status: 200, headers: { "set-cookie": "PHPSESSID=s1; path=/; domain=.zerozero.pt" } });
|
||||
}
|
||||
if (url.pathname === "/ax_login.php" && method === "POST") {
|
||||
const form = init!.body as FormData;
|
||||
this.logins++;
|
||||
if (form.get("login_username") !== "kapta" || form.get("login_password") !== this.password) return new Response(JSON.stringify({ status: false, msg: "Dados de acesso inválidos" }));
|
||||
return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; path=/; domain=.zerozero.pt" } });
|
||||
}
|
||||
}
|
||||
if (url.hostname !== "fotos.zerozero.pt") return new Response(null, { status: 404 });
|
||||
if (url.pathname === "/api/auth/login") return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&client_id=fotos&state=st1" });
|
||||
if (url.pathname === "/api/auth/callback") return redirect("/", "desk=ok; Path=/; HttpOnly");
|
||||
const signedIn = this.cookie(init, "desk");
|
||||
if (!signedIn) return Response.json({ error: "unauthorized" }, { status: 401 });
|
||||
if (url.pathname === "/api/auth/me") return Response.json({ role: "photographer", photographer_name: "Kapta+" });
|
||||
const game = (id: string, date: string, home: string, away: string) => ({ id, edition_id: "219039", date, home_team_name: home, away_team_name: away, edition_name: "UEFA Europa League 2026/27" });
|
||||
const games = [game("12627747", "2026-10-15 17:45:00", "Torreense", "Sunderland"), game("12627748", "2026-10-22 20:00:00", "Torreense", "Sunderland")];
|
||||
if (url.pathname === "/api/content/upcoming") return Response.json(games);
|
||||
const one = /^\/api\/content\/games\/(\d+)$/.exec(url.pathname);
|
||||
if (one) {
|
||||
const g = games.find((x) => x.id === one[1]);
|
||||
return g ? Response.json(g) : Response.json({ error: "not found" }, { status: 404 });
|
||||
}
|
||||
if (url.pathname === "/api/upload" && method === "POST") {
|
||||
const h = new Headers(init?.headers);
|
||||
const meta = Object.fromEntries(
|
||||
(h.get("upload-metadata") ?? "").split(",").map((pair) => {
|
||||
const [k, v] = pair.split(" ");
|
||||
return [k!, Buffer.from(v ?? "", "base64").toString("utf8")];
|
||||
}),
|
||||
);
|
||||
const id = `img-${this.uploads.size + 1}`;
|
||||
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
|
||||
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
|
||||
}
|
||||
const patch = /^\/upload\/(.+)$/.exec(url.pathname);
|
||||
if (patch && method === "PATCH") {
|
||||
const up = this.uploads.get(patch[1]!)!;
|
||||
if (Number(new Headers(init?.headers).get("upload-offset")) !== up.data.length) return new Response(null, { status: 409 });
|
||||
up.data = Buffer.concat([up.data, Buffer.from(init!.body as Uint8Array)]);
|
||||
return new Response(null, { status: 204, headers: { "upload-offset": String(up.data.length) } });
|
||||
}
|
||||
return new Response(null, { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
describe("zerozero", () => {
|
||||
it("reads game ids from links, knows teams by their names and finds the event's game", () => {
|
||||
expect(zerozeroGameId("https://fotos.zerozero.pt/edicoes/219039/12627747")).toBe("12627747");
|
||||
expect(zerozeroGameId(" 12627747 ")).toBe("12627747");
|
||||
expect(zerozeroGameId("https://www.zerozero.pt/jogo/2026-10-15-torreense-sunderland/12627747")).toBe("12627747");
|
||||
expect(zerozeroGameId("https://example.com/12627747")).toBeNull();
|
||||
expect(sameTeam("SC Torreense", "Torreense")).toBe(true);
|
||||
expect(sameTeam("Sporting CP", "Sporting")).toBe(true);
|
||||
expect(sameTeam("SL Benfica", "FC Porto")).toBe(false);
|
||||
const games = [
|
||||
{ id: "1", date: "2026-10-15 17:45:00", home: "Torreense", away: "Sunderland", competition: null },
|
||||
{ id: "2", date: "2026-10-15 17:45:00", home: "Sunderland", away: "Torreense", competition: null },
|
||||
];
|
||||
const lisbon = (d: string) => new Date(`${d.replace(" ", "T")}+01:00`);
|
||||
expect(matchGame(games, { home: "SC Torreense", away: "Sunderland AFC", startsAt: new Date("2026-10-15T16:45:00Z") }, lisbon)?.id).toBe("1");
|
||||
expect(matchGame(games, { home: "Torreense", away: "Sunderland", startsAt: new Date("2026-10-16T16:45:00Z") }, lisbon)).toBeNull();
|
||||
const jar = new CookieJar();
|
||||
jar.store("https://www.zerozero.pt/x", new Headers([["set-cookie", "a=1; Domain=.zerozero.pt; Path=/"]]));
|
||||
jar.store("https://fotos.zerozero.pt/x", new Headers([["set-cookie", "b=2; Path=/"]]));
|
||||
expect(jar.header("https://fotos.zerozero.pt/api")).toBe("a=1; b=2");
|
||||
expect(jar.header("https://www.zerozero.pt/")).toBe("a=1");
|
||||
});
|
||||
});
|
||||
|
||||
describe("delivery", () => {
|
||||
let ctx: TestContext;
|
||||
let dir: string;
|
||||
let ingestRoot: string;
|
||||
let nc: FakeNextcloud;
|
||||
let zz: FakeZerozero;
|
||||
let broadcaster: MemoryBroadcaster;
|
||||
let ingest: IngestService;
|
||||
let delivery: DeliveryService;
|
||||
@@ -78,11 +175,13 @@ describe("delivery", () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-del-"));
|
||||
ingestRoot = path.join(dir, "ingest");
|
||||
nc = new FakeNextcloud();
|
||||
zz = new FakeZerozero();
|
||||
const sites: typeof fetch = (input, init) => (zz.handles(input) ? zz.fetch(input, init) : nc.fetch(input, init));
|
||||
broadcaster = new MemoryBroadcaster();
|
||||
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot, DELIVERY_SECRET_KEY: KEY }, broadcaster, nc.fetch);
|
||||
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage"), INGEST_ROOT: ingestRoot, DELIVERY_SECRET_KEY: KEY }, broadcaster, sites);
|
||||
const storage = new LocalStorage(ctx.config.STORAGE_ROOT);
|
||||
ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner(ctx.config.JWT_SECRET, 3600), broadcaster, ingestRoot, log: quiet });
|
||||
delivery = new DeliveryService({ db: ctx.db, storage, secrets: new SecretBox(KEY), broadcaster, log: quiet, fetchImpl: nc.fetch });
|
||||
delivery = new DeliveryService({ db: ctx.db, storage, secrets: new SecretBox(KEY), broadcaster, log: quiet, fetchImpl: sites });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
@@ -94,6 +193,7 @@ describe("delivery", () => {
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
Object.assign(nc, { folders: new Set(["/"]), files: new Map(), shares: new Map(), failPuts: 0, status: undefined, auth: [] });
|
||||
Object.assign(zz, { logins: 0, uploads: new Map(), password: "zz-pass" });
|
||||
broadcaster.sent.length = 0;
|
||||
});
|
||||
|
||||
@@ -211,6 +311,105 @@ describe("delivery", () => {
|
||||
expect((resend.json() as { queued: { sequence: number }[] }).queued[0]?.sequence).toBe(3); // numbers are never reused
|
||||
});
|
||||
|
||||
it("ZeroZero: signs in, finds the event's game, and uploads with the photographer as author", async () => {
|
||||
const { orgId, token } = await setup();
|
||||
const event = (
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(token), payload: { home: "SC Torreense", away: "Sunderland", sport: "futebol", startsAt: "2026-10-15T16:45:00Z" } })
|
||||
).json() as { id: string };
|
||||
const bad = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "ZZ errado", kind: "ZEROZERO", baseUrl: "https://example.com", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "{originalName}" },
|
||||
});
|
||||
expect(bad.statusCode).toBe(400);
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", username: "kapta", password: "zz-pass", folderTemplate: "zerozero", fileNameTemplate: "PS_{home} x {away}_{n}.jpg", longEdge: 3000, jpegQuality: 92 },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) })).json()).toEqual({ ok: true, account: "Kapta+" });
|
||||
|
||||
// The game is found by teams and time; a link chooses another one.
|
||||
const found = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game?eventId=${event.id}`, headers: bearer(token) });
|
||||
expect(found.json()).toMatchObject({ chosen: false, game: { id: "12627747", home: "Torreense", away: "Sunderland" } });
|
||||
const chosen = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: "https://fotos.zerozero.pt/edicoes/219039/12627748" } });
|
||||
expect(chosen.json()).toMatchObject({ chosen: true, game: { id: "12627748" } });
|
||||
const forgot = await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: null } });
|
||||
expect(forgot.json()).toMatchObject({ chosen: false, game: { id: "12627747" } });
|
||||
expect((await ctx.app.inject({ method: "PUT", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, headers: bearer(token), payload: { eventId: event.id, game: "99999999" } })).statusCode).toBe(502);
|
||||
|
||||
const a = await photo("zz-a.jpg", "2026:10:15 18:10:00", { width: 6000, height: 4000 });
|
||||
const b = await photo("zz-b.jpg", "2026:10:15 18:20:00");
|
||||
await ctx.db.photo.updateMany({ where: { id: { in: [a, b] } }, data: { eventId: event.id } });
|
||||
// Only the best: without the autopilot, the photographer's stars decide.
|
||||
await ctx.db.photo.update({ where: { id: b }, data: { rating: 3 } });
|
||||
const best = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/best`, headers: bearer(token), payload: { targetId, eventId: event.id, count: 1, dryRun: true } });
|
||||
expect(best.json()).toEqual({ chosen: [b], queued: [], skipped: [] });
|
||||
const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a, b] } });
|
||||
expect(res.statusCode).toBe(202);
|
||||
zz.logins = 0;
|
||||
await drain();
|
||||
const items = await ctx.db.deliveryItem.findMany({ where: { targetId }, orderBy: { sequence: "asc" } });
|
||||
expect(items.map((i) => [i.status, i.lastError])).toEqual([
|
||||
["DONE", null],
|
||||
["DONE", null],
|
||||
]);
|
||||
expect(items.map((i) => i.remotePath).sort()).toEqual(["12627747/img-1", "12627747/img-2"]);
|
||||
expect((await ctx.db.event.findUniqueOrThrow({ where: { id: event.id } })).zerozeroGameId).toBe("12627747");
|
||||
const first = [...zz.uploads.values()].find((u) => u.meta.filename?.endsWith("_1.jpg"))!;
|
||||
expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" });
|
||||
expect(first.data.length).toBe(first.length);
|
||||
expect((await sharp(first.data).metadata()).width).toBe(3000);
|
||||
// Signed in once for the whole batch.
|
||||
expect(zz.logins).toBe(1);
|
||||
|
||||
// A wrong password stops at once, with the desk's message.
|
||||
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
|
||||
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
|
||||
expect(failed.statusCode).toBe(502);
|
||||
expect(failed.json()).toMatchObject({ message: "zerozero: Dados de acesso inválidos" });
|
||||
});
|
||||
|
||||
it("a folder on a computer: rendered here, then taken and saved by that computer's desktop app", async () => {
|
||||
const { orgId, token } = await setup();
|
||||
const noMachine = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets`, headers: bearer(token), payload: { name: "Pasta", kind: "LOCAL", baseUrl: "relativa/pasta", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" } });
|
||||
expect(noMachine.statusCode).toBe(400);
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/delivery-targets`,
|
||||
headers: bearer(token),
|
||||
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "PS_{home} x {away}_{n}.jpg" },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) })).json()).toEqual({ ok: true, account: "/Users/peter/Entregas" });
|
||||
|
||||
const a = await photo("local-a.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
|
||||
await drain();
|
||||
const waiting = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } });
|
||||
expect([waiting.status, waiting.remotePath]).toEqual(["WAITING", "VSC x AAAS/PS_VSC x AAAS_1.jpg"]);
|
||||
// Still on its way: the library shows it as queued, and it is not sent twice.
|
||||
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
|
||||
expect(again.json()).toMatchObject({ queued: [], skipped: [{ reason: "already_delivered" }] });
|
||||
|
||||
// Another computer gets nothing; this one gets the file and where it goes.
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0002-other" } })).json()).toEqual({ items: [] });
|
||||
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string; folder: string; path: string }[] };
|
||||
expect(claim.items.map((i) => [i.folder, i.path])).toEqual([["/Users/peter/Entregas", "VSC x AAAS/PS_VSC x AAAS_1.jpg"]]);
|
||||
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
|
||||
expect(file.statusCode).toBe(200);
|
||||
expect((await sharp(file.rawPayload).metadata()).format).toBe("jpeg");
|
||||
const done = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-result`, headers: bearer(token), payload: { ok: true, path: "/Users/peter/Entregas/VSC x AAAS/PS_VSC x AAAS_1.jpg" } });
|
||||
expect(done.json()).toMatchObject({ status: "DONE", remotePath: "/Users/peter/Entregas/VSC x AAAS/PS_VSC x AAAS_1.jpg" });
|
||||
// The server's copy is gone once the computer has it.
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it("retries transient errors with back-off and stops at auth errors", async () => {
|
||||
const { orgId, token, target } = await setup();
|
||||
const id = await photo("a.jpg", "2026:09:23 21:10:00");
|
||||
|
||||
@@ -299,7 +299,7 @@ describe("faces", () => {
|
||||
expect(list.samples[0]).toMatchObject({ suggested: "7", person: "Miguel Silva (VSC)" });
|
||||
const crop = await ctx.app.inject({ method: "GET", url: list.samples[0]!.crop });
|
||||
expect(crop.statusCode).toBe(200);
|
||||
expect((await sharp(crop.rawPayload).metadata()).height).toBeLessThanOrEqual(256);
|
||||
expect((await sharp(crop.rawPayload).metadata()).height).toBeLessThanOrEqual(512);
|
||||
// Collecting again adds nothing.
|
||||
expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { collected: number }).collected).toBe(0);
|
||||
|
||||
@@ -408,4 +408,26 @@ describe("faces", () => {
|
||||
await faces.refreshSuggestions(day1.id);
|
||||
expect((await listed()).groups.find((g) => g.id === g3.id)!.suggestion).toBeNull();
|
||||
});
|
||||
it("is surer when face and shirt agree on the same player", async () => {
|
||||
const { token, day1, day2 } = await setup();
|
||||
await photo("2026:09:23 21:00:00", [1]);
|
||||
await drain();
|
||||
const listed = (eventId: string) => ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/face-groups`, headers: bearer(token) }).then((r) => r.json() as { groups: { id: string; person: unknown; suggestion: { name: string; score: number } | null }[] });
|
||||
const [g] = (await listed(day1.id)).groups;
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g!.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva", club: "VSC", number: "7" } });
|
||||
// A week later: the face alone.
|
||||
await photo("2026:09:30 21:00:00", [1]);
|
||||
await photo("2026:09:30 21:01:00", [1]);
|
||||
await drain();
|
||||
const later = (await listed(day2.id)).groups[0]!;
|
||||
const byFace = later.suggestion!;
|
||||
expect(byFace.name).toBe("Miguel Silva");
|
||||
// The shirt reads 7 too.
|
||||
await ctx.db.face.updateMany({ where: { groupId: later.id }, data: { jerseyNumber: "7", jerseyScore: 0.9 } });
|
||||
await faces.refreshSuggestions(day2.id);
|
||||
const both = (await listed(day2.id)).groups[0]!.suggestion!;
|
||||
expect(both.name).toBe("Miguel Silva");
|
||||
expect(both.score).toBeGreaterThan(byFace.score);
|
||||
expect(both.score).toBeLessThanOrEqual(0.99);
|
||||
});
|
||||
});
|
||||
@@ -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, fpaProva, fpfDate, lisbonTime, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { type Fetch, fpaProva, fpaShortName, fpfDate, lisbonTime, parseFpaBoletim, parseFpaClubTerms, parseFpaMatchPage, parseFpaReferees, parseFpfLineups, seasonOf } from "../src/sports/providers.js";
|
||||
import { SportsService } from "../src/sports/service.js";
|
||||
import { LocalStorage } from "../src/storage/storage.js";
|
||||
import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js";
|
||||
@@ -58,6 +58,43 @@ describe("federation data", () => {
|
||||
expect(seasonOf(new Date("2027-03-01"))).toBe("20262027");
|
||||
});
|
||||
|
||||
it("reads the FPA match report: numbers and licences, the officials' letters, the referees", () => {
|
||||
const r = parseFpaBoletim(BOLETIM);
|
||||
expect(r.available).toBe(true);
|
||||
expect(r.home.map((p) => [p.number, p.name, p.externalId, p.position])).toEqual([
|
||||
["1", "Rui Lopes", "100001", null],
|
||||
["7", "Tiago Ferreira", "100002", null],
|
||||
["A", "Paulo Antunes", null, "Oficial A"],
|
||||
["B", "Nuno Rocha", null, "Oficial B"],
|
||||
]);
|
||||
expect(r.home[0]!.fullName).toBe("Rui Manuel Sousa Lopes");
|
||||
expect(r.away.map((p) => [p.number, p.name])).toEqual([
|
||||
["5", "João Alves"],
|
||||
["A", "Sérgio Paiva"],
|
||||
]);
|
||||
expect(r.referees).toEqual([
|
||||
{ name: "Duarte Sá", fullName: "Duarte Miguel Sá", role: "REFEREE", externalId: "185283" },
|
||||
{ name: "Inês Mota", fullName: "Inês Mota", role: "REFEREE", externalId: "183622" },
|
||||
{ name: "Carlos Mesa", fullName: "Carlos Mesa", role: "TABLE_OFFICIAL", externalId: "213551" },
|
||||
{ name: "Mário Delegado", fullName: "Mário Delegado", role: "DELEGATE", externalId: null },
|
||||
]);
|
||||
expect(parseFpaBoletim("<html><body><table><tr><td>Equipa A :: X</td></tr></table></body></html>").available).toBe(false);
|
||||
expect(fpaShortName("Ana Lima")).toBe("Ana Lima");
|
||||
expect(parseFpaClubTerms(CLUB_PAGE)).toEqual({ season: "374", levels: [{ id: "59", name: "Seniores M - ACR" }, { id: "4", name: "Seniores M" }, { id: "11", name: "Seniores F" }] });
|
||||
expect(parseFpaReferees("<body><a>Cursos Árbitros</a><table><tr><td>Árbitros</td>\n<td>Ana Lima, Bruno Costa</td></tr><tr><td>Delegados</td><td>Mário Silva</td></tr><tr><td>Oficiais de Mesa</td><td>Rita Sá, Luís Mota</td></tr></table></body>")).toEqual([
|
||||
{ name: "Ana Lima", role: "REFEREE" },
|
||||
{ name: "Bruno Costa", role: "REFEREE" },
|
||||
{ name: "Rita Sá", role: "TABLE_OFFICIAL" },
|
||||
{ name: "Luís Mota", role: "TABLE_OFFICIAL" },
|
||||
]);
|
||||
const page = parseFpaMatchPage(MATCH_PAGE);
|
||||
expect([...page.benchCipa.home]).toEqual([
|
||||
["A", "81778"],
|
||||
["B", "36457"],
|
||||
]);
|
||||
expect([...page.benchCipa.away]).toEqual([["A", "114813"]]);
|
||||
});
|
||||
|
||||
it("parses FPA competitions, FPF dates and FPF match sheets", () => {
|
||||
expect(fpaProva("PO01 - Campeonato Betclic Masculino")).toEqual({ code: "PO01", name: "Campeonato Betclic Masculino" });
|
||||
expect(fpaProva("PO01A - Divisao de Honra Masculina")).toEqual({ code: "PO01A", name: "Divisao de Honra Masculina" });
|
||||
@@ -76,16 +113,137 @@ describe("federation data", () => {
|
||||
|
||||
// --- the federations, offline ---------------------------------------------------------------------------------------
|
||||
|
||||
// UEFA's match JSON (match.uefa.com), trimmed to what is read.
|
||||
const TORREENSE = { id: "2603107", internationalName: "Torreense", teamCode: "TOR", logoUrl: "https://img.uefa.com/imgml/TP/teams/logos/70x70/2603107.png" };
|
||||
const SUNDERLAND = { id: "53360", internationalName: "Sunderland", teamCode: "SUN" };
|
||||
const LYON = { id: "5312", internationalName: "Lyon", teamCode: "LYO" };
|
||||
const UEFA_MATCHES = [
|
||||
{
|
||||
id: "2049001",
|
||||
kickOffTime: { date: "2026-10-01", dateTime: "2026-10-01T19:00:00Z", utcOffsetInHours: 1 },
|
||||
homeTeam: LYON,
|
||||
awayTeam: TORREENSE,
|
||||
stadium: { translations: { name: { EN: "OL Stadium" } }, city: { EN: "Lyon", PT: "Lyon" } },
|
||||
score: { total: { home: 1, away: 2 } },
|
||||
status: "FINISHED",
|
||||
matchday: { name: "MD1", longName: "Matchday 1" },
|
||||
referees: [],
|
||||
},
|
||||
{
|
||||
id: "2050091",
|
||||
kickOffTime: { date: "2026-10-15", dateTime: "2026-10-15T16:45:00Z", utcOffsetInHours: 1 },
|
||||
homeTeam: TORREENSE,
|
||||
awayTeam: SUNDERLAND,
|
||||
stadium: { name: { EN: "Estádio Dr. Magalhães Pessoa" }, city: { EN: "Leiria" } },
|
||||
score: null,
|
||||
status: "UPCOMING",
|
||||
lineupStatus: "NOT_AVAILABLE",
|
||||
matchday: { name: "MD2", longName: "Matchday 2" },
|
||||
referees: [
|
||||
{ person: { translations: { name: { EN: "Enea Jorgji" } } }, role: "REFEREE" },
|
||||
{ person: { name: { EN: "Denis Rexha" } }, role: "ASSISTANT_REFEREE_ONE" },
|
||||
{ person: { name: { EN: "Ridiger Çokaj" } }, role: "ASSISTANT_REFEREE_TWO" },
|
||||
{ person: { name: { EN: "Juxhin Xhaja" } }, role: "FOURTH_OFFICIAL" },
|
||||
{ person: { name: { EN: "Daniele Doveri" } }, role: "VIDEO_ASSISTANT_REFEREE" },
|
||||
{ person: { name: { EN: "Thibault De Gendt" } }, role: "UEFA_DELEGATE" },
|
||||
],
|
||||
},
|
||||
];
|
||||
const uefaPlayer = (id: string, name: string, extra: object = {}) => ({ id, internationalName: name, imageUrl: `https://img.uefa.com/imgml/TP/players/1/2027/324x324/${id}.jpg`, ...extra });
|
||||
const UEFA_SHEET = {
|
||||
homeTeam: { field: [{ jerseyNumber: 1, type: "GOALKEEPER", player: uefaPlayer("9001", "Lucas Perri") }], bench: [], coaches: [] },
|
||||
awayTeam: {
|
||||
field: [
|
||||
{ jerseyNumber: 1, type: "GOALKEEPER", player: uefaPlayer("8001", "Lucas Paes") },
|
||||
{ jerseyNumber: 9, type: "PLAYER", player: uefaPlayer("8002", "Stopira", { fieldPosition: "FORWARD", translations: { fieldPosition: { PT: "Avançado" } } }) },
|
||||
],
|
||||
bench: [{ jerseyNumber: 21, type: "PLAYER", player: uefaPlayer("8003", "Manuel Pozo") }],
|
||||
coaches: [{ role: "COACH", person: { id: "7001", translations: { name: { EN: "Luís Tralhão" } } } }],
|
||||
},
|
||||
};
|
||||
|
||||
/** A handball match report as the FPA prints it (invented people), in its own charset. */
|
||||
const tr = (...cells: string[]) => `<tr>${cells.map((c) => `<td class="texto">${c}</td>`).join("")}</tr>`;
|
||||
const BOLETIM = `<html><head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>FAP :: Boletim do Jogo n. 28</title></head><body>
|
||||
<table><tr><td><table class="tabela">${tr("Resultado 1ª Parte", "A", "B")}${tr("14", "10", "19", "19", "", "", "33", "29")}</table></td></tr></table>
|
||||
<table class="tabela"><tr><td class="textob" colspan="11">Equipa A :: VITÓRIA SC </td></tr>
|
||||
${tr("Nº", "CIPA", "Nome", "G", "A", "2'", "2'", "2'", "D", "E", "TP")}
|
||||
${tr("1", "100001", "Rui Manuel Sousa Lopes", "0")}
|
||||
${tr("07", "100002", "Tiago Ferreira", "4")}
|
||||
${tr("Oficial A", "Grau 3", "Paulo Jorge Antunes", "X")}
|
||||
${tr("Oficial B", "Grau 4", "Nuno Miguel Rocha", "")}
|
||||
</table>
|
||||
<table>${tr("1º Time-out 09:33 2º Time-out --:--")}</table>
|
||||
<table class="tabela"><tr><td class="textob" colspan="11">Equipa B :: ÁGUAS SANTAS MILANEZA</td></tr>
|
||||
${tr("Nº", "CIPA", "Nome", "G")}
|
||||
${tr("5", "100003", "João Pedro Gonçalves Alves", "6")}
|
||||
${tr("Oficial A", "Trei. Estagiário Grau 2", "Sérgio Paiva", "")}
|
||||
</table>
|
||||
<table>${tr("Árbitro 1")}${tr("Nome:", "Duarte Miguel Sá")}${tr("CIPA:", "185283")}${tr("Árbitro 2")}${tr("Nome:", "Inês Mota")}${tr("CIPA:", "183622")}
|
||||
${tr("Oficial Mesa 1")}${tr("Nome:", "Carlos Mesa")}${tr("CIPA:", "213551")}${tr("Delegado 1")}${tr("Nome:", "Mário Delegado")}</table>
|
||||
</body></html>`;
|
||||
const pane = (id: string, rows: [string, string, string][]) =>
|
||||
`<div class="module-table bulletin__team-players js-module-tabs-pane" data-pane="${id}"><div class="module-table__header"><div>Nº</div><div>Nº CIPA</div><div>Nome</div></div><div class="module-table__content">${rows
|
||||
.map(([n, cipa, name]) => `<div class="module-table__row"><div>${n}</div><div><a href="/associado/${cipa}/" title="Ver ${name}">${cipa}</a></div><div>${name}</div></div>`)
|
||||
.join("")}</div></div>`;
|
||||
/** The match page once played: referees by name, and a pane per team with every licence number. */
|
||||
const MATCH_PAGE = `<html><body><table><tr><td>Árbitros</td><td>Duarte Sá, Inês Mota</td></tr></table>${pane("team-a", [
|
||||
["1", "100001", "Rui Lopes"],
|
||||
["Oficial A", "81778", "Paulo Antunes"],
|
||||
["Oficial B", "36457", "Nuno Rocha"],
|
||||
])}${pane("team-b", [["Oficial A", "114813", "Sérgio Paiva"]])}</body></html>`;
|
||||
const CLUB_PAGE = `<script>var TABLE_CONTENT_1 = {"title":"Resultados","club_id":"140","dropdowns":[{"tabId":"all","id":"season","label":"\\u00c9poca","options":[{"term_id":"374","name":"\\u00c9poca 2026/27"},{"term_id":"373","name":"\\u00c9poca 2025/26"}]},{"tabId":"all","id":"level","label":"Escal\\u00f5es","options":[{"term_id":"59","name":"Seniores M - ACR"},{"term_id":"4","name":"Seniores M"},{"term_id":"11","name":"Seniores F"}]}]};</script>`;
|
||||
const fpaGame = (id: string, day: string, home: [string, string, string], away: [string, string, string], goals: [number, number] | null) => ({
|
||||
ID_PROVA_JOGO: id,
|
||||
JOG_DATA: day,
|
||||
JOG_HORA: "16:00",
|
||||
JOG_NUM_JOGO: "28",
|
||||
EQUIPA_CASA_ID: home[0],
|
||||
CLUBE_CASA_ID: home[1],
|
||||
EQUIPA_CASA: home[2],
|
||||
EQUIPA_FORA_ID: away[0],
|
||||
CLUBE_FORA_ID: away[1],
|
||||
EQUIPA_FORA: away[2],
|
||||
GOLOS_CASA: goals ? String(goals[0]) : null,
|
||||
GOLOS_FORA: goals ? String(goals[1]) : null,
|
||||
LOCAL: "DESP. UNIDADE VIMARANENSE",
|
||||
FASE: "1a Fase",
|
||||
PROVA: "PO01 - Campeonato Betclic Masculino",
|
||||
PRO_SEXO: "M",
|
||||
});
|
||||
const VITORIA: [string, string, string] = ["43045", "140", "VITÓRIA SC"];
|
||||
const AGUAS: [string, string, string] = ["42964", "141", "ÁGUAS SANTAS MILANEZA"];
|
||||
|
||||
const BENFICA = { id: 1, external_id: "278", name: "SL Benfica", abbreviation: "SLB", logo: "https://www.ligaportugal.pt/l/slb.png" };
|
||||
const PORTO = { id: 2, external_id: "157", name: "FC Porto", abbreviation: "FCP" };
|
||||
const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos?: string }[]; png: Buffer }) => {
|
||||
const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos?: string }[]; png: Buffer; handball?: boolean }) => {
|
||||
const calls: string[] = [];
|
||||
const fetcher: Fetch = async (url) => {
|
||||
calls.push(url);
|
||||
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 (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"));
|
||||
if (state.handball && u.host === "si.fpa.pt" && u.pathname.includes("print_boletim"))
|
||||
return bytes(u.searchParams.get("P_ID_PROVA_JOGO") === "323264" ? Buffer.from(BOLETIM, "latin1") : Buffer.from("<html><body></body></html>"));
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/jogo/323264/") return bytes(Buffer.from(MATCH_PAGE, "utf8"));
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname === "/jogo/323500/")
|
||||
return bytes(
|
||||
Buffer.from(
|
||||
"<html><body><h2>Jogo 41</h2><table><tr><td>Árbitros</td><td>Duarte Sá, Bruno Costa</td></tr><tr><td>Delegados</td><td>Mário</td></tr><tr><td>Oficiais de Mesa</td><td>Carlos Mesa</td></tr></table></body></html>",
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const licence = /^\/associado\/(100001|185283)\/$/.exec(u.pathname)?.[1];
|
||||
if (state.handball && u.host === "portal.fpa.pt" && licence)
|
||||
return bytes(Buffer.from(`<html><body><img src="https://si.fpa.pt/blob/obj_anexo/FOTO_CIPA/555_${licence}.JPG"></body></html>`, "utf8"));
|
||||
if (state.handball && u.host === "portal.fpa.pt" && u.pathname.startsWith("/associado/")) return bytes(Buffer.from('<html><body><img src="https://portal.fpa.pt/wp-content/themes/fap/no-image.png"></body></html>'));
|
||||
if (state.handball && u.host === "si.fpa.pt" && u.pathname.includes("FOTO_CIPA")) return bytes(state.png);
|
||||
if (u.host === "ws.fpa.pt")
|
||||
return json([
|
||||
...(state.handball ? [fpaGame("323500", "2026-10-17", VITORIA, AGUAS, null)] : []),
|
||||
{
|
||||
ID_PROVA_JOGO: "323405",
|
||||
JOG_DATA: "2026-10-14",
|
||||
@@ -103,6 +261,11 @@ const fakeSites = (state: { benfica: { shirtNumber: number; name: string; photos
|
||||
GOLOS_FORA: null,
|
||||
},
|
||||
]);
|
||||
if (u.host === "match.uefa.com") {
|
||||
if (u.pathname === "/v5/matches") return json(u.searchParams.get("competitionId") === "14" && u.searchParams.get("offset") === "0" ? UEFA_MATCHES : []);
|
||||
if (u.pathname === "/v5/matches/2049001/lineups") return json(UEFA_SHEET);
|
||||
if (u.pathname.endsWith("/lineups")) return json({ homeTeam: { field: [], bench: [], coaches: [] }, awayTeam: { field: [], bench: [], coaches: [] } });
|
||||
}
|
||||
if (u.pathname.endsWith("/competition/teams")) return json(u.searchParams.get("competition") === "ligaportugalbetclic" ? [BENFICA, PORTO] : []);
|
||||
if (u.pathname.endsWith("/team/squad"))
|
||||
return json({ players: u.searchParams.get("id") === "278" ? state.benfica : [{ shirtNumber: 99, name: "Diogo Costa", position: "Guarda-Redes" }] });
|
||||
@@ -126,14 +289,14 @@ describe("sports data service", () => {
|
||||
let dir: string;
|
||||
let sports: SportsService;
|
||||
let sites: ReturnType<typeof fakeSites>;
|
||||
const state = { benfica: [] as { shirtNumber: number; name: string; photos?: string }[], png: Buffer.alloc(0) };
|
||||
const state = { benfica: [] as { shirtNumber: number; name: string; photos?: string }[], png: Buffer.alloc(0), handball: false };
|
||||
|
||||
beforeAll(async () => {
|
||||
dir = await mkdtemp(path.join(tmpdir(), "pr-sports-"));
|
||||
sites = fakeSites(state);
|
||||
ctx = await createTestApp({ STORAGE_ROOT: path.join(dir, "storage") }, undefined, sites.fetcher as unknown as typeof fetch);
|
||||
state.png = await sharp({ create: { width: 200, height: 200, channels: 4, background: { r: 200, g: 0, b: 0, alpha: 0.5 } } }).png().toBuffer();
|
||||
sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0 });
|
||||
sports = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: sites.fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
|
||||
});
|
||||
afterAll(async () => {
|
||||
await ctx.app.close();
|
||||
@@ -142,6 +305,7 @@ describe("sports data service", () => {
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await resetDb(ctx.db);
|
||||
state.handball = false;
|
||||
state.benfica = [
|
||||
{ shirtNumber: 14, name: "Vangelis Pavlidis", photos: "https://www.ligaportugal.pt/p/pavlidis.png" },
|
||||
{ shirtNumber: 1, name: "Anatoliy Trubin" },
|
||||
@@ -159,10 +323,17 @@ describe("sports data service", () => {
|
||||
["FPA", "PO09", "20262027"],
|
||||
["LIGA", "ligaportugalbetclic", "20262027"],
|
||||
["LIGA", "ligaportugalmeusuper", "20262027"],
|
||||
["UEFA", "1", "20262027"],
|
||||
["UEFA", "2019", "20262027"],
|
||||
["UEFA", "14", "20262027"],
|
||||
["UEFA", "27", "20262027"],
|
||||
["UEFA", "28", "20262027"],
|
||||
]);
|
||||
const fixtures = await ctx.db.sportsFixture.findMany({ include: { homeTeam: true, awayTeam: true }, orderBy: { startsAt: "asc" } });
|
||||
expect(fixtures.map((f) => [f.homeTeam.name, f.awayTeam.name, f.startsAt.toISOString()])).toEqual([
|
||||
["Lyon", "Torreense", "2026-10-01T19:00:00.000Z"],
|
||||
["MADEIRA SAD", "ABC DE BRAGA", "2026-10-14T18:30:00.000Z"],
|
||||
["Torreense", "Sunderland", "2026-10-15T16:45:00.000Z"],
|
||||
["SL Benfica", "FC Porto", "2026-10-18T19:30:00.000Z"],
|
||||
]);
|
||||
const benfica = await ctx.db.sportsTeam.findFirstOrThrow({ where: { name: "SL Benfica" } });
|
||||
@@ -267,4 +438,117 @@ describe("sports data service", () => {
|
||||
expect((await ctx.app.inject({ method: "GET", url: "/v1/sports/competitions" })).statusCode).toBe(401);
|
||||
expect((await ctx.app.inject({ method: "POST", url: "/v1/sports/competitions", headers: bearer(token), payload: { url: "competitionId=1&seasonId=105" } })).statusCode).toBe(403);
|
||||
});
|
||||
it("FPA: squads from the match reports, licence photos and the referees of the event", async () => {
|
||||
state.handball = true;
|
||||
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "vitoria", role: "OWNER" });
|
||||
await ctx.db.organization.update({ where: { id: org!.id }, data: { biometricsEnabled: true } });
|
||||
const r = await sports.refreshFpa(now);
|
||||
expect(r.errors).toEqual([]);
|
||||
const vitoria = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "43045" } });
|
||||
expect((await sports.squad(vitoria.id)).map((p) => [p.number, p.name])).toEqual([
|
||||
["1", "Rui Lopes"],
|
||||
["7", "Tiago Ferreira"],
|
||||
["A", "Paulo Antunes"],
|
||||
["B", "Nuno Rocha"],
|
||||
]);
|
||||
// The game already played is kept, its report read once (with its referees).
|
||||
const played = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "323264" } });
|
||||
expect(played.lineupAt).not.toBeNull();
|
||||
expect(played).toMatchObject({ homeScore: 33, awayScore: 29 });
|
||||
expect((played.officials as { name: string }[]).map((o) => o.name)).toEqual(["Duarte Sá", "Inês Mota", "Carlos Mesa", "Mário Delegado"]);
|
||||
// The bench officials' licence comes from the match page; the referees and table officials are kept by licence.
|
||||
expect((await ctx.db.sportsPlayer.findFirstOrThrow({ where: { teamId: vitoria.id, number: "A" } })).externalId).toBe("81778");
|
||||
const refs = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "FPA", externalId: "ARBITRAGEM" } });
|
||||
expect((await sports.squad(refs.id)).map((p) => [p.name, p.externalId, p.fullName])).toEqual([
|
||||
["Carlos Mesa", "213551", "Carlos Mesa"],
|
||||
["Duarte Sá", "185283", "Duarte Miguel Sá"],
|
||||
["Inês Mota", "183622", "Inês Mota"],
|
||||
]);
|
||||
// A second refresh starts no team again.
|
||||
const before = sites.calls.length;
|
||||
await sports.refreshFpa(new Date(now.getTime() + 7 * 3600_000));
|
||||
expect(sites.calls.slice(before).filter((u) => u.includes("/clube/") || u.includes("print_boletim"))).toEqual([]);
|
||||
|
||||
const token = (await login(ctx.app, user.email)).body.accessToken;
|
||||
const next = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "323500" } });
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${org!.id}/events`,
|
||||
headers: bearer(token),
|
||||
payload: { home: "VITÓRIA SC", away: "ÁGUAS SANTAS MILANEZA", startsAt: next.startsAt.toISOString(), fixtureId: next.id },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) })).statusCode).toBe(200);
|
||||
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
||||
expect(people.map((p) => [p.name, p.club, p.number, !!p.referenceKey])).toEqual([
|
||||
["Bruno Costa", "Arbitragem", null, false],
|
||||
["Carlos Mesa", "Arbitragem", null, false],
|
||||
["Duarte Sá", "Arbitragem", null, true],
|
||||
["João Alves", "ÁGUAS SANTAS MILANEZA", "5", false],
|
||||
["Nuno Rocha", "VITÓRIA SC", "B", false],
|
||||
["Paulo Antunes", "VITÓRIA SC", "A", false],
|
||||
["Rui Lopes", "VITÓRIA SC", "1", true],
|
||||
["Sérgio Paiva", "ÁGUAS SANTAS MILANEZA", "A", false],
|
||||
["Tiago Ferreira", "VITÓRIA SC", "7", false],
|
||||
]);
|
||||
|
||||
// Photos of each player in the event: confirmed faces, and faces taken for them (70% or more) not confirmed yet.
|
||||
const eventId = created.json().id as string;
|
||||
const byName = new Map(people.map((p) => [p.name, p.id]));
|
||||
const shot = (n: number) => ctx.db.photo.create({ data: { organizationId: org!.id, eventId, originalName: `IMG_${n}.JPG`, byteSize: 1, storageKey: `k${n}`, sha256: `sha${n}`, status: "READY", source: "UPLOAD" } });
|
||||
const group = (data: { personId?: string; suggestedPersonId?: string; suggestionScore?: number }) => ctx.db.faceGroup.create({ data: { organizationId: org!.id, eventId, model: "m", ...data } });
|
||||
const face = (photoId: string, groupId: string) => ctx.db.face.create({ data: { organizationId: org!.id, photoId, groupId, x0: 0, y0: 0, x1: 0.1, y1: 0.1, score: 0.9, model: "m" } });
|
||||
const [p1, p2, p3, p4] = await Promise.all([shot(1), shot(2), shot(3), shot(4)]);
|
||||
const confirmed = await group({ personId: byName.get("Rui Lopes")! });
|
||||
const likely = await group({ suggestedPersonId: byName.get("Rui Lopes")!, suggestionScore: 0.8 });
|
||||
const doubtful = await group({ suggestedPersonId: byName.get("Tiago Ferreira")!, suggestionScore: 0.5 });
|
||||
await face(p1!.id, confirmed.id);
|
||||
await face(p2!.id, confirmed.id);
|
||||
await face(p2!.id, likely.id); // already confirmed in this photo: counted once
|
||||
await face(p3!.id, likely.id);
|
||||
await face(p4!.id, doubtful.id);
|
||||
const squads = (await ctx.app.inject({ method: "GET", url: `/v1/events/${eventId}/squads`, headers: bearer(token) })).json() as { sides: { players: { name: string; photos: { confirmed: number; likely: number } }[] }[] };
|
||||
const photosOf = (name: string) => squads.sides.flatMap((s) => s.players).find((p) => p.name === name)!.photos;
|
||||
expect(photosOf("Rui Lopes")).toEqual({ confirmed: 2, likely: 1 });
|
||||
expect(photosOf("Tiago Ferreira")).toEqual({ confirmed: 0, likely: 0 });
|
||||
});
|
||||
|
||||
it("UEFA: matches with the referee team, squads from match sheets, and the referees as people of the event", async () => {
|
||||
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "torreense", role: "OWNER" });
|
||||
await sports.refreshDue(now);
|
||||
const uel = await ctx.db.sportsCompetition.findFirstOrThrow({ where: { provider: "UEFA", externalId: "14" } });
|
||||
expect(uel).toMatchObject({ name: "UEFA Europa League", sport: "futebol", lastError: null });
|
||||
const torreense = await ctx.db.sportsTeam.findFirstOrThrow({ where: { provider: "UEFA", externalId: "2603107" } });
|
||||
// The squad, from Matchday 1's sheet: numbers, goalkeeper, position in Portuguese, the coach.
|
||||
expect((await sports.squad(torreense.id)).map((p) => [p.number, p.name, p.position])).toEqual([
|
||||
["1", "Lucas Paes", "Guarda-Redes"],
|
||||
["9", "Stopira", "Avançado"],
|
||||
["21", "Manuel Pozo", null],
|
||||
[null, "Luís Tralhão", "Treinador"],
|
||||
]);
|
||||
// The next match's sheet is not out yet: read again around kick-off.
|
||||
const next = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "2050091" } });
|
||||
expect(next).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa, Leiria", lineupAt: null });
|
||||
expect((next.officials as { role: string }[]).map((o) => o.role)).toContain("REFEREE");
|
||||
|
||||
const token = (await login(ctx.app, user.email)).body.accessToken;
|
||||
const list = (await ctx.app.inject({ method: "GET", url: `/v1/sports/fixtures?from=2026-10-12&q=Torreense`, headers: bearer(token) })).json();
|
||||
const fixture = list.fixtures.find((f: { id: string }) => f.id === next.id);
|
||||
expect(fixture).toMatchObject({ competition: { name: "UEFA Europa League" }, home: { name: "Torreense" }, away: { name: "Sunderland" } });
|
||||
const created = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/events`, headers: bearer(token), payload: { home: "Torreense", away: "Sunderland", startsAt: fixture.startsAt, fixtureId: fixture.id } });
|
||||
expect(created.statusCode).toBe(201);
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/events/${created.json().id}/squads/sync`, headers: bearer(token) });
|
||||
const people = await ctx.db.person.findMany({ where: { organizationId: org!.id }, orderBy: { name: "asc" } });
|
||||
// Players and coach of Torreense, and the referee team on the pitch (not the VAR or the delegate).
|
||||
expect(people.map((p) => [p.name, p.club, p.number])).toEqual([
|
||||
["Denis Rexha", "Arbitragem", null],
|
||||
["Enea Jorgji", "Arbitragem", null],
|
||||
["Juxhin Xhaja", "Arbitragem", null],
|
||||
["Lucas Paes", "Torreense", "1"],
|
||||
["Luís Tralhão", "Torreense", null],
|
||||
["Manuel Pozo", "Torreense", "21"],
|
||||
["Ridiger Çokaj", "Arbitragem", null],
|
||||
["Stopira", "Torreense", "9"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { ApiClient, DeliveryTarget } from "@photoreport/sdk";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ImportTargets } from "../library/ImportTargets.js";
|
||||
import { type DeliveryShell, saveWaitingDeliveries } from "./localDeliveries.js";
|
||||
|
||||
const shell = (over: Partial<DeliveryShell> = {}): DeliveryShell => ({
|
||||
machine: async () => "desktop-0123456789abcdef",
|
||||
pick: async () => "/Users/peter/Entregas",
|
||||
write: async (folder, path) => `${folder}/${path}`,
|
||||
profiles: async () => ({ photoMechanic: [], photoMechanicAccounts: [], filezilla: null }),
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("deliveries to a folder on this computer", () => {
|
||||
it("saves what waits for this computer and tells the server where (or why not)", async () => {
|
||||
const results: unknown[] = [];
|
||||
const api = {
|
||||
claimLocalDeliveries: vi.fn(async (_org: string, machine: string) => ({
|
||||
items:
|
||||
machine === "desktop-0123456789abcdef"
|
||||
? [
|
||||
{ id: "a", folder: "/Users/peter/Entregas", path: "VSC x AAAS/PS_1.jpg", byteSize: 3 },
|
||||
{ id: "b", folder: "/Users/peter/Entregas", path: "VSC x AAAS/PS_2.jpg", byteSize: 3 },
|
||||
]
|
||||
: [],
|
||||
})),
|
||||
localDeliveryFile: vi.fn(async () => new Uint8Array([1, 2, 3]).buffer),
|
||||
localDeliveryResult: vi.fn(async (_org: string, id: string, r: unknown) => {
|
||||
results.push([id, r]);
|
||||
return {};
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
const writes: string[] = [];
|
||||
const r = await saveWaitingDeliveries(
|
||||
api,
|
||||
"org",
|
||||
shell({
|
||||
write: async (folder, path, bytes) => {
|
||||
if (path.endsWith("_2.jpg")) throw new Error("disk full");
|
||||
writes.push(`${folder}/${path}:${bytes.byteLength}`);
|
||||
return `${folder}/${path}`;
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(r).toEqual({ saved: 1, failed: 1 });
|
||||
expect(writes).toEqual(["/Users/peter/Entregas/VSC x AAAS/PS_1.jpg:3"]);
|
||||
expect(results).toEqual([
|
||||
["a", { ok: true, path: "/Users/peter/Entregas/VSC x AAAS/PS_1.jpg" }],
|
||||
["b", { ok: false, error: "disk full" }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const SITES = `<FileZilla3><Servers><Server><Host>ftp.clube.pt</Host><Port>21</Port><Protocol>0</Protocol><User>fotos</User><Name>Clube</Name><RemoteDir>1 0 8 imprensa</RemoteDir></Server><Server><Host>ftp.jornal.pt</Host><Protocol>0</Protocol><User>j</User><Name>Jornal</Name></Server></Servers></FileZilla3>`;
|
||||
|
||||
describe("importing destinations", () => {
|
||||
it("brings the chosen ones in, with the password typed here", async () => {
|
||||
const created: unknown[] = [];
|
||||
const api = {
|
||||
createDeliveryTarget: vi.fn(async (_org: string, input: { name: string }) => {
|
||||
created.push(input);
|
||||
return { id: `t${created.length}`, ...input } as unknown as DeliveryTarget;
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
const onImported = vi.fn();
|
||||
render(
|
||||
<ImportTargets
|
||||
api={api}
|
||||
orgId="org"
|
||||
existing={[{ name: "Jornal" } as DeliveryTarget]}
|
||||
shell={shell({ profiles: async () => ({ photoMechanic: [], photoMechanicAccounts: [], filezilla: SITES }) })}
|
||||
onClose={() => {}}
|
||||
onImported={onImported}
|
||||
/>,
|
||||
);
|
||||
// A name already taken here gets the source added.
|
||||
expect(await screen.findByDisplayValue("Jornal (FileZilla)")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Importar" }).hasAttribute("disabled")).toBe(true);
|
||||
// Typing the password chooses it.
|
||||
fireEvent.change(screen.getAllByPlaceholderText("Senha")[0]!, { target: { value: "segredo" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Importar 1" }));
|
||||
await waitFor(() => expect(onImported).toHaveBeenCalled());
|
||||
expect(created).toEqual([
|
||||
expect.objectContaining({ name: "Clube", kind: "FTP", baseUrl: "ftp://ftp.clube.pt", username: "fotos", password: "segredo", folderTemplate: "/imprensa/", fileNameTemplate: "{originalName}" }),
|
||||
]);
|
||||
expect(await screen.findByText("Importado")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("says when the desktop app is too old for it", async () => {
|
||||
render(<ImportTargets api={{} as ApiClient} orgId="org" existing={[]} shell={shell({ profiles: async () => Promise.reject(new Error("command not found")) })} onClose={() => {}} onImported={() => {}} />);
|
||||
expect(await screen.findByText(/atualiza a app/)).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import type { ImportSources } from "../library/importTargets.js";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
|
||||
/** The desktop shell's side of "a folder on this computer" and of importing destinations (src-tauri/src/deliver.rs). */
|
||||
export interface DeliveryShell {
|
||||
/** This computer's id: the server hands it the files of its folders. */
|
||||
machine(): Promise<string>;
|
||||
/** The system's folder picker; the folder becomes a place files may be saved. */
|
||||
pick(): Promise<string | null>;
|
||||
/** Saves a file under a chosen folder; returns where. */
|
||||
write(folder: string, path: string, bytes: ArrayBuffer): Promise<string>;
|
||||
/** Destinations saved in Photo Mechanic and FileZilla (without passwords). */
|
||||
profiles(): Promise<ImportSources>;
|
||||
}
|
||||
|
||||
export const desktopDeliveryShell: DeliveryShell = {
|
||||
machine: () => desktopInvoke<string>("delivery_machine"),
|
||||
pick: () => desktopInvoke<string | null>("delivery_folder_pick"),
|
||||
write: async (folder, path, bytes) => {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
// The file is the raw body; where it goes rides in headers (percent-encoded: names with accents).
|
||||
return invoke<string>("delivery_write", new Uint8Array(bytes), { headers: { folder: encodeURIComponent(folder), path: encodeURIComponent(path) } });
|
||||
},
|
||||
profiles: () => desktopInvoke<ImportSources>("import_upload_profiles"),
|
||||
};
|
||||
|
||||
/** One pass: takes what waits for this computer's folders, saves each file, and tells the server. */
|
||||
export async function saveWaitingDeliveries(api: ApiClient, orgId: string, shell: DeliveryShell): Promise<{ saved: number; failed: number }> {
|
||||
const machine = await shell.machine();
|
||||
const { items } = await api.claimLocalDeliveries(orgId, machine);
|
||||
let saved = 0;
|
||||
let failed = 0;
|
||||
for (const item of items) {
|
||||
try {
|
||||
const bytes = await api.localDeliveryFile(orgId, item.id);
|
||||
const where = await shell.write(item.folder, item.path, bytes);
|
||||
await api.localDeliveryResult(orgId, item.id, { ok: true, path: where });
|
||||
saved++;
|
||||
} catch (err) {
|
||||
failed++;
|
||||
const error = err instanceof Error ? err.message : String(err);
|
||||
await api.localDeliveryResult(orgId, item.id, { ok: false, error }).catch(() => {});
|
||||
}
|
||||
}
|
||||
return { saved, failed };
|
||||
}
|
||||
|
||||
const EVERY_MS = 10_000;
|
||||
|
||||
/** Desktop only, while signed in: saves deliveries meant for this computer's folders as they are rendered. */
|
||||
export function LocalDeliveries({ shell = desktopDeliveryShell, enabled = isDesktop(), everyMs = EVERY_MS }: { shell?: DeliveryShell; enabled?: boolean; everyMs?: number }) {
|
||||
const { api, organization } = useAuth();
|
||||
const orgId = organization?.id;
|
||||
useEffect(() => {
|
||||
if (!enabled || !orgId) return;
|
||||
let alive = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const tick = async () => {
|
||||
try {
|
||||
// Keep going while there is more (a batch of 10 at a time).
|
||||
for (let round = 0; round < 20 && alive; round++) {
|
||||
const r = await saveWaitingDeliveries(api, orgId, shell);
|
||||
if (r.saved + r.failed < 10) break;
|
||||
}
|
||||
} catch {
|
||||
// Offline, or a desktop app too old for this: try again later.
|
||||
}
|
||||
if (alive) timer = setTimeout(() => void tick(), everyMs);
|
||||
};
|
||||
void tick();
|
||||
return () => {
|
||||
alive = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [api, orgId, shell, enabled, everyMs]);
|
||||
return null;
|
||||
}
|
||||
+45
-3
@@ -58,6 +58,12 @@ export const t = {
|
||||
noPlayersFilter: "Sem jogador",
|
||||
clearFilter: "Limpar filtro",
|
||||
sendN: (n: number) => (n ? `Enviar ${n}` : "Enviar"),
|
||||
bestButton: "Melhores…",
|
||||
bestHelp: "Envia só as melhores fotos deste jogo: momentos de jogo (bola, duelos, festejos), nítidas e espalhadas pelo jogo, sem repetidas. As fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
|
||||
bestCount: "Quantas fotos",
|
||||
bestSend: (target: string) => `Enviar as melhores para ${target}`,
|
||||
bestSent: (queued: number, chosen: number) => (queued === chosen ? `${chosen} melhores na fila` : `${chosen} escolhidas, ${queued} na fila (as outras já tinham ido)`),
|
||||
bestNone: "Não há fotos de jogo para escolher",
|
||||
sendTo: "Enviar para",
|
||||
selectToSend: "Seleciona as fotografias a enviar (⌘A seleciona todas as do filtro).",
|
||||
setUpDelivery: "Configurar envio",
|
||||
@@ -153,6 +159,7 @@ export const t = {
|
||||
select: "Selecionar para juntar",
|
||||
photos: (n: number) => (n === 1 ? "1 foto" : `${n} fotos`),
|
||||
namePlaceholder: "Nome ou \\código\\",
|
||||
official: (letter: string) => `Oficial ${letter}`,
|
||||
ignore: "Ignorar",
|
||||
unignore: "Repor",
|
||||
merge: "Juntar os dois grupos",
|
||||
@@ -188,6 +195,33 @@ export const t = {
|
||||
captured: "Captura",
|
||||
photographer: "Fotógrafo",
|
||||
deliverTo: "Entregar em",
|
||||
importTargets: {
|
||||
title: "Importar destinos",
|
||||
button: "Importar…",
|
||||
help: "Destinos guardados no Photo Mechanic (contas e modelos de upload) e no FileZilla, neste computador. Servidor, utilizador, pasta, tamanho, qualidade e nome do ficheiro vêm de lá; a senha escreves aqui (essas apps não a deixam ler). Escolhe os que queres e escreve a senha de cada um.",
|
||||
none: "Não encontrei destinos do Photo Mechanic nem do FileZilla neste computador.",
|
||||
tooOld: "Esta versão da app ainda não sabe importar destinos: atualiza a app.",
|
||||
showArchived: "Mostrar os modelos arquivados do Photo Mechanic",
|
||||
archived: "arquivado",
|
||||
name: "Nome",
|
||||
original: "Original",
|
||||
password: "Senha",
|
||||
key: "Chave privada (PEM) ou senha",
|
||||
missingPassword: "Falta a senha nalguns dos escolhidos.",
|
||||
done: "Importado",
|
||||
import: (n: number) => (n ? `Importar ${n}` : "Importar"),
|
||||
},
|
||||
zerozero: {
|
||||
looking: "a procurar o jogo…",
|
||||
error: "erro ao ligar ao ZeroZero",
|
||||
found: "encontrado",
|
||||
chosen: "escolhido",
|
||||
notFound: "jogo não encontrado: escolhe-o",
|
||||
change: "mudar",
|
||||
pasteHelp: "Cola o link da página do jogo em fotos.zerozero.pt (ou o número do jogo).",
|
||||
auto: "Procurar pelas equipas e hora",
|
||||
use: "Usar",
|
||||
},
|
||||
autopilot: {
|
||||
button: "Piloto automático",
|
||||
enable: "Ligar o piloto automático neste evento",
|
||||
@@ -202,6 +236,11 @@ export const t = {
|
||||
minLongEdge: "Resolução mínima do recorte",
|
||||
deliver: "Enviar as escolhidas para",
|
||||
noDelivery: "Não enviar",
|
||||
selection: "O que enviar",
|
||||
selectionBursts: "As escolhidas de cada sequência",
|
||||
selectionBest: "Só as melhores do jogo",
|
||||
bestCount: "Fotos na galeria (aprox.)",
|
||||
bestHelp: "Uma galeria curta de momentos de jogo: bola em jogo, duelos e festejos, jogadores grandes e nítidos no enquadramento, espalhados pelo jogo (a cada 5 minutos entram as melhores desse período). Aquecimento e intervalo ficam de fora; as fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
|
||||
learnt: "Aprendido com as tuas correções",
|
||||
learntHelp: (n: number, venue: string | null) => `${n} ${n === 1 ? "foto corrigida" : "fotos corrigidas"}${venue ? " neste recinto" : ""}. Aplica-se às próximas fotos que chegarem.`,
|
||||
learning: (n: number) => `A aprender: ${n} ${n === 1 ? "correção" : "correções"} até agora (a partir de 5 que concordem, as próximas fotos já chegam assim).`,
|
||||
@@ -239,7 +278,7 @@ export const t = {
|
||||
shareLink: "Link de partilha",
|
||||
copyLink: "Copiar link",
|
||||
copied: "Copiado",
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", DONE: "Entregue", FAILED: "Falhou" },
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou" },
|
||||
codeList: "Substituição de códigos",
|
||||
codeListHelp: "Uma linha por código: código, tab, texto. Escreve \\v7\\ numa legenda e é trocado pelo texto. Listas do Photo Mechanic servem tal como estão.",
|
||||
save: "Guardar",
|
||||
@@ -287,15 +326,18 @@ export const t = {
|
||||
startsAt: "Início",
|
||||
photographers: "Fotógrafos",
|
||||
pickMatch: "Escolher o jogo",
|
||||
pickMatchHelp: "Jogos da Liga Portugal, FPF e FPA 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 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.",
|
||||
searchMatch: "Equipa, competição ou pavilhão",
|
||||
noMatches: "Nenhum jogo encontrado.",
|
||||
linked: "Ligado ao jogo oficial",
|
||||
unlink: "Desligar",
|
||||
},
|
||||
sports: {
|
||||
photosHelp: (confirmed: number, likely: number) =>
|
||||
`${confirmed} ${confirmed === 1 ? "foto confirmada" : "fotos confirmadas"} neste jogo` + (likely ? `, mais ${likely} em que as caras dizem que é ele (70% ou mais, por confirmar)` : ""),
|
||||
notPerson: "Ainda não está nas pessoas: atualiza as pessoas a partir dos plantéis",
|
||||
title: "Plantéis e códigos",
|
||||
help: "Os plantéis vêm da Liga Portugal, FPF e FPA e são atualizados de 6 em 6 horas. Escolhe as competições e o formato: os códigos entram na lista de substituição (no topo, em bloco; as tuas linhas mantêm-se e têm prioridade).",
|
||||
help: "Os plantéis vêm da Liga Portugal, FPF, FPA e UEFA e são atualizados de 6 em 6 horas (na UEFA, das fichas de jogo: ficam completos à medida que as equipas jogam, e a do próprio jogo chega cerca de 1 hora antes; no andebol, dos boletins de jogo da FPA das ligas e taças seniores, com os oficiais pela letra do cartão). Escolhe as competições e o formato: os códigos entram na lista de substituição (no topo, em bloco; as tuas linhas mantêm-se e têm prioridade).",
|
||||
competitions: "Competições",
|
||||
prefix: "Prefixo da equipa",
|
||||
prefixShort: "Curto (b14)",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AutopilotSettings } from "@photoreport/contracts";
|
||||
import type { ApiClient, AutopilotStyle, DeliveryTarget, EventSummary } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { ZerozeroGamePicker } from "./ZerozeroGame.js";
|
||||
|
||||
/**
|
||||
* Autopilot for the open event (docs/photo-editing-rules.md): photos arriving by FTP or the desktop app's ingest
|
||||
@@ -88,6 +89,32 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.selection}</span>
|
||||
<select className="h-6 max-w-[180px] border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.selection} onChange={(e) => void save({ ...s, selection: e.target.value as AutopilotSettings["selection"] })}>
|
||||
<option value="bursts">{L.selectionBursts}</option>
|
||||
<option value="best">{L.selectionBest}</option>
|
||||
</select>
|
||||
</label>
|
||||
{s.selection === "best" && (
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{L.bestCount}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={5}
|
||||
max={300}
|
||||
disabled={!s.enabled || !props.canEdit}
|
||||
value={s.bestCount}
|
||||
onChange={(e) => setS({ ...s, bestCount: Math.max(5, Math.min(300, Number(e.target.value) || 5)) })}
|
||||
onBlur={() => void save(s)}
|
||||
className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink"
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
{s.selection === "best" && <p className="text-faint">{L.bestHelp}</p>}
|
||||
{s.deliverTargetId && props.targets.find((x) => x.id === s.deliverTargetId)?.kind === "ZEROZERO" && (
|
||||
<ZerozeroGamePicker api={props.api} orgId={props.event.organizationId} targetId={s.deliverTargetId} eventId={props.event.id} />
|
||||
)}
|
||||
{state === "error" && <p className="text-danger">{t.unexpectedError}</p>}
|
||||
{state === "saving" && <p className="text-faint">…</p>}
|
||||
<Learnt api={props.api} event={props.event} />
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FaceGroupSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient, type PersonSummary } from "@photoreport/sdk";
|
||||
import { ApiError, type ApiClient, type SquadPerson } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { t } from "../i18n.js";
|
||||
@@ -30,16 +30,37 @@ export function FaceCrop({ src, box, aspect, size = 72 }: { src: string; box: {
|
||||
);
|
||||
}
|
||||
|
||||
/** Lower case without accents: "Osório" finds "Osorio". */
|
||||
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
|
||||
|
||||
/** People whose name, full name, club or number contain every word typed (any order, accents ignored). */
|
||||
export function matchPeople(people: SquadPerson[], typed: string, limit = 8): SquadPerson[] {
|
||||
const words = fold(typed).split(/\s+/).filter(Boolean);
|
||||
// A \code\ is replaced on the server, not looked up here.
|
||||
if (!words.length || typed.trimStart().startsWith("\\")) return [];
|
||||
const scored: { p: SquadPerson; rank: number }[] = [];
|
||||
for (const p of people) {
|
||||
const name = fold(p.name);
|
||||
const hay = `${name} ${fold(p.fullName ?? "")} ${fold(p.club ?? "")} ${p.number ? `#${fold(p.number)} ${fold(p.number)}` : ""}`;
|
||||
if (!words.every((w) => hay.includes(w))) continue;
|
||||
scored.push({ p, rank: name.startsWith(words[0]!) ? 0 : words.every((w) => name.includes(w)) ? 1 : 2 });
|
||||
}
|
||||
return scored.sort((a, b) => a.rank - b.rank || a.p.name.localeCompare(b.p.name)).slice(0, limit).map((s) => s.p);
|
||||
}
|
||||
|
||||
function GroupCard(props: {
|
||||
api: ApiClient;
|
||||
group: FaceGroupSummary;
|
||||
people: PersonSummary[];
|
||||
people: SquadPerson[];
|
||||
selected: boolean;
|
||||
onSelect: () => void;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const { api, group } = props;
|
||||
const [name, setName] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
const [active, setActive] = useState(0);
|
||||
const matches = open ? matchPeople(props.people, name) : [];
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -59,6 +80,12 @@ function GroupCard(props: {
|
||||
const submit = () => {
|
||||
const typed = name.trim();
|
||||
if (!typed) return;
|
||||
const picked = matches[active];
|
||||
if (picked) {
|
||||
setOpen(false);
|
||||
void confirm({ personId: picked.id });
|
||||
return;
|
||||
}
|
||||
const existing = props.people.find((p) => p.name.toLowerCase() === typed.toLowerCase());
|
||||
void confirm(existing ? { personId: existing.id } : { name: typed });
|
||||
};
|
||||
@@ -98,7 +125,7 @@ function GroupCard(props: {
|
||||
</button>
|
||||
)}
|
||||
<form
|
||||
className="flex gap-1"
|
||||
className="relative flex gap-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
@@ -106,8 +133,26 @@ function GroupCard(props: {
|
||||
>
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
list="pr-people"
|
||||
onChange={(e) => {
|
||||
setName(e.target.value);
|
||||
setOpen(true);
|
||||
setActive(0);
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
onBlur={() => setTimeout(() => setOpen(false), 150)}
|
||||
onKeyDown={(e) => {
|
||||
if (!matches.length) return;
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setActive((a) => (a + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length);
|
||||
} else if (e.key === "Escape") {
|
||||
setOpen(false);
|
||||
}
|
||||
}}
|
||||
role="combobox"
|
||||
aria-expanded={matches.length > 0}
|
||||
aria-autocomplete="list"
|
||||
autoComplete="off"
|
||||
placeholder={t.faces.namePlaceholder}
|
||||
aria-label={t.faces.namePlaceholder}
|
||||
className="h-7 min-w-0 flex-1 border border-black bg-[#161617] px-2 text-[12px] text-ink placeholder:text-faint focus:border-accent focus:outline-none"
|
||||
@@ -115,6 +160,33 @@ function GroupCard(props: {
|
||||
<button disabled={busy || !name.trim()} className="h-7 bg-accent px-2 text-[12px] font-semibold text-white disabled:opacity-40">
|
||||
OK
|
||||
</button>
|
||||
{matches.length > 0 && (
|
||||
<ul role="listbox" className="absolute left-0 right-0 top-full z-20 mt-px max-h-64 overflow-auto border border-black bg-[#161617] shadow-lg">
|
||||
{matches.map((p, i) => (
|
||||
<li
|
||||
key={p.id}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
setOpen(false);
|
||||
void confirm({ personId: p.id });
|
||||
}}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
className={`cursor-pointer px-2 py-1 text-[12px] ${i === active ? "bg-[#24344a] text-ink" : "text-muted"}`}
|
||||
>
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="truncate text-ink">{p.name}</span>
|
||||
<span className="shrink-0 font-mono text-[10px] text-faint">
|
||||
{p.number ? `${/^[A-F]$/.test(p.number) ? t.faces.official(p.number) : `#${p.number}`} · ` : ""}
|
||||
{p.club ?? ""}
|
||||
</span>
|
||||
</div>
|
||||
{p.fullName && p.fullName !== p.name && <div className="truncate text-[10px] text-faint">{p.fullName}</div>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
@@ -134,7 +206,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
|
||||
const [pending, setPending] = useState(0);
|
||||
const [unclear, setUnclear] = useState(0);
|
||||
const [showSingles, setShowSingles] = useState(false);
|
||||
const [people, setPeople] = useState<PersonSummary[]>([]);
|
||||
const [people, setPeople] = useState<SquadPerson[]>([]);
|
||||
const [selected, setSelected] = useState<string[]>([]);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
@@ -174,11 +246,6 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
|
||||
|
||||
return (
|
||||
<section aria-label={t.faces.title} className="p-3">
|
||||
<datalist id="pr-people">
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={p.name} />
|
||||
))}
|
||||
</datalist>
|
||||
<div className="mb-3 flex flex-wrap items-center gap-3 text-[12px] text-muted">
|
||||
<span>{t.faces.summary(groups?.length ?? 0, open)}</span>
|
||||
{pending > 0 && <span className="font-mono text-[11px] text-[#7fb0ff]">{t.faces.pending(pending)}</span>}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { ApiError, type ApiClient, type DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { type DeliveryShell, desktopDeliveryShell } from "../desktop/localDeliveries.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { type ImportCandidate, importCandidates } from "./importTargets.js";
|
||||
|
||||
interface Row {
|
||||
c: ImportCandidate;
|
||||
selected: boolean;
|
||||
name: string;
|
||||
password: string;
|
||||
result: "ok" | string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Desktop: the upload destinations saved in Photo Mechanic and FileZilla on this computer, to bring in as
|
||||
* destinations. Server, user, folders and output settings come from there; passwords are typed here (the other
|
||||
* apps keep them to themselves).
|
||||
*/
|
||||
export function ImportTargets(props: { api: ApiClient; orgId: string; existing: DeliveryTarget[]; shell?: DeliveryShell; onClose: () => void; onImported: (targets: DeliveryTarget[]) => void }) {
|
||||
const L = t.importTargets;
|
||||
const shell = props.shell ?? desktopDeliveryShell;
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [archived, setArchived] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const taken = new Set(props.existing.map((x) => x.name.toLowerCase()));
|
||||
shell.profiles().then(
|
||||
(sources) =>
|
||||
setRows(
|
||||
importCandidates(sources).map((c) => ({
|
||||
c,
|
||||
selected: false,
|
||||
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
|
||||
password: "",
|
||||
result: null,
|
||||
})),
|
||||
),
|
||||
() => setError(L.tooOld),
|
||||
);
|
||||
// Once, when opened.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const set = (i: number, patch: Partial<Row>) => setRows((list) => list!.map((r, n) => (n === i ? { ...r, ...patch } : r)));
|
||||
const chosen = (rows ?? []).filter((r) => r.selected && r.result !== "ok");
|
||||
|
||||
const run = async () => {
|
||||
setBusy(true);
|
||||
const made: DeliveryTarget[] = [];
|
||||
for (const r of chosen) {
|
||||
const i = rows!.indexOf(r);
|
||||
try {
|
||||
const { c } = r;
|
||||
const target = await props.api.createDeliveryTarget(props.orgId, {
|
||||
name: r.name.trim(),
|
||||
kind: c.kind,
|
||||
baseUrl: c.baseUrl,
|
||||
username: c.username,
|
||||
password: r.password,
|
||||
folderTemplate: c.folderTemplate,
|
||||
fileNameTemplate: c.fileNameTemplate,
|
||||
longEdge: c.longEdge,
|
||||
jpegQuality: c.jpegQuality,
|
||||
sharpen: c.sharpen,
|
||||
dpi: c.dpi,
|
||||
keepExif: c.keepExif,
|
||||
srgb: c.srgb,
|
||||
});
|
||||
made.push(target);
|
||||
set(i, { result: "ok", password: "" });
|
||||
} catch (err) {
|
||||
set(i, { result: err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : t.unexpectedError });
|
||||
}
|
||||
}
|
||||
setBusy(false);
|
||||
if (made.length) props.onImported(made);
|
||||
};
|
||||
|
||||
const shown = (rows ?? []).map((r, i) => ({ r, i })).filter(({ r }) => archived || !r.c.archived);
|
||||
const input = "h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none";
|
||||
|
||||
return (
|
||||
<div role="dialog" aria-modal="true" aria-label={L.title} className="fixed inset-0 z-30 flex items-center justify-center bg-black/60 p-4">
|
||||
<div className="flex max-h-full w-full max-w-4xl flex-col border border-line bg-panel shadow-2xl">
|
||||
<div className="panel-head">
|
||||
<span>{L.title}</span>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-4 text-[12px]">
|
||||
<p className="mb-3 text-faint">{L.help}</p>
|
||||
{error && <p className="text-danger">{error}</p>}
|
||||
{!rows && !error && <p className="text-faint">…</p>}
|
||||
{rows && rows.length === 0 && <p className="text-faint">{L.none}</p>}
|
||||
{rows && rows.some((r) => r.c.archived) && (
|
||||
<label className="mb-2 flex items-center gap-2 text-muted">
|
||||
<input type="checkbox" checked={archived} onChange={(e) => setArchived(e.target.checked)} /> {L.showArchived}
|
||||
</label>
|
||||
)}
|
||||
<ul className="space-y-1.5">
|
||||
{shown.map(({ r, i }) => (
|
||||
<li key={r.c.key} className={`grid grid-cols-[auto_1fr_1fr] items-start gap-2 border border-[#151516] p-2 ${r.selected ? "bg-cell-on" : "bg-cell"}`}>
|
||||
<input type="checkbox" aria-label={r.c.origin} className="mt-1.5" disabled={!!r.c.problem || r.result === "ok"} checked={r.selected} onChange={(e) => set(i, { selected: e.target.checked })} />
|
||||
<div className="min-w-0 space-y-1">
|
||||
<input className={input} value={r.name} disabled={r.result === "ok"} onChange={(e) => set(i, { name: e.target.value })} aria-label={L.name} />
|
||||
<p className="truncate text-[11px] text-faint" title={r.c.origin}>
|
||||
{r.c.source} · {r.c.origin}
|
||||
{r.c.archived ? ` · ${L.archived}` : ""}
|
||||
</p>
|
||||
<p className="truncate font-mono text-[10.5px] text-muted" title={`${r.c.baseUrl} ${r.c.folderTemplate}`}>
|
||||
{r.c.baseUrl || "—"} · {r.c.username || "—"} · {r.c.folderTemplate}
|
||||
</p>
|
||||
<p className="font-mono text-[10.5px] text-faint">
|
||||
{r.c.longEdge >= 12000 ? L.original : `${r.c.longEdge} px`} · JPEG {r.c.jpegQuality} · {r.c.fileNameTemplate}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{r.c.problem ? (
|
||||
<p className="text-[#f0a35a]">{r.c.problem}</p>
|
||||
) : r.result === "ok" ? (
|
||||
<p className="text-ok">{L.done}</p>
|
||||
) : r.c.keyAuth ? (
|
||||
<textarea className={`${input} h-16 font-mono text-[10.5px]`} placeholder={L.key} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} spellCheck={false} />
|
||||
) : (
|
||||
<input type="password" autoComplete="new-password" className={input} placeholder={L.password} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} />
|
||||
)}
|
||||
{r.result && r.result !== "ok" && <p className="text-danger">{r.result}</p>}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 border-t border-line px-4 py-3">
|
||||
{chosen.some((r) => !r.password) && <span className="mr-auto text-[11px] text-[#f0a35a]">{L.missingPassword}</span>}
|
||||
<button type="button" onClick={props.onClose} className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on">
|
||||
{t.cancel}
|
||||
</button>
|
||||
<button disabled={busy || !chosen.length || chosen.some((r) => !r.password || !r.name.trim())} onClick={() => void run()} className="h-8 bg-accent px-4 text-[13px] font-semibold text-white disabled:opacity-40">
|
||||
{L.import(chosen.length)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,15 +5,19 @@ import { useNavigate } from "react-router";
|
||||
import { t } from "../i18n.js";
|
||||
import { deliver } from "../offline/sync.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import { ZerozeroGamePicker } from "./ZerozeroGame.js";
|
||||
|
||||
const LAST_TARGET = "deliver.target";
|
||||
const BEST_COUNT = "deliver.bestCount";
|
||||
|
||||
/**
|
||||
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to a
|
||||
* destination. With no destination yet it leads to where one is set up.
|
||||
*/
|
||||
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; onQueued: (items: DeliveryItemSummary[]) => void }) {
|
||||
const { api, orgId, selection, targets } = props;
|
||||
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; eventId?: string | null; onQueued: (items: DeliveryItemSummary[]) => void }) {
|
||||
const { api, orgId, selection, targets, eventId } = props;
|
||||
const [bestOpen, setBestOpen] = useState(false);
|
||||
const [bestCount, setBestCount] = useState(() => Number(prefs.get(BEST_COUNT)) || 30);
|
||||
const navigate = useNavigate();
|
||||
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
@@ -51,8 +55,28 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
}
|
||||
};
|
||||
|
||||
const target = targets.find((x) => x.id === targetId);
|
||||
// Only the best of the open event: a short gallery of game moments, spread over the match.
|
||||
const sendBest = async () => {
|
||||
if (!eventId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.deliverBest(orgId, { targetId, eventId, count: bestCount });
|
||||
prefs.set(LAST_TARGET, targetId);
|
||||
prefs.set(BEST_COUNT, String(bestCount));
|
||||
props.onQueued(r.queued);
|
||||
setBestOpen(false);
|
||||
setNote(r.chosen.length ? t.bestSent(r.queued.length, r.chosen.length) : t.bestNone);
|
||||
} catch (err) {
|
||||
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1">
|
||||
<span className="relative flex items-center gap-1">
|
||||
{target?.kind === "ZEROZERO" && eventId && <ZerozeroGamePicker api={api} orgId={orgId} targetId={targetId} eventId={eventId} compact />}
|
||||
{targets.length > 1 && (
|
||||
<select aria-label={t.deliverTo} value={targetId} onChange={(e) => setTargetId(e.target.value)} className="h-6 max-w-[140px] border border-black bg-cell px-1 text-[12px] text-ink">
|
||||
{targets.map((x) => (
|
||||
@@ -70,6 +94,29 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
>
|
||||
{t.sendN(photos.length)}
|
||||
</button>
|
||||
{eventId && (
|
||||
<button onClick={() => setBestOpen((o) => !o)} aria-expanded={bestOpen} title={t.bestHelp} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.bestButton}
|
||||
</button>
|
||||
)}
|
||||
{bestOpen && (
|
||||
<form
|
||||
className="absolute right-0 top-7 z-30 w-[300px] space-y-2 border border-black bg-panel p-3 text-[12px] shadow-xl"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void sendBest();
|
||||
}}
|
||||
>
|
||||
<p className="text-faint">{t.bestHelp}</p>
|
||||
<label className="flex items-center justify-between gap-2">
|
||||
<span>{t.bestCount}</span>
|
||||
<input type="number" min={1} max={300} value={bestCount} onChange={(e) => setBestCount(Math.max(1, Math.min(300, Number(e.target.value) || 1)))} className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink" />
|
||||
</label>
|
||||
<button disabled={busy || !targetId} className="h-7 w-full bg-accent font-semibold text-white disabled:opacity-40">
|
||||
{t.bestSend(target?.name ?? "")}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{note && <span className="text-[11px] text-ok">{note}</span>}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -71,7 +71,18 @@ export function SquadsButton({ api, event, canEdit, onSaved }: { api: ApiClient;
|
||||
<li key={p.id} className="flex gap-2">
|
||||
<span className="w-7 shrink-0 text-right font-mono text-accent">{p.number ?? "–"}</span>
|
||||
<span className="truncate text-ink">{p.name}</span>
|
||||
<span className="ml-auto text-faint">{p.personId ? "✓" : ""}</span>
|
||||
<span className="ml-auto shrink-0 font-mono text-[11px]" title={p.personId ? t.sports.photosHelp(p.photos?.confirmed ?? 0, p.photos?.likely ?? 0) : t.sports.notPerson}>
|
||||
{!p.personId ? (
|
||||
<span className="text-faint">·</span>
|
||||
) : p.photos && p.photos.confirmed + p.photos.likely > 0 ? (
|
||||
<>
|
||||
{p.photos.confirmed > 0 && <span className="text-ink">{p.photos.confirmed}</span>}
|
||||
{p.photos.likely > 0 && <span className="text-faint">{p.photos.confirmed > 0 ? " " : ""}+{p.photos.likely}</span>}
|
||||
</>
|
||||
) : (
|
||||
<span className="text-faint">0</span>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { DESTINATION_EXAMPLES } from "@photoreport/metadata";
|
||||
import { ApiError, type ApiClient, type DeliveryKind, type DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useState } from "react";
|
||||
import { desktopDeliveryShell } from "../desktop/localDeliveries.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
|
||||
const SIZES = [12000, 6000, 4000, 3500, 3000, 2000];
|
||||
|
||||
@@ -40,6 +42,22 @@ const KINDS: Record<DeliveryKind, { label: string; address: string; placeholder:
|
||||
secret: "Refresh token (ou token de acesso)",
|
||||
help: "Com uma app Dropbox: app key e refresh token. Sem app key, o campo seguinte é um token de acesso de longa duração.",
|
||||
},
|
||||
LOCAL: {
|
||||
label: "Pasta no computador",
|
||||
address: "Pasta",
|
||||
placeholder: "",
|
||||
user: "",
|
||||
secret: "",
|
||||
help: "Os ficheiros finais (tamanho, IPTC, nome) são guardados numa pasta deste computador pela app, quando está aberta. Serve para testar as regras ou para escolher depois o que enviar.",
|
||||
},
|
||||
ZEROZERO: {
|
||||
label: "ZeroZero (fotos.zerozero.pt)",
|
||||
address: "Endereço",
|
||||
placeholder: "https://fotos.zerozero.pt",
|
||||
user: "Utilizador ou email do zerozero.pt",
|
||||
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).",
|
||||
},
|
||||
};
|
||||
|
||||
const PRESETS = {
|
||||
@@ -56,6 +74,7 @@ const PRESETS = {
|
||||
abola: { label: "A Bola (SFTP)", kind: "SFTP", baseUrl: "sftp://transfer.ringier.ch", longEdge: 12000, ...DESTINATION_EXAMPLES.abola },
|
||||
fpa: { label: "Estrutura FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.fpa },
|
||||
liga: { label: "Estrutura Liga", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.liga },
|
||||
zerozero: { label: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", longEdge: 3000, folder: "zerozero", fileName: "{originalName}", jpegQuality: 90, sharpen: false },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
@@ -104,7 +123,12 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const { password, ...rest } = v;
|
||||
(target ? api.updateDeliveryTarget(orgId, target.id, password ? v : rest) : api.createDeliveryTarget(orgId, v)).then(
|
||||
if (v.kind === "LOCAL" && !v.baseUrl) {
|
||||
setBusy(false);
|
||||
setError("Escolhe a pasta.");
|
||||
return;
|
||||
}
|
||||
(target ? api.updateDeliveryTarget(orgId, target.id, password ? v : rest) : api.createDeliveryTarget(orgId, v.kind === "LOCAL" ? rest : v)).then(
|
||||
(target) => onCreated(target),
|
||||
(err) => {
|
||||
setBusy(false);
|
||||
@@ -149,10 +173,12 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
|
||||
value={v.kind}
|
||||
onChange={(e) => {
|
||||
const kind = e.target.value as DeliveryKind;
|
||||
setV({ ...v, kind, baseUrl: KINDS[kind].placeholder });
|
||||
setV({ ...v, kind, baseUrl: KINDS[kind].placeholder, ...(kind === "ZEROZERO" && { folderTemplate: "zerozero", fileNameTemplate: "{originalName}", longEdge: 3000, jpegQuality: 90 }), ...(kind === "LOCAL" && { folderTemplate: "/{event}/", username: "" }) });
|
||||
}}
|
||||
>
|
||||
{(Object.keys(KINDS) as DeliveryKind[]).map((kind) => (
|
||||
{(Object.keys(KINDS) as DeliveryKind[])
|
||||
.filter((kind) => kind !== "LOCAL" || isDesktop() || v.kind === "LOCAL")
|
||||
.map((kind) => (
|
||||
<option key={kind} value={kind}>
|
||||
{KINDS[kind].label}
|
||||
</option>
|
||||
@@ -161,7 +187,31 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
|
||||
</label>
|
||||
{field("name", "Nome (ex.: A Bola, FPA, Liga)")}
|
||||
</div>
|
||||
{v.kind !== "DROPBOX" && field("baseUrl", k.address, { placeholder: k.placeholder, spellCheck: false })}
|
||||
{v.kind === "LOCAL" && (
|
||||
<div>
|
||||
<span className="mb-1 block text-[11px] text-faint">{k.address}</span>
|
||||
<div className="flex gap-2">
|
||||
<span className={`${input} flex items-center truncate font-mono text-[12px]`}>{v.baseUrl.startsWith("/") || /^[A-Za-z]:/.test(v.baseUrl) ? v.baseUrl : "—"}</span>
|
||||
{isDesktop() && (
|
||||
<button
|
||||
type="button"
|
||||
className="h-8 shrink-0 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
|
||||
onClick={() =>
|
||||
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
|
||||
([folder, machine]) => folder && setV((cur) => ({ ...cur, baseUrl: folder, username: machine })),
|
||||
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
|
||||
)
|
||||
}
|
||||
>
|
||||
Escolher pasta…
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 text-[11px] leading-snug text-faint">{k.help}</p>
|
||||
</div>
|
||||
)}
|
||||
{v.kind !== "DROPBOX" && v.kind !== "ZEROZERO" && v.kind !== "LOCAL" && field("baseUrl", k.address, { placeholder: k.placeholder, spellCheck: false })}
|
||||
{v.kind !== "LOCAL" && (
|
||||
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
|
||||
{field("username", k.user, { autoComplete: "off", spellCheck: false })}
|
||||
<label className="block">
|
||||
@@ -189,8 +239,9 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
<p className="text-[11px] leading-snug text-faint">{k.help} Fica guardada encriptada e nunca volta a ser mostrada.</p>
|
||||
{field("folderTemplate", "Pasta ({event} = Casa x Fora)")}
|
||||
)}
|
||||
{v.kind !== "LOCAL" && <p className="text-[11px] leading-snug text-faint">{k.help} Fica guardada encriptada e nunca volta a ser mostrada.</p>}
|
||||
{v.kind !== "ZEROZERO" && field("folderTemplate", v.kind === "LOCAL" ? "Subpasta ({event} = Casa x Fora)" : "Pasta ({event} = Casa x Fora)")}
|
||||
{field("fileNameTemplate", "Nome do ficheiro ({originalName} mantém o da câmara, {n:pad3} numera 001, 002…)")}
|
||||
<fieldset className="grid grid-cols-2 gap-3 border border-line p-3 max-sm:grid-cols-1">
|
||||
<legend className="px-1 text-[11px] text-faint">Saída (como no uploader do Photo Mechanic)</legend>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { ApiError, type ApiClient, type ZerozeroGame } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
|
||||
/** "2026-10-15 17:45:00" → "15/10 17:45". */
|
||||
const when = (d: string) => `${d.slice(8, 10)}/${d.slice(5, 7)} ${d.slice(11, 16)}`;
|
||||
|
||||
/**
|
||||
* The event's game on fotos.zerozero.pt, for a ZeroZero destination: the one found by teams and time (or chosen
|
||||
* before), and a way to choose another by pasting the game's link.
|
||||
*/
|
||||
export function ZerozeroGamePicker(props: { api: ApiClient; orgId: string; targetId: string; eventId: string; compact?: boolean }) {
|
||||
const L = t.zerozero;
|
||||
const [state, setState] = useState<{ game: ZerozeroGame | null; chosen: boolean } | "loading" | { error: string }>("loading");
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [link, setLink] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
setState("loading");
|
||||
props.api.zerozeroGame(props.orgId, props.targetId, props.eventId).then(
|
||||
(r) => live && setState(r),
|
||||
(err) => live && setState({ error: err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : t.unexpectedError }),
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [props.api, props.orgId, props.targetId, props.eventId]);
|
||||
|
||||
const choose = async (game: string | null) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
setState(await props.api.setZerozeroGame(props.orgId, props.targetId, props.eventId, game));
|
||||
setEditing(false);
|
||||
setLink("");
|
||||
} catch (err) {
|
||||
setState({ error: err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : t.unexpectedError });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const label =
|
||||
state === "loading" ? (
|
||||
<span className="text-faint">{L.looking}</span>
|
||||
) : "error" in state ? (
|
||||
<span className="text-danger" title={state.error}>
|
||||
{L.error}
|
||||
</span>
|
||||
) : state.game ? (
|
||||
<span className="truncate text-ink" title={`${state.game.competition ?? ""} · ${state.game.id}`}>
|
||||
{state.game.home} x {state.game.away} · {when(state.game.date)} <span className="text-faint">({state.chosen ? L.chosen : L.found})</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-warn">{L.notFound}</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<span className={`relative flex min-w-0 items-center gap-1.5 text-[11px] ${props.compact ? "max-w-[280px]" : ""}`}>
|
||||
<span className="shrink-0 font-semibold uppercase tracking-wide text-faint">ZZ</span>
|
||||
{label}
|
||||
<button type="button" className="shrink-0 text-faint underline hover:text-ink" onClick={() => setEditing((e) => !e)}>
|
||||
{L.change}
|
||||
</button>
|
||||
{editing && (
|
||||
<form
|
||||
className="absolute right-0 top-6 z-40 w-[340px] space-y-2 border border-black bg-panel p-2 shadow-xl"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (link.trim()) void choose(link.trim());
|
||||
}}
|
||||
>
|
||||
<p className="text-faint">{L.pasteHelp}</p>
|
||||
<input autoFocus value={link} onChange={(e) => setLink(e.target.value)} placeholder="https://fotos.zerozero.pt/edicoes/…/…" className="h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none" />
|
||||
<div className="flex justify-between gap-2">
|
||||
<button type="button" disabled={busy} className="text-faint underline hover:text-ink" onClick={() => void choose(null)}>
|
||||
{L.auto}
|
||||
</button>
|
||||
<button disabled={busy || !link.trim()} className="h-6 bg-accent px-3 font-semibold text-white disabled:opacity-40">
|
||||
{L.use}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fileZillaDir, importCandidates, parsePmAccounts, parsePmSnapshot } from "./importTargets.js";
|
||||
|
||||
// As Photo Mechanic writes them (invented accounts; passwords already removed by the desktop app).
|
||||
const FTP_ACCOUNTS = `---
|
||||
:connection_settings_dialog:
|
||||
:settings:
|
||||
JORNAL - ARQUIVO:
|
||||
- arquivo
|
||||
- ''
|
||||
- :server_addr_edit:
|
||||
:value: ftp.jornal.pt
|
||||
:port_edit:
|
||||
:value: '21'
|
||||
:passive_check:
|
||||
:checked: true
|
||||
:dest_folder_edit:
|
||||
:value: /fotografia/
|
||||
:copy_photos_combo:
|
||||
:selected: into destination with name
|
||||
:folder_name_edit:
|
||||
:value: /{iptcyear4}.{iptcmonth0}.{iptcday0} {event}
|
||||
JORNAL DIRETO:
|
||||
- direto
|
||||
- ''
|
||||
- :server_addr_edit:
|
||||
:value: ftp.jornal.pt
|
||||
:port_edit:
|
||||
:value: '2121'
|
||||
:dest_folder_edit:
|
||||
:value: /PORTO/
|
||||
:copy_photos_combo:
|
||||
:selected: directly into destination folder
|
||||
:folder_name_edit:
|
||||
:value: ''
|
||||
:selected_item: JORNAL DIRETO
|
||||
`;
|
||||
const SFTP_ACCOUNTS = `---
|
||||
:connection_settings_dialog:
|
||||
:settings:
|
||||
AGENCIA-SFTP:
|
||||
- agencia-images
|
||||
- ''
|
||||
- :server_addr_edit:
|
||||
:value: transfer.agencia.ch
|
||||
:port_edit:
|
||||
:value: '22'
|
||||
:dest_folder_edit:
|
||||
:value: !binary |-
|
||||
4oGE
|
||||
:copy_photos_combo:
|
||||
:selected: into destination with name
|
||||
:folder_name_edit:
|
||||
:value: /{event}
|
||||
:key_based_auth:
|
||||
:checked: false
|
||||
`;
|
||||
const snapshot = (template: string) =>
|
||||
`<?xml version="1.0" encoding="UTF-8"?>\n<TemplateSettings>\n <SerializedTemplate>---\nmain_dialog: |\n ---\n :templates_combo:\n :selected: FTP\ncurrent_template: ${JSON.stringify(template)}\n</SerializedTemplate>\n</TemplateSettings>\n`;
|
||||
const DIRETO = snapshot(
|
||||
"---\n:upload_dialog:\n :selected_account: JORNAL DIRETO\n:dest_path_edit:\n :value: /PORTO/\n:scale_box_radio:\n :checked: true\n:scale_box_size_edit:\n :value: '2500'\n:jpeg_qlty100_slider:\n :value: 80\n:preserve_exif_check:\n :checked: false\n:render_res_edit:\n :value: '72'\n:rename_as_check:\n :checked: true\n:rename_string_edit:\n :value: PS_{event}_{timesort}\n:sharpen_check:\n :checked: true\n",
|
||||
);
|
||||
const ORPHAN = snapshot("---\n:upload_dialog:\n :selected_account: CONTA APAGADA\n:send_original_radio:\n :checked: true\n");
|
||||
const FILEZILLA = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<FileZilla3><Servers><Folder>Clientes<Server><Host>ftp.clube.pt</Host><Port>21</Port><Protocol>4</Protocol><Logontype>1</Logontype><User>fotos</User><Name>Clube</Name><RemoteDir>1 0 7 imprensa 9 2026 2027</RemoteDir></Server></Folder>
|
||||
<Server><Host>s3.amazonaws.com</Host><Port>443</Port><Protocol>5</Protocol><Name>S3</Name></Server>
|
||||
<Server><Host>sftp.agencia.pt</Host><Port>2222</Port><Protocol>1</Protocol><Logontype>5</Logontype><User>a</User><Name>Agência</Name></Server></Servers></FileZilla3>`;
|
||||
|
||||
describe("importing upload destinations", () => {
|
||||
it("reads Photo Mechanic's accounts (binary values, ports, folder modes)", () => {
|
||||
const ftp = parsePmAccounts(FTP_ACCOUNTS);
|
||||
expect(ftp.map((a) => [a.name, a.user, a.host, a.port, a.destFolder, a.folderName])).toEqual([
|
||||
["JORNAL - ARQUIVO", "arquivo", "ftp.jornal.pt", "21", "/fotografia/", "/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}"],
|
||||
["JORNAL DIRETO", "direto", "ftp.jornal.pt", "2121", "/PORTO/", ""],
|
||||
]);
|
||||
expect(parsePmAccounts(SFTP_ACCOUNTS)[0]).toMatchObject({ user: "agencia-images", destFolder: "/", keyAuth: false });
|
||||
});
|
||||
|
||||
it("reads an upload template's settings", () => {
|
||||
expect(parsePmSnapshot(DIRETO)).toMatchObject({ selected_account: "JORNAL DIRETO", dest_path_edit: "/PORTO/", scale_box_size_edit: "2500", jpeg_qlty100_slider: "80", rename_string_edit: "PS_{event}_{timesort}" });
|
||||
});
|
||||
|
||||
it("makes destinations of templates (with their account), unused accounts and FileZilla sites", () => {
|
||||
const list = importCandidates({
|
||||
photoMechanic: [
|
||||
{ kind: "FTP", name: "Direto Porto", archived: false, text: DIRETO },
|
||||
{ kind: "FTP", name: "Velho", archived: true, text: ORPHAN },
|
||||
],
|
||||
photoMechanicAccounts: [
|
||||
{ kind: "FTP", name: "FTP", text: FTP_ACCOUNTS },
|
||||
{ kind: "SFTP", name: "SFTP", text: SFTP_ACCOUNTS },
|
||||
],
|
||||
filezilla: FILEZILLA,
|
||||
});
|
||||
const by = (name: string) => list.find((c) => c.name === name)!;
|
||||
expect(by("Direto Porto")).toMatchObject({ kind: "FTP", baseUrl: "ftp://ftp.jornal.pt:2121", username: "direto", folderTemplate: "/PORTO/", fileNameTemplate: "PS_{event}_{timesort}.jpg", longEdge: 2500, jpegQuality: 80, keepExif: false, dpi: 72, sharpen: true, problem: null });
|
||||
expect(by("Velho")).toMatchObject({ archived: true, baseUrl: "", longEdge: 12000, problem: 'a conta "CONTA APAGADA" não está nas contas do Photo Mechanic' });
|
||||
// JORNAL DIRETO is used by a template; the other accounts come on their own.
|
||||
expect(list.filter((c) => c.origin.startsWith("conta")).map((c) => [c.name, c.baseUrl, c.folderTemplate])).toEqual([
|
||||
["JORNAL - ARQUIVO", "ftp://ftp.jornal.pt", "/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}/"],
|
||||
["AGENCIA-SFTP", "sftp://transfer.agencia.ch", "/{event}/"],
|
||||
]);
|
||||
expect(list.filter((c) => c.source === "FileZilla").map((c) => [c.name, c.baseUrl, c.username, c.folderTemplate, c.keyAuth])).toEqual([
|
||||
["Clube", "ftps://ftp.clube.pt", "fotos", "/imprensa/2026 2027/", false],
|
||||
["Agência", "sftp://sftp.agencia.pt:2222", "a", "/", true],
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads FileZilla's remote folders", () => {
|
||||
expect(fileZillaDir("1 0 4 home 5 fotos")).toBe("/home/fotos/");
|
||||
expect(fileZillaDir("")).toBe("/");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
import type { DeliveryKind } from "@photoreport/sdk";
|
||||
|
||||
/**
|
||||
* Upload destinations saved in other apps on this computer, as PhotoReport destinations. The desktop app reads the
|
||||
* files (apps/desktop/src-tauri/src/deliver.rs, `import_upload_profiles`) and removes the passwords; the person types
|
||||
* them when importing.
|
||||
*
|
||||
* - Photo Mechanic: accounts per kind (`templates/builtin/FTP-conn.yml`: `name: [user, password, settings]`) and
|
||||
* upload templates (`snapshot/builtin/<kind>/<name>.snap`: the dialog's settings, naming the account they use).
|
||||
* - FileZilla: the site manager (`sitemanager.xml`).
|
||||
*/
|
||||
|
||||
export interface ImportSources {
|
||||
photoMechanic: { kind: string; name: string; archived: boolean; text: string }[];
|
||||
photoMechanicAccounts: { kind: string; name: string; text: string }[];
|
||||
filezilla: string | null;
|
||||
}
|
||||
|
||||
export interface ImportCandidate {
|
||||
key: string;
|
||||
source: "Photo Mechanic" | "FileZilla";
|
||||
/** What it is called there (template, account or site). */
|
||||
origin: string;
|
||||
archived: boolean;
|
||||
name: string;
|
||||
kind: Extract<DeliveryKind, "FTP" | "SFTP">;
|
||||
baseUrl: string;
|
||||
username: string;
|
||||
folderTemplate: string;
|
||||
fileNameTemplate: string;
|
||||
longEdge: number;
|
||||
jpegQuality: number;
|
||||
sharpen: boolean;
|
||||
srgb: boolean;
|
||||
keepExif: boolean;
|
||||
dpi: number;
|
||||
/** SFTP with a key in Photo Mechanic: the private key goes where the password would. */
|
||||
keyAuth: boolean;
|
||||
/** Why it cannot be imported as it is (no server known). */
|
||||
problem: string | null;
|
||||
}
|
||||
|
||||
interface PmAccount {
|
||||
name: string;
|
||||
user: string;
|
||||
host: string;
|
||||
port: string;
|
||||
destFolder: string;
|
||||
copyMode: string;
|
||||
folderName: string;
|
||||
keyAuth: boolean;
|
||||
}
|
||||
|
||||
const fromBase64 = (b64: string) => {
|
||||
try {
|
||||
const bin = atob(b64.replace(/\s+/g, ""));
|
||||
return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
/** A YAML scalar as Photo Mechanic writes it: plain, '…' or "…", or a `!binary |-` block (base64 on the next lines). */
|
||||
function scalar(raw: string, next: () => string | undefined): string {
|
||||
const v = raw.trim();
|
||||
if (v.startsWith("!binary")) return fromBase64(next() ?? "");
|
||||
if (v.startsWith("'") && v.endsWith("'")) return v.slice(1, -1).replace(/''/g, "'");
|
||||
if (v.startsWith('"') && v.endsWith('"')) {
|
||||
try {
|
||||
return JSON.parse(v) as string;
|
||||
} catch {
|
||||
return v.slice(1, -1);
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Photo Mechanic's slash look-alike (U+2044) in folder names is a slash. */
|
||||
const slashes = (s: string) => s.replace(/⁄/g, "/");
|
||||
|
||||
/** Accounts of one kind (FTP-conn.yml, SFTP-conn.yml). */
|
||||
export function parsePmAccounts(text: string): PmAccount[] {
|
||||
const lines = text.split(/\r?\n/);
|
||||
const out: PmAccount[] = [];
|
||||
let inSettings = false;
|
||||
let settingsIndent = 0;
|
||||
let current: PmAccount | null = null;
|
||||
let items = 0;
|
||||
let key: string | null = null;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]!;
|
||||
const indent = line.length - line.trimStart().length;
|
||||
const t = line.trim();
|
||||
if (!t) continue;
|
||||
if (t === ":settings:") {
|
||||
inSettings = true;
|
||||
settingsIndent = indent;
|
||||
continue;
|
||||
}
|
||||
if (!inSettings) continue;
|
||||
if (indent <= settingsIndent) {
|
||||
inSettings = false;
|
||||
continue;
|
||||
}
|
||||
// An account: "NAME:" one level in.
|
||||
if (indent === settingsIndent + 2 && t.endsWith(":") && !t.startsWith("-") && !t.startsWith(":")) {
|
||||
current = { name: t.slice(0, -1).replace(/^'(.*)'$/, "$1"), user: "", host: "", port: "", destFolder: "", copyMode: "", folderName: "", keyAuth: false };
|
||||
out.push(current);
|
||||
items = 0;
|
||||
continue;
|
||||
}
|
||||
if (!current) continue;
|
||||
const next = () => lines[++i]?.trim();
|
||||
if (t.startsWith("- ") && indent <= settingsIndent + 4) {
|
||||
items++;
|
||||
const rest = t.slice(2);
|
||||
if (items === 1) current.user = scalar(rest, next);
|
||||
else if (rest.startsWith(":")) key = rest.replace(/:$/, "").slice(1);
|
||||
continue;
|
||||
}
|
||||
// ":server_addr_edit:" then ":value: …" / ":checked: …" / ":selected: …" one level in.
|
||||
const m = /^:([a-z_]+):\s*(.*)$/.exec(t);
|
||||
if (!m) continue;
|
||||
if (!m[2]) {
|
||||
key = m[1]!;
|
||||
continue;
|
||||
}
|
||||
const value = scalar(m[2], next);
|
||||
if (!key) continue;
|
||||
if (key === "server_addr_edit") current.host = value;
|
||||
else if (key === "port_edit") current.port = value;
|
||||
else if (key === "dest_folder_edit") current.destFolder = slashes(value);
|
||||
else if (key === "copy_photos_combo") current.copyMode = value;
|
||||
else if (key === "folder_name_edit") current.folderName = slashes(value);
|
||||
else if (key === "key_based_auth" && m[1] === "checked") current.keyAuth = value === "true";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** An upload template: the dialog's settings (`current_template`, a YAML document inside the XML). */
|
||||
export function parsePmSnapshot(xml: string): Record<string, string> {
|
||||
const body = /<SerializedTemplate>([\s\S]*?)<\/SerializedTemplate>/.exec(xml)?.[1] ?? "";
|
||||
const unescaped = body.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
||||
const quoted = /current_template:\s*("(?:[^"\\]|\\.)*")/.exec(unescaped)?.[1];
|
||||
let inner = "";
|
||||
try {
|
||||
inner = quoted ? (JSON.parse(quoted) as string) : "";
|
||||
} catch {
|
||||
inner = "";
|
||||
}
|
||||
const out: Record<string, string> = {};
|
||||
let key: string | null = null;
|
||||
for (const line of inner.split("\n")) {
|
||||
const m = /^\s*:([a-zA-Z0-9_]+):\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
if (!m[2]) key = m[1]!;
|
||||
// ":dest_path_edit:" / ":value: /PORTO/" under it; ":selected_account: X" stands for itself.
|
||||
else if (["value", "checked", "selected", "label"].includes(m[1]!)) {
|
||||
if (key) out[key] = scalar(m[2], () => undefined);
|
||||
} else out[m[1]!] = scalar(m[2], () => undefined);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const join = (folder: string, name: string) => {
|
||||
const f = folder.replace(/\/+$/, "");
|
||||
const n = name.replace(/^\/+/, "");
|
||||
return `${f}/${n}`.replace(/\/{2,}/g, "/");
|
||||
};
|
||||
const asFolder = (p: string) => {
|
||||
const s = p.trim() || "/";
|
||||
return (s.startsWith("/") ? s : `/${s}`).replace(/\/?$/, "/");
|
||||
};
|
||||
const address = (kind: "FTP" | "SFTP", host: string, port: string) => {
|
||||
const def = kind === "SFTP" ? "22" : "21";
|
||||
return `${kind === "SFTP" ? "sftp" : "ftp"}://${host}${port && port !== def ? `:${port}` : ""}`;
|
||||
};
|
||||
|
||||
function accountFolder(a: PmAccount): string {
|
||||
return /directly/i.test(a.copyMode) || !a.folderName ? a.destFolder || "/" : join(a.destFolder || "/", a.folderName);
|
||||
}
|
||||
|
||||
/** Every destination found, Photo Mechanic's templates first (with their account), then accounts no template uses. */
|
||||
export function importCandidates(src: ImportSources): ImportCandidate[] {
|
||||
const out: ImportCandidate[] = [];
|
||||
const accounts = new Map<string, { kind: "FTP" | "SFTP"; account: PmAccount }>();
|
||||
for (const file of src.photoMechanicAccounts) {
|
||||
const kind = file.kind.toUpperCase() === "SFTP" ? "SFTP" : file.kind.toUpperCase() === "FTP" ? "FTP" : null;
|
||||
if (!kind) continue;
|
||||
for (const a of parsePmAccounts(file.text)) accounts.set(`${kind}:${a.name}`, { kind, account: a });
|
||||
}
|
||||
const used = new Set<string>();
|
||||
for (const snap of src.photoMechanic) {
|
||||
const kind = snap.kind.toUpperCase() === "SFTP" ? "SFTP" : snap.kind.toUpperCase() === "FTP" ? "FTP" : null;
|
||||
if (!kind) continue;
|
||||
const s = parsePmSnapshot(snap.text);
|
||||
const accountName = s.selected_account ?? "";
|
||||
const found = accounts.get(`${kind}:${accountName}`);
|
||||
if (found) used.add(`${kind}:${accountName}`);
|
||||
const original = s.send_original_radio === "true" || s.scale_none_radio === "true";
|
||||
const box = Number(s.scale_box_size_edit);
|
||||
out.push({
|
||||
key: `pm:${kind}:${snap.archived ? "archive/" : ""}${snap.name}`,
|
||||
source: "Photo Mechanic",
|
||||
origin: accountName ? `${snap.name} → ${accountName}` : snap.name,
|
||||
archived: snap.archived,
|
||||
name: snap.name,
|
||||
kind,
|
||||
baseUrl: found ? address(kind, found.account.host, found.account.port) : "",
|
||||
username: found?.account.user ?? "",
|
||||
folderTemplate: asFolder(s.dest_path_edit ? slashes(s.dest_path_edit) : found ? accountFolder(found.account) : "/"),
|
||||
fileNameTemplate: s.rename_as_check === "true" && s.rename_string_edit ? `${s.rename_string_edit}${/\.[a-z]{3,4}$/i.test(s.rename_string_edit) ? "" : ".jpg"}` : "{originalName}",
|
||||
longEdge: original || !(box >= 800) ? 12000 : Math.min(12000, Math.max(800, Math.round(box))),
|
||||
jpegQuality: Math.min(100, Math.max(40, Number(s.jpeg_qlty100_slider) || 100)),
|
||||
sharpen: s.sharpen_check === "true",
|
||||
srgb: s.convert_to_sRGB_check === "true",
|
||||
keepExif: s.preserve_exif_check !== "false",
|
||||
dpi: Math.min(1200, Math.max(72, Number(s.render_res_edit) || 300)),
|
||||
keyAuth: found?.account.keyAuth ?? false,
|
||||
problem: found ? null : accountName ? `a conta "${accountName}" não está nas contas do Photo Mechanic` : "sem conta",
|
||||
});
|
||||
}
|
||||
for (const [k, { kind, account }] of accounts) {
|
||||
if (used.has(k)) continue;
|
||||
out.push({
|
||||
key: `pm-account:${k}`,
|
||||
source: "Photo Mechanic",
|
||||
origin: `conta ${account.name}`,
|
||||
archived: false,
|
||||
name: account.name,
|
||||
kind,
|
||||
baseUrl: account.host ? address(kind, account.host, account.port) : "",
|
||||
username: account.user,
|
||||
folderTemplate: asFolder(accountFolder(account)),
|
||||
fileNameTemplate: "{originalName}",
|
||||
longEdge: 4000,
|
||||
jpegQuality: 100,
|
||||
sharpen: false,
|
||||
srgb: false,
|
||||
keepExif: true,
|
||||
dpi: 300,
|
||||
keyAuth: account.keyAuth,
|
||||
problem: account.host ? null : "sem servidor",
|
||||
});
|
||||
}
|
||||
if (src.filezilla) out.push(...fileZillaCandidates(src.filezilla));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** FileZilla's remote path: "<type> <prefix length> [prefix] <length> <segment> …" → "/a/b/". */
|
||||
export function fileZillaDir(raw: string): string {
|
||||
const tokens = raw.trim().split(" ");
|
||||
if (tokens.length < 2) return "/";
|
||||
let i = 2;
|
||||
if (Number(tokens[1]) > 0) i++;
|
||||
const parts: string[] = [];
|
||||
while (i < tokens.length) {
|
||||
const len = Number(tokens[i]);
|
||||
let seg = tokens[i + 1] ?? "";
|
||||
i += 2;
|
||||
// A segment with spaces was split: put it back together to its length.
|
||||
while (seg.length < len && i < tokens.length) seg += ` ${tokens[i++]}`;
|
||||
if (seg) parts.push(seg);
|
||||
}
|
||||
return `/${parts.join("/")}${parts.length ? "/" : ""}`;
|
||||
}
|
||||
|
||||
export function fileZillaCandidates(xml: string): ImportCandidate[] {
|
||||
const doc = new DOMParser().parseFromString(xml, "application/xml");
|
||||
const out: ImportCandidate[] = [];
|
||||
const text = (el: Element, tag: string) => el.getElementsByTagName(tag)[0]?.textContent?.trim() ?? "";
|
||||
for (const server of Array.from(doc.getElementsByTagName("Server"))) {
|
||||
const protocol = text(server, "Protocol");
|
||||
// 0 FTP, 1 SFTP, 3 FTPS (implicit), 4 FTPES (explicit TLS): others (S3, WebDAV…) are left out.
|
||||
if (!["0", "1", "3", "4", ""].includes(protocol)) continue;
|
||||
const kind = protocol === "1" ? "SFTP" : "FTP";
|
||||
const host = text(server, "Host");
|
||||
const port = text(server, "Port");
|
||||
const tls = protocol === "3" || protocol === "4";
|
||||
const name = text(server, "Name") || host;
|
||||
const def = kind === "SFTP" ? "22" : "21";
|
||||
out.push({
|
||||
key: `fz:${name}:${host}`,
|
||||
source: "FileZilla",
|
||||
origin: name,
|
||||
archived: false,
|
||||
name,
|
||||
kind,
|
||||
baseUrl: host ? `${kind === "SFTP" ? "sftp" : tls ? "ftps" : "ftp"}://${host}${port && port !== def ? `:${port}` : ""}` : "",
|
||||
username: text(server, "User"),
|
||||
folderTemplate: fileZillaDir(text(server, "RemoteDir")),
|
||||
fileNameTemplate: "{originalName}",
|
||||
longEdge: 4000,
|
||||
jpegQuality: 100,
|
||||
sharpen: false,
|
||||
srgb: false,
|
||||
keepExif: true,
|
||||
dpi: 300,
|
||||
keyAuth: text(server, "Logontype") === "5",
|
||||
problem: host ? null : "sem servidor",
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { matchPeople } from "./FacesView.js";
|
||||
|
||||
const people = [
|
||||
{ id: "1", name: "Ana Sousa", fullName: "Ana Sofia Osorio Sousa", club: "CDE GIL EANES", number: "B", faceCount: 0, reference: null },
|
||||
{ id: "2", name: "Ana Pico", fullName: "Ana Rita Escolastico Silva Alves Pico", club: "CDE GIL EANES", number: "A", faceCount: 0, reference: null },
|
||||
{ id: "3", name: "Sofia Costa", fullName: null, club: "CALE", number: "7", faceCount: 0, reference: null },
|
||||
];
|
||||
|
||||
describe("person picker", () => {
|
||||
it("finds people by any part of the full name, without accents, in any order", () => {
|
||||
expect(matchPeople(people, "Sofia Osório").map((p) => p.name)).toEqual(["Ana Sousa"]);
|
||||
expect(matchPeople(people, "sofia").map((p) => p.name)).toEqual(["Sofia Costa", "Ana Sousa"]);
|
||||
expect(matchPeople(people, "ana gil").map((p) => p.name)).toEqual(["Ana Pico", "Ana Sousa"]);
|
||||
expect(matchPeople(people, "#7").map((p) => p.name)).toEqual(["Sofia Costa"]);
|
||||
expect(matchPeople(people, "\\b14\\")).toEqual([]);
|
||||
expect(matchPeople(people, " ")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -4,12 +4,15 @@ import { useCallback, useEffect, useState } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { ImportTargets } from "../library/ImportTargets.js";
|
||||
import { TargetForm } from "../library/TargetForm.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { PageHeader } from "./Shell.js";
|
||||
|
||||
const STATUS_COLOR: Record<DeliveryItemSummary["status"], string> = {
|
||||
QUEUED: "text-faint",
|
||||
RUNNING: "text-[#7fb0ff]",
|
||||
WAITING: "text-[#7fb0ff]",
|
||||
DONE: "text-ok",
|
||||
FAILED: "text-[#f0a35a]",
|
||||
};
|
||||
@@ -19,6 +22,7 @@ export function DeliveryPage() {
|
||||
const { api, organization, role } = useAuth();
|
||||
const isAdmin = role !== null && hasRole(role, "ADMIN");
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [editing, setEditing] = useState<DeliveryTarget | null>(null);
|
||||
const [copyName, setCopyName] = useState<string | null>(null);
|
||||
const orgId = organization?.id ?? "";
|
||||
@@ -80,9 +84,16 @@ export function DeliveryPage() {
|
||||
<div className="panel-head">
|
||||
<span>Destinos</span>
|
||||
{isAdmin && (
|
||||
<button className="text-base leading-none text-muted hover:text-ink" onClick={() => setAdding(true)} aria-label="Novo destino" title="Novo destino">
|
||||
+
|
||||
</button>
|
||||
<span className="flex items-center gap-3">
|
||||
{isDesktop() && (
|
||||
<button className="text-[11px] normal-case tracking-normal text-muted hover:text-ink" onClick={() => setImporting(true)} title={t.importTargets.title}>
|
||||
{t.importTargets.button}
|
||||
</button>
|
||||
)}
|
||||
<button className="text-base leading-none text-muted hover:text-ink" onClick={() => setAdding(true)} aria-label="Novo destino" title="Novo destino">
|
||||
+
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{targets.length === 0 && <p className="px-3 py-3 text-xs text-faint">{t.noTargets}</p>}
|
||||
@@ -256,6 +267,18 @@ export function DeliveryPage() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{importing && (
|
||||
<ImportTargets
|
||||
api={api}
|
||||
orgId={orgId}
|
||||
existing={targets}
|
||||
onClose={() => setImporting(false)}
|
||||
onImported={(made) => {
|
||||
setTargets((list) => [...list, ...made].sort((x, y) => x.name.localeCompare(y.name)));
|
||||
setTargetId((current) => current || made[0]!.id);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{adding && (
|
||||
<TargetForm
|
||||
api={api}
|
||||
|
||||
@@ -352,6 +352,7 @@ export function LibraryPage() {
|
||||
orgId={orgId}
|
||||
selection={selection}
|
||||
targets={targets}
|
||||
eventId={openEvent?.id ?? null}
|
||||
onQueued={(items) => items.forEach((item) => dispatch({ type: "message", message: { type: "delivery.updated", item } }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useAuth } from "../auth.js";
|
||||
import { Bell } from "../components/Bell.js";
|
||||
import { Logo } from "../components/ui.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { LocalDeliveries } from "../desktop/localDeliveries.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { IngestProvider } from "../library/ingest.js";
|
||||
|
||||
@@ -117,6 +118,7 @@ export function Shell() {
|
||||
</header>
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<LocalDeliveries />
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<IngestProvider>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.8",
|
||||
"version": "0.3.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.8"
|
||||
version = "0.3.9"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
|
||||
|
||||
@@ -29,6 +29,11 @@ fn main() {
|
||||
"update_install",
|
||||
"ui_status",
|
||||
"ui_check",
|
||||
"delivery_machine",
|
||||
"delivery_folders",
|
||||
"delivery_folder_pick",
|
||||
"delivery_write",
|
||||
"import_upload_profiles",
|
||||
]),
|
||||
))
|
||||
.expect("failed to run tauri-build");
|
||||
|
||||
@@ -43,7 +43,12 @@
|
||||
"allow-update-check",
|
||||
"allow-update-install",
|
||||
"allow-ui-status",
|
||||
"allow-ui-check"
|
||||
"allow-ui-check",
|
||||
"allow-delivery-machine",
|
||||
"allow-delivery-folders",
|
||||
"allow-delivery-folder-pick",
|
||||
"allow-delivery-write",
|
||||
"allow-import-upload-profiles"
|
||||
],
|
||||
"remote": {
|
||||
"urls": [
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-delivery-folder-pick"
|
||||
description = "Enables the delivery_folder_pick command without any pre-configured scope."
|
||||
commands.allow = ["delivery_folder_pick"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-delivery-folder-pick"
|
||||
description = "Denies the delivery_folder_pick command without any pre-configured scope."
|
||||
commands.deny = ["delivery_folder_pick"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-delivery-folders"
|
||||
description = "Enables the delivery_folders command without any pre-configured scope."
|
||||
commands.allow = ["delivery_folders"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-delivery-folders"
|
||||
description = "Denies the delivery_folders command without any pre-configured scope."
|
||||
commands.deny = ["delivery_folders"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-delivery-machine"
|
||||
description = "Enables the delivery_machine command without any pre-configured scope."
|
||||
commands.allow = ["delivery_machine"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-delivery-machine"
|
||||
description = "Denies the delivery_machine command without any pre-configured scope."
|
||||
commands.deny = ["delivery_machine"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-delivery-write"
|
||||
description = "Enables the delivery_write command without any pre-configured scope."
|
||||
commands.allow = ["delivery_write"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-delivery-write"
|
||||
description = "Denies the delivery_write command without any pre-configured scope."
|
||||
commands.deny = ["delivery_write"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-import-upload-profiles"
|
||||
description = "Enables the import_upload_profiles command without any pre-configured scope."
|
||||
commands.allow = ["import_upload_profiles"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-import-upload-profiles"
|
||||
description = "Denies the import_upload_profiles command without any pre-configured scope."
|
||||
commands.deny = ["import_upload_profiles"]
|
||||
@@ -0,0 +1,526 @@
|
||||
//! Deliveries to a folder on this computer, and importing upload destinations from other apps.
|
||||
//!
|
||||
//! A "folder on a computer" destination is rendered on the server like any other (size, IPTC, name); this app takes
|
||||
//! the files waiting for it and saves them. It only ever writes inside folders the person chose here with the system's
|
||||
//! folder picker (kept in the app's config folder), never anywhere a page asks: the web app is loaded from the server.
|
||||
//!
|
||||
//! Importing reads two fixed places, never a path a page passes: Photo Mechanic's upload accounts and templates
|
||||
//! (`fileupload`), and FileZilla's site manager. Passwords are removed here and never reach the page: the person
|
||||
//! types them once when importing.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
struct Settings {
|
||||
/// This computer's id for the server ("which computer saves these files").
|
||||
machine: String,
|
||||
/// Folders chosen with the picker: the only places files are written.
|
||||
folders: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Deliveries {
|
||||
dir: Option<PathBuf>,
|
||||
settings: Mutex<Option<Settings>>,
|
||||
}
|
||||
|
||||
impl Deliveries {
|
||||
#[cfg(test)]
|
||||
fn at(dir: PathBuf) -> Self {
|
||||
Self {
|
||||
dir: Some(dir),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn dir(&self) -> PathBuf {
|
||||
self.dir.clone().unwrap_or_else(|| {
|
||||
dirs::config_dir()
|
||||
.or_else(dirs::home_dir)
|
||||
.unwrap_or_else(std::env::temp_dir)
|
||||
.join("pt.photoreport.desktop")
|
||||
})
|
||||
}
|
||||
|
||||
fn with<T>(&self, f: impl FnOnce(&mut Settings) -> T) -> T {
|
||||
let mut guard = self.settings.lock().unwrap();
|
||||
if guard.is_none() {
|
||||
let loaded: Settings = std::fs::read(self.dir().join("deliveries.json"))
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice(&b).ok())
|
||||
.unwrap_or_default();
|
||||
*guard = Some(loaded);
|
||||
}
|
||||
let settings = guard.as_mut().unwrap();
|
||||
let before = serde_json::to_vec(settings).unwrap_or_default();
|
||||
if settings.machine.is_empty() {
|
||||
use rand::Rng;
|
||||
let id: u64 = rand::thread_rng().r#gen();
|
||||
settings.machine = format!("desktop-{id:016x}");
|
||||
}
|
||||
let out = f(settings);
|
||||
let after = serde_json::to_vec(settings).unwrap_or_default();
|
||||
if before != after {
|
||||
let dir = self.dir();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::fs::write(dir.join("deliveries.json"), after);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn machine(&self) -> String {
|
||||
self.with(|s| s.machine.clone())
|
||||
}
|
||||
|
||||
pub fn folders(&self) -> Vec<String> {
|
||||
self.with(|s| s.folders.clone())
|
||||
}
|
||||
|
||||
pub fn add_folder(&self, path: &Path) -> String {
|
||||
let p = path.to_string_lossy().to_string();
|
||||
self.with(|s| {
|
||||
if !s.folders.contains(&p) {
|
||||
s.folders.push(p.clone());
|
||||
}
|
||||
});
|
||||
p
|
||||
}
|
||||
|
||||
/// Writes `relative` (folders and file name from the destination's templates) under a chosen folder.
|
||||
pub fn write(&self, folder: &str, relative: &str, data: &[u8]) -> Result<PathBuf, String> {
|
||||
if !self.folders().iter().any(|f| f == folder) {
|
||||
return Err("folder_not_chosen_on_this_computer".into());
|
||||
}
|
||||
let target = safe_join(Path::new(folder), relative)?;
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
// Written beside it and moved into place: a file is never seen half-written.
|
||||
let tmp = target.with_extension("photoreport-part");
|
||||
std::fs::write(&tmp, data).map_err(|e| e.to_string())?;
|
||||
std::fs::rename(&tmp, &target).map_err(|e| {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
e.to_string()
|
||||
})?;
|
||||
Ok(target)
|
||||
}
|
||||
}
|
||||
|
||||
/// `base` + a relative path from a template, refusing anything that climbs out (`..`) or is absolute.
|
||||
fn safe_join(base: &Path, relative: &str) -> Result<PathBuf, String> {
|
||||
let rel = relative.replace('\\', "/");
|
||||
let rel = rel.trim_start_matches('/');
|
||||
if rel.is_empty() {
|
||||
return Err("empty_path".into());
|
||||
}
|
||||
let mut out = base.to_path_buf();
|
||||
for part in Path::new(rel).components() {
|
||||
match part {
|
||||
Component::Normal(p) => {
|
||||
let name = p.to_string_lossy();
|
||||
// Characters no file system takes (Windows' set): replaced, as Photo Mechanic does.
|
||||
let clean: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') || c.is_control() {
|
||||
'_'
|
||||
} else {
|
||||
c
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
out.push(clean);
|
||||
}
|
||||
Component::CurDir => {}
|
||||
_ => return Err("invalid_path".into()),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn percent_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' && i + 2 < bytes.len() {
|
||||
if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
|
||||
out.push(v);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).to_string()
|
||||
}
|
||||
|
||||
// ---- importing destinations from other apps ----------------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Snapshot {
|
||||
/// FTP, SFTP, ...
|
||||
pub kind: String,
|
||||
pub name: String,
|
||||
pub archived: bool,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Default, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ImportSources {
|
||||
/// Photo Mechanic's accounts per kind (YAML, passwords removed) and its saved upload templates.
|
||||
pub photo_mechanic: Vec<Snapshot>,
|
||||
pub photo_mechanic_accounts: Vec<Snapshot>,
|
||||
/// FileZilla's site manager (XML, passwords removed).
|
||||
pub filezilla: Option<String>,
|
||||
}
|
||||
|
||||
/// Photo Mechanic's account files list each account as `name: [user, password, settings]`; the password (the second
|
||||
/// item, often `!binary`) is dropped with whatever belongs to it.
|
||||
pub fn strip_pm_passwords(yaml: &str) -> String {
|
||||
let mut out = Vec::new();
|
||||
let mut item_indent: Option<usize> = None;
|
||||
let mut items = 0;
|
||||
let mut skipping: Option<usize> = None;
|
||||
for line in yaml.lines() {
|
||||
let indent = line.len() - line.trim_start().len();
|
||||
let trimmed = line.trim_start();
|
||||
if let Some(depth) = skipping {
|
||||
if indent > depth && !trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
skipping = None;
|
||||
}
|
||||
if trimmed.ends_with(':') && !trimmed.starts_with('-') && !trimmed.starts_with(':') {
|
||||
// An account name: its list items follow.
|
||||
item_indent = None;
|
||||
items = 0;
|
||||
} else if trimmed.starts_with("- ") || trimmed == "-" {
|
||||
if item_indent.is_none() {
|
||||
item_indent = Some(indent);
|
||||
}
|
||||
if item_indent == Some(indent) {
|
||||
items += 1;
|
||||
if items == 2 {
|
||||
skipping = Some(indent);
|
||||
out.push(format!("{}- ''", " ".repeat(indent)));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(line.to_string());
|
||||
}
|
||||
out.join("\n")
|
||||
}
|
||||
|
||||
/// FileZilla keeps passwords as `<Pass>` (plain or base64): removed.
|
||||
pub fn strip_filezilla_passwords(xml: &str) -> String {
|
||||
let mut out = String::with_capacity(xml.len());
|
||||
let mut rest = xml;
|
||||
while let Some(start) = rest.find("<Pass") {
|
||||
out.push_str(&rest[..start]);
|
||||
let after = &rest[start..];
|
||||
if let Some(end) = after.find("</Pass>") {
|
||||
rest = &after[end + "</Pass>".len()..];
|
||||
} else if let Some(end) = after.find("/>") {
|
||||
rest = &after[end + 2..];
|
||||
} else {
|
||||
rest = "";
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
fn read_text(p: &Path) -> Option<String> {
|
||||
std::fs::read(p)
|
||||
.ok()
|
||||
.map(|b| String::from_utf8_lossy(&b).to_string())
|
||||
}
|
||||
|
||||
/// Where Photo Mechanic keeps its upload settings (macOS: ~/Library/Preferences/com.camerabits.PhotoMechanic…;
|
||||
/// Windows: %APPDATA%\Camera Bits\Photo Mechanic…).
|
||||
fn pm_upload_dirs(home: &Path, config: Option<&Path>) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let prefs = home.join("Library").join("Preferences");
|
||||
if let Ok(entries) = std::fs::read_dir(&prefs) {
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with("com.camerabits.PhotoMechanic")
|
||||
&& e.path().join("fileupload").is_dir()
|
||||
{
|
||||
out.push(e.path().join("fileupload"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(config) = config {
|
||||
if let Ok(entries) = std::fs::read_dir(config.join("Camera Bits")) {
|
||||
for e in entries.flatten() {
|
||||
if e.path().join("fileupload").is_dir() {
|
||||
out.push(e.path().join("fileupload"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
pub fn import_sources(home: &Path, config: Option<&Path>) -> ImportSources {
|
||||
let mut sources = ImportSources::default();
|
||||
for dir in pm_upload_dirs(home, config) {
|
||||
if let Ok(entries) = std::fs::read_dir(dir.join("templates").join("builtin")) {
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
let Some(kind) = name.strip_suffix("-conn.yml") else {
|
||||
continue;
|
||||
};
|
||||
if let Some(text) = read_text(&e.path()) {
|
||||
if text.contains(":settings:") {
|
||||
sources.photo_mechanic_accounts.push(Snapshot {
|
||||
kind: kind.to_string(),
|
||||
name: kind.to_string(),
|
||||
archived: false,
|
||||
text: strip_pm_passwords(&text),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(kinds) = std::fs::read_dir(dir.join("snapshot").join("builtin")) {
|
||||
for k in kinds.flatten().filter(|k| k.path().is_dir()) {
|
||||
let kind = k.file_name().to_string_lossy().to_string();
|
||||
for (folder, archived) in [(k.path(), false), (k.path().join("Archive"), true)] {
|
||||
let Ok(files) = std::fs::read_dir(&folder) else {
|
||||
continue;
|
||||
};
|
||||
for f in files.flatten() {
|
||||
let name = f.file_name().to_string_lossy().to_string();
|
||||
let Some(stem) = name.strip_suffix(".snap") else {
|
||||
continue;
|
||||
};
|
||||
if let Some(text) = read_text(&f.path()) {
|
||||
sources.photo_mechanic.push(Snapshot {
|
||||
kind: kind.clone(),
|
||||
name: stem.to_string(),
|
||||
archived,
|
||||
text,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
sources
|
||||
.photo_mechanic
|
||||
.sort_by(|a, b| (a.archived, &a.kind, &a.name).cmp(&(b.archived, &b.kind, &b.name)));
|
||||
sources
|
||||
.photo_mechanic_accounts
|
||||
.sort_by(|a, b| a.kind.cmp(&b.kind));
|
||||
let mut fz = vec![
|
||||
home.join(".config")
|
||||
.join("filezilla")
|
||||
.join("sitemanager.xml"),
|
||||
];
|
||||
if let Some(config) = config {
|
||||
fz.push(config.join("FileZilla").join("sitemanager.xml"));
|
||||
fz.push(config.join("filezilla").join("sitemanager.xml"));
|
||||
}
|
||||
sources.filezilla = fz
|
||||
.iter()
|
||||
.find_map(|p| read_text(p))
|
||||
.map(|t| strip_filezilla_passwords(&t));
|
||||
sources
|
||||
}
|
||||
|
||||
// ---- commands -------------------------------------------------------------------------------------------------
|
||||
|
||||
/// This computer's id (the server hands the files of its folders to it).
|
||||
#[tauri::command]
|
||||
pub fn delivery_machine(state: tauri::State<'_, Deliveries>) -> String {
|
||||
state.machine()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delivery_folders(state: tauri::State<'_, Deliveries>) -> Vec<String> {
|
||||
state.folders()
|
||||
}
|
||||
|
||||
/// The system's folder picker; the folder chosen becomes a place deliveries may be saved. None: closed.
|
||||
#[tauri::command]
|
||||
pub async fn delivery_folder_pick(
|
||||
app: tauri::AppHandle,
|
||||
state: tauri::State<'_, Deliveries>,
|
||||
) -> Result<Option<String>, String> {
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
app.dialog()
|
||||
.file()
|
||||
.set_title("Pasta para as entregas")
|
||||
.pick_folder(move |picked| {
|
||||
let _ = tx.send(picked);
|
||||
});
|
||||
let Some(picked) = rx.await.map_err(|e| e.to_string())? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = picked.into_path().map_err(|e| e.to_string())?;
|
||||
Ok(Some(state.add_folder(&path)))
|
||||
}
|
||||
|
||||
/// Saves one delivered file. The bytes are the request body; the chosen folder and the path under it come in the
|
||||
/// `folder` and `path` headers (percent-encoded). Returns where it was saved.
|
||||
#[tauri::command]
|
||||
pub fn delivery_write(
|
||||
request: tauri::ipc::Request<'_>,
|
||||
state: tauri::State<'_, Deliveries>,
|
||||
) -> Result<String, String> {
|
||||
let header = |name: &str| {
|
||||
request
|
||||
.headers()
|
||||
.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(percent_decode)
|
||||
.ok_or_else(|| format!("missing {name}"))
|
||||
};
|
||||
let folder = header("folder")?;
|
||||
let path = header("path")?;
|
||||
let tauri::ipc::InvokeBody::Raw(data) = request.body() else {
|
||||
return Err("expected the file as the body".into());
|
||||
};
|
||||
state
|
||||
.write(&folder, &path, data)
|
||||
.map(|p| p.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer (without passwords).
|
||||
#[tauri::command]
|
||||
pub fn import_upload_profiles() -> ImportSources {
|
||||
let home = dirs::home_dir().unwrap_or_default();
|
||||
import_sources(&home, dirs::config_dir().as_deref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pr-deliver-{name}-{}", rand::random::<u32>()));
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_only_inside_chosen_folders() {
|
||||
let dir = tmp("cfg");
|
||||
let out = tmp("out");
|
||||
let d = Deliveries::at(dir.clone());
|
||||
assert!(d.machine().starts_with("desktop-"));
|
||||
assert_eq!(
|
||||
d.machine(),
|
||||
Deliveries::at(dir.clone()).machine(),
|
||||
"kept between runs"
|
||||
);
|
||||
let folder = out.to_string_lossy().to_string();
|
||||
assert_eq!(
|
||||
d.write(&folder, "a/b.jpg", b"x").unwrap_err(),
|
||||
"folder_not_chosen_on_this_computer"
|
||||
);
|
||||
d.add_folder(&out);
|
||||
let p = d
|
||||
.write(&folder, "/VSC x AAAS/PS_VSC x AAAS_1.jpg", b"jpeg")
|
||||
.unwrap();
|
||||
assert_eq!(std::fs::read(&p).unwrap(), b"jpeg");
|
||||
assert!(p.starts_with(&out));
|
||||
assert_eq!(
|
||||
d.write(&folder, "../escape.jpg", b"x").unwrap_err(),
|
||||
"invalid_path"
|
||||
);
|
||||
assert_eq!(
|
||||
d.write(&folder, "a/../../escape.jpg", b"x").unwrap_err(),
|
||||
"invalid_path"
|
||||
);
|
||||
let odd = d.write(&folder, "Jogo: 1/foto?.jpg", b"x").unwrap();
|
||||
assert!(odd.ends_with("Jogo_ 1/foto_.jpg"), "{odd:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_headers() {
|
||||
assert_eq!(
|
||||
percent_decode("Competi%C3%A7%C3%B5es%20Nacionais"),
|
||||
"Competições Nacionais"
|
||||
);
|
||||
assert_eq!(percent_decode("a%2"), "a%2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn photo_mechanic_passwords_never_leave() {
|
||||
let yaml = "---\n:connection_settings_dialog:\n :settings:\n COFINA - ARQUIVO:\n - mnoticiasex\n - !binary |-\n c2VjcmV0\n - :server_addr_edit:\n :value: ftp.cofina.pt\n :dest_folder_edit:\n :value: /fotografia/\n FPF:\n - fpf\n - plainsecret\n - :server_addr_edit:\n :value: ftp.fpf.pt\n";
|
||||
let out = strip_pm_passwords(yaml);
|
||||
assert!(
|
||||
!out.contains("c2VjcmV0") && !out.contains("plainsecret"),
|
||||
"{out}"
|
||||
);
|
||||
assert!(
|
||||
out.contains("- mnoticiasex")
|
||||
&& out.contains("ftp.cofina.pt")
|
||||
&& out.contains("/fotografia/")
|
||||
&& out.contains("ftp.fpf.pt"),
|
||||
"{out}"
|
||||
);
|
||||
assert_eq!(out.matches("- ''").count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filezilla_passwords_never_leave() {
|
||||
let xml = r#"<Server><Host>ftp.x.pt</Host><User>u</User><Pass encoding="base64">c2VjcmV0</Pass><Name>X</Name></Server>"#;
|
||||
assert_eq!(
|
||||
strip_filezilla_passwords(xml),
|
||||
"<Server><Host>ftp.x.pt</Host><User>u</User><Name>X</Name></Server>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_photo_mechanic_and_filezilla() {
|
||||
let home = tmp("home");
|
||||
let pm = home.join("Library/Preferences/com.camerabits.PhotoMechanic/fileupload");
|
||||
std::fs::create_dir_all(pm.join("templates/builtin")).unwrap();
|
||||
std::fs::create_dir_all(pm.join("snapshot/builtin/FTP/Archive")).unwrap();
|
||||
std::fs::write(pm.join("templates/builtin/FTP-conn.yml"), "---\n:connection_settings_dialog:\n :settings:\n A:\n - u\n - !binary |-\n c2VjcmV0\n - :x: 1\n").unwrap();
|
||||
std::fs::write(pm.join("templates/builtin/Box-conn.yml"), "--- {}\n").unwrap();
|
||||
std::fs::write(
|
||||
pm.join("snapshot/builtin/FTP/DIR.snap"),
|
||||
"<TemplateSettings/>",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
pm.join("snapshot/builtin/FTP/Archive/OLD.snap"),
|
||||
"<TemplateSettings/>",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::create_dir_all(home.join(".config/filezilla")).unwrap();
|
||||
std::fs::write(
|
||||
home.join(".config/filezilla/sitemanager.xml"),
|
||||
"<Pass>p</Pass><Host>h</Host>",
|
||||
)
|
||||
.unwrap();
|
||||
let s = import_sources(&home, None);
|
||||
assert_eq!(s.photo_mechanic_accounts.len(), 1);
|
||||
assert!(!s.photo_mechanic_accounts[0].text.contains("c2VjcmV0"));
|
||||
assert_eq!(
|
||||
s.photo_mechanic
|
||||
.iter()
|
||||
.map(|x| (x.name.as_str(), x.archived))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![("DIR", false), ("OLD", true)]
|
||||
);
|
||||
assert_eq!(s.filezilla.as_deref(), Some("<Host>h</Host>"));
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
//! inside the desktop app (see apps/app/src/platform.ts). The refresh token never touches disk in clear:
|
||||
//! it lives in the OS keychain (macOS Keychain, Windows Credential Manager, Secret Service on Linux).
|
||||
//! `ftp` runs the local FTP server cameras send photos to; `local` finds originals on disk for the editor; `catalog`
|
||||
//! indexes the photographer's own folders for it; `updater` keeps the shell itself current.
|
||||
//! indexes the photographer's own folders for it; `deliver` saves deliveries to folders here and imports upload
|
||||
//! destinations from Photo Mechanic and FileZilla; `updater` keeps the shell itself current.
|
||||
|
||||
mod catalog;
|
||||
mod deliver;
|
||||
mod ftp;
|
||||
mod local;
|
||||
mod preview;
|
||||
@@ -81,6 +83,7 @@ pub fn run() {
|
||||
.manage(ftp::FtpState::default())
|
||||
.manage(local::LocalIndex::default())
|
||||
.manage(catalog::Catalog::default())
|
||||
.manage(deliver::Deliveries::default())
|
||||
.manage(shared)
|
||||
.setup(|app| {
|
||||
use tauri::Manager;
|
||||
@@ -127,7 +130,12 @@ pub fn run() {
|
||||
updater::update_check,
|
||||
updater::update_install,
|
||||
ui::ui_status,
|
||||
ui::ui_check
|
||||
ui::ui_check,
|
||||
deliver::delivery_machine,
|
||||
deliver::delivery_folders,
|
||||
deliver::delivery_folder_pick,
|
||||
deliver::delivery_write,
|
||||
deliver::import_upload_profiles
|
||||
])
|
||||
.run(context);
|
||||
if let Err(err) = result {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.8",
|
||||
"version": "0.3.9",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
+43
-4
@@ -206,12 +206,16 @@ group.
|
||||
|
||||
Face and number are used together:
|
||||
|
||||
- **Face sure, number agrees (or none read):** the face's suggestion.
|
||||
- **Face sure, number agrees:** the face's suggestion, surer (score + 0.15 × the reading, at most 0.99).
|
||||
- **Face sure, no number read:** the face's suggestion. Faces come from confirmed groups and from the official
|
||||
headshots (Liga, UEFA, FPA licence photos) that squads bring as reference photos, so even a first match has faces to go by.
|
||||
- **Face sure, number clearly another (two or more readings):** still the face's suggestion, at 0.8 × its score.
|
||||
- **Face not sure (weak, or two people too close):** among the people the face is near to, the one whose number was
|
||||
read; else the squad player who wears that number in either team of the event (0.9 × the mean reading).
|
||||
- **Both teams have that number:** the kit colour decides. Each face keeps the median colour of the middle of its
|
||||
chest; each team's colour is the median of its players already confirmed in the event (goalkeepers left out).
|
||||
chest; each team's colour is the median of its players already confirmed in the event, or suggested with face and
|
||||
shirt agreeing (score 0.85 and up), goalkeepers left out. The same colour also decides between two people the
|
||||
face is near to who both wear the number read.
|
||||
The group goes to the team whose colour is clearly closer, never when the two kits are alike or the group's
|
||||
colour sits in between.
|
||||
|
||||
@@ -228,9 +232,26 @@ every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisati
|
||||
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup. Gives teams, squads (numbers,
|
||||
positions, official headshots) and the season's fixtures.
|
||||
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
|
||||
fixtures. The FPA publishes no squads, so handball squads are still pasted or imported into people.
|
||||
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
|
||||
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
|
||||
number (CIPA), and the bench officials by their card letter (Oficial A-F, kept as the "number" so the shirt-number
|
||||
reader can name them; their CIPA comes from the match page's team panes, as the report gives their coaching grade
|
||||
there). Referees and table officials come with full name and CIPA too, and are kept as one more FPA "team"
|
||||
(`ARBITRAGEM`), so the names the match page gives before a game find their licence, photo and full name. A team without a squad starts from its club's last three reports (club page → season and
|
||||
level ids → `getJogosClubeEpocaEscalao`), eight teams per refresh; after that each report of a game played is read
|
||||
once (reports read before licence numbers were kept are read again, 40 per refresh). Referees and table officials
|
||||
come from the report, or from the match page (named some days before) for games with an event; both become people.
|
||||
Licence photos (`portal.fpa.pt/associado/<CIPA>/`) are looked up only for the people of an event being synced,
|
||||
with biometrics on, and become their reference photos. Names are first + last name ("Rui Lopes"), the full name
|
||||
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.
|
||||
- **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
|
||||
played, and the match's own sheet from 1 h before kick-off. On an event, the referee team on the pitch
|
||||
(referee, assistants, fourth official) becomes people of club "Arbitragem". Asked sparingly and cached: if it
|
||||
changes, events still work with names typed by hand.
|
||||
|
||||
What organisations do with it:
|
||||
|
||||
@@ -274,7 +295,7 @@ organization). Every message goes through PostgreSQL `LISTEN/NOTIFY` (`photorepo
|
||||
every API process publish, every API process delivers to its own sockets. No Redis/Valkey and no sticky
|
||||
sessions needed. Messages: `photo.added`, `photo.updated` (culling, players), `delivery.updated`.
|
||||
|
||||
## Client delivery (Nextcloud, SFTP, FTP, Dropbox)
|
||||
## Client delivery (Nextcloud, SFTP, FTP, Dropbox, ZeroZero, a folder on a computer)
|
||||
|
||||
PhotoReport storage is the source of truth; Nextcloud receives organised copies. Any client organization can have one or
|
||||
more destinations on any Nextcloud instance, each with its own folder and file-name templates (variables
|
||||
@@ -294,6 +315,24 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
|
||||
key fails the delivery until an admin resets it.
|
||||
- **FTP:** `ftps://` for explicit TLS.
|
||||
- **Dropbox:** app key plus refresh token, or a long-lived access token.
|
||||
- **A folder on a computer** (`LOCAL`): the worker renders the file as for any destination and keeps it (status
|
||||
`WAITING`, `<org>/deliveries/<item>.jpg`); the desktop app of that computer (its id is the target's user) takes it
|
||||
(`/deliveries/local/claim`, `/local-file`, `/local-result`, every 10 s while open) and saves it under the folder,
|
||||
with the templates' subfolders and name. It only writes inside folders chosen there with the system's folder
|
||||
picker (`src-tauri/src/deliver.rs`), never a path a page passes. For testing a destination's rules, or keeping
|
||||
the finished files to choose from later.
|
||||
- **Importing destinations** (desktop, "Importar…" in Destinos): Photo Mechanic's upload accounts
|
||||
(`fileupload/templates/builtin/<kind>-conn.yml`) and templates (`fileupload/snapshot/builtin/<kind>/*.snap`), and
|
||||
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places with the passwords removed there;
|
||||
`library/importTargets.ts` turns them into destinations (server, user, folder, size, quality, rename) and the
|
||||
person types each password.
|
||||
- **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server
|
||||
signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`,
|
||||
cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=<game>` with the file name and the
|
||||
author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the
|
||||
event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games
|
||||
by both teams and kick-off within 3 hours. The delivered item's remote path is `<game>/<image id>`
|
||||
(`DELETE /api/images/<id>` takes it back).
|
||||
|
||||
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
|
||||
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Templates accept Photo Mechanic's variable
|
||||
|
||||
@@ -83,6 +83,26 @@ measurement, the median of the last 60 corrections, at the same venue when there
|
||||
|
||||
The autopilot's panel in the app shows what it has learnt and has "Esquecer". The burst picks are not learnt yet.
|
||||
|
||||
## 5. Only the best
|
||||
|
||||
Some clients (ZeroZero) want a short gallery of the match, not every usable frame. With "Só as melhores do
|
||||
jogo" the autopilot still flags each burst's picks for the photographer, but delivers only a curated set of
|
||||
about the gallery size asked (`apps/api/src/autopilot/curate.ts`):
|
||||
|
||||
- the match (from kick-off, its typical length by sport: football 115 min with the break, handball 80) is cut
|
||||
into 5-minute windows; each window may add its share of the gallery, and a share it did not use (the break,
|
||||
a quiet spell) carries forward, at most three windows' worth at once; at most 10% over the size in all;
|
||||
- one candidate per burst (its best frame), ranked by game moment: the frame score, more with the ball in play
|
||||
(×1.3), a duel or a celebration (several people in the subject), less when the subject is small (far away);
|
||||
the photographer's stars count (+20% each), a rejected frame never goes;
|
||||
- frames well below the match's typical frame (half the median) are left out even when the window has room,
|
||||
and never two frames of the same moment (8 s);
|
||||
- warm-up and line-ups (more than 5 minutes before kick-off) are not candidates;
|
||||
- a window is decided a minute after it ends, so the gallery reaches the client with about 6 minutes' delay.
|
||||
|
||||
After the match, "Melhores…" in the library sends the best N of the event the same way (filling up to N with
|
||||
the best frames left when the windows' shares fall short); without the autopilot, stars and picks rank.
|
||||
|
||||
## Sources
|
||||
|
||||
- AP and NPPA codes, summarised by the CUNY Newmark J-School: https://photo.journalism.cuny.edu/?p=201
|
||||
|
||||
@@ -43,6 +43,12 @@ export const AutopilotSettings = z.object({
|
||||
burstGapSec: z.number().min(0.2).max(10).default(1.5),
|
||||
/** Deliver the picks to this target as they are chosen (null: don't). */
|
||||
deliverTargetId: z.string().uuid().nullable().default(null),
|
||||
/**
|
||||
* What is delivered: every burst's picks, or only the best of the match (a short gallery of game moments, spread
|
||||
* over the match, about `bestCount` photos; apps/api/src/autopilot/curate.ts).
|
||||
*/
|
||||
selection: z.enum(["bursts", "best"]).default("bursts"),
|
||||
bestCount: z.number().int().min(5).max(300).default(30),
|
||||
});
|
||||
export type AutopilotSettings = z.infer<typeof AutopilotSettings>;
|
||||
|
||||
@@ -57,7 +63,7 @@ export type PhotoDelivery = "NONE" | "QUEUED" | "DONE" | "FAILED";
|
||||
/** A photo's overall delivery state from the status of each of its deliveries. */
|
||||
export function deliveryState(statuses: readonly string[]): PhotoDelivery {
|
||||
if (statuses.includes("DONE")) return "DONE";
|
||||
if (statuses.some((x) => x === "QUEUED" || x === "RUNNING")) return "QUEUED";
|
||||
if (statuses.some((x) => x === "QUEUED" || x === "RUNNING" || x === "WAITING")) return "QUEUED";
|
||||
return statuses.length ? "FAILED" : "NONE";
|
||||
}
|
||||
|
||||
@@ -97,7 +103,8 @@ export interface PhotoSummary {
|
||||
urls: { thumb: string; preview: string; source: string };
|
||||
}
|
||||
|
||||
export type DeliveryStatus = "QUEUED" | "RUNNING" | "DONE" | "FAILED";
|
||||
/** WAITING: rendered for a folder on a computer, until that computer's desktop app takes it. */
|
||||
export type DeliveryStatus = "QUEUED" | "RUNNING" | "WAITING" | "DONE" | "FAILED";
|
||||
|
||||
export interface DeliveryItemSummary {
|
||||
id: string;
|
||||
@@ -121,6 +128,16 @@ export const DeliveryRequest = z.object({
|
||||
});
|
||||
export type DeliveryRequest = z.infer<typeof DeliveryRequest>;
|
||||
|
||||
/** Sends only the best of an event's photos (game moments, spread over the match; apps/api/src/autopilot/best.ts). */
|
||||
export const DeliveryBestRequest = z.object({
|
||||
targetId: z.string().uuid(),
|
||||
eventId: z.string().uuid(),
|
||||
count: z.number().int().min(1).max(300),
|
||||
/** Only work out the choice (to show it), send nothing. */
|
||||
dryRun: z.boolean().default(false),
|
||||
});
|
||||
export type DeliveryBestRequest = z.infer<typeof DeliveryBestRequest>;
|
||||
|
||||
/** Server-to-client realtime messages for the library (room `org:<id>`). */
|
||||
export type LibraryMessage =
|
||||
| { type: "photo.added"; photo: PhotoSummary }
|
||||
|
||||
@@ -15,6 +15,7 @@ describe("Photo Mechanic variables", () => {
|
||||
it("falls back to the event day without a capture time", () => {
|
||||
const v = buildVars(event, {});
|
||||
expect(v.datesort).toBe("20261011");
|
||||
expect(v.todaysort).toMatch(/^\d{8}$/);
|
||||
expect(v.timesort).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -144,5 +144,10 @@ function photoMechanicDates(day: Date, shot: Date | undefined): Record<string, s
|
||||
second: t?.ss,
|
||||
/** hhmmss plus hundredths: sorts in shooting order and tells burst frames apart. */
|
||||
timesort: t ? `${t.hh}${t.mm}${t.ss}${t.cs}` : undefined,
|
||||
/** The day it is sent (Lisbon), as Photo Mechanic's {todaysort}. */
|
||||
todaysort: (() => {
|
||||
const n = parts(new Date());
|
||||
return `${n.y}${n.m}${n.d}`;
|
||||
})(),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
|
||||
import type { AgendaEntry, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role } from "./types.js";
|
||||
import type { AgendaEntry, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
|
||||
|
||||
/**
|
||||
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
|
||||
@@ -93,6 +93,26 @@ export class ApiClient {
|
||||
return this.request("POST", `/v1/photos/${photoId}/original/request`);
|
||||
}
|
||||
|
||||
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
|
||||
claimLocalDeliveries(orgId: string, machine: string) {
|
||||
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });
|
||||
}
|
||||
|
||||
/** The rendered file of a delivery this computer took. */
|
||||
async localDeliveryFile(orgId: string, itemId: string): Promise<ArrayBuffer> {
|
||||
const res = await this.fetchImpl(this.absolute(`/v1/orgs/${orgId}/deliveries/${itemId}/local-file`), {
|
||||
headers: { authorization: `Bearer ${await this.realtimeToken()}` },
|
||||
credentials: "include",
|
||||
});
|
||||
if (!res.ok) throw new ApiError(res.status, `http_${res.status}`, null);
|
||||
return res.arrayBuffer();
|
||||
}
|
||||
|
||||
/** Saved (and where), or why not. */
|
||||
localDeliveryResult(orgId: string, itemId: string, result: { ok: boolean; path?: string; error?: string }) {
|
||||
return this.request<DeliveryItemSummary>("POST", `/v1/orgs/${orgId}/deliveries/${itemId}/local-result`, result);
|
||||
}
|
||||
|
||||
/** The full-resolution original, or null while it is still only on the photographer's computer. */
|
||||
async originalBytes(photoId: string): Promise<ArrayBuffer | null> {
|
||||
const res = await this.fetchImpl(this.absolute(`/v1/photos/${photoId}/original`), {
|
||||
@@ -769,6 +789,21 @@ export class ApiClient {
|
||||
return this.request<void>("DELETE", `/v1/orgs/${orgId}/ftp-accounts/${accountId}`);
|
||||
}
|
||||
|
||||
/** Only the best of an event (game moments spread over the match); `dryRun` only works out the choice. */
|
||||
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean }) {
|
||||
return this.request<{ chosen: string[]; queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries/best`, input);
|
||||
}
|
||||
|
||||
/** ZeroZero: the event's game on the photo desk (the chosen one, or the one found by teams and time). */
|
||||
zerozeroGame(orgId: string, targetId: string, eventId: string) {
|
||||
return this.request<{ game: ZerozeroGame | null; chosen: boolean }>("GET", `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game?eventId=${encodeURIComponent(eventId)}`);
|
||||
}
|
||||
|
||||
/** Chooses the event's game from a link or id on fotos.zerozero.pt (null: forget it and look it up again). */
|
||||
setZerozeroGame(orgId: string, targetId: string, eventId: string, game: string | null) {
|
||||
return this.request<{ game: ZerozeroGame | null; chosen: boolean }>("PUT", `/v1/orgs/${orgId}/delivery-targets/${targetId}/zerozero-game`, { eventId, game });
|
||||
}
|
||||
|
||||
deliver(orgId: string, targetId: string, photoIds: string[], again = false) {
|
||||
return this.request<{ queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries`, { targetId, photoIds, again });
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ export interface EventInput {
|
||||
|
||||
// ---- sports data ----------------------------------------------------------------------------------------
|
||||
|
||||
export type SportsProvider = "LIGA" | "FPF" | "FPA";
|
||||
export type SportsProvider = "LIGA" | "FPF" | "FPA" | "UEFA";
|
||||
|
||||
export interface SportsCompetition {
|
||||
id: string;
|
||||
@@ -171,7 +171,17 @@ export interface EventSquads {
|
||||
sides: {
|
||||
side: "home" | "away";
|
||||
team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null };
|
||||
players: { id: string; number: string | null; name: string; fullName: string | null; position: string | null; hasPhoto: boolean; personId: string | null }[];
|
||||
players: {
|
||||
id: string;
|
||||
number: string | null;
|
||||
name: string;
|
||||
fullName: string | null;
|
||||
position: string | null;
|
||||
hasPhoto: boolean;
|
||||
personId: string | null;
|
||||
/** Photos of them in this event: confirmed, and taken for them by the faces (70% or more) not confirmed yet. */
|
||||
photos?: { confirmed: number; likely: number };
|
||||
}[];
|
||||
}[];
|
||||
}
|
||||
|
||||
@@ -190,7 +200,17 @@ export interface IptcIssue {
|
||||
detail: string;
|
||||
}
|
||||
|
||||
export type DeliveryKind = "NEXTCLOUD" | "SFTP" | "FTP" | "DROPBOX";
|
||||
/** 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";
|
||||
|
||||
/** A game on fotos.zerozero.pt (date in Lisbon time, "2026-10-15 17:45:00"). */
|
||||
export interface ZerozeroGame {
|
||||
id: string;
|
||||
date: string;
|
||||
home: string;
|
||||
away: string;
|
||||
competition: string | null;
|
||||
}
|
||||
|
||||
export interface DeliveryTarget {
|
||||
id: string;
|
||||
@@ -254,7 +274,8 @@ export interface DeliveryTargetInput {
|
||||
kind?: DeliveryKind;
|
||||
baseUrl: string;
|
||||
username: string;
|
||||
password: string;
|
||||
/** Write-only; not for LOCAL. */
|
||||
password?: string;
|
||||
folderTemplate: string;
|
||||
fileNameTemplate: string;
|
||||
longEdge?: number;
|
||||
@@ -273,6 +294,8 @@ export interface PersonSummary {
|
||||
}
|
||||
|
||||
export interface SquadPerson extends PersonSummary {
|
||||
/** The full name from the squad, when it differs from the short one used in captions. */
|
||||
fullName?: string | null;
|
||||
faceCount: number;
|
||||
/** Reference photo (squad headshot) and whether its face has been read. */
|
||||
reference: { status: "NONE" | "PENDING" | "RUNNING" | "DONE" | "FAILED"; url: string } | null;
|
||||
|
||||
Reference in new issue
Block a user