Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
003b8fceb8 | ||
|
|
a5cbbe594d | ||
|
|
e8339cdf3f | ||
|
|
42664869fc | ||
|
|
b0e1664375 | ||
|
|
e74ca03f23 | ||
|
|
b4d3cedacc | ||
|
|
caeee877ba | ||
|
|
28291a5f96 | ||
|
|
eadb535d8f | ||
|
|
8c39c6eb34 | ||
|
|
c782c73abd | ||
|
|
6b2f060463 | ||
|
|
97265b8de2 | ||
|
|
520e51209c | ||
|
|
467df72a59 | ||
|
|
706aa8a5df | ||
|
|
c32012a0cd | ||
|
|
e554c2e7d6 | ||
|
|
3860e2e1e0 | ||
|
|
ae7f8eb6f9 | ||
|
|
f8611ad405 | ||
|
|
cda3885fcd | ||
|
|
b58bc3129e | ||
|
|
c16730f540 | ||
|
|
655ec1bba8 | ||
|
|
b694e93a2b | ||
|
|
aae9ab8d0b | ||
|
|
cceabdef06 | ||
|
|
17784c8b22 | ||
|
|
24ec8095f6 |
No files matched your search
@@ -1,7 +1,8 @@
|
||||
name: desktop-release
|
||||
# Tag `desktop-vX.Y.Z` builds the desktop installers and attaches them to a Gitea release.
|
||||
# Linux builds on the standard runner. macOS (.dmg) and Windows (.msi) need runners with those labels:
|
||||
# register one on a Mac and one on a Windows machine, then uncomment the matrix entries.
|
||||
# Linux builds on the standard runner. macOS (.dmg) builds on a Mac registered as a runner with the label "macos"
|
||||
# (infra/desktop/macos-runner.sh, once); a release made while that Mac is off waits for it. Windows (.msi) needs a
|
||||
# runner labelled "windows": register one, then uncomment its entry.
|
||||
#
|
||||
# Self-updates (apps/desktop/src-tauri/src/updater.rs): with the secret TAURI_SIGNING_PRIVATE_KEY (and
|
||||
# TAURI_SIGNING_PRIVATE_KEY_PASSWORD) and the variable TAURI_UPDATER_PUBKEY set (`tauri signer generate`), each job
|
||||
@@ -20,10 +21,10 @@ jobs:
|
||||
- runner: ubuntu-latest
|
||||
bundles: deb,appimage
|
||||
platform: linux-x86_64
|
||||
# - runner: macos
|
||||
# bundles: dmg,app
|
||||
# platform: darwin-universal
|
||||
# args: --target universal-apple-darwin
|
||||
- runner: macos
|
||||
bundles: dmg,app
|
||||
platform: darwin-universal
|
||||
args: --target universal-apple-darwin
|
||||
# - runner: windows
|
||||
# bundles: msi
|
||||
# platform: windows-x86_64
|
||||
@@ -46,6 +47,9 @@ jobs:
|
||||
with:
|
||||
node-version: 22
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Both Mac processors (universal app)
|
||||
if: runner.os == 'macOS'
|
||||
run: rustup target add aarch64-apple-darwin x86_64-apple-darwin
|
||||
- name: Photo engine (WebAssembly)
|
||||
run: |
|
||||
rustup target add wasm32-unknown-unknown
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "pending_uploads" ADD COLUMN "from_desktop" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -0,0 +1,14 @@
|
||||
-- CreateEnum
|
||||
CREATE TYPE "JerseyRegion" AS ENUM ('CHEST', 'SHORTS');
|
||||
|
||||
-- DropIndex
|
||||
DROP INDEX "jersey_samples_face_id_key";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "jersey_samples" ADD COLUMN "region" "JerseyRegion" NOT NULL DEFAULT 'CHEST';
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "jersey_samples_face_id_region_key" ON "jersey_samples"("face_id", "region");
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "faces" ADD COLUMN "jersey_crops" INTEGER NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "faces" ADD COLUMN "kit_colour" DOUBLE PRECISION[] DEFAULT ARRAY[]::DOUBLE PRECISION[];
|
||||
@@ -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
|
||||
}
|
||||
@@ -647,12 +654,16 @@ model Face {
|
||||
/// Shirt number read under the face by the jersey model (null: not run, or not legible) and its confidence.
|
||||
jerseyNumber String? @map("jersey_number")
|
||||
jerseyScore Float? @map("jersey_score")
|
||||
/// The set of number crops its training samples were made with (`JERSEY_CROPS` in jersey/service.ts); 0: none yet.
|
||||
jerseyCrops Int @default(0) @map("jersey_crops")
|
||||
/// Median RGB of the kit under the face (chest): tells the two teams apart when both have a player with a number.
|
||||
kitColour Float[] @default([]) @map("kit_colour")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
photo Photo @relation(fields: [photoId], references: [id], onDelete: Cascade)
|
||||
group FaceGroup? @relation(fields: [groupId], references: [id], onDelete: SetNull)
|
||||
jerseySample JerseySample?
|
||||
jerseySamples JerseySample[]
|
||||
|
||||
@@index([photoId])
|
||||
@@index([groupId])
|
||||
@@ -1097,6 +1108,8 @@ model PendingUpload {
|
||||
offset Int @default(0)
|
||||
/// Set when this upload is a preview standing in for an original kept on the desktop: {sha256, size, width, height}.
|
||||
original Json?
|
||||
/// An original sent by the desktop app's ingest (its local FTP): edited by the event's autopilot like FTP photos.
|
||||
fromDesktop Boolean @default(false) @map("from_desktop")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
@@ -1104,6 +1117,14 @@ model PendingUpload {
|
||||
@@map("pending_uploads")
|
||||
}
|
||||
|
||||
/// Where a shirt-number crop is taken from, under the face.
|
||||
enum JerseyRegion {
|
||||
/// Chest and belly: the front number of handball (and most other) kits.
|
||||
CHEST
|
||||
/// Waist to mid-thigh: the front number of football kits (Liga Portugal shirts have none on the chest).
|
||||
SHORTS
|
||||
}
|
||||
|
||||
enum JerseySampleStatus {
|
||||
/// Made from a confirmed face and the squad's number; waiting for a person to check it.
|
||||
PENDING
|
||||
@@ -1122,7 +1143,9 @@ enum JerseySampleStatus {
|
||||
model JerseySample {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
organizationId String @map("organization_id") @db.Uuid
|
||||
faceId String @unique @map("face_id") @db.Uuid
|
||||
faceId String @map("face_id") @db.Uuid
|
||||
/// Where on the player the crop is: football kits carry the front number on the shorts, handball on the chest.
|
||||
region JerseyRegion @default(CHEST)
|
||||
photoId String @map("photo_id") @db.Uuid
|
||||
personId String? @map("person_id") @db.Uuid
|
||||
/// Torso box in fractions of the photo.
|
||||
@@ -1141,6 +1164,7 @@ model JerseySample {
|
||||
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
|
||||
face Face @relation(fields: [faceId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([faceId, region])
|
||||
@@index([organizationId, status])
|
||||
@@map("jersey_samples")
|
||||
}
|
||||
@@ -1165,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 {
|
||||
@@ -1271,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")
|
||||
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr
|
||||
await registerCalendarRoutes(app, { sessions, calendar: new CalendarService({ db, secrets, ...(fetchImpl && { fetchImpl }) }) });
|
||||
await registerOrgRoutes(app, { db, sessions });
|
||||
const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch });
|
||||
await registerEventRoutes(app, { db, sessions, sports });
|
||||
await registerEventRoutes(app, { db, sessions, sports, broadcaster });
|
||||
await registerSportsRoutes(app, { db, sessions, sports });
|
||||
await registerPhotoRoutes(app, { db, sessions, storage, signer, broadcaster });
|
||||
await registerCompositionRoutes(app, { db, sessions, storage, storageRoot: config.STORAGE_ROOT });
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,6 +124,10 @@ export class AutopilotService {
|
||||
else if (angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
|
||||
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand);
|
||||
|
||||
// Someone already edited it (on the desktop app without a network, before it was uploaded): their edit
|
||||
// stands; the autopilot still scores the frame for its burst.
|
||||
const human = await db.photoEdit.count({ where: { photoId, NOT: { clientId: "autopilot" } } });
|
||||
if (human) ops.length = 0;
|
||||
if (ops.length) {
|
||||
await develop.append(photoId, photo.uploaderId ?? photo.event?.createdById ?? null, {
|
||||
clientId: "autopilot",
|
||||
@@ -125,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,
|
||||
@@ -176,7 +188,8 @@ export class AutopilotService {
|
||||
}
|
||||
// Variety: the second pick gets a slightly tighter frame than the first.
|
||||
const second = best[1];
|
||||
if (second?.rec?.crop && second.rec.subject && settings.crop) {
|
||||
const secondEdited = second ? await db.photoEdit.count({ where: { photoId: second.id, NOT: { clientId: "autopilot" } } }) : 0;
|
||||
if (second?.rec?.crop && second.rec.subject && settings.crop && !secondEdited) {
|
||||
const rect = constrainRotated(tighter(second.rec.crop, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
|
||||
await develop
|
||||
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
|
||||
@@ -189,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. */
|
||||
|
||||
@@ -5,8 +5,9 @@
|
||||
*
|
||||
* - The subject is who is in focus, not who is biggest: blurred players in the foreground are scenery.
|
||||
* - With a ball near the subject, the ball and the sharp players contesting it come along.
|
||||
* - The crop is usually two thirds of the frame (the same shape), moved to put the subject in the middle with
|
||||
* room above the heads. Legs may be cut; heads and the ball may not.
|
||||
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
|
||||
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
|
||||
* crowd and the stands). Legs may be cut; heads and the ball may not.
|
||||
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
|
||||
*
|
||||
* Boxes are fractions of the upright photo (0..1, y down).
|
||||
@@ -50,7 +51,23 @@ const MIN_BALL = 0.3;
|
||||
/** Smaller people (in photo heights) are too far away to be what the photo is about. */
|
||||
const MIN_HEIGHT = 0.08;
|
||||
/** Tuning, fitted to Peter's crops (exported so the evaluation script can sweep it). */
|
||||
export const TUNING = { inFocus: 0.55, usualScale: 0.72, wScale: 1.0, wFill: 0.6, wCentre: 1.2, wHead: 0.8, headAt: 0.1, wCut: 1.2, wJoint: 0.8 };
|
||||
export const TUNING = {
|
||||
inFocus: 0.55,
|
||||
usualScale: 0.72,
|
||||
wScale: 1.0,
|
||||
wFill: 1.0,
|
||||
fillAt: 0.6,
|
||||
wCentre: 1.2,
|
||||
wHead: 0.8,
|
||||
headMin: 0.04,
|
||||
headMax: 0.16,
|
||||
wChest: 1.4,
|
||||
chestAt: 0.42,
|
||||
wBelow: 2.5,
|
||||
belowMax: 0.08,
|
||||
wCut: 1.2,
|
||||
wJoint: 0.8,
|
||||
};
|
||||
|
||||
/**
|
||||
* Where the joints of a standing person roughly are, as fractions of their box from the top (neck, hips, knees,
|
||||
@@ -151,13 +168,17 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
ch = cw / ratio;
|
||||
}
|
||||
if (cw < w(s) + 0.01 || ch < mustBottom - s.y0 + headroom || cw < minWidth - 1e-9) continue;
|
||||
// Vertical positions: from the heads just under the top edge to the bottom of the subject just above the
|
||||
// bottom edge (all the spare height above them: the crowd, the stands, never a strip of empty pitch below).
|
||||
const top = s.y0 - headroom;
|
||||
const spare = Math.max(0, ch - (mustBottom - top));
|
||||
for (let i = 0; i <= 24; i++) {
|
||||
const x0 = Math.min(Math.max(0, s.x1 - cw + (i / 24) * (cw - w(s))), 1 - cw);
|
||||
for (let j = 0; j <= 16; j++) {
|
||||
const y0 = Math.min(Math.max(0, s.y0 - headroom - (j / 16) * 0.3 * ch), 1 - ch);
|
||||
for (let j = 0; j <= 20; j++) {
|
||||
const y0 = Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
|
||||
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
|
||||
if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio) + jointCost(r, inSubject, others, mainSharp);
|
||||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject) + jointCost(r, inSubject, others, mainSharp);
|
||||
if (!best || c < best.cost) best = { rect: r, cost: c };
|
||||
}
|
||||
}
|
||||
@@ -166,7 +187,7 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
|
||||
return { rect: best.rect, subject: s, reason, people: inSubject.length };
|
||||
}
|
||||
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number): number {
|
||||
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[]): number {
|
||||
let c = 0;
|
||||
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
|
||||
for (const p of others) {
|
||||
@@ -181,11 +202,20 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
|
||||
const k = Math.max(ch, w(r) / ratio);
|
||||
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
|
||||
// The subject fills a good part of the height (people tall in the frame).
|
||||
c += TUNING.wFill * Math.max(0, 0.55 - tallest / ch);
|
||||
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
||||
// Centred across.
|
||||
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
|
||||
// Heads a little below the top.
|
||||
c += TUNING.wHead * Math.abs((s.y0 - r.y0) / ch - TUNING.headAt);
|
||||
// Heads a little below the top: not touching it, not floating in empty space.
|
||||
const head = (s.y0 - r.y0) / ch;
|
||||
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - TUNING.headMax));
|
||||
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
|
||||
// the middle with a strip of grass below.
|
||||
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||||
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
|
||||
c += TUNING.wChest * Math.abs(chest - TUNING.chestAt);
|
||||
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
|
||||
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
|
||||
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -205,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: body.again, 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,9 +10,15 @@ 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;
|
||||
/** How long a delivery waits for an original still on the photographer's computer before it gives up. */
|
||||
export const ORIGINAL_WAIT_MS = 72 * 3600_000;
|
||||
/** How often it asks that computer again while waiting. */
|
||||
export const ORIGINAL_ASK_MS = 60_000;
|
||||
/** Running items older than this belonged to a worker that died; they go back in the queue. */
|
||||
const STALE_RUNNING_MS = 10 * 60_000;
|
||||
|
||||
@@ -43,6 +49,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 +107,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 +169,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 +181,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 +206,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()) };
|
||||
}
|
||||
|
||||
@@ -208,23 +221,50 @@ export class DeliveryService {
|
||||
const { db, storage, log } = this.deps;
|
||||
const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } });
|
||||
let update: Partial<DeliveryItem>;
|
||||
if (!item.photo.originalStored) {
|
||||
// Only the desktop's 2048 px preview is here: delivering it would send a small photo. Ask the desktop app
|
||||
// that keeps the original to send it, and try again shortly (waiting does not count as an attempt).
|
||||
this.deps.broadcaster.library(item.organizationId, { type: "original.requested", photoId: item.photoId, sha256: item.photo.sha256 });
|
||||
update =
|
||||
Date.now() - item.createdAt.getTime() > ORIGINAL_WAIT_MS
|
||||
? { status: "FAILED", lastError: "original_not_here", finishedAt: new Date() }
|
||||
: { status: "QUEUED", attempts: Math.max(0, item.attempts - 1), lastError: "waiting_for_original", nextAttemptAt: new Date(Date.now() + ORIGINAL_ASK_MS) };
|
||||
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;
|
||||
}
|
||||
try {
|
||||
const vars = buildVars(
|
||||
eventInfoOf(item.event),
|
||||
{ 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 +281,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;
|
||||
}
|
||||
@@ -59,8 +59,11 @@ export function newer(candidate: string, current: string): boolean {
|
||||
return a.pre > b.pre;
|
||||
}
|
||||
|
||||
/** The full installer a person downloads and opens, per platform. */
|
||||
const INSTALLER: Record<string, RegExp> = { darwin: /\.dmg$/, windows: /\.msi$|-setup\.exe$/, linux: /\.AppImage$/ };
|
||||
|
||||
export class DesktopReleases {
|
||||
private cache: { at: number; release: GiteaRelease | null } | null = null;
|
||||
private cache: { at: number; releases: GiteaRelease[] } | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly config: DesktopReleaseConfig,
|
||||
@@ -71,15 +74,26 @@ export class DesktopReleases {
|
||||
return { authorization: `token ${this.config.token}`, accept: "application/json" };
|
||||
}
|
||||
|
||||
/** The newest published `desktop-v*` release. */
|
||||
async latest(): Promise<GiteaRelease | null> {
|
||||
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.release;
|
||||
/** Published `desktop-v*` releases, newest first. */
|
||||
async releases(): Promise<GiteaRelease[]> {
|
||||
if (this.cache && Date.now() - this.cache.at < CACHE_MS) return this.cache.releases;
|
||||
const res = await this.fetchImpl(`${this.config.api.replace(/\/$/, "")}/releases?limit=50`, { headers: this.headers() });
|
||||
if (!res.ok) throw new Error(`gitea releases: ${res.status}`);
|
||||
const all = ((await res.json()) as GiteaRelease[]).filter((r) => !r.draft && !r.prerelease && r.tag_name.startsWith("desktop-v"));
|
||||
all.sort((x, y) => (newer(x.tag_name.slice(9), y.tag_name.slice(9)) ? -1 : 1));
|
||||
this.cache = { at: Date.now(), release: all[0] ?? null };
|
||||
return this.cache.release;
|
||||
this.cache = { at: Date.now(), releases: all };
|
||||
return all;
|
||||
}
|
||||
|
||||
/** The newest release that has this platform's update (a newer one may still be building, or wait for its Mac). */
|
||||
private async forPlatform(target: string, arch: string): Promise<{ release: GiteaRelease; manifest: GiteaAsset } | null> {
|
||||
// Universal macOS builds serve both Apple chips.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
for (const release of await this.releases()) {
|
||||
const manifest = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
|
||||
if (manifest) return { release, manifest };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async download(asset: GiteaAsset): Promise<Response> {
|
||||
@@ -88,30 +102,36 @@ export class DesktopReleases {
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Tauri's dynamic update answer for one platform, or null when there is nothing newer. */
|
||||
async updateFor(target: string, arch: string, current: string): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string } | null> {
|
||||
const release = await this.latest();
|
||||
if (!release) return null;
|
||||
// Universal macOS builds serve both Apple chips.
|
||||
const names = [`update-${target}-${arch}.json`, ...(target === "darwin" ? ["update-darwin-universal.json"] : [])];
|
||||
const asset = names.map((n) => release.assets.find((a) => a.name === n)).find(Boolean);
|
||||
if (!asset) return null;
|
||||
const manifest = Manifest.parse(await (await this.download(asset)).json());
|
||||
/**
|
||||
* Tauri's dynamic update answer for one platform, or null when there is nothing newer. `installer` (ignored by
|
||||
* Tauri) is the full installer of the same release: the app offers it when it cannot update itself.
|
||||
*/
|
||||
async updateFor(
|
||||
target: string,
|
||||
arch: string,
|
||||
current: string,
|
||||
): Promise<{ version: string; notes: string; pub_date?: string; url: string; signature: string; installer?: string } | null> {
|
||||
const found = await this.forPlatform(target, arch);
|
||||
if (!found) return null;
|
||||
const { release } = found;
|
||||
const manifest = Manifest.parse(await (await this.download(found.manifest)).json());
|
||||
if (!newer(manifest.version, current)) return null;
|
||||
if (!release.assets.some((a) => a.name === manifest.file)) return null;
|
||||
const installer = release.assets.find((a) => INSTALLER[target]?.test(a.name));
|
||||
return {
|
||||
version: manifest.version,
|
||||
notes: manifest.notes ?? release.body ?? "",
|
||||
...(manifest.pub_date ?? release.published_at ? { pub_date: (manifest.pub_date ?? release.published_at)! } : {}),
|
||||
url: `/v1/desktop/download/${release.id}/${encodeURIComponent(manifest.file)}`,
|
||||
signature: manifest.signature,
|
||||
...(installer ? { installer: `/v1/desktop/download/${release.id}/${encodeURIComponent(installer.name)}` } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The installer itself, streamed from the release. */
|
||||
/** The installer itself, streamed from a desktop release. */
|
||||
async file(releaseId: number, name: string): Promise<{ body: Readable; size: string | null } | null> {
|
||||
const release = await this.latest();
|
||||
if (!release || release.id !== releaseId) return null;
|
||||
const release = (await this.releases()).find((r) => r.id === releaseId);
|
||||
if (!release) return null;
|
||||
const asset = release.assets.find((a) => a.name === name);
|
||||
if (!asset || /\.json$/.test(name)) return null;
|
||||
const res = await this.download(asset);
|
||||
@@ -135,7 +155,8 @@ export async function registerDesktopRoutes(app: FastifyInstance, deps: { releas
|
||||
try {
|
||||
const update = await releases.updateFor(target, arch, version);
|
||||
if (!update) return reply.code(204).send();
|
||||
return { ...update, url: `${deps.publicApiUrl.replace(/\/$/, "")}${update.url}` };
|
||||
const base = deps.publicApiUrl.replace(/\/$/, "");
|
||||
return { ...update, url: `${base}${update.url}`, ...(update.installer ? { installer: `${base}${update.installer}` } : {}) };
|
||||
} catch (err) {
|
||||
req.log.warn({ err }, "desktop update check failed");
|
||||
return reply.code(204).send();
|
||||
|
||||
@@ -54,3 +54,18 @@ export const THRESHOLDS: Record<string, { match: number; group: number; margin:
|
||||
* in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder.
|
||||
*/
|
||||
export const MIN_SHARPNESS = 45;
|
||||
|
||||
/**
|
||||
* A face this much softer than the sharpest one in the same photo is out of the focus plane (the crowd behind the
|
||||
* player, a bench in front), however textured: not worth identifying.
|
||||
*/
|
||||
export const RELATIVE_SHARPNESS = 0.25;
|
||||
|
||||
/**
|
||||
* The faces worth identifying in one photo: the ones in focus. Faces with no measure (older analyses) stay.
|
||||
* Editors only want names for who the photo is about; boxes on a blurred crowd are noise.
|
||||
*/
|
||||
export function inFocus<T extends { sharpness?: number | null }>(faces: T[]): T[] {
|
||||
const sharpest = Math.max(0, ...faces.map((f) => f.sharpness ?? 0));
|
||||
return faces.filter((f) => f.sharpness == null || (f.sharpness >= MIN_SHARPNESS && f.sharpness >= RELATIVE_SHARPNESS * sharpest));
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { createReadStream } from "node:fs";
|
||||
import sharp from "sharp";
|
||||
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
|
||||
import { FaceRejected, JERSEY_MIN_SCORE, majorityNumber, type FaceService } from "./service.js";
|
||||
import { MIN_SHARPNESS } from "./math.js";
|
||||
import { inFocus, MIN_SHARPNESS } from "./math.js";
|
||||
|
||||
const EventParams = z.object({ eventId: z.uuid() });
|
||||
const GroupParams = z.object({ groupId: z.uuid() });
|
||||
@@ -139,7 +139,10 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, facesStatus: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
|
||||
if (!photo) throw notFound("photo_not_found");
|
||||
await requireMembership(db, req, photo.organizationId, "INGESTER");
|
||||
const list = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
|
||||
const all = await db.face.findMany({ where: { photoId }, include: { group: { include: { person: true, suggested: true } } }, orderBy: { x0: "asc" } });
|
||||
// Blurred faces (photos analysed before they were left out) are not boxed, unless someone already named them.
|
||||
const focused = new Set(inFocus(all).map((f) => f.id));
|
||||
const list = all.filter((f) => focused.has(f.id) || f.group?.person);
|
||||
// The previews are the edited photo: boxes are also given in its (cropped, straightened) frame.
|
||||
const crop = photo.renderedSeq > 0 ? cropOfSettings(photo.developSnapshot) : null;
|
||||
return {
|
||||
@@ -164,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,
|
||||
})),
|
||||
|
||||
+131
-19
@@ -5,9 +5,12 @@ import type { FaceGroup, Person } from "../generated/prisma/client.js";
|
||||
import type { IngestLogger } from "../ingest/service.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { type Box, torsoBox } from "../jersey/crop.js";
|
||||
import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox } from "../jersey/crop.js";
|
||||
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 {
|
||||
@@ -32,7 +35,7 @@ export function majorityNumber(faces: { jerseyNumber: string | null; jerseyScore
|
||||
}
|
||||
|
||||
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
|
||||
import { addToMean, cosine, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
|
||||
import type { FaceEngine } from "./process.js";
|
||||
|
||||
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
|
||||
@@ -87,6 +90,18 @@ export class FaceService {
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos left without analysis in an organization that has face analysis on (they arrived while it was off, or
|
||||
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
|
||||
*/
|
||||
async queueMissed(): Promise<number> {
|
||||
const r = await this.deps.db.photo.updateMany({
|
||||
where: { facesStatus: "NONE", status: "READY", organization: { biometricsEnabled: true } },
|
||||
data: { facesStatus: "PENDING" },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/** Detects, stores and groups the faces of one claimed photo. Never throws. */
|
||||
async process(photoId: string): Promise<void> {
|
||||
const { db, storage, log, engine } = this.deps;
|
||||
@@ -94,18 +109,27 @@ export class FaceService {
|
||||
if (!engine) throw new Error("face engine not configured");
|
||||
const photo = await db.photo.findUniqueOrThrow({ where: { id: photoId } });
|
||||
const analysis = await engine.analyse(storage.resolve(photo.storageKey));
|
||||
const faces = analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE);
|
||||
// The shirt number under each clear face, when a number model is installed.
|
||||
// Only faces in focus are kept: the blurred crowd and benches are not who the photo is about.
|
||||
const faces = inFocus(analysis.faces.filter((f) => Math.max(f.x1 - f.x0, f.y1 - f.y0) >= MIN_FACE_SIDE));
|
||||
// The shirt number under each clear face, when a number model is installed: on the chest (handball) or the
|
||||
// shorts (football), whichever the model reads with more confidence.
|
||||
const numbers = new Map<number, JerseyReading>();
|
||||
if (this.deps.jersey) {
|
||||
for (const [i, f] of faces.entries()) {
|
||||
if (f.sharpness != null && f.sharpness < MIN_SHARPNESS) continue;
|
||||
const box = torsoBox(f, analysis.width, analysis.height);
|
||||
if (!box) continue;
|
||||
const reading = await this.deps.jersey.read(storage.resolve(photo.storageKey), box).catch(() => null);
|
||||
if (reading?.number) numbers.set(i, reading);
|
||||
for (const { box } of numberBoxes(f, analysis.width, analysis.height)) {
|
||||
const reading = await this.deps.jersey.read(storage.resolve(photo.storageKey), box).catch(() => null);
|
||||
const best = numbers.get(i);
|
||||
if (reading?.number && (!best || reading.score > best.score)) numbers.set(i, reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The kit colour under each face: tells the two teams apart when both have a player with the read number.
|
||||
const small = faces.length ? await smallImage(storage.resolve(photo.storageKey)).catch(() => null) : null;
|
||||
const kits = faces.map((f) => {
|
||||
const chest = small ? torsoBox(f, small.width, small.height) : null;
|
||||
return small && chest ? kitColour(small, chest) : null;
|
||||
});
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.face.deleteMany({ where: { photoId } });
|
||||
for (const [i, f] of faces.entries()) {
|
||||
@@ -124,6 +148,7 @@ export class FaceService {
|
||||
model: engine.model,
|
||||
jerseyNumber: n?.number ?? null,
|
||||
jerseyScore: n?.score ?? null,
|
||||
kitColour: kits[i] ?? [],
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -201,10 +226,30 @@ export class FaceService {
|
||||
const ok = first && first.s >= match && (!second || first.s - second.s >= margin);
|
||||
let suggestedPersonId = ok ? first.p.id : null;
|
||||
let suggestionScore = ok ? first.s : null;
|
||||
if (!ok) {
|
||||
// No face match: the shirt number, if the faces agree on one and exactly one player of these teams wears it.
|
||||
const byNumber = await this.suggestByNumber(g.id, eventId);
|
||||
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
|
||||
const read = await this.groupNumber(g.id);
|
||||
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,
|
||||
// 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;
|
||||
} else {
|
||||
// No face to go by: the number (and, when both teams have it, the colour of the kit).
|
||||
const byNumber = await this.suggestByNumber(g.id, eventId, read);
|
||||
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
|
||||
}
|
||||
}
|
||||
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
|
||||
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
|
||||
@@ -218,11 +263,12 @@ export class FaceService {
|
||||
return majorityNumber(faces);
|
||||
}
|
||||
|
||||
/** A suggestion from the shirt number: only when one squad player of the event's teams has it. Never names on its own. */
|
||||
private async suggestByNumber(groupId: string, eventId: string): Promise<{ personId: string; score: number } | null> {
|
||||
/**
|
||||
* A suggestion from the shirt number: when one squad player of the event's teams has it, or when both teams have
|
||||
* one and the kit colour clearly says which team. Never names on its own.
|
||||
*/
|
||||
private async suggestByNumber(groupId: string, eventId: string, read: NumberVote): Promise<{ personId: string; score: number } | null> {
|
||||
const { db } = this.deps;
|
||||
const read = await this.groupNumber(groupId);
|
||||
if (!read) return null;
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true },
|
||||
@@ -231,16 +277,24 @@ export class FaceService {
|
||||
// Linked to the official match: the squads say who wears the number.
|
||||
const teamIds = [event.homeTeamId, event.awayTeamId].filter((t): t is string => !!t);
|
||||
if (teamIds.length) {
|
||||
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, goneAt: null, number: read.number }, select: { id: true } });
|
||||
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, goneAt: null, number: read.number }, select: { id: true, teamId: true } });
|
||||
const people = players.length
|
||||
? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, select: { id: true } })
|
||||
: [];
|
||||
if (people.length === 1) return { personId: people[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
|
||||
if (players.length) return null; // two players with that number, or not people yet: no guess
|
||||
if (people.length === 2) {
|
||||
// One in each team: the kit colour of this group against each team's (from players already confirmed here).
|
||||
const byPlayer = new Map(players.map((p) => [p.id, p.teamId]));
|
||||
const withTeam = await db.person.findMany({ where: { id: { in: people.map((p) => p.id) } }, select: { id: true, sportsPlayerId: true } });
|
||||
const team = await this.teamByKit(groupId, eventId);
|
||||
const pick = team ? withTeam.find((p) => p.sportsPlayerId && byPlayer.get(p.sportsPlayerId) === team.teamId) : undefined;
|
||||
if (pick && team) return { personId: pick.id, score: Math.round(read.score * 0.85 * team.sure * 1000) / 1000 };
|
||||
}
|
||||
if (players.length) return null; // two players with that number and no clear kit, or not people yet: no guess
|
||||
}
|
||||
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(norm);
|
||||
const candidates = (await db.person.findMany({ where: { organizationId: event.organizationId, number: { not: null }, club: { not: null } } }))
|
||||
.filter((p) => String(Number(p.number!.trim())) === read.number)
|
||||
.filter((p) => normLabel(p.number) === read.number)
|
||||
.filter((p) => {
|
||||
const club = norm(p.club!);
|
||||
return teams.some((t) => t && (t.includes(club) || club.includes(t)));
|
||||
@@ -249,6 +303,58 @@ 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
|
||||
* is clearly closer. `sure` is 1 when it is very clear, less when only fairly.
|
||||
*/
|
||||
async teamByKit(groupId: string, eventId: string): Promise<{ teamId: string; sure: number } | null> {
|
||||
const { db } = this.deps;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { homeTeamId: true, awayTeamId: true } });
|
||||
if (!event?.homeTeamId || !event.awayTeamId) return null;
|
||||
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;
|
||||
// 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 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.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]);
|
||||
}
|
||||
const home = median(byTeam.get(event.homeTeamId) ?? []);
|
||||
const away = median(byTeam.get(event.awayTeamId) ?? []);
|
||||
if (!home || !away || colourDistance(home, away) < 60) return null; // unknown, or kits too alike to tell
|
||||
const dh = colourDistance(mine, home);
|
||||
const da = colourDistance(mine, away);
|
||||
const [near, far, teamId] = dh < da ? [dh, da, event.homeTeamId] : [da, dh, event.awayTeamId];
|
||||
if (near > 0.6 * far || near > 90) return null;
|
||||
return { teamId, sure: near < 0.35 * far ? 1 : 0.9 };
|
||||
}
|
||||
|
||||
/** Adds the confirmed person's name to the players of these photos (keeps names already there). */
|
||||
private async nameConfirmedPhotos(photoIds: string[]): Promise<void> {
|
||||
if (!photoIds.length) return;
|
||||
@@ -399,8 +505,14 @@ export class FaceWorker {
|
||||
|
||||
start(): void {
|
||||
void this.service.requeueStale();
|
||||
let missedAt = 0;
|
||||
const tick = async () => {
|
||||
try {
|
||||
if (Date.now() - missedAt > 60_000) {
|
||||
missedAt = Date.now();
|
||||
const n = await this.service.queueMissed();
|
||||
if (n) this.opts.log.info({ photos: n }, "faces: queued photos left without analysis");
|
||||
}
|
||||
for (const id of await this.service.claimReferences(5)) await this.service.processReference(id);
|
||||
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
|
||||
for (const id of ids) {
|
||||
|
||||
@@ -204,7 +204,8 @@ export class IngestService {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
private async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
|
||||
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
|
||||
const { db, storage, log } = this.deps;
|
||||
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
|
||||
const size = (await stat(file)).size;
|
||||
@@ -218,6 +219,8 @@ export class IngestService {
|
||||
data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) },
|
||||
});
|
||||
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
|
||||
// Deliveries waiting for it go now.
|
||||
await db.deliveryItem.updateMany({ where: { photoId: photo.id, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
|
||||
this.deps.broadcaster.library(photo.organizationId, { type: "original.stored", photoId: photo.id });
|
||||
return { status: "ingested", photoId: photo.id, eventId: updated.eventId };
|
||||
}
|
||||
|
||||
@@ -29,8 +29,46 @@ export function torsoBox(face: Box, width: number, height: number): Box | null {
|
||||
return { x0: box.x0 / width, y0: box.y0 / height, x1: box.x1 / width, y1: box.y1 / height };
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
/**
|
||||
* Where the shorts number is, from the face: waist to mid-thigh, about three and a half faces wide. Football kits
|
||||
* (all of Liga Portugal) carry no number on the chest; the front number is on one leg of the shorts, small, so this
|
||||
* crop is tighter than the torso one to keep it readable.
|
||||
*/
|
||||
export function shortsBox(face: Box, width: number, height: number): Box | null {
|
||||
const fw = (face.x1 - face.x0) * width;
|
||||
const fh = (face.y1 - face.y0) * height;
|
||||
if (fw < 12 || fh < 12) return null;
|
||||
const cx = ((face.x0 + face.x1) / 2) * width;
|
||||
const top = face.y1 * height + 3.4 * fh;
|
||||
const box = {
|
||||
x0: Math.max(0, cx - 1.8 * fw),
|
||||
x1: Math.min(width, cx + 1.8 * fw),
|
||||
y0: Math.max(0, top),
|
||||
y1: Math.min(height, top + 3.4 * fh),
|
||||
};
|
||||
// Cut off by the frame (the shorts below the bottom edge): nothing to read.
|
||||
if (box.y1 - box.y0 < 2 * fh || box.x1 - box.x0 < 2 * fw) return null;
|
||||
return { x0: box.x0 / width, y0: box.y0 / height, x1: box.x1 / width, y1: box.y1 / height };
|
||||
}
|
||||
|
||||
export type JerseyRegion = "CHEST" | "SHORTS";
|
||||
|
||||
/** The crops under a face where a front number may be, in the order they are tried. */
|
||||
export function numberBoxes(face: Box, width: number, height: number): { region: JerseyRegion; box: Box }[] {
|
||||
const out: { region: JerseyRegion; box: Box }[] = [];
|
||||
const chest = torsoBox(face, width, height);
|
||||
if (chest) out.push({ region: "CHEST", box: chest });
|
||||
const shorts = shortsBox(face, width, height);
|
||||
if (shorts) out.push({ region: "SHORTS", box: shorts });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -39,5 +77,47 @@ 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. */
|
||||
export interface SmallImage {
|
||||
data: Buffer;
|
||||
width: number;
|
||||
height: number;
|
||||
channels: number;
|
||||
}
|
||||
|
||||
export async function smallImage(original: string, side = 512): Promise<SmallImage> {
|
||||
const { data, info } = await sharp(original).rotate().resize(side, side, { fit: "inside" }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
|
||||
return { data, width: info.width, height: info.height, channels: info.channels };
|
||||
}
|
||||
|
||||
/**
|
||||
* The colour of the kit under a face: the median of each channel in the middle of the chest crop (away from arms,
|
||||
* background and the number itself as much as a box can be). Median, not mean, so stripes and a sponsor's logo
|
||||
* pull it less. Null when the box has no pixels.
|
||||
*/
|
||||
export function kitColour(img: SmallImage, chest: Box): number[] | null {
|
||||
const x0 = Math.floor((chest.x0 + (chest.x1 - chest.x0) * 0.3) * img.width);
|
||||
const x1 = Math.ceil((chest.x0 + (chest.x1 - chest.x0) * 0.7) * img.width);
|
||||
const y0 = Math.floor((chest.y0 + (chest.y1 - chest.y0) * 0.05) * img.height);
|
||||
const y1 = Math.ceil((chest.y0 + (chest.y1 - chest.y0) * 0.55) * img.height);
|
||||
const ch: number[][] = [[], [], []];
|
||||
for (let y = Math.max(0, y0); y < Math.min(img.height, y1); y++) {
|
||||
for (let x = Math.max(0, x0); x < Math.min(img.width, x1); x++) {
|
||||
const i = (y * img.width + x) * img.channels;
|
||||
for (let c = 0; c < 3; c++) ch[c]!.push(img.data[i + c]!);
|
||||
}
|
||||
}
|
||||
if (!ch[0]!.length) return null;
|
||||
return ch.map((v) => {
|
||||
v.sort((a, b) => a - b);
|
||||
return v[v.length >> 1]!;
|
||||
});
|
||||
}
|
||||
|
||||
/** Distance between two kit colours (RGB, 0-441). */
|
||||
export function colourDistance(a: number[], b: number[]): number {
|
||||
return Math.hypot(a[0]! - b[0]!, a[1]! - b[1]!, a[2]! - b[2]!);
|
||||
}
|
||||
@@ -18,8 +18,8 @@ export interface JerseyReading {
|
||||
}
|
||||
|
||||
/**
|
||||
* The shirt-number model trained with workers/ml/jersey (ONNX): the torso crop in, a number 0-99 or
|
||||
* "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
|
||||
* The shirt-number model trained with workers/ml/jersey (ONNX): a chest or shorts crop in, a number 0-99, a handball
|
||||
* official's card letter (A-F) or "illegible" out. Loaded once by the worker; one crop takes a few tens of milliseconds on a CPU core.
|
||||
*/
|
||||
export class JerseyModel {
|
||||
private constructor(
|
||||
|
||||
@@ -47,6 +47,13 @@ export async function registerJerseyRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
return reply.header("content-type", "image/jpeg").header("cache-control", "private, max-age=86400").send(createReadStream(await jersey.cropFile(sample)));
|
||||
});
|
||||
|
||||
/** Teaching starts over: every answer is dropped and the samples are to review again. */
|
||||
app.post("/v1/orgs/:orgId/jersey/reset", { preHandler: authenticate }, async (req) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
await requireMembership(db, req, orgId, "EDITOR");
|
||||
return { reset: await jersey.reset(orgId) };
|
||||
});
|
||||
|
||||
/** The checked dataset, for `workers/ml/jersey/train.py` (download it from the app). */
|
||||
app.get("/v1/orgs/:orgId/jersey/dataset", { preHandler: authenticate }, async (req, reply) => {
|
||||
const { orgId } = OrgParams.parse(req.params);
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Db } from "../db.js";
|
||||
import type { JerseySample, JerseySampleStatus } from "../generated/prisma/client.js";
|
||||
import type { LocalStorage } from "../storage/storage.js";
|
||||
import { MIN_SHARPNESS } from "../faces/math.js";
|
||||
import { cropJpeg, torsoBox } from "./crop.js";
|
||||
import { cropJpeg, numberBoxes } from "./crop.js";
|
||||
|
||||
export interface SampleView {
|
||||
id: string;
|
||||
@@ -12,14 +12,28 @@ export interface SampleView {
|
||||
suggested: string | null;
|
||||
label: string | null;
|
||||
status: JerseySampleStatus;
|
||||
region: "CHEST" | "SHORTS";
|
||||
crop: string;
|
||||
}
|
||||
|
||||
export const NUMBER = /^\d{1,3}$/;
|
||||
|
||||
/** What a crop can be labelled with: a shirt number, or the letter on a handball official's card (A-F; B is usually the head coach). */
|
||||
export const LABEL = /^(\d{1,3}|[A-F])$/;
|
||||
|
||||
/** "07" and "7" are the same shirt; "b" and "Oficial B" are the same card. Null when it is neither. */
|
||||
export function normLabel(raw: string | null | undefined): string | null {
|
||||
const s = (raw ?? "").trim().replace(/^oficial\s*/i, "").toUpperCase();
|
||||
if (NUMBER.test(s)) return String(Number(s));
|
||||
return LABEL.test(s) ? s : null;
|
||||
}
|
||||
|
||||
/** Bumped when the crops change (2: chest and shorts), so faces collected before get the new ones once. */
|
||||
export const JERSEY_CROPS = 2;
|
||||
|
||||
/**
|
||||
* Training data for reading shirt numbers. Every face in a group confirmed as someone whose squad entry has a
|
||||
* number becomes a sample (the torso under the face, labelled with that number); people check them in the app
|
||||
* number becomes samples (the chest and the shorts under the face, labelled with that number); people check them in the app
|
||||
* (right, corrected, not legible). The checked samples are the dataset `workers/ml/jersey` trains on.
|
||||
*/
|
||||
export class JerseyService {
|
||||
@@ -30,42 +44,45 @@ 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 {
|
||||
return sig === this.sig(id);
|
||||
}
|
||||
|
||||
/** Makes samples for confirmed faces that have none yet. Returns how many were added. */
|
||||
/** Makes the samples confirmed faces do not have yet (one per region). Returns how many were added. */
|
||||
async collect(organizationId: string): Promise<number> {
|
||||
const { db } = this.deps;
|
||||
const faces = await db.face.findMany({
|
||||
where: {
|
||||
organizationId,
|
||||
jerseySample: null,
|
||||
jerseyCrops: { lt: JERSEY_CROPS },
|
||||
OR: [{ sharpness: null }, { sharpness: { gte: MIN_SHARPNESS } }],
|
||||
group: { person: { number: { not: null } } },
|
||||
},
|
||||
include: { photo: { select: { width: true, height: true } }, group: { include: { person: true } } },
|
||||
include: { photo: { select: { width: true, height: true } }, group: { include: { person: true } }, jerseySamples: { select: { region: true } } },
|
||||
take: 5000,
|
||||
});
|
||||
let added = 0;
|
||||
for (const f of faces) {
|
||||
const person = f.group?.person;
|
||||
if (!person?.number || !f.photo.width || !f.photo.height) continue;
|
||||
const box = torsoBox(f, f.photo.width, f.photo.height);
|
||||
if (!box) continue;
|
||||
await db.jerseySample.create({
|
||||
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person.id, ...box, suggested: person.number.trim() },
|
||||
});
|
||||
added++;
|
||||
const have = new Set(f.jerseySamples.map((s) => s.region));
|
||||
const boxes = person?.number && f.photo.width && f.photo.height ? numberBoxes(f, f.photo.width, f.photo.height) : [];
|
||||
for (const { region, box } of boxes) {
|
||||
if (have.has(region)) continue;
|
||||
await db.jerseySample.create({
|
||||
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: normLabel(person!.number) ?? person!.number!.trim() },
|
||||
});
|
||||
added++;
|
||||
}
|
||||
await db.face.update({ where: { id: f.id }, data: { jerseyCrops: JERSEY_CROPS } });
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
async view(s: JerseySample & { person?: { name: string } | null }): Promise<SampleView> {
|
||||
return { id: s.id, photoId: s.photoId, person: s.person?.name ?? null, suggested: s.suggested, label: s.label, status: s.status, crop: this.cropUrl(s.id) };
|
||||
return { id: s.id, photoId: s.photoId, person: s.person?.name ?? null, suggested: s.suggested, label: s.label, status: s.status, region: s.region, crop: this.cropUrl(s.id) };
|
||||
}
|
||||
|
||||
async list(organizationId: string, status: JerseySampleStatus, limit: number): Promise<SampleView[]> {
|
||||
@@ -83,20 +100,31 @@ export class JerseyService {
|
||||
}
|
||||
|
||||
async review(sample: JerseySample, userId: string, input: { status: "CONFIRMED" | "ILLEGIBLE" | "SKIPPED" | "PENDING"; label?: string | null | undefined }): Promise<JerseySample> {
|
||||
const raw = input.status === "CONFIRMED" ? (input.label ?? sample.suggested)?.trim() : null;
|
||||
// "07" and "7" are the same shirt.
|
||||
const label = raw && NUMBER.test(raw) ? String(Number(raw)) : raw;
|
||||
if (input.status === "CONFIRMED" && (!label || !NUMBER.test(label))) throw new Error("label_required");
|
||||
const label = input.status === "CONFIRMED" ? normLabel(input.label ?? sample.suggested) : null;
|
||||
if (input.status === "CONFIRMED" && !label) throw new Error("label_required");
|
||||
return this.deps.db.jerseySample.update({
|
||||
where: { id: sample.id },
|
||||
data: { status: input.status, label: label ?? null, reviewedById: input.status === "PENDING" ? null : userId, reviewedAt: input.status === "PENDING" ? null : new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts teaching over: every checked sample goes back to "to review" (answers given so far are dropped; the
|
||||
* samples and their crops stay). Returns how many were reset.
|
||||
*/
|
||||
async reset(organizationId: string): Promise<number> {
|
||||
const r = await this.deps.db.jerseySample.updateMany({
|
||||
where: { organizationId, status: { not: "PENDING" } },
|
||||
data: { status: "PENDING", label: null, reviewedById: null, reviewedAt: null },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
/** 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));
|
||||
@@ -110,8 +138,8 @@ export class JerseyService {
|
||||
return {
|
||||
version: 1,
|
||||
createdAt: new Date().toISOString(),
|
||||
classes: "0-99 and 'illegible'",
|
||||
samples: samples.map((s) => ({ id: s.id, label: s.status === "ILLEGIBLE" ? "illegible" : s.label!, crop: this.cropUrl(s.id) })),
|
||||
classes: "0-99, A-F (officials' cards) and 'illegible'",
|
||||
samples: samples.map((s) => ({ id: s.id, region: s.region, label: s.status === "ILLEGIBLE" ? "illegible" : s.label!, crop: this.cropUrl(s.id) })),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Db } from "../db.js";
|
||||
import { applyRename } from "./rename.js";
|
||||
|
||||
/**
|
||||
* Photos that just joined an event (moved by hand, or claimed from "Sem evento" when the event was created or its
|
||||
* window changed) get what arriving in it would have given them: the event's arrival name, faces analysed again so
|
||||
* they group with the event's people, and the event's autopilot edit (FTP and desktop photos only, as on arrival).
|
||||
*/
|
||||
export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise<void> {
|
||||
if (!ids.length) return;
|
||||
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } });
|
||||
if (!event) return;
|
||||
if (event.organization.biometricsEnabled) {
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED"] } }, data: { facesStatus: "PENDING" } });
|
||||
}
|
||||
if ((event.autopilot as { enabled?: boolean } | null)?.enabled === true) {
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "UPLOAD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } });
|
||||
}
|
||||
for (const id of ids) await applyRename(db, id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos waiting in "Sem evento" taken during this event's ingest window (by the photographers it is assigned to,
|
||||
* or anyone when it has none): photos sent before the event was created, or before its times were corrected.
|
||||
*/
|
||||
export async function claimInbox(db: Db, eventId: string): Promise<string[]> {
|
||||
const event = await db.event.findUnique({
|
||||
where: { id: eventId },
|
||||
select: { organizationId: true, archivedAt: true, ingestFrom: true, ingestUntil: true, assignments: { select: { userId: true } } },
|
||||
});
|
||||
if (!event || event.archivedAt) return [];
|
||||
const photos = await db.photo.findMany({
|
||||
where: {
|
||||
organizationId: event.organizationId,
|
||||
eventId: null,
|
||||
capturedAt: { gte: event.ingestFrom, lte: event.ingestUntil },
|
||||
...(event.assignments.length && { uploaderId: { in: event.assignments.map((a) => a.userId) } }),
|
||||
},
|
||||
select: { id: true },
|
||||
take: 20_000,
|
||||
});
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (!ids.length) return [];
|
||||
// Only the ones still in the inbox (another event may have claimed some meanwhile).
|
||||
await db.photo.updateMany({ where: { id: { in: ids }, eventId: null }, data: { eventId } });
|
||||
const claimed = (await db.photo.findMany({ where: { id: { in: ids }, eventId }, select: { id: true } })).map((p) => p.id);
|
||||
await joinedEvent(db, eventId, claimed);
|
||||
return claimed;
|
||||
}
|
||||
@@ -8,7 +8,9 @@ import type { Db } from "../db.js";
|
||||
import { type Event, Prisma } from "../generated/prisma/client.js";
|
||||
import { compact } from "../lib/compact.js";
|
||||
import { badRequest, notFound } from "../lib/errors.js";
|
||||
import type { Broadcaster } from "../realtime.js";
|
||||
import type { SportsService } from "../sports/service.js";
|
||||
import { claimInbox } from "./adopt.js";
|
||||
|
||||
const HOUR = 3600_000;
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
@@ -77,8 +79,20 @@ export function ingestWindow(startsAt: Date, from?: Date, until?: Date): { inges
|
||||
return { ingestFrom, ingestUntil };
|
||||
}
|
||||
|
||||
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService }) {
|
||||
export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; sports?: SportsService; broadcaster?: Broadcaster }) {
|
||||
const { db } = deps;
|
||||
|
||||
/** Photos in "Sem evento" taken during the event join it (and the open libraries move them). */
|
||||
async function claim(orgId: string, eventId: string): Promise<void> {
|
||||
const ids = await claimInbox(db, eventId).catch((err) => {
|
||||
app.log.warn({ err, eventId }, "event: claiming inbox photos failed");
|
||||
return [] as string[];
|
||||
});
|
||||
if (ids.length) {
|
||||
app.log.info({ eventId, photos: ids.length }, "event: claimed photos from the inbox");
|
||||
deps.broadcaster?.library(orgId, { type: "photo.updated", ids, patch: { eventId } });
|
||||
}
|
||||
}
|
||||
const authenticate = requireAuth(deps.sessions);
|
||||
|
||||
const loadEvent = async (req: FastifyRequest, eventId: string, minRole: "PHOTOGRAPHER" | "INGESTER" | "EDITOR") => {
|
||||
@@ -156,7 +170,8 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
include,
|
||||
});
|
||||
if (event.homeTeamId || event.awayTeamId) syncSquads(event.id);
|
||||
return reply.code(201).send(serialize(event));
|
||||
await claim(orgId, event.id);
|
||||
return reply.code(201).send(serialize(await db.event.findUniqueOrThrow({ where: { id: event.id }, include })));
|
||||
});
|
||||
|
||||
app.get("/v1/events/:eventId", { preHandler: authenticate }, async (req) => {
|
||||
@@ -196,6 +211,11 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
|
||||
});
|
||||
const teamsChanged = (match.homeTeamId !== undefined && match.homeTeamId !== current.homeTeamId) || (match.awayTeamId !== undefined && match.awayTeamId !== current.awayTeamId);
|
||||
if (teamsChanged && (event.homeTeamId || event.awayTeamId)) syncSquads(event.id);
|
||||
// New times, new photographers or back from the archive: photos waiting in "Sem evento" may now belong here.
|
||||
if (startsAt || ingestFrom || ingestUntil || photographerIds || archived === false) {
|
||||
await claim(event.organizationId, eventId);
|
||||
return serialize(await db.event.findUniqueOrThrow({ where: { id: eventId }, include }));
|
||||
}
|
||||
return serialize(event);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { applyRename } from "./rename.js";
|
||||
import { joinedEvent } from "./adopt.js";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { PhotoBatchPatch } from "@photoreport/contracts";
|
||||
import { expandCodes, IptcTemplate, parseCodeList } from "@photoreport/metadata";
|
||||
@@ -95,8 +95,8 @@ export async function registerPhotoRoutes(
|
||||
if (patch.eventId !== undefined) data.eventId = patch.eventId;
|
||||
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
|
||||
if (result.count !== ids.length) throw notFound("photo_not_found");
|
||||
// Moved to another event: arrival names that use the event follow it.
|
||||
if (patch.eventId) for (const id of ids) await applyRename(db, id);
|
||||
// Moved to another event: arrival names, faces and the autopilot follow it.
|
||||
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
|
||||
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
|
||||
return { updated: result.count };
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { deliveryState, type PhotoSummary } from "@photoreport/contracts";
|
||||
import type { Photo } from "../generated/prisma/client.js";
|
||||
import type { UrlSigner } from "../storage/storage.js";
|
||||
import { deliveredName } from "../delivery/service.js";
|
||||
|
||||
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null };
|
||||
export type PhotoWithUploader = Photo & { uploader: { id: string; name: string } | null; deliveries?: { status: string }[] };
|
||||
|
||||
export const photoInclude = { uploader: { select: { id: true, name: true } } } as const;
|
||||
export const photoInclude = { uploader: { select: { id: true, name: true } }, deliveries: { select: { status: true } } } as const;
|
||||
|
||||
export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSummary {
|
||||
return {
|
||||
@@ -16,6 +16,8 @@ export function toSummary(photo: PhotoWithUploader, signer: UrlSigner): PhotoSum
|
||||
sha256: photo.sha256,
|
||||
originalStored: photo.originalStored,
|
||||
status: photo.status,
|
||||
...(photo.status === "FAILED" && { error: photo.error }),
|
||||
...(photo.deliveries && { delivery: deliveryState(photo.deliveries.map((d) => d.status)) }),
|
||||
width: photo.width,
|
||||
height: photo.height,
|
||||
capturedAt: photo.capturedAt?.toISOString() ?? null,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { appendFile, mkdir, rm, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import sharp from "sharp";
|
||||
import { z } from "zod";
|
||||
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
@@ -16,6 +17,7 @@ import { photoInclude, toSummary } from "./serialize.js";
|
||||
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
const UploadQuery = z.object({ eventId: z.uuid().optional() });
|
||||
const PhotoParams = z.object({ photoId: z.uuid() });
|
||||
export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
@@ -59,6 +61,39 @@ export async function registerUploadRoutes(
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The desktop app sends the original of a photo that only has its preview here, when the file on that computer
|
||||
* no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo:
|
||||
* the same pixel size as declared then; the library keeps the photo's own fingerprint and metadata.
|
||||
*/
|
||||
app.post("/v1/photos/:photoId/original", { preHandler: authenticate }, async (req, reply) => {
|
||||
const { photoId } = PhotoParams.parse(req.params);
|
||||
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { id: true, organizationId: true, sha256: true, storageKey: true, originalStored: true, width: true, height: true } });
|
||||
if (!photo) throw new AppError(404, "photo_not_found");
|
||||
await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
|
||||
const part = await req.file();
|
||||
if (!part) throw badRequest("file_missing");
|
||||
if (photo.originalStored) {
|
||||
part.file.resume();
|
||||
return { stored: true };
|
||||
}
|
||||
const tmpDir = storage.resolve(".uploads");
|
||||
await mkdir(tmpDir, { recursive: true });
|
||||
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
|
||||
try {
|
||||
await pipeline(part.file, createWriteStream(tmp));
|
||||
if (part.file.truncated) throw new AppError(413, "file_too_large");
|
||||
const meta = await sharp(tmp).metadata().catch(() => null);
|
||||
const turned = (meta?.orientation ?? 1) >= 5;
|
||||
const [w, h] = turned ? [meta?.height, meta?.width] : [meta?.width, meta?.height];
|
||||
if (meta?.format !== "jpeg" || !photo.width || w !== photo.width || h !== photo.height) return reply.code(409).send({ error: "not_the_same_photo" });
|
||||
await ingest.storeOriginal(photo, tmp, ".jpg");
|
||||
return { stored: true };
|
||||
} finally {
|
||||
await rm(tmp, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// ---- resumable (chunked) uploads ----------------------------------------------------------------
|
||||
// Weak venue Wi-Fi and mobile data drop big uploads: the client sends 4 MB chunks, and after a failure (or a
|
||||
// reload, same file) asks where the server is and carries on from there.
|
||||
@@ -78,6 +113,8 @@ export async function registerUploadRoutes(
|
||||
height: z.number().int().positive().max(100_000).optional(),
|
||||
})
|
||||
.optional(),
|
||||
/** A full original from the desktop app's ingest (its local FTP), not a hand upload. */
|
||||
desktop: z.boolean().optional(),
|
||||
});
|
||||
|
||||
app.post("/v1/orgs/:orgId/uploads/resumable", { preHandler: authenticate }, async (req, reply) => {
|
||||
@@ -106,7 +143,7 @@ export async function registerUploadRoutes(
|
||||
if (known && known.status !== "FAILED") return reply.code(200).send({ status: "duplicate", photo: toSummary(known, signer) });
|
||||
}
|
||||
const upload = await db.pendingUpload.create({
|
||||
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }) },
|
||||
data: { organizationId: orgId, userId, eventId: body.eventId ?? null, fileName: name, size: body.size, fingerprint: body.fingerprint, ...(body.original && { original: body.original }), ...(body.desktop && { fromDesktop: true }) },
|
||||
});
|
||||
return reply.code(201).send({ id: upload.id, offset: 0, size: upload.size });
|
||||
});
|
||||
@@ -152,7 +189,7 @@ export async function registerUploadRoutes(
|
||||
const outcome = await ingest.ingest(partPath(id), {
|
||||
organizationId: upload.organizationId,
|
||||
userId: upload.userId,
|
||||
source: upload.original ? "DESKTOP" : "UPLOAD",
|
||||
source: upload.original || upload.fromDesktop ? "DESKTOP" : "UPLOAD",
|
||||
originalName: upload.fileName,
|
||||
eventId: upload.eventId ?? undefined,
|
||||
original: (upload.original as PreviewOf | null) ?? undefined,
|
||||
|
||||
@@ -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,38 @@ 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);
|
||||
await develop.append(photoId, userId, { clientId: "offline-queue", ops: [{ opId: "mine-1", command: { command: "develop.set", params: { values: { "light.exposure": -0.5 } } } }] });
|
||||
await runQueue();
|
||||
const edits = await ctx.db.photoEdit.findMany({ where: { photoId } });
|
||||
expect(edits.map((e) => e.clientId)).toEqual(["offline-queue"]);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE");
|
||||
});
|
||||
|
||||
it("leaves events without autopilot alone", async () => {
|
||||
const { orgId, userId, eventId } = await setup(false);
|
||||
await shot(orgId, userId, eventId, 0, 100);
|
||||
|
||||
@@ -61,6 +61,20 @@ describe("automatic crop", () => {
|
||||
expect(minCropWidth(2048, 1365)).toBe(1);
|
||||
});
|
||||
|
||||
it("frames the upper body near the middle, with the spare height above and not a strip of pitch below", () => {
|
||||
// A player kneeling in celebration, small in a wide frame (Braga x Sporting, October 2026).
|
||||
const kneeling = { ...person(0.41, 0.19, 0.58, 0.55), sharpness: 1 };
|
||||
const c = compose({ width: 6000, height: 4000, people: [kneeling], balls: [] }, null, { minWidth: 0.4 })!;
|
||||
const ch = c.rect.y1 - c.rect.y0;
|
||||
const below = (c.rect.y1 - kneeling.y1) / ch;
|
||||
const chest = (kneeling.y0 + 0.3 * (kneeling.y1 - kneeling.y0) - c.rect.y0) / ch;
|
||||
expect(below).toBeLessThanOrEqual(0.12);
|
||||
expect(chest).toBeGreaterThan(0.3);
|
||||
expect(chest).toBeLessThan(0.5);
|
||||
// Heads below the top edge, never touching it.
|
||||
expect((kneeling.y0 - c.rect.y0) / ch).toBeGreaterThanOrEqual(0.03);
|
||||
});
|
||||
|
||||
it("proposes nothing for an empty pitch or a distant crowd", () => {
|
||||
expect(compose({ ...frame, people: [person(0.1, 0.4, 0.13, 0.45), person(0.5, 0.4, 0.52, 0.46)], balls: [] })).toBeNull();
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -202,12 +302,138 @@ describe("delivery", () => {
|
||||
|
||||
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries?targetId=${target.id}`, headers: bearer(token) });
|
||||
expect((list.json() as { counts: Record<string, number> }).counts).toEqual({ DONE: 2 });
|
||||
// The library shows them as sent (the "Enviadas" / "Por enviar" filters).
|
||||
const photos = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos`, headers: bearer(token) });
|
||||
expect((photos.json() as { photos: { delivery: string }[] }).photos.map((p) => p.delivery)).toEqual(["DONE", "DONE"]);
|
||||
const again = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first] } });
|
||||
expect(again.json()).toMatchObject({ queued: [], skipped: [{ photoId: first, reason: "already_delivered" }] });
|
||||
const resend = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId: target.id, photoIds: [first], again: true } });
|
||||
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("waits for an original still on the photographer's computer instead of delivering its preview", async () => {
|
||||
const { orgId, token } = await setup();
|
||||
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: "{originalName}" },
|
||||
});
|
||||
const targetId = (created.json() as { id: string }).id;
|
||||
const a = await photo("preview-only.jpg", "2026:09:23 21:10:00");
|
||||
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
|
||||
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.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_original", 0]);
|
||||
expect(waiting.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now());
|
||||
|
||||
// The original arrives (the ingest moves waiting deliveries forward): now it is rendered.
|
||||
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: true } });
|
||||
await ctx.db.deliveryItem.updateMany({ where: { photoId: a, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
|
||||
await drain();
|
||||
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -29,7 +29,7 @@ describe("desktop updates", () => {
|
||||
|
||||
it("answers with the newest desktop release for the platform, through the API, and nothing when up to date", async () => {
|
||||
const releases = [
|
||||
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz")] },
|
||||
{ id: 7, tag_name: "desktop-v0.3.0", draft: false, prerelease: false, body: "Catálogo local", published_at: "2026-10-13T09:00:00Z", assets: [asset(1, "update-darwin-universal.json"), asset(2, "PhotoReport_universal.app.tar.gz"), asset(4, "PhotoReport_0.3.0_universal.dmg")] },
|
||||
{ id: 9, tag_name: "desktop-v0.4.0", draft: true, prerelease: false, body: "", published_at: null, assets: [] },
|
||||
{ id: 5, tag_name: "v1.2.0", draft: false, prerelease: false, body: "", published_at: null, assets: [] },
|
||||
{ id: 3, tag_name: "desktop-v0.2.0", draft: false, prerelease: false, body: "", published_at: null, assets: [] },
|
||||
@@ -39,7 +39,7 @@ describe("desktop updates", () => {
|
||||
const r = new DesktopReleases({ api: API, token: "read-token-123" }, impl);
|
||||
|
||||
const update = await r.updateFor("darwin", "aarch64", "0.2.0");
|
||||
expect(update).toMatchObject({ version: "0.3.0", notes: "Catálogo local", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz" });
|
||||
expect(update).toMatchObject({ version: "0.3.0", notes: "Catálogo local", url: "/v1/desktop/download/7/PhotoReport_universal.app.tar.gz", installer: "/v1/desktop/download/7/PhotoReport_0.3.0_universal.dmg" });
|
||||
expect(await r.updateFor("darwin", "x86_64", "0.3.0")).toBeNull();
|
||||
expect(await r.updateFor("windows", "x86_64", "0.2.0")).toBeNull();
|
||||
expect(calls.every((c) => c.auth === "token read-token-123")).toBe(true);
|
||||
@@ -53,4 +53,21 @@ describe("desktop updates", () => {
|
||||
expect(await r.file(3, "PhotoReport_universal.app.tar.gz")).toBeNull();
|
||||
expect(await r.file(7, "update-darwin-universal.json")).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps offering the last release built for a platform while a newer one is still building", async () => {
|
||||
const releases = [
|
||||
// 0.3.5: Linux done, the Mac still building (or switched off).
|
||||
{ id: 12, tag_name: "desktop-v0.3.5", draft: false, prerelease: false, body: "", published_at: null, assets: [asset(20, "update-linux-x86_64.json"), asset(21, "PhotoReport_0.3.5_amd64.AppImage")] },
|
||||
{ id: 11, tag_name: "desktop-v0.3.4", draft: false, prerelease: false, body: "Mac", published_at: null, assets: [asset(10, "update-darwin-universal.json"), asset(11, "PhotoReport.app.tar.gz")] },
|
||||
];
|
||||
const files = {
|
||||
"update-linux-x86_64.json": { version: "0.3.5", file: "PhotoReport_0.3.5_amd64.AppImage", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
|
||||
"update-darwin-universal.json": { version: "0.3.4", file: "PhotoReport.app.tar.gz", signature: "dW50cnVzdGVkIGNvbW1lbnQ6IHNpZw==" },
|
||||
"PhotoReport.app.tar.gz": "mac bytes",
|
||||
};
|
||||
const r = new DesktopReleases({ api: API, token: "t" }, fakeGitea(releases, files).impl);
|
||||
expect(await r.updateFor("linux", "x86_64", "0.3.2")).toMatchObject({ version: "0.3.5", url: "/v1/desktop/download/12/PhotoReport_0.3.5_amd64.AppImage" });
|
||||
expect(await r.updateFor("darwin", "aarch64", "0.3.2")).toMatchObject({ version: "0.3.4", url: "/v1/desktop/download/11/PhotoReport.app.tar.gz" });
|
||||
expect(await r.file(11, "PhotoReport.app.tar.gz")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
+117
-12
@@ -83,7 +83,7 @@ describe("faces", () => {
|
||||
|
||||
/** Ingests a photo with the given people's faces in it. */
|
||||
let n = 0;
|
||||
async function photo(taken: string, people: number[], sharpness: number | null = 200): Promise<string> {
|
||||
async function photo(taken: string, people: number[], sharpness: number | null | (number | null)[] = 200): Promise<string> {
|
||||
n++;
|
||||
const data = await sharp({ create: { width: 600, height: 400, channels: 3, background: { r: n % 256, g: (n * 7) % 256, b: (n * 13) % 256 } } })
|
||||
.jpeg()
|
||||
@@ -97,7 +97,7 @@ describe("faces", () => {
|
||||
engine.byColor.set(sha, {
|
||||
width: 600,
|
||||
height: 400,
|
||||
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness, landmarks: [], embedding: personVector(p, n) })),
|
||||
faces: people.map((p, i) => ({ x0: 0.1 + i * 0.2, y0: 0.2, x1: 0.18 + i * 0.2, y1: 0.32, score: 0.9, sharpness: Array.isArray(sharpness) ? sharpness[i]! : sharpness, landmarks: [], embedding: personVector(p, n) })),
|
||||
});
|
||||
const out = await ingest.ingestFile(file);
|
||||
if (out.status !== "ingested") throw new Error(JSON.stringify(out));
|
||||
@@ -125,6 +125,20 @@ describe("faces", () => {
|
||||
expect(await faces.claim(5)).toEqual([id]);
|
||||
});
|
||||
|
||||
it("queues photos left without analysis while biometrics are on, and leaves other organizations alone", async () => {
|
||||
await setup(true);
|
||||
const id = await photo("2026:09:23 21:00:00", [1]);
|
||||
expect(await faces.claim(5)).toEqual([id]);
|
||||
await drain();
|
||||
// A photo that slipped through as "no analysis" (it arrived while a toggle raced its ingest).
|
||||
await ctx.db.photo.update({ where: { id }, data: { facesStatus: "NONE" } });
|
||||
const other = await seedUser(ctx.db, "[email protected]", { org: "clube", role: "OWNER" });
|
||||
const theirs = await ctx.db.photo.create({ data: { organizationId: other.org!.id, source: "UPLOAD", originalName: "x.jpg", sha256: "f".repeat(64), byteSize: 1, storageKey: "x", status: "READY" } });
|
||||
expect(await faces.queueMissed()).toBe(1);
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id } })).facesStatus).toBe("PENDING");
|
||||
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: theirs.id } })).facesStatus).toBe("NONE");
|
||||
});
|
||||
|
||||
it("reads the faces again from the original when it replaces a desktop preview", async () => {
|
||||
const { orgId } = await setup();
|
||||
const user = await ctx.db.user.findFirstOrThrow();
|
||||
@@ -219,17 +233,19 @@ describe("faces", () => {
|
||||
expect((await list())[0]!.ignored).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps blurred faces out of the groups, and says how many", async () => {
|
||||
it("only identifies faces in focus: not soft photos, not the blurred crowd behind a sharp player", async () => {
|
||||
const { token, day1 } = await setup();
|
||||
await photo("2026:09:23 21:00:00", [1]);
|
||||
await photo("2026:09:23 21:01:00", [1]);
|
||||
// The player sharp, two fans in the stand behind him out of focus (textured, but far softer).
|
||||
const withCrowd = await photo("2026:09:23 21:01:00", [1, 8, 9], [400, 60, 50]);
|
||||
await photo("2026:09:23 21:02:00", [8], 12);
|
||||
await photo("2026:09:23 21:03:00", [9], 12);
|
||||
await drain();
|
||||
const body = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as { groups: { size: number }[]; unclear: number };
|
||||
expect(body.groups.map((g) => g.size)).toEqual([2]);
|
||||
expect(body.unclear).toBe(2);
|
||||
expect(await ctx.db.face.count()).toBe(4);
|
||||
expect(await ctx.db.face.count()).toBe(2);
|
||||
const boxes = (await ctx.app.inject({ method: "GET", url: `/v1/photos/${withCrowd}/faces`, headers: bearer(token) })).json() as { faces: unknown[] };
|
||||
expect(boxes.faces).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("learns a person from a reference photo and suggests them from the first match", async () => {
|
||||
@@ -278,11 +294,12 @@ describe("faces", () => {
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g.id}/confirm`, headers: bearer(token), payload: { name: "Miguel Silva (VSC)", club: "VSC", number: "07" } });
|
||||
const orgId = (await ctx.db.photo.findFirstOrThrow()).organizationId;
|
||||
const list = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { collected: number; samples: { id: string; suggested: string; crop: string; person: string }[] };
|
||||
expect(list.collected).toBe(2);
|
||||
expect(list.samples[0]).toMatchObject({ suggested: "07", person: "Miguel Silva (VSC)" });
|
||||
expect(list.collected).toBe(4); // chest and shorts of two faces
|
||||
expect(list.samples.map((x) => (x as unknown as { region: string }).region).sort()).toEqual(["CHEST", "CHEST", "SHORTS", "SHORTS"]);
|
||||
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);
|
||||
|
||||
@@ -291,6 +308,21 @@ describe("faces", () => {
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[1]!.id}/review`, headers: bearer(token), payload: { status: "ILLEGIBLE" } });
|
||||
const dataset = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/dataset`, headers: bearer(token) })).json() as { samples: { label: string }[] };
|
||||
expect(dataset.samples.map((s) => s.label).sort()).toEqual(["7", "illegible"]);
|
||||
|
||||
// A handball official's card: the letter is a label like a number.
|
||||
const card = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "b" } });
|
||||
expect(card.json()).toMatchObject({ status: "CONFIRMED", label: "B" });
|
||||
const bad = await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[3]!.id}/review`, headers: bearer(token), payload: { status: "CONFIRMED", label: "Z" } });
|
||||
expect(bad.statusCode).toBe(400);
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/jersey/samples/${list.samples[2]!.id}/review`, headers: bearer(token), payload: { status: "PENDING" } });
|
||||
|
||||
// Starting over: every answer is dropped, the samples are to review again.
|
||||
const reset = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/jersey/reset`, headers: bearer(token) });
|
||||
expect(reset.json()).toEqual({ reset: 2 });
|
||||
expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/dataset`, headers: bearer(token) })).json() as { samples: unknown[] }).samples).toEqual([]);
|
||||
const again = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/jersey/samples`, headers: bearer(token) })).json() as { samples: { label: string | null; status: string }[] };
|
||||
expect(again.samples.length).toBe(list.samples.length);
|
||||
expect(again.samples.every((s) => s.status === "PENDING" && s.label === null)).toBe(true);
|
||||
});
|
||||
|
||||
it("suggests a squad player from the shirt number the faces agree on, when only one of these teams wears it", async () => {
|
||||
@@ -303,16 +335,24 @@ describe("faces", () => {
|
||||
{ organizationId: orgId, name: "Zé Sete", club: "VSC", number: "7" },
|
||||
],
|
||||
});
|
||||
// The number model reads 10, 10 and (once, less sure) 16 on this player's shirt.
|
||||
// Football: nothing on the chest; on the shorts the model reads 10, 10 and (once, less sure) 16.
|
||||
const readings = ["10", "10", "16"];
|
||||
let calls = 0;
|
||||
const reader = { read: async () => ({ number: readings[calls++ % 3]!, score: calls === 3 ? 0.75 : 0.95 }) };
|
||||
let shorts = 0;
|
||||
const reader = {
|
||||
read: async () => {
|
||||
calls++;
|
||||
if (calls % 2 === 1) return { number: null, score: 0.9 }; // the chest crop comes first
|
||||
const n = shorts++;
|
||||
return { number: readings[n]!, score: n === 2 ? 0.75 : 0.95 };
|
||||
},
|
||||
};
|
||||
const withNumbers = new FaceService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), broadcaster, log: quiet, engine, jersey: reader });
|
||||
await photo("2026:09:23 21:00:00", [5]);
|
||||
await photo("2026:09:23 21:01:00", [5]);
|
||||
await photo("2026:09:23 21:02:00", [5]);
|
||||
for (let ids = await withNumbers.claim(10); ids.length; ids = await withNumbers.claim(10)) for (const id of ids) await withNumbers.process(id);
|
||||
expect(calls).toBe(3);
|
||||
expect(calls).toBe(6); // chest and shorts of each face
|
||||
|
||||
const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as {
|
||||
groups: { person: unknown; suggestion: { name: string; score: number } | null; number: { value: string; votes: number } | null }[];
|
||||
@@ -325,4 +365,69 @@ describe("faces", () => {
|
||||
expect(groups[0]!.person).toBeNull();
|
||||
expect((await ctx.db.photo.findMany({ select: { players: true } })).every((p) => p.players.length === 0)).toBe(true);
|
||||
});
|
||||
it("tells apart two players with the same number, one per team, by the colour of the kit", async () => {
|
||||
const { token, day1, orgId } = await setup();
|
||||
const team = (name: string, ext: string) => ctx.db.sportsTeam.create({ data: { provider: "FPA", externalId: ext, sport: "handball", name, slug: name.toLowerCase() } });
|
||||
const home = await team("VSC", "t1");
|
||||
const away = await team("AAAS", "t2");
|
||||
await ctx.db.event.update({ where: { id: day1.id }, data: { homeTeamId: home.id, awayTeamId: away.id } });
|
||||
const player = async (teamId: string, name: string, number: string, position: string | null = null) => {
|
||||
const sp = await ctx.db.sportsPlayer.create({ data: { teamId, season: "20262027", name, number, position } });
|
||||
return ctx.db.person.create({ data: { organizationId: orgId, name, number, sportsPlayerId: sp.id } });
|
||||
};
|
||||
const homeSeven = await player(home.id, "Casa Sete", "7");
|
||||
const awaySeven = await player(away.id, "Fora Sete", "7");
|
||||
await player(home.id, "Casa Dez", "10");
|
||||
await player(away.id, "Fora Dez", "10");
|
||||
await player(away.id, "Fora Guarda-Redes", "1", "Guarda-Redes");
|
||||
|
||||
// Two players already confirmed in this event: the home side plays in red, the away side in blue.
|
||||
await photo("2026:09:23 21:00:00", [1]);
|
||||
await photo("2026:09:23 21:01:00", [2]);
|
||||
await drain();
|
||||
const listed = () => ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) }).then((r) => r.json() as { groups: { id: string; size: number; person: { name: string } | null; suggestion: { name: string; score: number } | null }[] });
|
||||
const [g1, g2] = (await listed()).groups;
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g1!.id}/confirm`, headers: bearer(token), payload: { personId: homeSeven.id } });
|
||||
await ctx.app.inject({ method: "POST", url: `/v1/face-groups/${g2!.id}/confirm`, headers: bearer(token), payload: { personId: awaySeven.id } });
|
||||
await ctx.db.face.updateMany({ where: { groupId: g1!.id }, data: { kitColour: [200, 30, 30] } });
|
||||
await ctx.db.face.updateMany({ where: { groupId: g2!.id }, data: { kitColour: [30, 40, 190] } });
|
||||
|
||||
// Someone new, whose shirt reads 10 (both teams have a 10), in red.
|
||||
await photo("2026:09:23 21:02:00", [3]);
|
||||
await photo("2026:09:23 21:03:00", [3]);
|
||||
await drain();
|
||||
const g3 = (await listed()).groups.find((g) => !g.person)!;
|
||||
await ctx.db.face.updateMany({ where: { groupId: g3.id }, data: { jerseyNumber: "10", jerseyScore: 0.95, kitColour: [190, 45, 35] } });
|
||||
await faces.refreshSuggestions(day1.id);
|
||||
const suggested = (await listed()).groups.find((g) => g.id === g3.id)!;
|
||||
expect(suggested.suggestion).toMatchObject({ name: "Casa Dez" });
|
||||
expect(suggested.person).toBeNull();
|
||||
|
||||
// A kit in between the two: no guess.
|
||||
await ctx.db.face.updateMany({ where: { groupId: g3.id }, data: { kitColour: [115, 35, 110] } });
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { numberBoxes, shortsBox, torsoBox } from "../src/jersey/crop.js";
|
||||
|
||||
// A player standing in a 3:2 frame: face 4% wide and 6% tall, high in the picture.
|
||||
const face = { x0: 0.48, y0: 0.1, x1: 0.52, y1: 0.16 };
|
||||
const W = 6000;
|
||||
const H = 4000;
|
||||
|
||||
describe("shirt-number crops", () => {
|
||||
it("takes the chest for handball and the shorts for football, the shorts lower and tighter", () => {
|
||||
const chest = torsoBox(face, W, H)!;
|
||||
const shorts = shortsBox(face, W, H)!;
|
||||
expect(chest.y0).toBeGreaterThan(face.y1);
|
||||
// The shorts start around the waist, under most of the chest crop, and reach mid-thigh.
|
||||
expect(shorts.y0).toBeGreaterThan(chest.y0 + (chest.y1 - chest.y0) * 0.6);
|
||||
expect(shorts.y1).toBeCloseTo(face.y1 + 6.8 * (face.y1 - face.y0), 5);
|
||||
expect(shorts.y1 - shorts.y0).toBeLessThan(chest.y1 - chest.y0);
|
||||
expect(numberBoxes(face, W, H).map((b) => b.region)).toEqual(["CHEST", "SHORTS"]);
|
||||
});
|
||||
|
||||
it("leaves out the shorts when the frame cuts them (a close-up from the waist up)", () => {
|
||||
const low = { x0: 0.45, y0: 0.4, x1: 0.55, y1: 0.55 };
|
||||
expect(shortsBox(low, W, H)).toBeNull();
|
||||
expect(numberBoxes(low, W, H).map((b) => b.region)).toEqual(["CHEST"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("labels", () => {
|
||||
it("reads shirt numbers and handball officials' cards the same way", async () => {
|
||||
const { normLabel } = await import("../src/jersey/service.js");
|
||||
expect(normLabel("07")).toBe("7");
|
||||
expect(normLabel(" 10 ")).toBe("10");
|
||||
expect(normLabel("b")).toBe("B");
|
||||
expect(normLabel("Oficial B")).toBe("B");
|
||||
expect(normLabel("G")).toBeNull();
|
||||
expect(normLabel("1234")).toBeNull();
|
||||
expect(normLabel(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("kit colour", () => {
|
||||
it("takes the median colour in the middle of the chest, so a logo or stripe pulls it little", async () => {
|
||||
const { kitColour } = await import("../src/jersey/crop.js");
|
||||
const width = 100;
|
||||
const height = 100;
|
||||
const data = Buffer.alloc(width * height * 3);
|
||||
for (let i = 0; i < width * height; i++) data.set([200, 20, 20], i * 3); // a red shirt
|
||||
for (let y = 40; y < 46; y++) for (let x = 45; x < 55; x++) data.set([255, 255, 255], (y * width + x) * 3); // a white logo
|
||||
expect(kitColour({ data, width, height, channels: 3 }, { x0: 0.2, y0: 0.2, x1: 0.8, y1: 0.9 })).toEqual([200, 20, 20]);
|
||||
});
|
||||
});
|
||||
@@ -178,6 +178,41 @@ describe("library", () => {
|
||||
expect((inbox.json() as { total: number }).total).toBe(1);
|
||||
});
|
||||
|
||||
it("an event created (or moved) after its photos arrived claims them from the inbox, live", async () => {
|
||||
const { orgId, admin, photographer } = await setup();
|
||||
const early = await service.ingestFile(await drop("foto.r1", "early.jpg", await jpeg({ color: "#994400", taken: "2026:10:09 20:26:47" })));
|
||||
const later = await service.ingestFile(await drop("foto.r1", "later.jpg", await jpeg({ color: "#004499", taken: "2026:10:09 22:17:05" })));
|
||||
const elsewhere = await service.ingestFile(await drop("foto.r1", "other.jpg", await jpeg({ color: "#449900", taken: "2026:09:03 16:37:46" })));
|
||||
expect([early, later, elsewhere].map((o) => (o as { eventId: string | null }).eventId)).toEqual([null, null, null]);
|
||||
broadcaster.sent.length = 0;
|
||||
|
||||
const created = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/orgs/${orgId}/events`,
|
||||
headers: bearer(admin),
|
||||
payload: { home: "SC Braga", away: "Sporting CP", startsAt: "2026-10-09T19:15:00Z", photographerIds: [photographer.id] },
|
||||
});
|
||||
expect(created.statusCode).toBe(201);
|
||||
const event = created.json() as { id: string; photoCount: number };
|
||||
expect(event.photoCount).toBe(2);
|
||||
const ids = [early, later].map((o) => (o as { photoId: string }).photoId);
|
||||
expect(broadcaster.sent.map((s) => s.message)).toContainEqual({ type: "photo.updated", ids: expect.arrayContaining(ids), patch: { eventId: event.id } });
|
||||
const inbox = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?event=inbox`, headers: bearer(admin) });
|
||||
expect((inbox.json() as { photos: { id: string }[] }).photos.map((p) => p.id)).toEqual([(elsewhere as { photoId: string }).photoId]);
|
||||
|
||||
// Moving its time to cover the September photo claims that one too.
|
||||
const moved = await ctx.app.inject({ method: "PATCH", url: `/v1/events/${event.id}`, headers: bearer(admin), payload: { startsAt: "2026-09-03T15:00:00Z" } });
|
||||
expect((moved.json() as { photoCount: number }).photoCount).toBe(3);
|
||||
});
|
||||
|
||||
it("says why a photo failed", async () => {
|
||||
const { orgId, admin } = await setup();
|
||||
await service.ingestFile(await drop("foto.r1", "cut.jpg", Buffer.from("not really a jpeg")));
|
||||
const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?status=FAILED`, headers: bearer(admin) });
|
||||
const [photo] = (list.json() as { photos: { status: string; error?: string }[] }).photos;
|
||||
expect(photo).toMatchObject({ status: "FAILED", error: expect.any(String) });
|
||||
});
|
||||
|
||||
it("marks unreadable files as failed instead of losing them", async () => {
|
||||
await setup();
|
||||
const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", Buffer.from("not really a jpeg")));
|
||||
|
||||
@@ -81,6 +81,47 @@ describe("resumable uploads", () => {
|
||||
expect((await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) })).json()).toEqual({ stored: true });
|
||||
});
|
||||
|
||||
it("takes an original changed on the desktop since (captions written into it) as that photo's original, if it is the same photo", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const original = await sharp({ create: { width: 1200, height: 800, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg({ quality: 95 }).toBuffer();
|
||||
const sha256 = createHash("sha256").update(original).digest("hex");
|
||||
const preview = await sharp(original).resize(600).jpeg().toBuffer();
|
||||
const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "IMG_0003.JPG", size: preview.length, fingerprint: "p", original: { sha256, size: original.length, width: 1200, height: 800 } } })).json() as { id: string };
|
||||
const photo = ((await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: preview })).json() as { photo: { id: string } }).photo;
|
||||
const post = (file: Buffer) => {
|
||||
const boundary = "----pr-original";
|
||||
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${sha256}.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
|
||||
return ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original`, headers: { ...bearer(token), "content-type": `multipart/form-data; boundary=${boundary}` }, payload: Buffer.concat([head, file, Buffer.from(`\r\n--${boundary}--\r\n`)]) });
|
||||
};
|
||||
// Another photo (another size) is refused.
|
||||
const other = await sharp({ create: { width: 1000, height: 800, channels: 3, background: "#808080" } }).jpeg().toBuffer();
|
||||
expect((await post(other)).statusCode).toBe(409);
|
||||
// The same photo with a caption written into it: a different file, the same pixel size.
|
||||
const captioned = await sharp(original).withMetadata({ exif: { IFD0: { ImageDescription: "SC Braga x Sporting CP" } } }).jpeg({ quality: 95 }).toBuffer();
|
||||
expect(createHash("sha256").update(captioned).digest("hex")).not.toBe(sha256);
|
||||
expect((await post(captioned)).json()).toEqual({ stored: true });
|
||||
const after = await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } });
|
||||
expect(after).toMatchObject({ originalStored: true, sha256 });
|
||||
expect(await ctx.db.photo.count()).toBe(1);
|
||||
expect((await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("counts a full original from the desktop app's FTP as camera ingest (the autopilot edits it), not a hand upload", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
const t = new Date("2026-10-13T15:00:00Z");
|
||||
const event = await ctx.db.event.create({ data: { organizationId: org!.id, home: "ABC", away: "FCP", startsAt: t, ingestFrom: t, ingestUntil: t, iptcTemplate: {}, autopilot: { enabled: true } } });
|
||||
const send = async (name: string, extra: object) => {
|
||||
const jpeg = await sharp({ create: { width: 900, height: 600, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg().toBuffer();
|
||||
const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name, size: jpeg.length, fingerprint: `${name}:${jpeg.length}`, eventId: event.id, ...extra } })).json() as { id: string };
|
||||
const done = await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: jpeg });
|
||||
return ctx.db.photo.findUniqueOrThrow({ where: { id: (done.json() as { photo: { id: string } }).photo.id } });
|
||||
};
|
||||
expect(await send("FTP_0001.JPG", { desktop: true })).toMatchObject({ source: "DESKTOP", autopilotStatus: "PENDING" });
|
||||
expect(await send("HAND_0001.JPG", {})).toMatchObject({ source: "UPLOAD", autopilotStatus: "NONE" });
|
||||
});
|
||||
|
||||
it("a photo that failed (a damaged file) is replaced when it is sent again", async () => {
|
||||
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
|
||||
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
|
||||
|
||||
@@ -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"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -p tsconfig.json --noEmit && vite build",
|
||||
"build": "tsc -p tsconfig.json --noEmit && vite build && node scripts/ui-manifest.mjs",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"preview": "vite preview"
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Writes dist/ui-manifest.json after `vite build`: every file of the build with its size and SHA-256, the version and
|
||||
// when it was built. The desktop app keeps the interface on disk and reads this to download only what changed
|
||||
// (apps/desktop/src-tauri/src/ui.rs).
|
||||
import { createHash } from "node:crypto";
|
||||
import { readdir, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const NAME = "ui-manifest.json";
|
||||
const dist = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../dist");
|
||||
|
||||
async function walk(dir) {
|
||||
const out = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) out.push(...(await walk(full)));
|
||||
else if (entry.isFile()) out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const files = [];
|
||||
for (const full of (await walk(dist)).sort()) {
|
||||
const rel = path.relative(dist, full).split(path.sep).join("/");
|
||||
if (rel === NAME) continue;
|
||||
const bytes = await readFile(full);
|
||||
files.push({ path: rel, size: (await stat(full)).size, sha256: createHash("sha256").update(bytes).digest("hex") });
|
||||
}
|
||||
const content = createHash("sha256").update(files.map((f) => `${f.path}:${f.sha256}`).join("\n")).digest("hex").slice(0, 16);
|
||||
const manifest = { version: process.env.VITE_APP_VERSION?.slice(0, 40) || content, builtAt: new Date().toISOString(), files };
|
||||
await writeFile(path.join(dist, NAME), JSON.stringify(manifest));
|
||||
console.log(`${NAME}: ${files.length} files, version ${manifest.version}`);
|
||||
@@ -7,4 +7,8 @@ describe("apiUrlFor", () => {
|
||||
expect(apiUrlFor(undefined, { protocol: "https:", hostname: "app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
|
||||
expect(apiUrlFor(undefined, { protocol: "http:", hostname: "localhost" })).toBe("http://localhost:3000");
|
||||
});
|
||||
|
||||
it("inside the desktop app, uses the API the app names (its interface may be the web build)", () => {
|
||||
expect(apiUrlFor(undefined, { protocol: "tauri:", hostname: "localhost" }, { api: "https://api.next.photoreport.pt/", app: "https://app.next.photoreport.pt" })).toBe("https://api.next.photoreport.pt");
|
||||
});
|
||||
});
|
||||
+6
-4
@@ -1,17 +1,19 @@
|
||||
import { ApiClient } from "@photoreport/sdk";
|
||||
import { desktopRefreshStore, isDesktop } from "./platform.js";
|
||||
import { desktopConfig, desktopRefreshStore, isDesktop } from "./platform.js";
|
||||
|
||||
/**
|
||||
* Where the API is: VITE_API_URL when the build sets it (the desktop app always does); otherwise next to this page,
|
||||
* Where the API is: what the desktop app says; VITE_API_URL when the build sets it; otherwise next to this page,
|
||||
* app.<domain> -> api.<domain>, so a web build works on any environment without rebuilding for it.
|
||||
*/
|
||||
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined): string {
|
||||
export function apiUrlFor(configured: string | undefined, location: { protocol: string; hostname: string } | undefined, desktop = desktopConfig()): string {
|
||||
// The desktop app says where its API is (its interface may be a version downloaded from the web build).
|
||||
if (desktop?.api) return desktop.api.replace(/\/+$/, "");
|
||||
if (configured) return configured.replace(/\/+$/, "");
|
||||
if (location?.hostname.startsWith("app.")) return `${location.protocol}//api.${location.hostname.slice(4)}`;
|
||||
return "http://localhost:3000";
|
||||
}
|
||||
|
||||
const API_URL = apiUrlFor(import.meta.env.VITE_API_URL as string | undefined, typeof window === "undefined" ? undefined : window.location);
|
||||
export const API_URL = apiUrlFor(import.meta.env.VITE_API_URL as string | undefined, typeof window === "undefined" ? undefined : window.location);
|
||||
|
||||
export function createApi(onSessionLost: () => void): ApiClient {
|
||||
return new ApiClient({
|
||||
|
||||
+29
-6
@@ -1,7 +1,8 @@
|
||||
import type { ApiClient, Me, Organization, Role } from "@photoreport/sdk";
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { createApi } from "./api.js";
|
||||
import { prefs } from "./platform.js";
|
||||
import { isNetworkError } from "./offline/queue.js";
|
||||
import { isDesktop, prefs } from "./platform.js";
|
||||
|
||||
type Status = "loading" | "signedOut" | "signedIn";
|
||||
|
||||
@@ -36,20 +37,41 @@ export function AuthProvider({ children, api: injected }: { children: ReactNode;
|
||||
const next = await api.me();
|
||||
setMe(next);
|
||||
setStatus("signedIn");
|
||||
// Desktop app: who is signed in, so the app opens without a network (the session itself is in the keychain).
|
||||
if (isDesktop()) prefs.set("me", JSON.stringify(next));
|
||||
}, [api]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.resume()
|
||||
.then(async (ok) => {
|
||||
let retry: ReturnType<typeof setInterval> | undefined;
|
||||
const start = () =>
|
||||
api.resume().then(async (ok) => {
|
||||
if (!alive) return;
|
||||
if (ok) await reload();
|
||||
else setStatus("signedOut");
|
||||
})
|
||||
.catch(() => alive && setStatus("signedOut"));
|
||||
});
|
||||
start().catch((err: unknown) => {
|
||||
if (!alive) return;
|
||||
// No network on the desktop app: carry on as the person last signed in here; the session is checked again
|
||||
// once the server answers (a refused session still signs out then).
|
||||
const kept = isDesktop() && isNetworkError(err) ? prefs.get("me") : null;
|
||||
if (!kept) {
|
||||
setStatus("signedOut");
|
||||
return;
|
||||
}
|
||||
setMe(JSON.parse(kept) as Me);
|
||||
setStatus("signedIn");
|
||||
const again = () =>
|
||||
void start().then(
|
||||
() => clearInterval(retry),
|
||||
() => {},
|
||||
);
|
||||
retry = setInterval(again, 20_000);
|
||||
window.addEventListener("online", again, { once: true });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(retry);
|
||||
};
|
||||
}, [api, reload]);
|
||||
|
||||
@@ -72,6 +94,7 @@ export function AuthProvider({ children, api: injected }: { children: ReactNode;
|
||||
completeDeviceSignIn: reload,
|
||||
signOut: async () => {
|
||||
await api.logout().catch(() => {});
|
||||
prefs.set("me", "");
|
||||
setMe(null);
|
||||
setStatus("signedOut");
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { desktopInvoke, type Invoke, isDesktop } from "../platform.js";
|
||||
import { API_URL } from "../api.js";
|
||||
import { desktopInvoke, type Invoke, isDesktop, openExternal } from "../platform.js";
|
||||
|
||||
interface UpdateInfo {
|
||||
version: string;
|
||||
@@ -10,39 +11,174 @@ interface UpdateInfo {
|
||||
|
||||
const EVERY_MS = 6 * 3600_000;
|
||||
|
||||
/** Desktop only: a new version of the app's shell, installed with one click (it restarts). */
|
||||
export function UpdateNotice({ invoke = desktopInvoke, enabled = isDesktop() }: { invoke?: Invoke; enabled?: boolean }) {
|
||||
const [update, setUpdate] = useState<UpdateInfo | null>(null);
|
||||
const [state, setState] = useState<"idle" | "installing" | "failed">("idle");
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
type Listen = (event: string, handler: () => void) => Promise<() => void>;
|
||||
|
||||
const tauriListen: Listen = async (event, handler) => (await import("@tauri-apps/api/event")).listen(event, handler);
|
||||
|
||||
/**
|
||||
* Desktop only: a newer interface was downloaded in the background (apps/desktop/src-tauri/src/ui.rs). It is used
|
||||
* from the next start; reloading now switches straight away (nothing is lost: edits wait in the local queue).
|
||||
*/
|
||||
export function UiReadyNotice({ listen = tauriListen, enabled = isDesktop(), reload = () => window.location.reload() }: { listen?: Listen; enabled?: boolean; reload?: () => void }) {
|
||||
const [ready, setReady] = useState(false);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
const check = () => void invoke<UpdateInfo | null>("update_check").then(setUpdate, () => {});
|
||||
check();
|
||||
const id = setInterval(check, EVERY_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [enabled, invoke]);
|
||||
|
||||
if (!update || dismissed) return null;
|
||||
let stop: (() => void) | undefined;
|
||||
let alive = true;
|
||||
listen("ui-ready", () => setReady(true)).then(
|
||||
(unlisten) => (alive ? (stop = unlisten) : unlisten()),
|
||||
() => {},
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
stop?.();
|
||||
};
|
||||
}, [enabled, listen]);
|
||||
if (!ready || dismissed) return null;
|
||||
return (
|
||||
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
|
||||
<span>{t.update.available(update.version, update.currentVersion)}</span>
|
||||
{update.notes && <span className="truncate text-muted">{update.notes}</span>}
|
||||
<button
|
||||
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-50"
|
||||
disabled={state === "installing"}
|
||||
onClick={() => {
|
||||
setState("installing");
|
||||
invoke("update_install").catch(() => setState("failed"));
|
||||
}}
|
||||
>
|
||||
{state === "installing" ? t.update.installing : t.update.install}
|
||||
<span>{t.update.uiReady}</span>
|
||||
<button className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong" onClick={reload}>
|
||||
{t.update.reload}
|
||||
</button>
|
||||
{state === "failed" && <span className="text-danger">{t.update.failed}</span>}
|
||||
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
|
||||
{t.update.later}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the server offers when the app cannot update itself (or its own check failed). */
|
||||
export interface ServerUpdate {
|
||||
version: string;
|
||||
currentVersion: string;
|
||||
installer: string | null;
|
||||
}
|
||||
|
||||
/** This computer's platform as the update endpoint names it (Mac builds are universal: one answer for both chips). */
|
||||
function platform(): { target: string; arch: string } {
|
||||
const ua = typeof navigator === "undefined" ? "" : navigator.userAgent;
|
||||
if (/Mac OS X|Macintosh/.test(ua)) return { target: "darwin", arch: "aarch64" };
|
||||
if (/Windows/.test(ua)) return { target: "windows", arch: "x86_64" };
|
||||
return { target: "linux", arch: "x86_64" };
|
||||
}
|
||||
|
||||
/** Asks the update endpoint directly, from the page: works whatever the installed shell can or cannot do. */
|
||||
export async function askServer(apiUrl = API_URL): Promise<ServerUpdate | null> {
|
||||
const currentVersion = await (await import("@tauri-apps/api/app")).getVersion();
|
||||
const { target, arch } = platform();
|
||||
const res = await fetch(`${apiUrl}/v1/desktop/update/${target}/${arch}/${encodeURIComponent(currentVersion)}`);
|
||||
if (res.status !== 200) return null;
|
||||
const body = (await res.json()) as { version?: string; installer?: string };
|
||||
if (!body.version) return null;
|
||||
return { version: body.version, currentVersion, installer: body.installer ?? null };
|
||||
}
|
||||
|
||||
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
/**
|
||||
* Desktop only: a new version of the app's shell, installed with one click (it restarts). When the installed shell
|
||||
* cannot do that (its own check fails, or it was built without the update key), the page asks the server itself and
|
||||
* offers the full installer instead, with the reason, so an update is never missed in silence.
|
||||
*/
|
||||
export function UpdateNotice({
|
||||
invoke = desktopInvoke,
|
||||
enabled = isDesktop(),
|
||||
server = askServer,
|
||||
open = openExternal,
|
||||
}: {
|
||||
invoke?: Invoke;
|
||||
enabled?: boolean;
|
||||
server?: () => Promise<ServerUpdate | null>;
|
||||
open?: (url: string) => Promise<void>;
|
||||
}) {
|
||||
const [update, setUpdate] = useState<UpdateInfo | null>(null);
|
||||
const [manual, setManual] = useState<(ServerUpdate & { reason: string | null }) | null>(null);
|
||||
const [state, setState] = useState<"idle" | "installing" | "failed">("idle");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
let alive = true;
|
||||
const check = async () => {
|
||||
let reason: string | null = null;
|
||||
try {
|
||||
const found = await invoke<UpdateInfo | null>("update_check");
|
||||
if (!alive) return;
|
||||
if (found) {
|
||||
setUpdate(found);
|
||||
setManual(null);
|
||||
return;
|
||||
}
|
||||
} catch (err) {
|
||||
reason = message(err);
|
||||
}
|
||||
try {
|
||||
const offered = await server();
|
||||
if (alive && offered) setManual({ ...offered, reason });
|
||||
} catch {
|
||||
// No network: the next check tries again.
|
||||
}
|
||||
};
|
||||
void check();
|
||||
const id = setInterval(() => void check(), EVERY_MS);
|
||||
return () => {
|
||||
alive = false;
|
||||
clearInterval(id);
|
||||
};
|
||||
}, [enabled, invoke, server]);
|
||||
|
||||
if (dismissed) return null;
|
||||
if (update) {
|
||||
return (
|
||||
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
|
||||
<span>{t.update.available(update.version, update.currentVersion)}</span>
|
||||
{update.notes && <span className="truncate text-muted">{update.notes}</span>}
|
||||
<button
|
||||
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-50"
|
||||
disabled={state === "installing"}
|
||||
onClick={() => {
|
||||
setState("installing");
|
||||
setError(null);
|
||||
invoke("update_install").catch((err: unknown) => {
|
||||
setState("failed");
|
||||
setError(message(err));
|
||||
});
|
||||
}}
|
||||
>
|
||||
{state === "installing" ? t.update.installing : t.update.install}
|
||||
</button>
|
||||
{state === "failed" && (
|
||||
<span className="text-danger">
|
||||
{t.update.failed}
|
||||
{error ? ` (${error})` : ""}
|
||||
</span>
|
||||
)}
|
||||
<button className="text-faint hover:text-ink" onClick={() => setDismissed(true)} aria-label={t.update.later}>
|
||||
{t.update.later}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!manual) return null;
|
||||
return (
|
||||
<div role="status" className="flex flex-wrap items-center gap-3 border-b border-black bg-[#1d2a3a] px-4 py-1.5 text-[12px] text-ink">
|
||||
<span>{t.update.available(manual.version, manual.currentVersion)}</span>
|
||||
<span className="text-muted">{t.update.manual}</span>
|
||||
{manual.reason && <span className="truncate text-faint">({manual.reason})</span>}
|
||||
{manual.installer && (
|
||||
<button
|
||||
className="ml-auto h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong"
|
||||
onClick={() => void open(manual.installer!)}
|
||||
>
|
||||
{t.update.download}
|
||||
</button>
|
||||
)}
|
||||
<button className={`${manual.installer ? "" : "ml-auto "}text-faint hover:text-ink`} onClick={() => setDismissed(true)} aria-label={t.update.later}>
|
||||
{t.update.later}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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("brings the saved password along when the other app keeps it readable", async () => {
|
||||
const created: { name: string; password?: string }[] = [];
|
||||
const api = {
|
||||
createDeliveryTarget: vi.fn(async (_org: string, input: { name: string; password?: string }) => {
|
||||
created.push(input);
|
||||
return { id: `t${created.length}`, ...input } as unknown as DeliveryTarget;
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
render(
|
||||
<ImportTargets
|
||||
api={api}
|
||||
orgId="org"
|
||||
existing={[]}
|
||||
shell={shell({ profiles: async () => ({ photoMechanic: [], photoMechanicAccounts: [], filezilla: SITES, passwords: { "fz:Clube:ftp.clube.pt": "guardada" }, unreadable: ["fz:Jornal:ftp.jornal.pt"] }) })}
|
||||
onClose={() => {}}
|
||||
onImported={() => {}}
|
||||
/>,
|
||||
);
|
||||
expect(await screen.findByText("senha guardada no FileZilla")).toBeTruthy();
|
||||
expect(screen.getByText("o FileZilla guarda esta senha cifrada: escreve-a")).toBeTruthy();
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Clube" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Importar 1" }));
|
||||
await waitFor(() => expect(created).toEqual([expect.objectContaining({ name: "Clube", password: "guardada" })]));
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Invoke } from "../platform.js";
|
||||
import { type CatalogFolder, LocalCatalog, type ScanStatus } from "./LocalCatalog.js";
|
||||
import { UpdateNotice } from "./UpdateNotice.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "./UpdateNotice.js";
|
||||
|
||||
describe("local catalogue", () => {
|
||||
it("adds a folder through the system picker, indexes it and shows the count", async () => {
|
||||
@@ -37,18 +37,55 @@ describe("local catalogue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("interface update notice", () => {
|
||||
it("says when a newer interface is ready and reloads into it", async () => {
|
||||
let fire: () => void = () => {};
|
||||
const listen = vi.fn(async (_event: string, handler: () => void) => {
|
||||
fire = handler;
|
||||
return () => {};
|
||||
});
|
||||
const reload = vi.fn();
|
||||
render(<UiReadyNotice listen={listen} enabled reload={reload} />);
|
||||
await waitFor(() => expect(listen).toHaveBeenCalledWith("ui-ready", expect.any(Function)));
|
||||
act(() => fire());
|
||||
fireEvent.click(await screen.findByText("Recarregar agora"));
|
||||
expect(reload).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("update notice", () => {
|
||||
it("offers a newer shell and installs it", async () => {
|
||||
const invoke = vi.fn(async (cmd: string) => (cmd === "update_check" ? { version: "0.3.0", currentVersion: "0.2.0", notes: "Catálogo local" } : null)) as unknown as Invoke;
|
||||
render(<UpdateNotice invoke={invoke} enabled />);
|
||||
render(<UpdateNotice invoke={invoke} enabled server={async () => null} />);
|
||||
expect(await screen.findByText("Nova versão da app: 0.3.0 (tens a 0.2.0).")).toBeTruthy();
|
||||
fireEvent.click(screen.getByText("Instalar e reiniciar"));
|
||||
expect(invoke).toHaveBeenCalledWith("update_install");
|
||||
});
|
||||
|
||||
it("offers the installer when the app cannot update itself, with the reason", async () => {
|
||||
const invoke = vi.fn(async () => {
|
||||
throw new Error("Could not fetch a valid release JSON from the remote");
|
||||
}) as unknown as Invoke;
|
||||
const server = vi.fn(async () => ({ version: "0.3.7", currentVersion: "0.3.5", installer: "https://api.example/v1/desktop/download/1/PhotoReport.dmg" }));
|
||||
const open = vi.fn(async () => {});
|
||||
render(<UpdateNotice invoke={invoke} enabled server={server} open={open} />);
|
||||
expect(await screen.findByText("Nova versão da app: 0.3.7 (tens a 0.3.5).")).toBeTruthy();
|
||||
expect(screen.getByText("(Could not fetch a valid release JSON from the remote)")).toBeTruthy();
|
||||
fireEvent.click(screen.getByText("Descarregar instalador"));
|
||||
expect(open).toHaveBeenCalledWith("https://api.example/v1/desktop/download/1/PhotoReport.dmg");
|
||||
});
|
||||
|
||||
it("asks the server too when the app itself finds nothing (a build without the update key)", async () => {
|
||||
const invoke = vi.fn(async () => null) as unknown as Invoke;
|
||||
const server = vi.fn(async () => ({ version: "0.3.7", currentVersion: "0.3.5", installer: null }));
|
||||
render(<UpdateNotice invoke={invoke} enabled server={server} />);
|
||||
expect(await screen.findByText("Nova versão da app: 0.3.7 (tens a 0.3.5).")).toBeTruthy();
|
||||
expect(screen.queryByText("Descarregar instalador")).toBeNull();
|
||||
});
|
||||
|
||||
it("stays quiet when there is nothing new, and outside the desktop app", async () => {
|
||||
const invoke = vi.fn(async () => null) as unknown as Invoke;
|
||||
const { container } = render(<UpdateNotice invoke={invoke} enabled />);
|
||||
const { container } = render(<UpdateNotice invoke={invoke} enabled server={async () => null} />);
|
||||
await waitFor(() => expect(invoke).toHaveBeenCalled());
|
||||
expect(container.textContent).toBe("");
|
||||
const never = vi.fn() as unknown as Invoke;
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import type { ImportSources } from "../library/importSources.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;
|
||||
}
|
||||
@@ -19,6 +19,15 @@ export interface OutboxStore {
|
||||
save(photoId: string, ops: PendingOp[]): void;
|
||||
}
|
||||
|
||||
/** The last edit state seen per photo, so a photo opens in Revelar without a network (IndexedDB in the app). */
|
||||
export interface StateStore {
|
||||
get(photoId: string): Promise<{ settings: string; seq: number } | undefined>;
|
||||
set(photoId: string, state: { settings: string; seq: number }): Promise<void> | void;
|
||||
}
|
||||
|
||||
/** A photo still only on this computer (local FTP): edits wait for its upload (see offline/queue.ts). */
|
||||
const isLocal = (photoId: string) => photoId.startsWith("local:");
|
||||
|
||||
export interface PendingOp {
|
||||
opId: string;
|
||||
command: EditCommand;
|
||||
@@ -63,15 +72,32 @@ export class DevelopSession {
|
||||
|
||||
constructor(
|
||||
readonly photoId: string,
|
||||
private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined },
|
||||
private readonly deps: { engine: SettingsEngine; api: DevelopApi; clientId: string; outbox?: OutboxStore | undefined; states?: StateStore | undefined; isOffline?: (err: unknown) => boolean },
|
||||
) {}
|
||||
|
||||
async load(): Promise<void> {
|
||||
const state = await this.deps.api.developState(this.photoId);
|
||||
let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings();
|
||||
for (const op of state.ops) base = this.safeApply(base, op.command);
|
||||
this.base = base;
|
||||
this.confirmedSeq = state.developSeq;
|
||||
if (isLocal(this.photoId)) {
|
||||
// Not on the server yet: starts from scratch; the edits go up after the photo.
|
||||
this.base = this.deps.engine.defaultSettings();
|
||||
this.confirmedSeq = 0;
|
||||
this.offline = true;
|
||||
} else {
|
||||
try {
|
||||
const state = await this.deps.api.developState(this.photoId);
|
||||
let base = state.snapshot ? JSON.stringify(state.snapshot) : this.deps.engine.defaultSettings();
|
||||
for (const op of state.ops) base = this.safeApply(base, op.command);
|
||||
this.base = base;
|
||||
this.confirmedSeq = state.developSeq;
|
||||
this.remember();
|
||||
} catch (err) {
|
||||
// No network: the state last seen here (or a fresh start); the edits are sent when the connection is back.
|
||||
if (!this.deps.isOffline?.(err)) throw err;
|
||||
const kept = await this.deps.states?.get(this.photoId);
|
||||
this.base = kept?.settings ?? this.deps.engine.defaultSettings();
|
||||
this.confirmedSeq = kept?.seq ?? 0;
|
||||
this.offline = true;
|
||||
}
|
||||
}
|
||||
this.pending = this.deps.outbox?.load(this.photoId).map((p) => ({ ...p, sent: false })) ?? [];
|
||||
this.loaded = true;
|
||||
this.changed();
|
||||
@@ -188,11 +214,13 @@ export class DevelopSession {
|
||||
this.confirmedSeq = op.seq;
|
||||
this.dropPending(op.opId);
|
||||
}
|
||||
this.remember();
|
||||
this.changed();
|
||||
}
|
||||
|
||||
/** Missed some ops (reconnect, a message lost): fetch everything after what we have, in order. */
|
||||
async catchUp(): Promise<void> {
|
||||
if (isLocal(this.photoId)) return;
|
||||
const state = await this.deps.api.developState(this.photoId, this.confirmedSeq);
|
||||
if (state.snapshot) {
|
||||
// The server answered with a snapshot (we were too far behind): start over from it.
|
||||
@@ -214,6 +242,11 @@ export class DevelopSession {
|
||||
if (this.sending || this.closed) return;
|
||||
const batch = this.pending.filter((p) => !p.sent).slice(0, 200);
|
||||
if (!batch.length) return;
|
||||
// A photo not uploaded yet: the edits stay in the outbox and follow it (offline/queue.ts).
|
||||
if (isLocal(this.photoId)) {
|
||||
this.persist();
|
||||
return;
|
||||
}
|
||||
this.sending = true;
|
||||
for (const op of batch) op.sent = true;
|
||||
try {
|
||||
@@ -253,6 +286,10 @@ export class DevelopSession {
|
||||
if (i >= 0) this.pending.splice(i, 1);
|
||||
}
|
||||
|
||||
private remember(): void {
|
||||
if (!isLocal(this.photoId)) void this.deps.states?.set(this.photoId, { settings: this.base, seq: this.confirmedSeq });
|
||||
}
|
||||
|
||||
private persist(): void {
|
||||
this.deps.outbox?.save(
|
||||
this.photoId,
|
||||
|
||||
+88
-7
@@ -34,12 +34,42 @@ export const t = {
|
||||
soon: "Em breve",
|
||||
events: "Eventos",
|
||||
inbox: "Sem evento",
|
||||
offline: {
|
||||
label: "sem ligação",
|
||||
waiting: (n: number) => (n === 1 ? "1 alteração à espera de ligação" : `${n} alterações à espera de ligação`),
|
||||
waitingHelp: "Feito sem ligação ao servidor: fica guardado neste computador e é enviado sozinho quando a ligação voltar.",
|
||||
queuedDelivery: "Sem ligação: o envio fica à espera e sai sozinho quando a ligação voltar.",
|
||||
editingOffline: "Sem ligação: as edições ficam guardadas neste computador e são enviadas quando a ligação voltar.",
|
||||
},
|
||||
moveToEvent: "Mover para evento",
|
||||
movedToEvent: (n: number, name: string) => `${n} ${n === 1 ? "foto movida" : "fotos movidas"} para ${name}`,
|
||||
newEvent: "Novo evento",
|
||||
noEvents: "Sem eventos. Cria o primeiro.",
|
||||
noPhotos: "Sem fotografias neste filtro.",
|
||||
noPhotosYet: "Ainda não chegaram fotografias. Assim que o FTP receber ficheiros, aparecem aqui.",
|
||||
filter: "Filtro",
|
||||
filters: { all: "Todas", PICK: "Escolhidas", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas", stars: "★ 3+", noPlayers: "Sem jogador" },
|
||||
flagFilter: { all: "Todas", PICK: "Escolhidas", UNFLAGGED: "Sem marca", UNREJECTED: "Sem rejeitadas", REJECT: "Rejeitadas" },
|
||||
starsAtLeast: "Estrelas (pelo menos)",
|
||||
starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`),
|
||||
colorLabel: "Cor",
|
||||
colors: { RED: "Vermelho", YELLOW: "Amarelo", GREEN: "Verde", BLUE: "Azul", PURPLE: "Roxo" },
|
||||
deliveryFilter: "Envio:",
|
||||
deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" },
|
||||
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",
|
||||
bestAgain: "Enviar de novo as que já foram entregues",
|
||||
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",
|
||||
noTargetsHelp: "Ainda não há destinos de envio (FTP da agência, pasta, etc.). Cria um em Entregar.",
|
||||
deliveryBadge: { QUEUED: "A enviar", DONE: "Enviada", FAILED: "Envio falhou" },
|
||||
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · I informação · E/Enter lupa · G/Esc grelha · D revelar",
|
||||
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
|
||||
ofTotal: (n: number, total: number) => `${n} de ${total}`,
|
||||
@@ -130,6 +160,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",
|
||||
@@ -165,6 +196,35 @@ 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, senha, pasta, tamanho, qualidade e nome do ficheiro vêm de lá. Uma senha que a outra app guarda cifrada tens de a escrever aqui.",
|
||||
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.",
|
||||
savedPassword: (app: string) => `senha guardada no ${app}`,
|
||||
encryptedPassword: (app: string) => `o ${app} guarda esta senha cifrada: escreve-a`,
|
||||
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",
|
||||
@@ -179,6 +239,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).`,
|
||||
@@ -216,7 +281,11 @@ export const t = {
|
||||
shareLink: "Link de partilha",
|
||||
copyLink: "Copiar link",
|
||||
copied: "Copiado",
|
||||
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", DONE: "Entregue", FAILED: "Falhou" },
|
||||
deliveryErrors: {
|
||||
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
|
||||
original_not_here: "O original nunca chegou do computador do fotógrafo",
|
||||
},
|
||||
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",
|
||||
@@ -264,15 +333,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. 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)",
|
||||
@@ -328,7 +400,11 @@ export const t = {
|
||||
install: "Instalar e reiniciar",
|
||||
installing: "A instalar…",
|
||||
failed: "Não foi possível instalar. Tenta mais tarde.",
|
||||
manual: "Esta instalação não se atualiza sozinha: descarrega o instalador e abre-o (só desta vez).",
|
||||
download: "Descarregar instalador",
|
||||
later: "Mais tarde",
|
||||
uiReady: "Nova versão da interface descarregada. Fica ativa ao recarregar (ou no próximo arranque).",
|
||||
reload: "Recarregar agora",
|
||||
},
|
||||
editorPanelsHelp: "Escolhe os painéis que queres ver ao editar. A escolha acompanha-te no web e no desktop.",
|
||||
saved: "Guardado",
|
||||
@@ -353,8 +429,9 @@ export const t = {
|
||||
numbers: {
|
||||
title: "Números das camisolas",
|
||||
counts: (pending: number, ok: number, bad: number) => `por rever ${pending} · certos ${ok} · ilegíveis ${bad}`,
|
||||
keys: "⏎ certo · dígitos + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
|
||||
cropAlt: "Tronco do jogador",
|
||||
keys: "⏎ certo · dígitos (ou A–F, oficiais) + ⏎ corrigir · X ilegível · S não é camisola · ⌫ desfazer",
|
||||
cropAlt: "Recorte do jogador",
|
||||
region: { CHEST: "peito", SHORTS: "calção" } as Record<"CHEST" | "SHORTS", string>,
|
||||
squadSays: (n: string) => `o plantel diz ${n}`,
|
||||
right: "Certo",
|
||||
other: "Outro número",
|
||||
@@ -364,7 +441,11 @@ export const t = {
|
||||
empty: "Nada por rever. Confirma grupos em Caras (com o número no plantel) e aparecem aqui os recortes.",
|
||||
collected: (n: number) => `${n} recortes novos a partir das caras confirmadas.`,
|
||||
perNumber: "Exemplos por número",
|
||||
help: "Cada recorte é o tronco de alguém já identificado pela cara; o número vem do plantel. Diz se está certo, corrige, ou marca que não se lê. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
|
||||
help: "Cada recorte é o peito ou o calção de alguém já identificado pela cara (no futebol o número da frente está no calção; no andebol, no peito); o número vem do plantel. Aqui ensinas a ler o número, não a reconhecer o jogador: só é \"Certo\" se o número se lê inteiro no recorte. Número tapado, cortado, só meio visível ou sem número: \"Não se lê\", mesmo que o jogador esteja certo. No andebol, os oficiais da equipa têm um cartão ao pescoço com uma letra (A a F; o B é normalmente o treinador principal): escreve a letra como se fosse o número. Uns milhares de exemplos chegam para treinar o modelo; quanto mais variados (números, equipas, ângulos), melhor.",
|
||||
reset: "Recomeçar o ensino",
|
||||
resetConfirm: (n: number) => `Apagar as ${n} respostas e rever tudo de novo`,
|
||||
resetCancel: "Cancelar",
|
||||
resetDone: (n: number) => `${n} respostas apagadas. Os recortes estão todos por rever.`,
|
||||
download: "Descarregar conjunto de treino",
|
||||
read: (n: string, votes: number) => `O modelo leu ${n} na camisola (${votes} ${votes === 1 ? "foto" : "fotos"})`,
|
||||
},
|
||||
|
||||
@@ -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} />
|
||||
|
||||
@@ -68,4 +68,17 @@ describe("new event form", () => {
|
||||
expect(createEvent).toHaveBeenCalledWith("o1", expect.objectContaining({ home: "Conferência de imprensa do FC Porto", venue: "Estádio do Dragão", iptcTemplate: expect.objectContaining({ caption: "Sérgio Conceição na antevisão do clássico" }) }));
|
||||
expect(shiftDay("2026-10-31", 1)).toBe("2026-11-01");
|
||||
});
|
||||
|
||||
it("searches the last two weeks too, for an event made after the match", async () => {
|
||||
const sportsFixtures = vi.fn(async (_q: { from: string; q?: string }) => ({ fixtures: [] }));
|
||||
const api = { createEvent: vi.fn(), sportsFixtures, listPeople: async () => ({ people: [] }), calendarStatus: async () => ({ connected: false }) } as unknown as ApiClient;
|
||||
render(<EventForm api={api} orgId="o1" onClose={() => undefined} onCreated={() => undefined} />);
|
||||
await waitFor(() => expect(sportsFixtures).toHaveBeenCalled());
|
||||
const hours = (q: { from: string }) => (Date.now() - Date.parse(q.from)) / 3600_000;
|
||||
expect(hours(sportsFixtures.mock.calls[0]![0])).toBeLessThan(13);
|
||||
fireEvent.change(screen.getByLabelText("Equipa, competição ou pavilhão"), { target: { value: "braga" } });
|
||||
await waitFor(() => expect(sportsFixtures.mock.calls.some(([q]) => q.q === "braga")).toBe(true));
|
||||
const search = sportsFixtures.mock.calls.find(([q]) => q.q === "braga")![0];
|
||||
expect(hours(search)).toBeGreaterThan(14 * 24 - 1);
|
||||
});
|
||||
});
|
||||
@@ -235,8 +235,10 @@ export function FixturePicker({ api, match, onPick, onClear }: { api: ApiClient;
|
||||
useEffect(() => {
|
||||
if (match) return;
|
||||
const timer = setTimeout(() => {
|
||||
const from = new Date(Date.now() - 12 * 3600_000).toISOString();
|
||||
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim() }) }).then((r) => setList(r.fixtures), () => setList([]));
|
||||
// Upcoming games by default; a search also finds the last two weeks (an event made after the match).
|
||||
const from = new Date(Date.now() - (q.trim() ? 14 * 24 : 12) * 3600_000).toISOString();
|
||||
const to = new Date(Date.now() + 14 * 24 * 3600_000).toISOString();
|
||||
api.sportsFixtures({ from, ...(q.trim() && { q: q.trim(), to }) }).then((r) => setList(r.fixtures), () => setList([]));
|
||||
}, 250);
|
||||
return () => clearTimeout(timer);
|
||||
}, [api, q, match]);
|
||||
|
||||
@@ -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,80 @@
|
||||
import type { ColorLabel } from "@photoreport/contracts";
|
||||
import { t } from "../i18n.js";
|
||||
import { LABEL_COLOR } from "./Grid.js";
|
||||
import { ALL_PHOTOS, isAll, type LibraryFilter } from "./store.js";
|
||||
|
||||
const FLAGS: LibraryFilter["flag"][] = ["all", "PICK", "UNFLAGGED", "UNREJECTED", "REJECT"];
|
||||
const DELIVERY: LibraryFilter["delivery"][] = ["any", "unsent", "queued", "sent", "failed"];
|
||||
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
|
||||
|
||||
const chip = (on: boolean) => (on ? "font-semibold text-ink" : "text-faint hover:text-muted");
|
||||
|
||||
/**
|
||||
* Photo Mechanic / Lightroom style filter bar: flag, stars (at least), colour, delivery state and photos without
|
||||
* players, all combinable. Clicking an active stars or colour choice again turns it off.
|
||||
*/
|
||||
export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryFilter) => void }) {
|
||||
const { filter: f, onChange } = props;
|
||||
const set = (patch: Partial<LibraryFilter>) => onChange({ ...f, ...patch });
|
||||
return (
|
||||
<div role="group" aria-label={t.filter} className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span className="text-faint">{t.filter}:</span>
|
||||
{FLAGS.map((flag) => (
|
||||
<button key={flag} onClick={() => set({ flag })} aria-pressed={f.flag === flag} className={chip(f.flag === flag)}>
|
||||
{t.flagFilter[flag]}
|
||||
</button>
|
||||
))}
|
||||
<span aria-hidden="true" className="text-line">|</span>
|
||||
<span className="flex items-center" role="group" aria-label={t.starsAtLeast}>
|
||||
{[1, 2, 3, 4, 5].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
onClick={() => set({ minRating: f.minRating === n ? 0 : n })}
|
||||
aria-pressed={f.minRating === n}
|
||||
aria-label={t.starsOrMore(n)}
|
||||
title={t.starsOrMore(n)}
|
||||
className={`px-[1px] text-[13px] ${n <= f.minRating ? "text-star" : "text-faint hover:text-muted"}`}
|
||||
>
|
||||
★
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" role="group" aria-label={t.colorLabel}>
|
||||
{COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
onClick={() => set({ color: f.color === c ? null : c })}
|
||||
aria-pressed={f.color === c}
|
||||
aria-label={t.colors[c]}
|
||||
title={t.colors[c]}
|
||||
className={`h-3 w-3 rounded-[2px] ${f.color === c ? "outline outline-1 outline-offset-1 outline-white" : "opacity-60 hover:opacity-100"}`}
|
||||
style={{ background: LABEL_COLOR[c] ?? undefined }}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
<span aria-hidden="true" className="text-line">|</span>
|
||||
<label className="flex items-center gap-1">
|
||||
<span className="text-faint">{t.deliveryFilter}</span>
|
||||
<select
|
||||
value={f.delivery}
|
||||
onChange={(e) => set({ delivery: e.target.value as LibraryFilter["delivery"] })}
|
||||
className={`h-6 border border-black bg-cell px-1 text-[12px] ${f.delivery === "any" ? "text-muted" : "text-ink"}`}
|
||||
>
|
||||
{DELIVERY.map((d) => (
|
||||
<option key={d} value={d}>
|
||||
{t.deliveryStates[d]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<button onClick={() => set({ noPlayers: !f.noPlayers })} aria-pressed={f.noPlayers} className={chip(f.noPlayers)}>
|
||||
{t.noPlayersFilter}
|
||||
</button>
|
||||
{!isAll(f) && (
|
||||
<button onClick={() => onChange(ALL_PHOTOS)} className="text-accent hover:underline">
|
||||
{t.clearFilter}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { ColorLabel, PhotoSummary } from "@photoreport/contracts";
|
||||
import { memo, useEffect, useRef } from "react";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { useCachedImage } from "../offline/cache.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
|
||||
export const LABEL_COLOR: Record<ColorLabel, string | null> = {
|
||||
NONE: null,
|
||||
@@ -26,6 +29,8 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
if (focused) ref.current?.scrollIntoView({ block: "nearest" });
|
||||
}, [focused]);
|
||||
const label = LABEL_COLOR[photo.colorLabel];
|
||||
// Desktop app: thumbnails are kept on the computer, so the grid shows without a network.
|
||||
const shown = useCachedImage(src, isDesktop());
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
@@ -44,7 +49,7 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
</span>
|
||||
<span className="flex min-h-0 w-full flex-1 items-center justify-center">
|
||||
{photo.status === "READY" ? (
|
||||
<img src={src} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
|
||||
shown && <img src={shown} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
|
||||
) : (
|
||||
<span className="font-mono text-[10px] uppercase text-faint">{photo.status === "FAILED" ? "erro" : "…"}</span>
|
||||
)}
|
||||
@@ -58,6 +63,15 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
</span>
|
||||
<span aria-hidden="true" className="h-2.5 w-2.5 rounded-[2px]" style={{ background: label ?? "transparent" }} />
|
||||
</span>
|
||||
{photo.delivery && photo.delivery !== "NONE" && (
|
||||
<span
|
||||
title={t.deliveryBadge[photo.delivery]}
|
||||
aria-label={t.deliveryBadge[photo.delivery]}
|
||||
className={`absolute left-1.5 top-1 text-[11px] font-bold ${photo.delivery === "DONE" ? "text-ok" : photo.delivery === "FAILED" ? "text-[#f0a35a]" : "text-[#7fb0ff]"}`}
|
||||
>
|
||||
{photo.delivery === "DONE" ? "✓" : photo.delivery === "FAILED" ? "!" : "↑"}
|
||||
</span>
|
||||
)}
|
||||
{photo.players.length > 0 && (
|
||||
<span className="absolute right-1.5 top-1 max-w-[70%] truncate text-[10px] text-muted">{photo.players[0]}</span>
|
||||
)}
|
||||
@@ -101,11 +115,17 @@ export interface LoupeFace {
|
||||
suggested: boolean;
|
||||
}
|
||||
|
||||
export function Loupe({ photo, src, index, total, faces = [] }: { photo: PhotoSummary; src: string; index: number; total: number; faces?: LoupeFace[] }) {
|
||||
export function Loupe({ photo, src, fallback, index, total, faces = [] }: { photo: PhotoSummary; src: string; fallback?: string; index: number; total: number; faces?: LoupeFace[] }) {
|
||||
// Desktop app: previews seen once show again without a network; never seen, the thumbnail stands in.
|
||||
const preview = useCachedImage(src, isDesktop());
|
||||
const thumb = useCachedImage(fallback ?? null, isDesktop() && !!fallback);
|
||||
const [failed, setFailed] = useState(false);
|
||||
useEffect(() => setFailed(false), [src]);
|
||||
const shown = (failed ? thumb : preview) ?? thumb ?? "";
|
||||
return (
|
||||
<section aria-label="Lupa" className="relative flex h-full min-h-[420px] items-center justify-center bg-[#121213] p-6">
|
||||
<span className="relative inline-block max-h-full max-w-full">
|
||||
<img src={src} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
|
||||
<img src={shown} onError={() => setFailed(true)} alt={photo.name} className="block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]" />
|
||||
{faces.map((f) => (
|
||||
<span
|
||||
key={f.id}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
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 "./importSources.js";
|
||||
|
||||
interface Row {
|
||||
c: ImportCandidate;
|
||||
selected: boolean;
|
||||
name: string;
|
||||
password: string;
|
||||
/** The password came from the other app ("saved"), or it keeps it encrypted ("encrypted"). */
|
||||
saved: "saved" | "encrypted" | null;
|
||||
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, output settings and the saved password (when the other app keeps it readable)
|
||||
* come from there; an encrypted password is typed here.
|
||||
*/
|
||||
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) => {
|
||||
const saved = sources.passwords?.[c.passwordKey];
|
||||
return {
|
||||
c,
|
||||
selected: false,
|
||||
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
|
||||
password: saved ?? "",
|
||||
saved: saved ? "saved" : sources.unreadable?.includes(c.passwordKey) ? "encrypted" : null,
|
||||
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, saved: null })} />
|
||||
)}
|
||||
{!r.c.problem && r.result !== "ok" && r.saved && <p className={`text-[11px] ${r.saved === "saved" ? "text-faint" : "text-[#f0a35a]"}`}>{r.saved === "saved" ? L.savedPassword(r.c.source) : L.encryptedPassword(r.c.source)}</p>}
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient, type DeliveryTarget, type IptcIssue } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { deliver as deliverOrQueue } from "../offline/sync.js";
|
||||
|
||||
const dateTime = new Intl.DateTimeFormat("pt-PT", { dateStyle: "short", timeStyle: "medium", timeZone: "Europe/Lisbon" });
|
||||
|
||||
@@ -72,8 +73,8 @@ export function InfoPanel(props: {
|
||||
setBusy(true);
|
||||
setDeliveryNote(null);
|
||||
try {
|
||||
const r = await api.deliver(props.orgId, targetId, picks.map((p) => p.id));
|
||||
setDeliveryNote(t.delivered(r.queued.length, r.skipped.length));
|
||||
const r = await deliverOrQueue(api, props.orgId, targetId, picks.map((p) => p.id));
|
||||
setDeliveryNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
|
||||
} catch (err) {
|
||||
setDeliveryNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ApiClient, DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { deliver, setIptc } from "../offline/sync.js";
|
||||
|
||||
/** The fields of Photo Mechanic's Info window, in its order. Lists are comma separated. */
|
||||
const FIELDS = [
|
||||
@@ -72,10 +73,10 @@ export function IptcInfo(props: { api: ApiClient; orgId: string; photos: PhotoSu
|
||||
set[f.id] = v === "" ? null : f.list ? v.split(",").map((x) => x.trim()).filter(Boolean) : v;
|
||||
}
|
||||
const ids = photos.map((p) => p.id);
|
||||
if (Object.keys(set).length) await api.setPhotosIptc(props.orgId, ids, set);
|
||||
if (Object.keys(set).length) await setIptc(api, props.orgId, ids, set);
|
||||
if (send && targetId) {
|
||||
const r = await api.deliver(props.orgId, targetId, ids);
|
||||
setNote(t.delivered(r.queued.length, r.skipped.length));
|
||||
const r = await deliver(api, props.orgId, targetId, ids);
|
||||
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
|
||||
setState("idle");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { EventSummary } from "@photoreport/sdk";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { type FtpStatus, type IncomingFile, type Invoke, useLocalFtp } from "./LocalFtp.js";
|
||||
import type { UploadStatus } from "./uploads.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
|
||||
const status = (running: boolean): FtpStatus => ({
|
||||
running,
|
||||
@@ -50,9 +51,9 @@ describe("local FTP feed", () => {
|
||||
{ path: "/x/FTP/B.JPG", name: "B.JPG", size: 10, modifiedMs: 2 },
|
||||
]);
|
||||
const added: { name: string; eventId: string | undefined; size: number; sha?: string }[] = [];
|
||||
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string }) => {
|
||||
const add = (files: Iterable<File>, eventId?: string, onSettled?: (f: File, s: UploadStatus) => void, original?: { sha256: string } | "original") => {
|
||||
for (const f of files) {
|
||||
added.push({ name: f.name, eventId, size: f.size, ...(original && { sha: original.sha256 }) });
|
||||
added.push({ name: f.name, eventId, size: f.size, ...(original && original !== "original" && { sha: original.sha256 }) });
|
||||
onSettled?.(f, f.name === "A.JPG" ? "done" : "failed");
|
||||
}
|
||||
};
|
||||
@@ -62,6 +63,8 @@ describe("local FTP feed", () => {
|
||||
await act(() => result.current.start());
|
||||
|
||||
await waitFor(() => expect(added).toHaveLength(2));
|
||||
// Each shows in the library as soon as it arrives (before the upload), and leaves once settled.
|
||||
await waitFor(() => expect(localPhotos.list()).toEqual([]));
|
||||
// Working locally (the default): previews go up, each with the fingerprint of its original.
|
||||
expect(added).toEqual([
|
||||
{ name: "A.JPG", eventId: "ev1", size: "preview of /x/FTP/A.JPG".length, sha: "sha-/x/FTP/A.JPG" },
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } from "../offline/local.js";
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import type { PreviewOf, UploadStatus } from "./uploads.js";
|
||||
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
/** Settings kept by the desktop shell (apps/desktop/src-tauri/src/ftp.rs). */
|
||||
export interface FtpSettings {
|
||||
@@ -50,7 +54,7 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/
|
||||
const IN_FLIGHT = 6;
|
||||
const POLL_MS = 1000;
|
||||
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => void;
|
||||
type Add = (files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => void;
|
||||
|
||||
export const eventLabel = (e: Pick<EventSummary, "title" | "home" | "away">) => e.title || [e.home, e.away].filter(Boolean).join(" x ");
|
||||
|
||||
@@ -74,7 +78,7 @@ const settingsError = (err: unknown): string => {
|
||||
* a time, sends them to the target event and, once the server has each one, tells the shell to move the original
|
||||
* into the event's work folder. Failed ones stay in the ingest folder and go again with "retry" (or next start).
|
||||
*/
|
||||
export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriInvoke) {
|
||||
export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriInvoke, orgId = "") {
|
||||
const [status, setStatus] = useState<FtpStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
/** An older desktop app without the FTP commands. */
|
||||
@@ -105,21 +109,38 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
|
||||
try {
|
||||
// Working locally: a 2048 px preview with the original's metadata goes up, the original stays here.
|
||||
const full = originalsRef.current;
|
||||
const [bytes, original] = await Promise.all([
|
||||
invoke<unknown>(full ? "ftp_read" : "ftp_preview", { path: f.path }).then(asArrayBuffer),
|
||||
full ? Promise.resolve(undefined) : invoke<PreviewOf>("ftp_info", { path: f.path }),
|
||||
]);
|
||||
const [preview, info] = await Promise.all([invoke<unknown>("ftp_preview", { path: f.path }).then(asArrayBuffer), invoke<PreviewOf>("ftp_info", { path: f.path })]);
|
||||
// In the library at once (with or without a network), from the preview made here; the server's copy
|
||||
// takes its place when the upload is done.
|
||||
const capturedAt = lisbonInstant(exifDateTime(preview));
|
||||
const eventId = to?.id ?? routeLocally((await cache.events(orgId))?.events ?? [], capturedAt);
|
||||
if (!localPhotos.bySha(info.sha256)) {
|
||||
let url = "";
|
||||
try {
|
||||
url = URL.createObjectURL(new Blob([preview], { type: "image/jpeg" }));
|
||||
} catch {
|
||||
/* no blob URLs here (tests): shown without a thumbnail */
|
||||
}
|
||||
localPhotos.put(localPhoto({ sha256: info.sha256, name: f.name, width: info.width, height: info.height, capturedAt, eventId, url }));
|
||||
// Culled before a restart (still offline): it comes back as it was left.
|
||||
for (const op of orgId ? offlineQueue(orgId).pending : []) if (op.kind === "patch" && op.ids.includes(localId(info.sha256))) localPhotos.patch(localId(info.sha256), op.patch as Partial<PhotoSummary>);
|
||||
}
|
||||
const bytes = full ? await invoke<unknown>("ftp_read", { path: f.path }).then(asArrayBuffer) : preview;
|
||||
const file = new File([bytes], f.name, { type: "image/jpeg", lastModified: f.modifiedMs });
|
||||
add([file], to?.id, (_file, result) => {
|
||||
// A full original from the camera still counts as FTP (the event's autopilot edits it), not a hand upload.
|
||||
add([file], to?.id, (_file, result, photo) => {
|
||||
inFlight.current--;
|
||||
if (result === "done" || result === "duplicate") {
|
||||
setCounts((c) => ({ ...c, sent: c.sent + 1 }));
|
||||
invoke("ftp_sent", { path: f.path, event: to?.title ?? "", date: to?.date ?? "" }).catch(() => {});
|
||||
// Changes made to it meanwhile now go to the server's copy.
|
||||
if (photo && orgId) offlineQueue(orgId).uploaded(info.sha256, photo.id);
|
||||
} else {
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
}
|
||||
localPhotos.remove(localId(info.sha256));
|
||||
pump();
|
||||
}, original);
|
||||
}, full ? "original" : info);
|
||||
} catch {
|
||||
inFlight.current--;
|
||||
setCounts((c) => ({ ...c, failed: c.failed + 1 }));
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import type { DeliveryItemSummary, PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient, type DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useEffect, useState } from "react";
|
||||
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[]; 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 [bestAgain, setBestAgain] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (targets.length && !targets.some((x) => x.id === targetId)) setTargetId(targets[0]!.id);
|
||||
}, [targets, targetId]);
|
||||
useEffect(() => {
|
||||
if (!note) return;
|
||||
const timer = setTimeout(() => setNote(null), 5000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [note]);
|
||||
|
||||
if (!targets.length) {
|
||||
return (
|
||||
<button onClick={() => navigate("/delivery")} title={t.noTargetsHelp} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.setUpDelivery}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const photos = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY");
|
||||
const send = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
// Without a network (or photos still uploading) the request waits on this computer and goes when it can.
|
||||
const r = await deliver(api, orgId, targetId, photos.map((p) => p.id));
|
||||
prefs.set(LAST_TARGET, targetId);
|
||||
props.onQueued(r.queued);
|
||||
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
|
||||
} catch (err) {
|
||||
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
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, again: bestAgain });
|
||||
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="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) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
<button
|
||||
onClick={() => void send()}
|
||||
disabled={busy || !photos.length || !targetId}
|
||||
title={photos.length ? `${t.sendTo} ${targets.find((x) => x.id === targetId)?.name ?? ""}` : t.selectToSend}
|
||||
className="h-6 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
|
||||
>
|
||||
{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>
|
||||
<label className="flex items-center gap-2 text-muted">
|
||||
<input type="checkbox" checked={bestAgain} onChange={(e) => setBestAgain(e.target.checked)} />
|
||||
{t.bestAgain}
|
||||
</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,29 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "./active.js";
|
||||
import { ALL_PHOTOS } from "./store.js";
|
||||
|
||||
describe("active photo across modules", () => {
|
||||
beforeEach(() => window.localStorage.clear());
|
||||
|
||||
it("remembers the photo you were on for its folder, and the library filter", () => {
|
||||
expect(activePhoto("o1", "e1")).toBeNull();
|
||||
setActivePhoto("o1", "e1", "p7");
|
||||
expect(activePhoto("o1", "e1")).toBe("p7");
|
||||
// Another folder (or organization) does not open on it.
|
||||
expect(activePhoto("o1", "e2")).toBeNull();
|
||||
expect(activePhoto("o2", "e1")).toBeNull();
|
||||
// Search results are not a folder to come back to.
|
||||
setActivePhoto("o1", "search:Rui", "p9");
|
||||
expect(activePhoto("o1", "e1")).toBe("p7");
|
||||
|
||||
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
|
||||
const picksToSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
|
||||
saveFilter("o1", picksToSend);
|
||||
expect(savedFilter("o1")).toEqual(picksToSend);
|
||||
// A filter saved by the previous version (one choice) still opens.
|
||||
window.localStorage.setItem("pr.filter:o1", "stars");
|
||||
expect(savedFilter("o1")).toEqual({ ...ALL_PHOTOS, minRating: 3 });
|
||||
window.localStorage.setItem("pr.filter:o1", "nonsense");
|
||||
expect(savedFilter("o1")).toEqual(ALL_PHOTOS);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { prefs } from "../platform.js";
|
||||
import { ALL_PHOTOS, type LibraryFilter } from "./store.js";
|
||||
|
||||
/**
|
||||
* Lightroom's active photo: the one every module opens on. Library (grid and loupe) and Develop share it, so
|
||||
* going from one to the other (D, G, E or the module links) stays on the photo you were on. Kept per
|
||||
* organization with the folder (event, inbox) it belongs to, and survives a reload.
|
||||
*/
|
||||
interface ActivePhoto {
|
||||
scope: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
const activeKey = (orgId: string) => `active:${orgId}`;
|
||||
const filterKey = (orgId: string) => `filter:${orgId}`;
|
||||
|
||||
/** The active photo of that folder, if there is one. */
|
||||
export function activePhoto(orgId: string, scope: string | null | undefined): string | null {
|
||||
if (!orgId || !scope) return null;
|
||||
try {
|
||||
const v = JSON.parse(prefs.get(activeKey(orgId)) ?? "null") as ActivePhoto | null;
|
||||
return v && typeof v.id === "string" && v.scope === scope ? v.id : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setActivePhoto(orgId: string, scope: string | null | undefined, id: string | null | undefined): void {
|
||||
if (!orgId || !scope || !id || scope.startsWith("search:")) return;
|
||||
prefs.set(activeKey(orgId), JSON.stringify({ scope, id } satisfies ActivePhoto));
|
||||
}
|
||||
|
||||
/** Filters saved by earlier versions (one choice at a time). */
|
||||
const LEGACY: Record<string, Partial<LibraryFilter>> = {
|
||||
all: {},
|
||||
PICK: { flag: "PICK" },
|
||||
UNREJECTED: { flag: "UNREJECTED" },
|
||||
REJECT: { flag: "REJECT" },
|
||||
stars: { minRating: 3 },
|
||||
noPlayers: { noPlayers: true },
|
||||
};
|
||||
const FLAGS = ["all", "PICK", "UNREJECTED", "REJECT", "UNFLAGGED"];
|
||||
const DELIVERY = ["any", "unsent", "queued", "sent", "failed"];
|
||||
const COLORS = ["RED", "YELLOW", "GREEN", "BLUE", "PURPLE"];
|
||||
|
||||
/** The library filter, which Develop's filmstrip follows too (as Lightroom's filmstrip does). */
|
||||
export function savedFilter(orgId: string): LibraryFilter {
|
||||
const raw = prefs.get(filterKey(orgId));
|
||||
if (!raw) return ALL_PHOTOS;
|
||||
if (raw in LEGACY) return { ...ALL_PHOTOS, ...LEGACY[raw] };
|
||||
try {
|
||||
const v = JSON.parse(raw) as Partial<LibraryFilter>;
|
||||
return {
|
||||
flag: FLAGS.includes(v.flag as string) ? v.flag! : "all",
|
||||
minRating: Number.isInteger(v.minRating) && v.minRating! >= 0 && v.minRating! <= 5 ? v.minRating! : 0,
|
||||
color: COLORS.includes(v.color as string) ? v.color! : null,
|
||||
delivery: DELIVERY.includes(v.delivery as string) ? v.delivery! : "any",
|
||||
noPlayers: v.noPlayers === true,
|
||||
};
|
||||
} catch {
|
||||
return ALL_PHOTOS;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveFilter(orgId: string, filter: LibraryFilter): void {
|
||||
if (orgId) prefs.set(filterKey(orgId), JSON.stringify(filter));
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fileZillaDir, importCandidates, parsePmAccounts, parsePmSnapshot } from "./importSources.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,313 @@
|
||||
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;
|
||||
/** Saved passwords the desktop app could read, by `passwordKey` (older apps: none). */
|
||||
passwords?: Record<string, string>;
|
||||
/** Keys of saved passwords that are encrypted (typed by hand). */
|
||||
unreadable?: string[];
|
||||
}
|
||||
|
||||
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;
|
||||
/** Where its saved password is found in `ImportSources.passwords` (the account or site). */
|
||||
passwordKey: string;
|
||||
}
|
||||
|
||||
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",
|
||||
passwordKey: `pm:${kind}:${accountName}`,
|
||||
});
|
||||
}
|
||||
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",
|
||||
passwordKey: `pm:${kind}:${account.name}`,
|
||||
});
|
||||
}
|
||||
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",
|
||||
passwordKey: `fz:${name}:${host}`,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -2,10 +2,11 @@ import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { isDesktop, localOriginal } from "../platform.js";
|
||||
import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js";
|
||||
import { useLocalFtp } from "./LocalFtp.js";
|
||||
import { useLibraryLive } from "./realtime.js";
|
||||
import { useUploadQueue } from "./uploads.js";
|
||||
import { useOfflineSync } from "../offline/sync.js";
|
||||
|
||||
type Ingest = { uploads: ReturnType<typeof useUploadQueue>; localFtp: ReturnType<typeof useLocalFtp>; desktop: boolean };
|
||||
|
||||
@@ -27,7 +28,8 @@ export function IngestProvider({ children }: { children: ReactNode }) {
|
||||
function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>["api"]; orgId: string; children: ReactNode }) {
|
||||
const desktop = isDesktop();
|
||||
const uploads = useUploadQueue(api, orgId);
|
||||
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId);
|
||||
const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId);
|
||||
useOfflineSync(api, orgId);
|
||||
return (
|
||||
<IngestContext.Provider value={{ uploads, localFtp, desktop }}>
|
||||
{desktop && !!orgId && <OriginalResponder api={api} add={uploads.add} />}
|
||||
@@ -47,15 +49,24 @@ function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"
|
||||
(m: LibraryMessage) => {
|
||||
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
|
||||
sending.current.add(m.sha256);
|
||||
void localOriginal(m.sha256).then((bytes) => {
|
||||
if (!bytes) {
|
||||
sending.current.delete(m.sha256);
|
||||
void localOriginal(m.sha256).then(async (bytes) => {
|
||||
if (bytes) {
|
||||
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
|
||||
return;
|
||||
}
|
||||
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
|
||||
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
|
||||
// photo's original, which the server checks is the same photo.
|
||||
try {
|
||||
const changed = await localOriginalChanged(m.sha256);
|
||||
if (changed) await api.sendOriginal(m.photoId, new Blob([changed], { type: "image/jpeg" }), `${m.sha256}.jpg`);
|
||||
} catch {
|
||||
/* not the same photo, or offline: asked again later */
|
||||
} finally {
|
||||
sending.current.delete(m.sha256);
|
||||
}
|
||||
});
|
||||
},
|
||||
[add],
|
||||
[add, api],
|
||||
);
|
||||
useLibraryLive(api, onMessage);
|
||||
return null;
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { initialLibrary, libraryReducer, matchesFilter, patchForKey } from "./store.js";
|
||||
import { ALL_PHOTOS, initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "./store.js";
|
||||
|
||||
const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}): PhotoSummary => ({
|
||||
id,
|
||||
@@ -60,7 +60,49 @@ describe("library store", () => {
|
||||
expect(patchForKey("4")).toEqual({ rating: 4 });
|
||||
expect(patchForKey("6")).toEqual({ colorLabel: "RED" });
|
||||
expect(patchForKey("q")).toBeUndefined();
|
||||
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), "UNREJECTED")).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { players: ["x"] }), "noPlayers")).toBe(false);
|
||||
const f = (patch: Partial<LibraryFilter>) => ({ ...ALL_PHOTOS, ...patch });
|
||||
expect(matchesFilter(photo("a", "", { flag: "REJECT" }), f({ flag: "UNREJECTED" }))).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { players: ["x"] }), f({ noPlayers: true }))).toBe(false);
|
||||
});
|
||||
|
||||
it("combines filters as Photo Mechanic does: picks with 2+ stars not sent yet", () => {
|
||||
const toSend = { ...ALL_PHOTOS, flag: "PICK" as const, minRating: 2, delivery: "unsent" as const };
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3 }), toSend)).toBe(true);
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 3, delivery: "DONE" }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 1 }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { flag: "NONE", rating: 5 }), toSend)).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), { ...ALL_PHOTOS, color: "GREEN" })).toBe(false);
|
||||
expect(matchesFilter(photo("a", "", { delivery: "FAILED" }), { ...ALL_PHOTOS, delivery: "failed" })).toBe(true);
|
||||
});
|
||||
|
||||
it("follows deliveries live: on its way, then sent (a later failure elsewhere doesn't undo sent)", () => {
|
||||
const item = (status: "QUEUED" | "DONE" | "FAILED") => ({ id: "i", targetId: "t", photoId: "a", eventId: "e1", sequence: 1, status, attempts: 0, lastError: null, remotePath: null, byteSize: null, updatedAt: "" });
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("QUEUED") } });
|
||||
expect(s.photos[0]!.delivery).toBe("QUEUED");
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("DONE") } });
|
||||
s = libraryReducer(s, { type: "message", message: { type: "delivery.updated", item: item("FAILED") } });
|
||||
expect(s.photos[0]!.delivery).toBe("DONE");
|
||||
});
|
||||
|
||||
it("comes back to the active photo from another module, once its page arrives, unless you pick one first", () => {
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "c" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
|
||||
// Not on the first page yet: the first photo shows meanwhile.
|
||||
expect(s.focus).toBe("a");
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
|
||||
expect([s.focus, [...s.selected], s.wanted]).toEqual(["c", ["c"], null]);
|
||||
|
||||
let t = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "d" });
|
||||
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("a", "1"), photo("b", "2")], done: false });
|
||||
t = libraryReducer(t, { type: "select", id: "b", mode: "single", visible: ["a", "b"] });
|
||||
t = libraryReducer(t, { type: "loaded", scope: "e1", photos: [photo("c", "3"), photo("d", "4")], done: true });
|
||||
expect(t.focus).toBe("b");
|
||||
|
||||
// Gone (deleted, moved): the first photo, and nothing left to look for.
|
||||
let u = libraryReducer(initialLibrary, { type: "load", scope: "e1", focus: "zz" });
|
||||
u = libraryReducer(u, { type: "loaded", scope: "e1", photos: [photo("a", "1")], done: true });
|
||||
expect([u.focus, u.wanted]).toEqual(["a", null]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ColorLabel, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
|
||||
/** Photos of the open event (or the inbox), in capture order, plus the selection. */
|
||||
export interface LibraryState {
|
||||
@@ -9,18 +9,22 @@ export interface LibraryState {
|
||||
/** The photo keyboard actions start from (and the one shown in the loupe). */
|
||||
focus: string | null;
|
||||
anchor: string | null;
|
||||
/** The active photo to come back to once its page has loaded (the folder may be long). */
|
||||
wanted: string | null;
|
||||
}
|
||||
|
||||
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null };
|
||||
export const initialLibrary: LibraryState = { scope: null, photos: [], loading: false, selected: new Set(), focus: null, anchor: null, wanted: null };
|
||||
|
||||
export type LibraryAction =
|
||||
| { type: "load"; scope: string }
|
||||
| { type: "load"; scope: string; focus?: string | null }
|
||||
| { type: "loaded"; scope: string; photos: PhotoSummary[]; done: boolean }
|
||||
| { type: "message"; message: LibraryMessage }
|
||||
| { type: "patch"; ids: string[]; patch: PhotoPatch }
|
||||
| { type: "select"; id: string; mode: "single" | "toggle" | "range"; visible: string[] }
|
||||
| { type: "selectAll"; visible: string[] }
|
||||
| { type: "move"; delta: number; visible: string[]; extend: boolean };
|
||||
| { type: "move"; delta: number; visible: string[]; extend: boolean }
|
||||
/** The photos still only on this computer (local FTP): those of this folder show, the others leave. */
|
||||
| { type: "local"; photos: PhotoSummary[] };
|
||||
|
||||
const byCapture = (a: PhotoSummary, b: PhotoSummary) =>
|
||||
(a.capturedAt ?? "").localeCompare(b.capturedAt ?? "") || a.originalName.localeCompare(b.originalName);
|
||||
@@ -40,25 +44,59 @@ function inScope(scope: string | null, photo: PhotoSummary): boolean {
|
||||
return scope === "inbox" ? photo.eventId === null : photo.eventId === scope;
|
||||
}
|
||||
|
||||
/** The server's copy replaces a local photo: what was done to it here stays (it is being sent too). */
|
||||
function replaceLocal(state: LibraryState, local: PhotoSummary, server: PhotoSummary): LibraryState {
|
||||
const keep: Partial<PhotoSummary> = {
|
||||
...(local.flag !== "NONE" && { flag: local.flag }),
|
||||
...(local.rating && { rating: local.rating }),
|
||||
...(local.colorLabel !== "NONE" && { colorLabel: local.colorLabel }),
|
||||
...(local.players.length && { players: local.players }),
|
||||
};
|
||||
const merged = { ...server, ...keep };
|
||||
const swap = (id: string | null) => (id === local.id ? server.id : id);
|
||||
const photos = inScope(state.scope, merged) ? state.photos.map((p) => (p.id === local.id ? merged : p)).filter((p, i, all) => all.findIndex((q) => q.id === p.id) === i) : state.photos.filter((p) => p.id !== local.id);
|
||||
return { ...state, photos, selected: new Set([...state.selected].map((id) => swap(id)!)), focus: swap(state.focus), anchor: swap(state.anchor), wanted: swap(state.wanted) };
|
||||
}
|
||||
|
||||
export function libraryReducer(state: LibraryState, action: LibraryAction): LibraryState {
|
||||
switch (action.type) {
|
||||
case "load":
|
||||
return { ...initialLibrary, scope: action.scope, loading: true };
|
||||
return { ...initialLibrary, scope: action.scope, loading: true, wanted: action.focus ?? null };
|
||||
case "loaded": {
|
||||
if (action.scope !== state.scope) return state;
|
||||
const seen = new Set(state.photos.map((p) => p.id));
|
||||
const photos = [...state.photos, ...action.photos.filter((p) => !seen.has(p.id))];
|
||||
// The active photo from another module (or the last visit): selected as soon as its page arrives.
|
||||
if (state.wanted && photos.some((p) => p.id === state.wanted)) {
|
||||
const id = state.wanted;
|
||||
return { ...state, photos, loading: !action.done, focus: id, selected: new Set([id]), anchor: id, wanted: null };
|
||||
}
|
||||
const focus = state.focus ?? photos[0]?.id ?? null;
|
||||
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus };
|
||||
const wanted = action.done ? null : state.wanted;
|
||||
return { ...state, photos, loading: !action.done, focus, selected: state.selected.size || !focus ? state.selected : new Set([focus]), anchor: state.anchor ?? focus, wanted };
|
||||
}
|
||||
case "message": {
|
||||
const m = action.message;
|
||||
if (m.type === "photo.added") {
|
||||
// The server's copy of a photo shown from this computer: it takes the local one's place (and selection).
|
||||
const local = state.photos.find((p) => p.id.startsWith("local:") && p.sha256 === m.photo.sha256);
|
||||
if (local) return replaceLocal(state, local, m.photo);
|
||||
if (!inScope(state.scope, m.photo) || state.photos.some((p) => p.id === m.photo.id)) return state;
|
||||
return { ...state, photos: [...state.photos, m.photo].sort(byCapture) };
|
||||
}
|
||||
if (m.type === "photo.updated") return libraryReducer(state, { type: "patch", ids: m.ids, patch: m.patch });
|
||||
if (m.type === "photo.edited") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, developSeq: m.developSeq } : p)) };
|
||||
if (m.type === "delivery.updated") {
|
||||
const { photoId, status } = m.item;
|
||||
return {
|
||||
...state,
|
||||
photos: state.photos.map((p) => {
|
||||
if (p.id !== photoId || p.delivery === "DONE") return p;
|
||||
const delivery = status === "DONE" ? "DONE" : status === "FAILED" ? (p.delivery === "QUEUED" ? "QUEUED" : "FAILED") : "QUEUED";
|
||||
return { ...p, delivery };
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (m.type === "photo.rendered") return { ...state, photos: state.photos.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)) };
|
||||
return state;
|
||||
}
|
||||
@@ -69,9 +107,23 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
if (action.patch.eventId !== undefined) photos = photos.filter((p) => inScope(state.scope, p));
|
||||
return { ...state, photos };
|
||||
}
|
||||
case "local": {
|
||||
const here = action.photos.filter((p) => inScope(state.scope, p) && !state.photos.some((q) => !q.id.startsWith("local:") && q.sha256 === p.sha256));
|
||||
const ids = new Set(here.map((p) => p.id));
|
||||
const kept = state.photos.filter((p) => !p.id.startsWith("local:") || ids.has(p.id));
|
||||
const byId = new Map(here.map((p) => [p.id, p]));
|
||||
const merged = kept.map((p) => byId.get(p.id) ?? p);
|
||||
const added = here.filter((p) => !kept.some((q) => q.id === p.id));
|
||||
if (!added.length && merged.length === state.photos.length && merged.every((p, i) => p === state.photos[i])) return state;
|
||||
const photos = [...merged, ...added].sort(byCapture);
|
||||
const gone = (id: string | null) => id !== null && id.startsWith("local:") && !ids.has(id);
|
||||
const selected = new Set([...state.selected].filter((id) => !gone(id)));
|
||||
return { ...state, photos, selected, focus: gone(state.focus) ? null : state.focus, anchor: gone(state.anchor) ? null : state.anchor };
|
||||
}
|
||||
case "select": {
|
||||
const { id, mode, visible } = action;
|
||||
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id };
|
||||
// Picking a photo by hand wins over the one still being looked for.
|
||||
if (mode === "single") return { ...state, selected: new Set([id]), focus: id, anchor: id, wanted: null };
|
||||
if (mode === "toggle") {
|
||||
const selected = new Set(state.selected);
|
||||
if (selected.has(id)) selected.delete(id);
|
||||
@@ -92,28 +144,43 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
|
||||
const at = state.focus ? visible.indexOf(state.focus) : -1;
|
||||
const next = visible[Math.max(0, Math.min(visible.length - 1, at < 0 ? 0 : at + delta))]!;
|
||||
if (extend) return libraryReducer({ ...state }, { type: "select", id: next, mode: "range", visible });
|
||||
return { ...state, selected: new Set([next]), focus: next, anchor: next };
|
||||
return { ...state, selected: new Set([next]), focus: next, anchor: next, wanted: null };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type FilterId = "all" | "PICK" | "UNREJECTED" | "REJECT" | "stars" | "noPlayers";
|
||||
/**
|
||||
* The library filter, combinable as in Photo Mechanic and Lightroom's filter bar: flag, minimum stars, colour,
|
||||
* delivery state and photos still without players. Every part narrows; the defaults show everything.
|
||||
*/
|
||||
export interface LibraryFilter {
|
||||
flag: "all" | "PICK" | "UNREJECTED" | "REJECT" | "UNFLAGGED";
|
||||
minRating: number;
|
||||
color: ColorLabel | null;
|
||||
delivery: "any" | "unsent" | "queued" | "sent" | "failed";
|
||||
noPlayers: boolean;
|
||||
}
|
||||
|
||||
export function matchesFilter(photo: PhotoSummary, filter: FilterId): boolean {
|
||||
switch (filter) {
|
||||
case "all":
|
||||
return true;
|
||||
case "PICK":
|
||||
return photo.flag === "PICK";
|
||||
case "REJECT":
|
||||
return photo.flag === "REJECT";
|
||||
case "UNREJECTED":
|
||||
return photo.flag !== "REJECT";
|
||||
case "stars":
|
||||
return photo.rating >= 3;
|
||||
case "noPlayers":
|
||||
return photo.players.length === 0;
|
||||
}
|
||||
export const ALL_PHOTOS: LibraryFilter = { flag: "all", minRating: 0, color: null, delivery: "any", noPlayers: false };
|
||||
|
||||
export function isAll(f: LibraryFilter): boolean {
|
||||
return f.flag === "all" && !f.minRating && !f.color && f.delivery === "any" && !f.noPlayers;
|
||||
}
|
||||
|
||||
export function matchesFilter(photo: PhotoSummary, f: LibraryFilter): boolean {
|
||||
if (f.flag === "PICK" && photo.flag !== "PICK") return false;
|
||||
if (f.flag === "REJECT" && photo.flag !== "REJECT") return false;
|
||||
if (f.flag === "UNREJECTED" && photo.flag === "REJECT") return false;
|
||||
if (f.flag === "UNFLAGGED" && photo.flag !== "NONE") return false;
|
||||
if (f.minRating && photo.rating < f.minRating) return false;
|
||||
if (f.color && photo.colorLabel !== f.color) return false;
|
||||
const d = photo.delivery ?? "NONE";
|
||||
if (f.delivery === "unsent" && d !== "NONE") return false;
|
||||
if (f.delivery === "queued" && d !== "QUEUED") return false;
|
||||
if (f.delivery === "sent" && d !== "DONE") return false;
|
||||
if (f.delivery === "failed" && d !== "FAILED") return false;
|
||||
if (f.noPlayers && photo.players.length) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Lightroom keys: P pick, X reject, U unflag, 0–5 stars, 6–9 colour labels (red, yellow, green, blue). */
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
|
||||
export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed";
|
||||
@@ -9,7 +11,7 @@ export interface UploadItem {
|
||||
size: number;
|
||||
status: UploadStatus;
|
||||
progress: number;
|
||||
error?: string;
|
||||
error?: string | undefined;
|
||||
}
|
||||
|
||||
const CONCURRENCY = 4;
|
||||
@@ -63,20 +65,23 @@ export interface PreviewOf {
|
||||
height: number;
|
||||
}
|
||||
|
||||
/** What a desktop ingest sends: a preview standing for its original, or the full original ("original"). */
|
||||
export type DesktopOrigin = PreviewOf | "original";
|
||||
|
||||
export async function sendResumable(
|
||||
api: ApiClient,
|
||||
orgId: string,
|
||||
file: File,
|
||||
eventId: string | undefined,
|
||||
onProgress: (p: number) => void,
|
||||
original?: PreviewOf,
|
||||
origin?: DesktopOrigin,
|
||||
): Promise<{ status: number; body: unknown }> {
|
||||
const fingerprint = `${file.name}:${file.size}:${file.lastModified}`;
|
||||
const begin = await xhr(
|
||||
"POST",
|
||||
api.absolute(`/v1/orgs/${orgId}/uploads/resumable`),
|
||||
await api.realtimeToken(),
|
||||
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(original && { original }) }),
|
||||
JSON.stringify({ name: file.name, size: file.size, fingerprint, ...(eventId && { eventId }), ...(origin === "original" ? { desktop: true } : origin ? { original: origin } : {}) }),
|
||||
"application/json",
|
||||
);
|
||||
if (begin.status !== 200 && begin.status !== 201) return begin;
|
||||
@@ -131,21 +136,26 @@ export async function sendResumable(
|
||||
*/
|
||||
export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
const [items, setItems] = useState<UploadItem[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: PreviewOf; onSettled?: (status: UploadStatus) => void }[]>([]);
|
||||
const queue = useRef<{ item: UploadItem; file: File; eventId: string | undefined; original?: DesktopOrigin; onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void }[]>([]);
|
||||
const running = useRef(0);
|
||||
/** No network: the queue waits (nothing fails) and carries on when the connection is back. */
|
||||
const paused = useRef(false);
|
||||
const resume = useRef<() => void>(() => {});
|
||||
|
||||
const update = useCallback((id: string, patch: Partial<UploadItem>) => {
|
||||
setItems((list) => list.map((i) => (i.id === id ? { ...i, ...patch } : i)));
|
||||
}, []);
|
||||
|
||||
const pump = useCallback(() => {
|
||||
while (running.current < CONCURRENCY && queue.current.length) {
|
||||
while (!paused.current && running.current < CONCURRENCY && queue.current.length) {
|
||||
const next = queue.current.shift()!;
|
||||
running.current++;
|
||||
void (async () => {
|
||||
const { item, file, eventId, original, onSettled } = next;
|
||||
let final: UploadStatus = "failed";
|
||||
update(item.id, { status: "uploading" });
|
||||
let filed: PhotoSummary | undefined;
|
||||
let waiting = false;
|
||||
update(item.id, { status: "uploading", error: undefined });
|
||||
try {
|
||||
let lastTick = 0;
|
||||
const res = await sendResumable(
|
||||
@@ -163,26 +173,45 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
original,
|
||||
);
|
||||
// The server took the file but could not read it as a photo: not sent (FTP keeps the original in ingest).
|
||||
const unreadable = (res.body as { photo?: { status?: string } } | null)?.photo?.status === "FAILED";
|
||||
if (unreadable) res.body = { error: "processing_failed" };
|
||||
const photo = (res.body as { photo?: PhotoSummary } | null)?.photo;
|
||||
if (photo?.status === "FAILED") res.body = { error: photo.error ? `processing_failed: ${photo.error}` : "processing_failed" };
|
||||
else if (res.status === 201) final = "done";
|
||||
else if (res.status === 200) final = "duplicate";
|
||||
else if (res.status === 0 || res.status === 502 || res.status === 503 || res.status === 504) throw new Error("network");
|
||||
if (photo && final !== "failed") filed = photo;
|
||||
if (final === "failed") update(item.id, { status: "failed", error: (res.body as { error?: string } | null)?.error ?? `http_${res.status}` });
|
||||
else update(item.id, { status: final, progress: 1 });
|
||||
} catch (err) {
|
||||
update(item.id, { status: "failed", error: (err as Error).message });
|
||||
if (isNetworkError(err)) {
|
||||
// No network (or the server is down): back to the front of the queue, which waits for the connection.
|
||||
waiting = true;
|
||||
update(item.id, { status: "queued", progress: 0, error: "offline" });
|
||||
queue.current.unshift(next);
|
||||
if (!paused.current) {
|
||||
paused.current = true;
|
||||
const again = () => {
|
||||
window.removeEventListener("online", again);
|
||||
clearTimeout(timer);
|
||||
paused.current = false;
|
||||
resume.current();
|
||||
};
|
||||
const timer = setTimeout(again, 15_000);
|
||||
window.addEventListener("online", again);
|
||||
}
|
||||
} else update(item.id, { status: "failed", error: (err as Error).message });
|
||||
} finally {
|
||||
onSettled?.(final);
|
||||
if (!waiting) onSettled?.(final, filed);
|
||||
running.current--;
|
||||
pump();
|
||||
}
|
||||
})();
|
||||
}
|
||||
}, [api, orgId, update]);
|
||||
resume.current = pump;
|
||||
|
||||
const add = useCallback(
|
||||
/** `onSettled` is called once per accepted file, after it is sent (or definitely failed). */
|
||||
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus) => void, original?: PreviewOf) => {
|
||||
(files: Iterable<File>, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => {
|
||||
const added: UploadItem[] = [];
|
||||
for (const file of files) {
|
||||
const item: UploadItem = { id: crypto.randomUUID(), name: file.name, size: file.size, status: "queued", progress: 0 };
|
||||
@@ -192,7 +221,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
|
||||
continue;
|
||||
}
|
||||
added.push(item);
|
||||
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus) => onSettled(file, status) }) });
|
||||
queue.current.push({ item, file, eventId, ...(original && { original }), ...(onSettled && { onSettled: (status: UploadStatus, photo?: PhotoSummary) => onSettled(file, status, photo) }) });
|
||||
}
|
||||
setItems((list) => [...list.filter((i) => i.status !== "done" && i.status !== "duplicate"), ...added]);
|
||||
pump();
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { kv } from "./kv.js";
|
||||
|
||||
/**
|
||||
* The last thing the server said, kept on this computer so the modules open without a network: the events, each
|
||||
* folder's photos, the edit state of photos opened in Revelar, and the thumbnails and previews already seen.
|
||||
*/
|
||||
|
||||
export interface CachedEvents {
|
||||
events: EventSummary[];
|
||||
inboxCount: number;
|
||||
}
|
||||
|
||||
export const cache = {
|
||||
events: (orgId: string) => kv.get<CachedEvents>(`events:${orgId}`),
|
||||
setEvents: (orgId: string, v: CachedEvents) => kv.set(`events:${orgId}`, v),
|
||||
photos: (orgId: string, scope: string) => kv.get<PhotoSummary[]>(`photos:${orgId}:${scope}`),
|
||||
setPhotos: (orgId: string, scope: string, photos: PhotoSummary[]) => kv.set(`photos:${orgId}:${scope}`, photos.filter((p) => !p.id.startsWith("local:"))),
|
||||
/** The edit state of a photo (settings JSON and the op-log position it stands for). */
|
||||
develop: (photoId: string) => kv.get<{ settings: string; seq: number }>(`develop:${photoId}`),
|
||||
setDevelop: (photoId: string, v: { settings: string; seq: number }) => kv.set(`develop:${photoId}`, v),
|
||||
};
|
||||
|
||||
/** A stable key for an image URL: the path and the edit version (the signature and expiry change, the image doesn't). */
|
||||
export function imageKey(url: string): string {
|
||||
try {
|
||||
const u = new URL(url, "http://x");
|
||||
return `img:${u.pathname}@${u.searchParams.get("v") ?? "0"}`;
|
||||
} catch {
|
||||
return `img:${url}`;
|
||||
}
|
||||
}
|
||||
|
||||
/** A few downloads at a time: a grid of 500 thumbnails must not open 500 connections. */
|
||||
const MAX_FETCHES = 6;
|
||||
let active = 0;
|
||||
const waiting: (() => void)[] = [];
|
||||
async function slot<T>(fn: () => Promise<T>): Promise<T> {
|
||||
if (active >= MAX_FETCHES) await new Promise<void>((r) => waiting.push(r));
|
||||
active++;
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
active--;
|
||||
waiting.shift()?.();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The image as a blob URL: from this computer when it was seen before, else downloaded once and kept. Null when it
|
||||
* can't be had (offline and never seen). The caller revokes the URL when done.
|
||||
*/
|
||||
export async function cachedImage(url: string): Promise<string | null> {
|
||||
if (url.startsWith("blob:") || url.startsWith("data:")) return url;
|
||||
const key = imageKey(url);
|
||||
const kept = await kv.get<Blob>(key);
|
||||
if (kept) return URL.createObjectURL(kept);
|
||||
try {
|
||||
const blob = await slot(async () => {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(`http_${res.status}`);
|
||||
return res.blob();
|
||||
});
|
||||
void kv.set(key, blob);
|
||||
return URL.createObjectURL(blob);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The image to show for `url`, through the cache on the desktop app (so it shows again without a network); in the
|
||||
* browser, the URL itself.
|
||||
*/
|
||||
export function useCachedImage(url: string | null, enabled: boolean): string | null {
|
||||
const [src, setSrc] = useState<string | null>(enabled ? null : url);
|
||||
useEffect(() => {
|
||||
if (!enabled || !url) {
|
||||
setSrc(url);
|
||||
return;
|
||||
}
|
||||
let alive = true;
|
||||
let made: string | null = null;
|
||||
void cachedImage(url).then((s) => {
|
||||
if (s && s !== url && s.startsWith("blob:")) made = s;
|
||||
if (alive) setSrc(s ?? url);
|
||||
else if (made) URL.revokeObjectURL(made);
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
if (made) URL.revokeObjectURL(made);
|
||||
};
|
||||
}, [url, enabled]);
|
||||
return src;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* A small key-value store on IndexedDB, for what the app keeps to work without a network (photo lists, thumbnails,
|
||||
* edit states). Where IndexedDB is missing or refuses (tests, private windows) it falls back to memory: the app
|
||||
* still works, it just doesn't keep anything across restarts.
|
||||
*/
|
||||
|
||||
const DB = "photoreport-offline";
|
||||
const STORE = "kv";
|
||||
|
||||
let opening: Promise<IDBDatabase | null> | null = null;
|
||||
const memory = new Map<string, unknown>();
|
||||
|
||||
function open(): Promise<IDBDatabase | null> {
|
||||
opening ??= new Promise((resolve) => {
|
||||
try {
|
||||
if (typeof indexedDB === "undefined") return resolve(null);
|
||||
const req = indexedDB.open(DB, 1);
|
||||
req.onupgradeneeded = () => req.result.createObjectStore(STORE);
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => resolve(null);
|
||||
req.onblocked = () => resolve(null);
|
||||
} catch {
|
||||
resolve(null);
|
||||
}
|
||||
});
|
||||
return opening;
|
||||
}
|
||||
|
||||
function run<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T | undefined> {
|
||||
return open().then(
|
||||
(db) =>
|
||||
new Promise<T | undefined>((resolve) => {
|
||||
if (!db) return resolve(undefined);
|
||||
try {
|
||||
const req = fn(db.transaction(STORE, mode).objectStore(STORE));
|
||||
req.onsuccess = () => resolve(req.result);
|
||||
req.onerror = () => resolve(undefined);
|
||||
} catch {
|
||||
resolve(undefined);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const kv = {
|
||||
async get<T>(key: string): Promise<T | undefined> {
|
||||
const db = await open();
|
||||
if (!db) return memory.get(key) as T | undefined;
|
||||
return (await run<T>("readonly", (s) => s.get(key) as IDBRequest<T>)) ?? undefined;
|
||||
},
|
||||
async set(key: string, value: unknown): Promise<void> {
|
||||
const db = await open();
|
||||
if (!db) {
|
||||
memory.set(key, value);
|
||||
return;
|
||||
}
|
||||
await run("readwrite", (s) => s.put(value, key));
|
||||
},
|
||||
async del(key: string): Promise<void> {
|
||||
memory.delete(key);
|
||||
await run("readwrite", (s) => s.delete(key));
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import type { EventSummary } from "@photoreport/sdk";
|
||||
import { localId } from "./queue.js";
|
||||
|
||||
/**
|
||||
* Photos that arrived on this computer (local FTP) and are not on the server yet: they show in the library at once,
|
||||
* from a preview made here, and can be culled, named and edited like any other. When the upload finishes the
|
||||
* server's copy takes their place (with what was done to them meanwhile).
|
||||
*/
|
||||
|
||||
/** The capture time in a JPEG's EXIF (DateTimeOriginal, else DateTime), as written by the camera (local wall time). */
|
||||
export function exifDateTime(bytes: ArrayBuffer): string | null {
|
||||
const v = new DataView(bytes);
|
||||
if (v.byteLength < 4 || v.getUint16(0) !== 0xffd8) return null;
|
||||
let off = 2;
|
||||
while (off + 4 <= v.byteLength) {
|
||||
const marker = v.getUint16(off);
|
||||
const size = v.getUint16(off + 2);
|
||||
if (marker === 0xffe1 && off + 10 <= v.byteLength && v.getUint32(off + 4) === 0x45786966) return readTiff(v, off + 10, off + 2 + size);
|
||||
if ((marker & 0xff00) !== 0xff00 || marker === 0xffda) return null;
|
||||
off += 2 + size;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readTiff(v: DataView, start: number, end: number): string | null {
|
||||
if (start + 8 > end) return null;
|
||||
const little = v.getUint16(start) === 0x4949;
|
||||
const u16 = (o: number) => v.getUint16(start + o, little);
|
||||
const u32 = (o: number) => v.getUint32(start + o, little);
|
||||
const ascii = (o: number, n: number) => {
|
||||
let s = "";
|
||||
for (let i = 0; i < n && start + o + i < end; i++) {
|
||||
const c = v.getUint8(start + o + i);
|
||||
if (!c) break;
|
||||
s += String.fromCharCode(c);
|
||||
}
|
||||
return s;
|
||||
};
|
||||
const entries = (ifd: number) => {
|
||||
const out = new Map<number, number>();
|
||||
if (ifd <= 0 || start + ifd + 2 > end) return out;
|
||||
const n = u16(ifd);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const e = ifd + 2 + i * 12;
|
||||
if (start + e + 12 > end) break;
|
||||
out.set(u16(e), e);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const text = (entry: number | undefined) => {
|
||||
if (entry === undefined) return null;
|
||||
const count = u32(entry + 4);
|
||||
return ascii(count <= 4 ? entry + 8 : u32(entry + 8), count);
|
||||
};
|
||||
const ifd0 = entries(u32(4));
|
||||
const exifAt = ifd0.get(0x8769);
|
||||
const exif = exifAt !== undefined ? entries(u32(exifAt + 8)) : new Map<number, number>();
|
||||
return text(exif.get(0x9003)) ?? text(ifd0.get(0x0132));
|
||||
}
|
||||
|
||||
/** "2026:10:09 20:26:47" (Lisbon wall time, as the API reads it) to an ISO instant. */
|
||||
export function lisbonInstant(exif: string | null): string | null {
|
||||
const m = exif?.match(/^(\d{4}):(\d{2}):(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
|
||||
if (!m) return null;
|
||||
const [y, mo, d, h, mi, s] = m.slice(1).map(Number) as [number, number, number, number, number, number];
|
||||
if (!y) return null;
|
||||
const guess = Date.UTC(y, mo - 1, d, h, mi, s);
|
||||
// Lisbon's offset at that moment (summer +1, winter 0).
|
||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: "Europe/Lisbon", hour12: false, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(new Date(guess));
|
||||
const get = (t: string) => Number(parts.find((p) => p.type === t)?.value);
|
||||
const asLisbon = Date.UTC(get("year"), get("month") - 1, get("day"), get("hour") % 24, get("minute"), get("second"));
|
||||
return new Date(guess - (asLisbon - guess)).toISOString();
|
||||
}
|
||||
|
||||
/** The event a photo taken at `at` belongs to, as the server would route it (offline guess; the server decides). */
|
||||
export function routeLocally(events: Pick<EventSummary, "id" | "ingestFrom" | "ingestUntil" | "archivedAt" | "startsAt">[], at: string | null): string | null {
|
||||
if (!at) return null;
|
||||
const t = Date.parse(at);
|
||||
const open = events.filter((e) => !e.archivedAt && Date.parse(e.ingestFrom) <= t && t <= Date.parse(e.ingestUntil));
|
||||
open.sort((a, b) => Date.parse(b.startsAt) - Date.parse(a.startsAt));
|
||||
return open[0]?.id ?? null;
|
||||
}
|
||||
|
||||
export function localPhoto(p: { sha256: string; name: string; width: number; height: number; capturedAt: string | null; eventId: string | null; url: string }): PhotoSummary {
|
||||
return {
|
||||
id: localId(p.sha256),
|
||||
eventId: p.eventId,
|
||||
originalName: p.name,
|
||||
name: p.name,
|
||||
sha256: p.sha256,
|
||||
originalStored: false,
|
||||
status: "READY",
|
||||
delivery: "NONE",
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
capturedAt: p.capturedAt,
|
||||
cameraModel: null,
|
||||
lens: null,
|
||||
focalLength: null,
|
||||
aperture: null,
|
||||
exposureTime: null,
|
||||
iso: null,
|
||||
rating: 0,
|
||||
flag: "NONE",
|
||||
colorLabel: "NONE",
|
||||
players: [],
|
||||
uploader: null,
|
||||
developSeq: 0,
|
||||
urls: { thumb: p.url, preview: p.url, source: p.url },
|
||||
};
|
||||
}
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
/** The photos waiting here, shared by the modules (the library shows them, the FTP feed adds and removes them). */
|
||||
class LocalPhotos {
|
||||
private photos = new Map<string, PhotoSummary>();
|
||||
private listeners = new Set<Listener>();
|
||||
/** Bumped on every change, for React's useSyncExternalStore. */
|
||||
version = 0;
|
||||
|
||||
list(): PhotoSummary[] {
|
||||
return [...this.photos.values()];
|
||||
}
|
||||
|
||||
get(id: string): PhotoSummary | undefined {
|
||||
return this.photos.get(id);
|
||||
}
|
||||
|
||||
bySha(sha256: string): PhotoSummary | undefined {
|
||||
return this.photos.get(localId(sha256));
|
||||
}
|
||||
|
||||
put(photo: PhotoSummary): void {
|
||||
this.photos.set(photo.id, photo);
|
||||
this.changed();
|
||||
}
|
||||
|
||||
/** Culling and naming done to a photo still here: kept so it goes up with the photo. */
|
||||
patch(id: string, change: Partial<PhotoSummary>): void {
|
||||
const p = this.photos.get(id);
|
||||
if (!p) return;
|
||||
this.photos.set(id, { ...p, ...change });
|
||||
this.changed();
|
||||
}
|
||||
|
||||
remove(id: string): void {
|
||||
const p = this.photos.get(id);
|
||||
if (!p) return;
|
||||
this.photos.delete(id);
|
||||
if (p.urls.thumb.startsWith("blob:")) setTimeout(() => URL.revokeObjectURL(p.urls.thumb), 60_000);
|
||||
this.changed();
|
||||
}
|
||||
|
||||
subscribe(fn: Listener): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
this.version++;
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
}
|
||||
|
||||
export const localPhotos = new LocalPhotos();
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { PhotoSummary } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { initialLibrary, libraryReducer } from "../library/store.js";
|
||||
import { exifDateTime, lisbonInstant, localPhoto, routeLocally } from "./local.js";
|
||||
import { isNetworkError, localId, OfflineQueue } from "./queue.js";
|
||||
|
||||
function memoryStore() {
|
||||
const m = new Map<string, string>();
|
||||
return {
|
||||
get: (k: string) => m.get(k) ?? null,
|
||||
set: (k: string, v: string) => void m.set(k, v),
|
||||
remove: (k: string) => void m.delete(k),
|
||||
keys: () => [...m.keys()],
|
||||
m,
|
||||
};
|
||||
}
|
||||
|
||||
const offline = () => new TypeError("Failed to fetch");
|
||||
|
||||
describe("offline queue", () => {
|
||||
let store: ReturnType<typeof memoryStore>;
|
||||
beforeEach(() => (store = memoryStore()));
|
||||
|
||||
it("tells a missing network from a refusal", () => {
|
||||
expect(isNetworkError(offline())).toBe(true);
|
||||
expect(isNetworkError(new ApiError(503, "down", null))).toBe(true);
|
||||
expect(isNetworkError(new ApiError(403, "forbidden", null))).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps changes across restarts and sends them in order when the server answers", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.add({ kind: "patch", ids: ["p1"], patch: { flag: "PICK" } });
|
||||
q.add({ kind: "deliver", targetId: "t1", ids: ["p1"], again: false });
|
||||
// Restarted: the same queue comes back from disk.
|
||||
const again = new OfflineQueue("o1", store);
|
||||
expect(again.size).toBe(2);
|
||||
|
||||
const calls: string[] = [];
|
||||
let online = false;
|
||||
const api = {
|
||||
updatePhotos: vi.fn(async () => {
|
||||
if (!online) throw offline();
|
||||
calls.push("patch");
|
||||
return { updated: 1 };
|
||||
}),
|
||||
deliver: vi.fn(async () => {
|
||||
calls.push("deliver");
|
||||
return { queued: [], skipped: [] };
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
await again.flush(api);
|
||||
expect(again.size).toBe(2); // still no network: nothing lost, nothing out of order
|
||||
online = true;
|
||||
await again.flush(api);
|
||||
expect(calls).toEqual(["patch", "deliver"]);
|
||||
expect(again.size).toBe(0);
|
||||
});
|
||||
|
||||
it("holds the changes of a photo still on this computer until it is uploaded, then sends them to its server copy", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
const local = localId("abc");
|
||||
q.add({ kind: "patch", ids: [local], patch: { rating: 4 } });
|
||||
q.add({ kind: "patch", ids: ["p2"], patch: { flag: "REJECT" } });
|
||||
store.set(`pr:outbox:${local}`, JSON.stringify([{ opId: "o-1", command: { command: "develop.set", params: { values: { "light.exposure": 0.3 } } } }]));
|
||||
const sent: { ids: string[] }[] = [];
|
||||
const edits: string[] = [];
|
||||
const api = {
|
||||
updatePhotos: vi.fn(async (_o: string, ids: string[]) => {
|
||||
sent.push({ ids });
|
||||
return { updated: ids.length };
|
||||
}),
|
||||
postEdits: vi.fn(async (photoId: string) => {
|
||||
edits.push(photoId);
|
||||
return { developSeq: 1, ops: [] };
|
||||
}),
|
||||
} as unknown as ApiClient;
|
||||
await q.flush(api);
|
||||
// The other photo's change goes; the local one waits (with its edits).
|
||||
expect(sent).toEqual([{ ids: ["p2"] }]);
|
||||
expect(edits).toEqual([]);
|
||||
q.uploaded("abc", "server-1");
|
||||
await q.flush(api);
|
||||
expect(sent).toEqual([{ ids: ["p2"] }, { ids: ["server-1"] }]);
|
||||
expect(edits).toEqual(["server-1"]);
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
|
||||
it("drops what the server refuses for good", async () => {
|
||||
const q = new OfflineQueue("o1", store);
|
||||
q.add({ kind: "patch", ids: ["gone"], patch: { flag: "PICK" } });
|
||||
const api = { updatePhotos: vi.fn(async () => Promise.reject(new ApiError(404, "photo_not_found", null))) } as unknown as ApiClient;
|
||||
await q.flush(api);
|
||||
expect(q.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
/** A minimal JPEG with an EXIF DateTimeOriginal (big-endian TIFF). */
|
||||
function jpegWithDate(date: string): ArrayBuffer {
|
||||
const enc = new TextEncoder().encode(`${date}\0`);
|
||||
const tiff: number[] = [0x4d, 0x4d, 0, 42, 0, 0, 0, 8];
|
||||
// IFD0: one entry, ExifIFD pointer -> 26
|
||||
tiff.push(0, 1, 0x87, 0x69, 0, 4, 0, 0, 0, 1, 0, 0, 0, 26, 0, 0, 0, 0);
|
||||
// Exif IFD at 26: one entry, DateTimeOriginal ASCII count 20 at offset 44
|
||||
tiff.push(0, 1, 0x90, 0x03, 0, 2, 0, 0, 0, enc.length, 0, 0, 0, 44, 0, 0, 0, 0);
|
||||
tiff.push(...enc);
|
||||
const app1 = [0x45, 0x78, 0x69, 0x66, 0, 0, ...tiff];
|
||||
const size = app1.length + 2;
|
||||
return new Uint8Array([0xff, 0xd8, 0xff, 0xe1, size >> 8, size & 0xff, ...app1, 0xff, 0xd9]).buffer;
|
||||
}
|
||||
|
||||
describe("photos arriving on this computer", () => {
|
||||
it("reads the capture time and files it in the event of that time, as the server would", () => {
|
||||
const at = lisbonInstant(exifDateTime(jpegWithDate("2026:10:09 20:26:47")));
|
||||
expect(at).toBe("2026-10-09T19:26:47.000Z"); // Lisbon summer time
|
||||
expect(lisbonInstant("2026:12:05 21:14:07")).toBe("2026-12-05T21:14:07.000Z");
|
||||
const events = [
|
||||
{ id: "braga", startsAt: "2026-10-09T19:15:00Z", ingestFrom: "2026-10-09T17:15:00Z", ingestUntil: "2026-10-09T23:15:00Z", archivedAt: null },
|
||||
{ id: "other", startsAt: "2026-10-10T15:00:00Z", ingestFrom: "2026-10-10T13:00:00Z", ingestUntil: "2026-10-10T19:00:00Z", archivedAt: null },
|
||||
];
|
||||
expect(routeLocally(events, at)).toBe("braga");
|
||||
expect(routeLocally(events, "2026-09-03T15:00:00Z")).toBeNull();
|
||||
});
|
||||
|
||||
it("show in the library at once and give way to the server's copy, keeping what was done to them", () => {
|
||||
const local = { ...localPhoto({ sha256: "abc", name: "PSR1.JPG", width: 6000, height: 4000, capturedAt: "2026-10-09T19:26:47Z", eventId: "e1", url: "blob:x" }), flag: "PICK" as const, rating: 3 };
|
||||
let s = libraryReducer(initialLibrary, { type: "load", scope: "e1" });
|
||||
s = libraryReducer(s, { type: "loaded", scope: "e1", photos: [], done: true });
|
||||
s = libraryReducer(s, { type: "local", photos: [local] });
|
||||
expect(s.photos.map((p) => p.id)).toEqual([localId("abc")]);
|
||||
s = libraryReducer(s, { type: "select", id: localId("abc"), mode: "single", visible: [localId("abc")] });
|
||||
const server = { ...local, id: "server-1", urls: { thumb: "/t", preview: "/p", source: "/s" }, flag: "NONE" as const, rating: 0 } as PhotoSummary;
|
||||
s = libraryReducer(s, { type: "message", message: { type: "photo.added", photo: server } });
|
||||
expect(s.photos.map((p) => [p.id, p.flag, p.rating])).toEqual([["server-1", "PICK", 3]]);
|
||||
expect([...s.selected]).toEqual(["server-1"]);
|
||||
// The local store then lets it go: nothing changes.
|
||||
expect(libraryReducer(s, { type: "local", photos: [] }).photos.map((p) => p.id)).toEqual(["server-1"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import type { PhotoPatch } from "@photoreport/contracts";
|
||||
import { ApiError, type ApiClient } from "@photoreport/sdk";
|
||||
|
||||
/**
|
||||
* Working without a network: what the photographer does while the server can't be reached (culling, players,
|
||||
* IPTC, "send to") is kept on this computer, in order, and sent when the connection comes back. Photos that only
|
||||
* exist here yet (arrived by FTP while offline) have a local id, `local:<sha256>`; their changes wait until the photo
|
||||
* is on the server and its id is known.
|
||||
*/
|
||||
|
||||
export type QueuedOp =
|
||||
| { id: string; kind: "patch"; ids: string[]; patch: PhotoPatch }
|
||||
| { id: string; kind: "iptc"; ids: string[]; set: Record<string, string | string[] | null> }
|
||||
| { id: string; kind: "deliver"; targetId: string; ids: string[]; again: boolean };
|
||||
|
||||
export type NewOp = QueuedOp extends infer O ? (O extends QueuedOp ? Omit<O, "id"> : never) : never;
|
||||
|
||||
const LOCAL = "local:";
|
||||
export const isLocalId = (id: string) => id.startsWith(LOCAL);
|
||||
export const localId = (sha256: string) => `${LOCAL}${sha256}`;
|
||||
|
||||
/** The server could not be reached (or is down): worth trying again later, unlike a refusal. */
|
||||
export function isNetworkError(err: unknown): boolean {
|
||||
if (err instanceof ApiError) return err.status === 0 || err.status === 502 || err.status === 503 || err.status === 504;
|
||||
return err instanceof TypeError || (err instanceof Error && /network|fetch|timeout|offline|load failed/i.test(err.message));
|
||||
}
|
||||
|
||||
type Store = { get(key: string): string | null; set(key: string, value: string): void; remove(key: string): void; keys(): string[] };
|
||||
|
||||
const browserStore: Store = {
|
||||
get: (k) => {
|
||||
try {
|
||||
return window.localStorage.getItem(k);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
set: (k, v) => {
|
||||
try {
|
||||
window.localStorage.setItem(k, v);
|
||||
} catch {
|
||||
/* full or unavailable: kept in memory by the caller */
|
||||
}
|
||||
},
|
||||
remove: (k) => {
|
||||
try {
|
||||
window.localStorage.removeItem(k);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
keys: () => {
|
||||
try {
|
||||
return Object.keys(window.localStorage);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** The develop outbox of one photo (see develop/session.ts `localOutbox`). */
|
||||
const OUTBOX = "pr:outbox:";
|
||||
|
||||
export class OfflineQueue {
|
||||
private ops: QueuedOp[];
|
||||
private listeners = new Set<() => void>();
|
||||
private running: Promise<void> | null = null;
|
||||
|
||||
constructor(
|
||||
readonly orgId: string,
|
||||
private readonly store: Store = browserStore,
|
||||
) {
|
||||
this.ops = this.read();
|
||||
}
|
||||
|
||||
private key = () => `pr.queue.${this.orgId}`;
|
||||
private mapKey = () => `pr.localmap`;
|
||||
|
||||
private read(): QueuedOp[] {
|
||||
try {
|
||||
const v = JSON.parse(this.store.get(this.key()) ?? "[]") as QueuedOp[];
|
||||
return Array.isArray(v) ? v : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private save(): void {
|
||||
if (this.ops.length) this.store.set(this.key(), JSON.stringify(this.ops));
|
||||
else this.store.remove(this.key());
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
|
||||
subscribe(fn: () => void): () => void {
|
||||
this.listeners.add(fn);
|
||||
return () => this.listeners.delete(fn);
|
||||
}
|
||||
|
||||
/** Changes waiting for the server (develop edits of photos not open count too). */
|
||||
get size(): number {
|
||||
return this.ops.length + this.outboxKeys().length;
|
||||
}
|
||||
|
||||
get pending(): readonly QueuedOp[] {
|
||||
return this.ops;
|
||||
}
|
||||
|
||||
add(op: NewOp): void {
|
||||
this.ops.push({ ...op, id: crypto.randomUUID() } as QueuedOp);
|
||||
this.save();
|
||||
}
|
||||
|
||||
/** The server id of a photo first seen here, once it is uploaded. */
|
||||
serverId(id: string): string | null {
|
||||
if (!isLocalId(id)) return id;
|
||||
try {
|
||||
const map = JSON.parse(this.store.get(this.mapKey()) ?? "{}") as Record<string, string>;
|
||||
return map[id.slice(LOCAL.length)] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A photo first seen here is now on the server: its waiting changes (and develop edits) can go. */
|
||||
uploaded(sha256: string, id: string): void {
|
||||
let map: Record<string, string> = {};
|
||||
try {
|
||||
map = JSON.parse(this.store.get(this.mapKey()) ?? "{}") as Record<string, string>;
|
||||
} catch {
|
||||
/* start over */
|
||||
}
|
||||
map[sha256] = id;
|
||||
// Only the recent ones are needed (photos are uploaded within hours).
|
||||
const entries = Object.entries(map).slice(-5000);
|
||||
this.store.set(this.mapKey(), JSON.stringify(Object.fromEntries(entries)));
|
||||
const outbox = this.store.get(`${OUTBOX}${localId(sha256)}`);
|
||||
if (outbox) {
|
||||
const existing = this.store.get(`${OUTBOX}${id}`);
|
||||
const merged = [...(existing ? (JSON.parse(existing) as unknown[]) : []), ...(JSON.parse(outbox) as unknown[])];
|
||||
this.store.set(`${OUTBOX}${id}`, JSON.stringify(merged));
|
||||
this.store.remove(`${OUTBOX}${localId(sha256)}`);
|
||||
}
|
||||
this.save();
|
||||
}
|
||||
|
||||
private outboxKeys(): string[] {
|
||||
return this.store.keys().filter((k) => k.startsWith(OUTBOX));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends what is waiting, in order. Stops at the first network failure (tries again later); drops what the server
|
||||
* refuses for good. Changes to a photo not uploaded yet wait, and so do later changes to that photo.
|
||||
*/
|
||||
flush(api: ApiClient): Promise<void> {
|
||||
this.running ??= this.doFlush(api).finally(() => {
|
||||
this.running = null;
|
||||
});
|
||||
return this.running;
|
||||
}
|
||||
|
||||
private async doFlush(api: ApiClient): Promise<void> {
|
||||
const blocked = new Set<string>();
|
||||
for (const op of [...this.ops]) {
|
||||
const ids = op.ids.map((id) => this.serverId(id));
|
||||
if (ids.some((id) => id === null) || op.ids.some((id) => blocked.has(id))) {
|
||||
for (const id of op.ids) blocked.add(id);
|
||||
continue;
|
||||
}
|
||||
const resolved = ids as string[];
|
||||
try {
|
||||
if (op.kind === "patch") await api.updatePhotos(this.orgId, resolved, op.patch);
|
||||
else if (op.kind === "iptc") await api.setPhotosIptc(this.orgId, resolved, op.set);
|
||||
else await api.deliver(this.orgId, op.targetId, resolved, op.again);
|
||||
} catch (err) {
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
|
||||
// Refused for good (photo deleted, no permission): nothing to retry.
|
||||
}
|
||||
this.ops = this.ops.filter((o) => o.id !== op.id);
|
||||
this.save();
|
||||
}
|
||||
await this.flushOutboxes(api);
|
||||
}
|
||||
|
||||
/** Develop edits made offline on photos no longer open (or uploaded since). Repeated ops are ignored by the server. */
|
||||
private async flushOutboxes(api: ApiClient): Promise<void> {
|
||||
for (const key of this.outboxKeys()) {
|
||||
const photoId = key.slice(OUTBOX.length);
|
||||
if (isLocalId(photoId)) {
|
||||
// Edited in Revelar before (and after) the upload: those edits follow the photo.
|
||||
const id = this.serverId(photoId);
|
||||
if (id) this.uploaded(photoId.slice(LOCAL.length), id);
|
||||
continue;
|
||||
}
|
||||
let ops: { opId: string; command: unknown }[];
|
||||
try {
|
||||
ops = JSON.parse(this.store.get(key) ?? "[]") as { opId: string; command: unknown }[];
|
||||
} catch {
|
||||
this.store.remove(key);
|
||||
continue;
|
||||
}
|
||||
if (!ops.length) {
|
||||
this.store.remove(key);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await api.postEdits(photoId, { clientId: "offline-queue", ops } as unknown as Parameters<ApiClient["postEdits"]>[1]);
|
||||
} catch (err) {
|
||||
if (isNetworkError(err) || (err instanceof ApiError && (err.status === 401 || err.status === 429))) return;
|
||||
}
|
||||
// Sent (or refused for good). An editor still open on the photo keeps its own copy and resends harmlessly.
|
||||
if (this.store.get(key) === JSON.stringify(ops)) this.store.remove(key);
|
||||
}
|
||||
for (const fn of this.listeners) fn();
|
||||
}
|
||||
}
|
||||
|
||||
const queues = new Map<string, OfflineQueue>();
|
||||
|
||||
/** One queue per organization, shared by the modules. */
|
||||
export function offlineQueue(orgId: string): OfflineQueue {
|
||||
let q = queues.get(orgId);
|
||||
if (!q) queues.set(orgId, (q = new OfflineQueue(orgId)));
|
||||
return q;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { PhotoPatch } from "@photoreport/contracts";
|
||||
import type { ApiClient } from "@photoreport/sdk";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { localPhotos } from "./local.js";
|
||||
import { isLocalId, isNetworkError, offlineQueue, type OfflineQueue } from "./queue.js";
|
||||
|
||||
/** How often waiting changes are tried while there are some (and whenever the system says the network is back). */
|
||||
const EVERY_MS = 10_000;
|
||||
|
||||
/** Sends the changes kept while offline, in the background, for as long as the organization is open. */
|
||||
export function useOfflineSync(api: ApiClient, orgId: string): void {
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const queue = offlineQueue(orgId);
|
||||
const tick = () => {
|
||||
if (queue.size) void queue.flush(api).catch(() => {});
|
||||
};
|
||||
tick();
|
||||
const timer = setInterval(tick, EVERY_MS);
|
||||
window.addEventListener("online", tick);
|
||||
return () => {
|
||||
clearInterval(timer);
|
||||
window.removeEventListener("online", tick);
|
||||
};
|
||||
}, [api, orgId]);
|
||||
}
|
||||
|
||||
/** How many changes are waiting for the server (for the "N à espera de ligação" note). */
|
||||
export function useQueueSize(orgId: string): number {
|
||||
const queue = orgId ? offlineQueue(orgId) : null;
|
||||
return useSyncExternalStore(
|
||||
(fn) => queue?.subscribe(fn) ?? (() => {}),
|
||||
() => queue?.size ?? 0,
|
||||
() => 0,
|
||||
);
|
||||
}
|
||||
|
||||
async function attempt(queue: OfflineQueue, ids: string[], send: (ids: string[]) => Promise<unknown>, keep: () => void): Promise<"sent" | "queued"> {
|
||||
// Photos still only on this computer: their changes go up with them.
|
||||
if (ids.some(isLocalId)) {
|
||||
keep();
|
||||
return "queued";
|
||||
}
|
||||
try {
|
||||
await send(ids);
|
||||
return "sent";
|
||||
} catch (err) {
|
||||
if (!isNetworkError(err)) throw err;
|
||||
keep();
|
||||
return "queued";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Culling, players and labels: sent now when the server answers, otherwise kept and sent when it does. Photos not
|
||||
* uploaded yet also keep the change on their local copy (it shows, and goes up with them).
|
||||
*/
|
||||
export function patchPhotos(api: ApiClient, orgId: string, ids: string[], patch: PhotoPatch): Promise<"sent" | "queued"> {
|
||||
for (const id of ids) if (isLocalId(id)) localPhotos.patch(id, patch as Record<string, unknown>);
|
||||
const queue = offlineQueue(orgId);
|
||||
return attempt(queue, ids, (x) => api.updatePhotos(orgId, x, patch), () => queue.add({ kind: "patch", ids, patch }));
|
||||
}
|
||||
|
||||
export function setIptc(api: ApiClient, orgId: string, ids: string[], set: Record<string, string | string[] | null>): Promise<"sent" | "queued"> {
|
||||
const queue = offlineQueue(orgId);
|
||||
return attempt(queue, ids, (x) => api.setPhotosIptc(orgId, x, set), () => queue.add({ kind: "iptc", ids, set }));
|
||||
}
|
||||
|
||||
/** "Send to": with no network (or photos still uploading) the request waits here and goes when it can. */
|
||||
export async function deliver(api: ApiClient, orgId: string, targetId: string, ids: string[], again = false) {
|
||||
const queue = offlineQueue(orgId);
|
||||
let answer: Awaited<ReturnType<ApiClient["deliver"]>> | null = null;
|
||||
const result = await attempt(
|
||||
queue,
|
||||
ids,
|
||||
async (x) => {
|
||||
answer = await api.deliver(orgId, targetId, x, again);
|
||||
},
|
||||
() => queue.add({ kind: "deliver", targetId, ids, again }),
|
||||
);
|
||||
return result === "sent" && answer ? { ...(answer as Awaited<ReturnType<ApiClient["deliver"]>>), waiting: false } : { queued: [], skipped: [], waiting: true };
|
||||
}
|
||||
@@ -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>}
|
||||
@@ -110,7 +121,7 @@ export function DeliveryPage() {
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
|
||||
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
|
||||
{i.remotePath ?? <span className="text-faint">—</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{i.lastError}</span>}
|
||||
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
|
||||
</td>
|
||||
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
|
||||
{t.deliveryStatus[i.status]}
|
||||
@@ -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}
|
||||
|
||||
@@ -8,7 +8,12 @@ import { DevelopPanels, Section, Slider } from "../develop/Panels.js";
|
||||
import { type Crop, cropOf, DevelopSession, localOutbox } from "../develop/session.js";
|
||||
import { constrainRotated, engineAuto, fitAspect, Viewer } from "../develop/Viewer.js";
|
||||
import { IptcInfo } from "../library/IptcInfo.js";
|
||||
import { applyPatch, patchForKey } from "../library/store.js";
|
||||
import { activePhoto, savedFilter, setActivePhoto } from "../library/active.js";
|
||||
import { cache } from "../offline/cache.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { patchPhotos } from "../offline/sync.js";
|
||||
import { applyPatch, type LibraryFilter, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop, localOriginal, prefs } from "../platform.js";
|
||||
@@ -28,6 +33,8 @@ const ASPECTS: { label: string; value: [number, number] | "original" | null }[]
|
||||
];
|
||||
|
||||
const CLIPBOARD = "develop.clipboard";
|
||||
/** The filmstrip loads the whole folder in pages of this size (a match can have thousands of photos). */
|
||||
const PAGE = 500;
|
||||
/** The aspect a new crop starts with (the last one chosen): "free", "original" or "W:H". Lightroom's default is the original. */
|
||||
const CROP_ASPECT = "develop.cropAspect";
|
||||
type AspectChoice = (typeof ASPECTS)[number]["value"];
|
||||
@@ -90,26 +97,71 @@ export function DevelopPage() {
|
||||
api.listDeliveryTargets(orgId).then((r) => setTargets(r.targets.filter((x) => !x.disabledAt)), () => {});
|
||||
}, [api, orgId, role]);
|
||||
|
||||
// The event (or inbox) the library has open.
|
||||
// The event (or inbox) the library has open, all of it (page by page), as the library shows it.
|
||||
const scope = orgId ? (prefs.get(`scope:${orgId}`) ?? null) : null;
|
||||
const [all, setAll] = useState<PhotoSummary[] | null>(null);
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
const scope = prefs.get(`scope:${orgId}`) ?? undefined;
|
||||
api.listPhotos(orgId, { ...(scope && { event: scope }), limit: 500 }).then(
|
||||
(r) => setPhotos(r.photos.filter((p) => p.status === "READY")),
|
||||
() => setPhotos([]),
|
||||
);
|
||||
}, [api, orgId]);
|
||||
let alive = true;
|
||||
void (async () => {
|
||||
const got: PhotoSummary[] = [];
|
||||
try {
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
const page = await api.listPhotos(orgId, { ...(scope && { event: scope }), offset, limit: PAGE });
|
||||
got.push(...page.photos);
|
||||
if (!alive) return;
|
||||
setAll([...got]);
|
||||
if (offset + page.photos.length >= page.total || page.photos.length === 0) break;
|
||||
}
|
||||
if (scope) void cache.setPhotos(orgId, scope, got);
|
||||
} catch (err) {
|
||||
// No network: the folder as last seen on this computer.
|
||||
const kept = isNetworkError(err) && scope ? await cache.photos(orgId, scope) : undefined;
|
||||
if (alive) setAll((a) => (a && a.length ? a : (kept ?? [])));
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [api, orgId, scope]);
|
||||
// Photos still only on this computer (local FTP) are in the filmstrip too, and can be edited already.
|
||||
const localVersion = useSyncExternalStore(
|
||||
(fn) => localPhotos.subscribe(fn),
|
||||
() => localPhotos.version,
|
||||
() => 0,
|
||||
);
|
||||
const withLocal = useMemo(() => {
|
||||
if (!all) return null;
|
||||
const here = localPhotos.list().filter((p) => (scope === "inbox" ? p.eventId === null : p.eventId === scope) && !all.some((q) => q.sha256 === p.sha256));
|
||||
return here.length ? [...all, ...here].sort((a, b) => (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "")) : all;
|
||||
}, [all, localVersion, scope]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
// The filmstrip follows the library's filter, like Lightroom's (the open photo stays even if it doesn't match).
|
||||
const filterJson = JSON.stringify(savedFilter(orgId));
|
||||
const filter = useMemo(() => JSON.parse(filterJson) as LibraryFilter, [filterJson]);
|
||||
useEffect(() => {
|
||||
if (!withLocal) return;
|
||||
const ready = withLocal.filter((p) => p.status === "READY");
|
||||
const shown = ready.filter((p) => matchesFilter(p, filter) || p.id === photoId);
|
||||
setPhotos(shown.length ? shown : ready);
|
||||
}, [withLocal, filter]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const current = photos.find((p) => p.id === photoId) ?? null;
|
||||
// Opened from the module link (no photo in the address): the active photo, the one you were on.
|
||||
useEffect(() => {
|
||||
if (!photoId && photos[0]) navigate(`/develop/${photos[0].id}`, { replace: true });
|
||||
}, [photoId, photos, navigate]);
|
||||
if (photoId || !photos.length) return;
|
||||
const active = activePhoto(orgId, scope);
|
||||
const start = (active && photos.find((p) => p.id === active)) || photos[0]!;
|
||||
navigate(`/develop/${start.id}`, { replace: true });
|
||||
}, [photoId, photos, navigate, orgId, scope]);
|
||||
useEffect(() => {
|
||||
if (current) setActivePhoto(orgId, scope, current.id);
|
||||
}, [orgId, scope, current?.id]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id);
|
||||
const canEdit = !!current && !!role && (hasRole(role, "INGESTER") || current.uploader?.id === me?.user.id || current.id.startsWith("local:"));
|
||||
|
||||
useEffect(() => {
|
||||
if (!current || typeof engine !== "object") return;
|
||||
const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox });
|
||||
const s = new DevelopSession(current.id, { engine, api, clientId: CLIENT_ID, outbox: localOutbox, states: { get: cache.develop, set: cache.setDevelop }, isOffline: isNetworkError });
|
||||
setSession(s);
|
||||
setSourceSize(null);
|
||||
setCropping(false);
|
||||
@@ -154,7 +206,8 @@ export function DevelopPage() {
|
||||
const patch = { ...change };
|
||||
if (patch.colorLabel && current.colorLabel === patch.colorLabel) patch.colorLabel = "NONE";
|
||||
setPhotos((list) => list.map((p) => (p.id === current.id ? applyPatch(p, patch) : p)));
|
||||
api.updatePhotos(orgId, [current.id], patch).catch(() => {
|
||||
// Without a network the change is kept here and sent when the connection is back.
|
||||
patchPhotos(api, orgId, [current.id], patch).catch(() => {
|
||||
setNote(t.unexpectedError);
|
||||
setPhotos((list) => list.map((p) => (p.id === current.id ? current : p)));
|
||||
});
|
||||
@@ -192,6 +245,8 @@ export function DevelopPage() {
|
||||
else if (e.key === "ArrowLeft") go(-1);
|
||||
else if (e.key === "\\") setBefore((b) => !b);
|
||||
else if (!mod && !e.altKey && e.key.toLowerCase() === "g") navigate("/", { state: { focus: current?.id } });
|
||||
// Lightroom: E is the library loupe on the same photo.
|
||||
else if (!mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "e") navigate("/", { state: { focus: current?.id, loupe: true } });
|
||||
else if (!mod && e.shiftKey && e.key.toLowerCase() === "a" && canEdit) void autoAllRef.current();
|
||||
else if (!mod && !e.shiftKey && e.key.toLowerCase() === "i" && canCull && current) setInfo(true);
|
||||
else if (!mod && !e.altKey && patchForKey(e.key)) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { GallerySummary, LibraryMessage, PhotoPatch, PhotoSummary } from "@photoreport/contracts";
|
||||
import { hasRole, type DeliveryTarget, type EventSummary } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
|
||||
import { useLocation, useNavigate } from "react-router";
|
||||
import { useAuth } from "../auth.js";
|
||||
import { pasteCommand } from "./DevelopPage.js";
|
||||
@@ -16,11 +16,17 @@ import { useIngest } from "../library/ingest.js";
|
||||
import { LocalFtpButton } from "../library/LocalFtp.js";
|
||||
import { AutopilotButton } from "../library/Autopilot.js";
|
||||
import { SquadsButton } from "../library/Squads.js";
|
||||
import { type FilterId, initialLibrary, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
|
||||
import { cache, type CachedEvents } from "../offline/cache.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { isNetworkError } from "../offline/queue.js";
|
||||
import { patchPhotos, useQueueSize } from "../offline/sync.js";
|
||||
import { FilterBar } from "../library/FilterBar.js";
|
||||
import { SendButton } from "../library/SendButton.js";
|
||||
import { prefs } from "../platform.js";
|
||||
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
|
||||
|
||||
const PAGE = 500;
|
||||
const FILTERS: FilterId[] = ["all", "PICK", "UNREJECTED", "REJECT", "stars", "noPlayers"];
|
||||
|
||||
const isTyping = (target: EventTarget | null) =>
|
||||
target instanceof HTMLElement && (target.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName));
|
||||
@@ -37,7 +43,15 @@ export function LibraryPage() {
|
||||
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
|
||||
const [iptcOpen, setIptcOpen] = useState(false);
|
||||
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
|
||||
const [filter, setFilter] = useState<FilterId>("all");
|
||||
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
|
||||
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
|
||||
const setFilter = useCallback(
|
||||
(f: LibraryFilter) => {
|
||||
setFilterState(f);
|
||||
saveFilter(orgId, f);
|
||||
},
|
||||
[orgId],
|
||||
);
|
||||
const [loupe, setLoupe] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [view, setView] = useState<"grid" | "faces">("grid");
|
||||
@@ -50,7 +64,16 @@ export function LibraryPage() {
|
||||
|
||||
const loadEvents = useCallback(async () => {
|
||||
if (!orgId) return;
|
||||
const r = await api.listEvents(orgId);
|
||||
let r: CachedEvents;
|
||||
try {
|
||||
r = await api.listEvents(orgId);
|
||||
void cache.setEvents(orgId, r);
|
||||
} catch (err) {
|
||||
// No network: the events as last seen here.
|
||||
const kept = isNetworkError(err) ? await cache.events(orgId) : undefined;
|
||||
if (!kept) throw err;
|
||||
r = kept;
|
||||
}
|
||||
setEvents(r.events);
|
||||
setInboxCount(r.inboxCount);
|
||||
return r.events;
|
||||
@@ -58,7 +81,8 @@ export function LibraryPage() {
|
||||
|
||||
const open = useCallback(
|
||||
async (scope: string) => {
|
||||
dispatch({ type: "load", scope });
|
||||
// Back on the photo that was active here, in any module (Lightroom keeps one active photo).
|
||||
dispatch({ type: "load", scope, focus: activePhoto(orgId, scope) });
|
||||
setLoupe(false);
|
||||
setSuggested([]);
|
||||
if (scope.startsWith("search:")) {
|
||||
@@ -70,12 +94,22 @@ export function LibraryPage() {
|
||||
return;
|
||||
}
|
||||
prefs.set(`scope:${orgId}`, scope);
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
const page = await api.listPhotos(orgId, { event: scope, offset, limit: PAGE });
|
||||
const done = offset + page.photos.length >= page.total || page.photos.length === 0;
|
||||
dispatch({ type: "loaded", scope, photos: page.photos, done });
|
||||
if (done) break;
|
||||
const all: PhotoSummary[] = [];
|
||||
try {
|
||||
for (let offset = 0; ; offset += PAGE) {
|
||||
const page = await api.listPhotos(orgId, { event: scope, offset, limit: PAGE });
|
||||
const done = offset + page.photos.length >= page.total || page.photos.length === 0;
|
||||
all.push(...page.photos);
|
||||
dispatch({ type: "loaded", scope, photos: page.photos, done });
|
||||
if (done) break;
|
||||
}
|
||||
void cache.setPhotos(orgId, scope, all);
|
||||
} catch (err) {
|
||||
if (!isNetworkError(err)) throw err;
|
||||
// No network: the folder as last seen on this computer (plus what arrived here since).
|
||||
dispatch({ type: "loaded", scope, photos: (await cache.photos(orgId, scope)) ?? [], done: true });
|
||||
}
|
||||
dispatch({ type: "local", photos: localPhotos.list() });
|
||||
},
|
||||
[api, orgId],
|
||||
);
|
||||
@@ -95,18 +129,45 @@ export function LibraryPage() {
|
||||
};
|
||||
}, [api, orgId, canCull, loadEvents, open]);
|
||||
|
||||
// Photos moved between events (by hand, or claimed from "Sem evento" when an event is created or its times
|
||||
// change): the counts follow, and the open event shows the ones that arrived in it.
|
||||
const scopeRef = useRef(state.scope);
|
||||
scopeRef.current = state.scope;
|
||||
const moved = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const onMoved = useCallback(
|
||||
(eventId: string | null) => {
|
||||
if (moved.current) clearTimeout(moved.current);
|
||||
moved.current = setTimeout(() => {
|
||||
void loadEvents().catch(() => {});
|
||||
if (eventId !== null && scopeRef.current === eventId) void open(eventId).catch(() => {});
|
||||
}, 400);
|
||||
},
|
||||
[loadEvents, open],
|
||||
);
|
||||
|
||||
const onMessage = useCallback(
|
||||
(message: LibraryMessage) => {
|
||||
dispatch({ type: "message", message });
|
||||
if (message.type === "photo.updated" && message.patch.eventId !== undefined) onMoved(message.patch.eventId);
|
||||
if (message.type === "faces.updated") setFacesTick((n) => n + 1);
|
||||
if (message.type === "photo.added") {
|
||||
if (message.photo.eventId === null) setInboxCount((n) => n + 1);
|
||||
else setEvents((list) => list.map((e) => (e.id === message.photo.eventId ? { ...e, photoCount: e.photoCount + 1 } : e)));
|
||||
}
|
||||
},
|
||||
[dispatch],
|
||||
[dispatch, onMoved],
|
||||
);
|
||||
const live = useLibraryLive(api, onMessage);
|
||||
// Photos still only on this computer (local FTP) join the folder they belong to.
|
||||
const localVersion = useSyncExternalStore(
|
||||
(fn) => localPhotos.subscribe(fn),
|
||||
() => localPhotos.version,
|
||||
() => 0,
|
||||
);
|
||||
useEffect(() => {
|
||||
dispatch({ type: "local", photos: localPhotos.list() });
|
||||
}, [localVersion]);
|
||||
const waitingChanges = useQueueSize(orgId);
|
||||
const { uploads, localFtp, desktop } = useIngest();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [dragging, setDragging] = useState(false);
|
||||
@@ -128,7 +189,8 @@ export function LibraryPage() {
|
||||
if (!ids.length || !canCull) return;
|
||||
dispatch({ type: "patch", ids, patch: change });
|
||||
try {
|
||||
await api.updatePhotos(orgId, ids, change);
|
||||
// Without a network the change is kept here and sent when the connection is back.
|
||||
await patchPhotos(api, orgId, ids, change);
|
||||
} catch {
|
||||
setError(t.unexpectedError);
|
||||
if (state.scope) void open(state.scope);
|
||||
@@ -175,15 +237,22 @@ export function LibraryPage() {
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [visibleIds, selection, focus, loupe, patch, navigate, canCull]);
|
||||
|
||||
// The photo you are on is the active one for every module (Develop opens on it).
|
||||
useEffect(() => {
|
||||
if (!state.wanted) setActivePhoto(orgId, state.scope, state.focus);
|
||||
}, [orgId, state.scope, state.focus, state.wanted]);
|
||||
|
||||
// Back from Develop (G): the photo that was open there is the one selected here.
|
||||
const location = useLocation();
|
||||
const backFocus = (location.state as { focus?: string } | null)?.focus;
|
||||
const back = location.state as { focus?: string; loupe?: boolean } | null;
|
||||
const backFocus = back?.focus;
|
||||
useEffect(() => {
|
||||
if (!backFocus || !state.photos.some((p) => p.id === backFocus)) return;
|
||||
dispatch({ type: "select", id: backFocus, mode: "single", visible: [] });
|
||||
if (back?.loupe) setLoupe(true);
|
||||
requestAnimationFrame(() => document.querySelector(`[data-photo-id="${backFocus}"]`)?.scrollIntoView({ block: "nearest" }));
|
||||
navigate(".", { replace: true, state: null });
|
||||
}, [backFocus, state.photos, navigate]);
|
||||
}, [backFocus, back?.loupe, state.photos, navigate]);
|
||||
|
||||
const onPick = useCallback(
|
||||
(id: string, e: React.MouseEvent) => dispatch({ type: "select", id, mode: e.shiftKey ? "range" : e.metaKey || e.ctrlKey ? "toggle" : "single", visible: visibleIds }),
|
||||
@@ -229,12 +298,7 @@ export function LibraryPage() {
|
||||
|
||||
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
|
||||
<span className="text-faint">{t.filter}:</span>
|
||||
{FILTERS.map((f) => (
|
||||
<button key={f} onClick={() => setFilter(f)} aria-pressed={filter === f} className={filter === f ? "font-semibold text-ink" : "text-faint hover:text-muted"}>
|
||||
{t.filters[f]}
|
||||
</button>
|
||||
))}
|
||||
<FilterBar filter={filter} onChange={setFilter} />
|
||||
{canCull && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && (
|
||||
<button
|
||||
onClick={() => setView(view === "faces" ? "grid" : "faces")}
|
||||
@@ -282,6 +346,45 @@ export function LibraryPage() {
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{canCull && (
|
||||
<SendButton
|
||||
api={api}
|
||||
orgId={orgId}
|
||||
selection={selection}
|
||||
targets={targets}
|
||||
eventId={openEvent?.id ?? null}
|
||||
onQueued={(items) => items.forEach((item) => dispatch({ type: "message", message: { type: "delivery.updated", item } }))}
|
||||
/>
|
||||
)}
|
||||
{canCull && selection.length > 0 && !state.scope?.startsWith("search:") && (
|
||||
<select
|
||||
aria-label={t.moveToEvent}
|
||||
className="h-6 border border-black bg-cell px-1.5 text-[12px] text-ink"
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const target = events.find((x) => x.id === e.target.value);
|
||||
if (!target) return;
|
||||
const ids = selection.map((p) => p.id);
|
||||
void api.updatePhotos(orgId, ids, { eventId: target.id }).then(
|
||||
() => {
|
||||
dispatch({ type: "patch", ids, patch: { eventId: target.id } });
|
||||
setInfo(t.movedToEvent(ids.length, target.title));
|
||||
setTimeout(() => setInfo(null), 4000);
|
||||
},
|
||||
() => setError(t.unexpectedError),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">{t.moveToEvent}…</option>
|
||||
{events
|
||||
.filter((x) => x.id !== state.scope && !x.archivedAt)
|
||||
.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{info && <span className="text-[11px] text-ok">{info}</span>}
|
||||
{canCull && prefs.get("develop.clipboard") && selection.length > 0 && (
|
||||
<button
|
||||
@@ -312,12 +415,17 @@ export function LibraryPage() {
|
||||
}}
|
||||
/>
|
||||
<span className="ml-auto flex items-center gap-3 font-mono text-[11px] text-faint">
|
||||
{waitingChanges > 0 && (
|
||||
<span className="text-star" title={t.offline.waitingHelp}>
|
||||
{t.offline.waiting(waitingChanges)}
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
{t.ofTotal(visible.length, state.photos.length)} · {picks} ⚑
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5" title={live}>
|
||||
<span className={`h-2 w-2 rounded-full ${live === "live" ? "bg-ok" : live === "connecting" ? "bg-star" : "bg-danger"}`} />
|
||||
{live === "live" ? "live" : live === "connecting" ? "…" : "offline"}
|
||||
{live === "live" ? "live" : live === "connecting" ? "…" : t.offline.label}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
@@ -344,7 +452,7 @@ export function LibraryPage() {
|
||||
{view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") ? (
|
||||
<FacesView api={api} orgId={orgId} eventId={state.scope} canAnalyse={canCreate} refreshKey={facesTick} />
|
||||
) : loupe && focus ? (
|
||||
<Loupe photo={focus} src={api.absolute(focus.urls.preview)} index={visibleIds.indexOf(focus.id)} total={visibleIds.length} faces={loupeFaces} />
|
||||
<Loupe photo={focus} src={api.absolute(focus.urls.preview)} fallback={api.absolute(focus.urls.thumb)} index={visibleIds.indexOf(focus.id)} total={visibleIds.length} faces={loupeFaces} />
|
||||
) : visible.length || suggested.length ? (
|
||||
<>
|
||||
<Grid photos={visible} selected={state.selected} focus={state.focus} srcFor={srcFor} onPick={onPick} onOpen={onOpenLoupe} />
|
||||
|
||||
@@ -19,6 +19,7 @@ export function NumbersPage() {
|
||||
const [done, setDone] = useState<JerseySample[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
const [confirmReset, setConfirmReset] = useState(false);
|
||||
const loading = useRef(false);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
@@ -73,7 +74,11 @@ export function NumbersPage() {
|
||||
if (isTyping(e.target) || e.metaKey || e.ctrlKey || e.altKey) return;
|
||||
if (/^\d$/.test(e.key)) {
|
||||
e.preventDefault();
|
||||
setTyped((x) => (x + e.key).slice(-3));
|
||||
setTyped((x) => (/^\d*$/.test(x) ? x + e.key : e.key).slice(-3));
|
||||
} else if (/^[a-f]$/i.test(e.key)) {
|
||||
// A handball official's card (Oficial A..F): one letter, never mixed with digits.
|
||||
e.preventDefault();
|
||||
setTyped(e.key.toUpperCase());
|
||||
} else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
void answer("CONFIRMED", typed || undefined);
|
||||
@@ -113,7 +118,10 @@ export function NumbersPage() {
|
||||
<div className="mx-auto grid max-w-6xl gap-6 p-6 max-sm:p-3 lg:grid-cols-[1fr_320px]">
|
||||
<section className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<span>{current?.person ?? t.numbers.title}</span>
|
||||
<span>
|
||||
{current?.person ?? t.numbers.title}
|
||||
{current && <span className="ml-2 border border-black bg-cell px-1.5 py-0.5 text-[10px] text-muted">{t.numbers.region[current.region]}</span>}
|
||||
</span>
|
||||
<span className="normal-case tracking-normal text-faint">{t.numbers.keys}</span>
|
||||
</div>
|
||||
{note && <p className="px-4 pt-3 text-[12px] text-muted">{note}</p>}
|
||||
@@ -131,9 +139,13 @@ export function NumbersPage() {
|
||||
<input
|
||||
aria-label={t.numbers.other}
|
||||
placeholder={t.numbers.other}
|
||||
inputMode="numeric"
|
||||
inputMode="text"
|
||||
value={typed}
|
||||
onChange={(e) => setTyped(e.target.value.replace(/\D/g, "").slice(0, 3))}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value.toUpperCase();
|
||||
const letter = /[A-F]/.exec(v)?.[0];
|
||||
setTyped(letter ?? v.replace(/\D/g, "").slice(0, 3));
|
||||
}}
|
||||
onKeyDown={(e) => e.key === "Enter" && void answer("CONFIRMED", typed || undefined)}
|
||||
className="h-9 w-28 border border-black bg-[#161617] px-2 text-center font-mono text-[15px] text-ink"
|
||||
/>
|
||||
@@ -178,6 +190,34 @@ export function NumbersPage() {
|
||||
{!stats?.numbers.length && <span className="text-[12px] text-faint">—</span>}
|
||||
</div>
|
||||
</section>
|
||||
{role !== null && hasRole(role, "EDITOR") && (c.CONFIRMED ?? 0) + (c.ILLEGIBLE ?? 0) + (c.SKIPPED ?? 0) > 0 && (
|
||||
<section className="border border-line bg-panel p-3">
|
||||
{confirmReset ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<button
|
||||
className="h-9 w-full bg-danger px-3 text-[13px] font-semibold text-white"
|
||||
onClick={() => {
|
||||
void api.resetJerseySamples(orgId).then((r) => {
|
||||
setConfirmReset(false);
|
||||
setDone([]);
|
||||
setNote(t.numbers.resetDone(r.reset));
|
||||
void load();
|
||||
});
|
||||
}}
|
||||
>
|
||||
{t.numbers.resetConfirm((c.CONFIRMED ?? 0) + (c.ILLEGIBLE ?? 0) + (c.SKIPPED ?? 0))}
|
||||
</button>
|
||||
<button className="text-[12px] text-faint underline" onClick={() => setConfirmReset(false)}>
|
||||
{t.numbers.resetCancel}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<button className="h-9 w-full border border-black bg-cell text-[13px] text-muted hover:text-ink" onClick={() => setConfirmReset(true)}>
|
||||
{t.numbers.reset}
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
{role !== null && hasRole(role, "EDITOR") && (
|
||||
<button className="h-9 w-full bg-accent font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong" onClick={() => void download()}>
|
||||
{t.numbers.download}
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useAuth } from "../auth.js";
|
||||
import { Bell } from "../components/Bell.js";
|
||||
import { Logo } from "../components/ui.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { LocalDeliveries } from "../desktop/localDeliveries.js";
|
||||
import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js";
|
||||
import { IngestProvider } from "../library/ingest.js";
|
||||
|
||||
const moduleClass = ({ isActive }: { isActive: boolean }) =>
|
||||
@@ -116,6 +117,8 @@ export function Shell() {
|
||||
</details>
|
||||
</header>
|
||||
<UpdateNotice />
|
||||
<UiReadyNotice />
|
||||
<LocalDeliveries />
|
||||
<main className="min-h-0 flex-1 overflow-auto">
|
||||
<IngestProvider>
|
||||
<Outlet />
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { RefreshTokenStore } from "@photoreport/sdk";
|
||||
|
||||
/** Set by the desktop app before the page runs (apps/desktop/src-tauri/src/lib.rs, `init_script`). */
|
||||
export function desktopConfig(): { api: string; app: string } | undefined {
|
||||
return typeof window === "undefined" ? undefined : (window as { __PHOTOREPORT__?: { api: string; app: string } }).__PHOTOREPORT__;
|
||||
}
|
||||
|
||||
/** True inside the Tauri desktop shell. */
|
||||
export const isDesktop = (): boolean => typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;
|
||||
|
||||
@@ -87,6 +92,20 @@ export function asArrayBuffer(data: unknown): ArrayBuffer {
|
||||
throw new Error("not binary data");
|
||||
}
|
||||
|
||||
/**
|
||||
* The file that was this photo's original when it arrived, changed since (another app wrote captions into it), or
|
||||
* null. Only for sending to the server as that photo's original; older desktop apps answer null.
|
||||
*/
|
||||
export async function localOriginalChanged(sha256: string, invokeImpl?: Invoke): Promise<ArrayBuffer | null> {
|
||||
if (!invokeImpl && !isDesktop()) return null;
|
||||
try {
|
||||
const invoke: Invoke = invokeImpl ?? (async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args));
|
||||
return asArrayBuffer(await invoke<unknown>("local_original_changed", { sha256 }));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The original of a photo from this computer (desktop app), found by its SHA-256: photos that came in through the
|
||||
* local FTP open straight from disk. Null when this computer doesn't have it (or in the browser).
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.3",
|
||||
"version": "0.3.12",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.3"
|
||||
version = "0.3.12"
|
||||
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."
|
||||
@@ -30,6 +30,9 @@ sha2 = "0.10"
|
||||
image = { version = "0.25", default-features = false, features = ["jpeg"] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-updater = "2"
|
||||
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring"] }
|
||||
|
||||
# Release builds: no symbols or debug info, whole-program optimisation, no unwinding tables. The binary only tells
|
||||
# a disassembler what machine code does, not what the functions were called.
|
||||
|
||||
@@ -9,6 +9,7 @@ fn main() {
|
||||
"ftp_start",
|
||||
"ftp_stop",
|
||||
"ftp_status",
|
||||
"ftp_check",
|
||||
"ftp_take",
|
||||
"ftp_retry",
|
||||
"ftp_read",
|
||||
@@ -16,6 +17,7 @@ fn main() {
|
||||
"ftp_open_folder",
|
||||
"ftp_save_settings",
|
||||
"local_original",
|
||||
"local_original_changed",
|
||||
"ftp_preview",
|
||||
"ftp_info",
|
||||
"catalog_folders",
|
||||
@@ -26,6 +28,13 @@ fn main() {
|
||||
"catalog_cancel",
|
||||
"update_check",
|
||||
"update_install",
|
||||
"ui_status",
|
||||
"ui_check",
|
||||
"delivery_machine",
|
||||
"delivery_folders",
|
||||
"delivery_folder_pick",
|
||||
"delivery_write",
|
||||
"import_upload_profiles",
|
||||
]),
|
||||
))
|
||||
.expect("failed to run tauri-build");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the web app from the server (always the latest version), so the server's pages get the same access.",
|
||||
"description": "Main window: core APIs, the keychain and local FTP commands and opening PhotoReport pages in the system browser. The window shows the interface kept on this computer (updated in the background from the server); the server's pages keep the same access.",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
@@ -24,6 +24,7 @@
|
||||
"allow-ftp-start",
|
||||
"allow-ftp-stop",
|
||||
"allow-ftp-status",
|
||||
"allow-ftp-check",
|
||||
"allow-ftp-take",
|
||||
"allow-ftp-retry",
|
||||
"allow-ftp-read",
|
||||
@@ -31,6 +32,7 @@
|
||||
"allow-ftp-open-folder",
|
||||
"allow-ftp-save-settings",
|
||||
"allow-local-original",
|
||||
"allow-local-original-changed",
|
||||
"allow-ftp-preview",
|
||||
"allow-ftp-info",
|
||||
"allow-catalog-folders",
|
||||
@@ -40,7 +42,14 @@
|
||||
"allow-catalog-status",
|
||||
"allow-catalog-cancel",
|
||||
"allow-update-check",
|
||||
"allow-update-install"
|
||||
"allow-update-install",
|
||||
"allow-ui-status",
|
||||
"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-ftp-check"
|
||||
description = "Enables the ftp_check command without any pre-configured scope."
|
||||
commands.allow = ["ftp_check"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-ftp-check"
|
||||
description = "Denies the ftp_check command without any pre-configured scope."
|
||||
commands.deny = ["ftp_check"]
|
||||
@@ -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,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-local-original-changed"
|
||||
description = "Enables the local_original_changed command without any pre-configured scope."
|
||||
commands.allow = ["local_original_changed"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-local-original-changed"
|
||||
description = "Denies the local_original_changed command without any pre-configured scope."
|
||||
commands.deny = ["local_original_changed"]
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user