Compare commits

...
Author SHA1 Message Date
spark 2f3c12be28 fix(upload): file a photo when the named event is gone
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 21s
ci / typescript (push) Failing after 14m0s
ci / rust (push) Successful in 10m40s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 59m53s
A missing event no longer refuses the photo.
2026-11-06 21:25:12 +00:00
spark d195860d56 fix(upload): file a photo when the named event is gone
ci / rust (pull_request) Successful in 9m14s
ci / typescript (pull_request) Failing after 13m54s
A drop was refused with event_not_in_organization, so most of the files never appeared. The photo is filed by its capture time instead. The desktop reads every file in the drop, not only the few the page list kept.
2026-11-06 21:25:10 +00:00
spark 557d7351ce fix(library): take the colour Photo Mechanic paints
ci / rust (push) Successful in 10m25s
ci / typescript (push) Failing after 14m39s
Colour class comes back into the library.
2026-11-06 21:18:46 +00:00
spark e5d7ca324f fix(library): take the colour Photo Mechanic paints
ci / rust (pull_request) Successful in 10m40s
ci / typescript (pull_request) Failing after 14m31s
The desktop re-read the file for a crop and a reject, and left the colour behind. Colour class 1, 3, 4, 5 and 7 become red, yellow, green, blue and purple on the photo.
2026-11-06 21:18:42 +00:00
spark 6721df6432 fix(sports): fill the handball city from the home club
ci / rust (push) Successful in 9m58s
ci / typescript (push) Failing after 13m14s
City from the home club locality.
2026-11-06 21:12:43 +00:00
spark 96539a1f60 fix(sports): fill the handball city from the home club
ci / rust (pull_request) Successful in 9m10s
ci / typescript (pull_request) Failing after 12m50s
The sheet names the hall. The town is the home club's locality, so Oriental is Lisboa and Albicastrense is Castelo Branco. The federation's own card is not used for a national team.
2026-11-06 21:12:40 +00:00
spark c628dcf288 fix(sports): keep the stadium and the home club town apart
ci / rust (push) Successful in 8m47s
ci / typescript (push) Failing after 12m54s
Stadium and home town on every federation import.
2026-11-06 21:06:27 +00:00
spark 82d64ad225 fix(sports): keep the stadium and the home club town apart
ci / rust (pull_request) Successful in 8m7s
ci / typescript (pull_request) Failing after 12m18s
The match calendar left Local and Cidade empty. The ground comes from each federation (Liga team/info, UEFA, EHF, FPA) and is stored separately from the town, then copied onto the event when the match is chosen.
2026-11-06 21:06:25 +00:00
spark 25a661ae22 fix(faces): compile the sure-face path and compare kit colour by hue
ci / rust (push) Successful in 6m53s
ci / typescript (push) Failing after 12m9s
Unblock the API deploy and compare kits by hue.
2026-11-06 20:58:44 +00:00
spark e8e6a40c7f fix(faces): compile the sure-face path and compare kit colour by hue
ci / rust (pull_request) Successful in 7m25s
ci / typescript (pull_request) Failing after 12m6s
The deploy rolled back because a kit lookup could be null. Shirt colour now follows hue ahead of brightness, so sun and shade stay one kit, and a goalkeeper's shirt is not treated as either outfield colour.
2026-11-06 20:58:40 +00:00
spark f24ad4e67a fix(faces): keep a sure face when the shirt number is also read
ci / typescript (push) Failing after 1m44s
ci / rust (push) Successful in 6m58s
BIT face stays when number is also read.
2026-11-06 20:43:44 +00:00
spark 35406a9539 fix(faces): keep a sure face when the shirt number is also read
ci / typescript (pull_request) Failing after 1m37s
ci / rust (pull_request) Successful in 6m14s
The number path replaced a recognised face whenever the stored number did not match, so the player vanished on the photo where both face and number were visible. Face plus number plus kit colour is now the strongest score, and the number only names someone when the face itself is not sure.
2026-11-06 20:43:42 +00:00
spark f02cc0beba fix(faces): rank face+number first and keep one face per player
ci / rust (push) Successful in 5m46s
ci / typescript (push) Failing after 11m14s
BIT-197.
2026-11-06 20:41:42 +00:00
spark 005a580694 fix(faces): rank face+number first and keep one face per player
ci / rust (pull_request) Successful in 5m48s
ci / typescript (pull_request) Failing after 10m17s
A clear shirt named every face that read that number, so two different faces both became the same player. Face plus number stays the strongest guess; the kit of a trusted teammate decides the team; a second dissimilar face loses the name.
2026-11-06 20:41:34 +00:00
spark de691aaa49 fix(faces,app): prefer clear jersey #; photo context menu
ci / rust (push) Successful in 7m35s
ci / typescript (push) Failing after 11m16s
BIT-195. Number-first suggestions when face does not match; PhotoReport context menu on photos.
2026-11-06 20:39:15 +00:00
spark b86f4f4c2e fix(faces,app): prefer clear jersey #; PhotoReport photo context menu
ci / rust (pull_request) Successful in 7m42s
ci / typescript (pull_request) Failing after 11m4s
A detected face with a clear shorts number and no similar person was left unnamed
when the face path won by default. Clear readings now drive the suggestion.

Right-click no longer opens the webview image menu — pick, reject, IPTC, remove, etc.
2026-11-06 20:38:57 +00:00
spark 481d2324eb fix(metadata): stop sending «…, em , no» captions without city/venue
ci / rust (push) Successful in 7m19s
ci / typescript (push) Failing after 10m16s
BIT-193. Empty city/venue left Portuguese stubs in Description/Headline on Cofina deliveries.
2026-11-06 20:25:40 +00:00
spark 6e8d81a0cb fix(metadata): stop sending «…, em , no» captions without city/venue
ci / rust (pull_request) Successful in 7m19s
ci / typescript (pull_request) Failing after 10m24s
The newsroom template left Portuguese prepositions when city and venue were empty, so Cofina got unusable Description/Headline text.
2026-11-06 20:25:13 +00:00
spark f8731553c1 fix(desktop): 0.3.29 — CropBias without Prisma for app build
ci / rust (push) Successful in 9m13s
ci / typescript (push) Failing after 11m16s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 26m29s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 30m16s
BIT-190 follow-up. desktop-v0.3.28 failed because planFrame pulled learning.ts/Prisma into the app tsc.
2026-11-06 14:25:09 +00:00
spark 1d96c38640 fix(desktop): 0.3.29 — keep CropBias out of Prisma for app build
ci / rust (pull_request) Successful in 9m22s
ci / typescript (pull_request) Failing after 11m19s
planFrame only needs the CropBias type; importing it from learning.ts pulled db/Prisma into the desktop app tsc and broke desktop-v0.3.28.
2026-11-06 14:24:42 +00:00
43 changed files with 1069 additions and 150 deletions

No files matched your search

@@ -0,0 +1,3 @@
-- Stadium name and the home club's town are stored apart, so a caption can say both.
ALTER TABLE "sports_teams" ADD COLUMN "city" TEXT;
ALTER TABLE "sports_fixtures" ADD COLUMN "city" TEXT;
+6
View File
@@ -1314,7 +1314,10 @@ model SportsTeam {
/// Lower-case, accent-free name with dashes; codes are derived from it (sl-benfica: b / slb).
slug String
logoUrl String? @map("logo_url")
/// The hall or stadium the club plays at.
venue String?
/// The club's town, kept apart from the stadium name.
city String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -1380,7 +1383,10 @@ model SportsFixture {
timeKnown Boolean @default(true) @map("time_known")
round String?
matchNumber String? @map("match_number")
/// Stadium or hall, without the town.
venue String?
/// Town of the home club.
city String?
homeScore Int? @map("home_score")
awayScore Int? @map("away_score")
/// FPF and UEFA: when the line-ups were read from the match sheet.
+20
View File
@@ -0,0 +1,20 @@
import type { Box } from "../composition/compose.js";
/** Soft crop after folding develop commands (autopilot or human). */
export interface FoldedCrop {
rect: Box;
angle: number;
}
/**
* Soft crop geometry of a correction: final minus autopilot (centre shift, size, straighten).
* Kept out of `learning.ts` so the desktop app can typecheck `planFrame` without Prisma.
*/
export interface CropBias {
dx: number;
dy: number;
/** Linear size: 1 = same area, >1 looser, <1 tighter. */
scale: number;
dAngle: number;
scene: "ball" | "group" | "person" | null;
}
+2 -15
View File
@@ -1,8 +1,10 @@
import type { EditCommand } from "@photoreport/contracts";
import type { Db } from "../db.js";
import type { Box } from "../composition/compose.js";
import type { CropBias, FoldedCrop } from "./cropBias.js";
import { TONE_KEYS, WB_KEYS } from "./look.js";
export type { CropBias, FoldedCrop } from "./cropBias.js";
export { TONE_KEYS, WB_KEYS };
/**
@@ -40,26 +42,11 @@ const CROP_SCENE = "__crop.scene";
const SCENE_CODE: Record<"ball" | "group" | "person", number> = { ball: 1, group: 2, person: 3 };
const SCENE_FROM: Record<number, "ball" | "group" | "person"> = { 1: "ball", 2: "group", 3: "person" };
export interface FoldedCrop {
rect: Box;
angle: number;
}
export interface FoldedEdits {
values: Record<string, number>;
crop: FoldedCrop | null;
}
/** Soft crop geometry of a correction: final minus autopilot (centre shift, size, straighten). */
export interface CropBias {
dx: number;
dy: number;
/** Linear size: 1 = same area, >1 looser, <1 tighter. */
scale: number;
dAngle: number;
scene: "ball" | "group" | "person" | null;
}
/** Settings after these commands, as far as the autopilot's controls go (merges of whole presets are ignored). */
export function fold(commands: EditCommand[]): FoldedEdits {
let values: Record<string, number> = {};
+1 -1
View File
@@ -2,7 +2,7 @@ import type { EditCommand } from "@photoreport/contracts";
import { type Box, type Detections, type FocusHint, clipsBall, compose, minCropWidth, planCrop } from "./compose.js";
import { biasCrop, constrainRotated, tighter } from "./geometry.js";
import { type Look, WB_KEYS, TONE_KEYS, detailForCrop, lookValues, toneApplied } from "../autopilot/look.js";
import type { CropBias } from "../autopilot/learning.js";
import type { CropBias } from "../autopilot/cropBias.js";
/** Straightening beyond this is more likely a creative tilt than a crooked horizon (matches the engine's band). */
const MAX_LEVEL = 8;
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { claimsToKeep, faceAndNumberScore, faceNumberKitScore, numberAndKitScore, numberOnlyScore } from "./rank.js";
describe("suggestion rank", () => {
it("puts face+number above number+kit, and that above number alone", () => {
const top = faceNumberKitScore(0.7, 0.95, 1);
const both = faceAndNumberScore(0.7, 0.95);
const kit = numberAndKitScore(0.95, 1);
const only = numberOnlyScore(0.95);
expect(top).toBeGreaterThan(both);
expect(both).toBeGreaterThan(kit);
expect(kit).toBeGreaterThan(only);
expect(top).toBeLessThanOrEqual(0.99);
expect(kit).toBeLessThanOrEqual(0.82);
});
it("keeps one face cluster when two different faces were both named as the same #9", () => {
const a = [1, 0, 0];
const b = [0, 1, 0];
const same = [0.99, 0.01, 0];
const keep = claimsToKeep(
[
{ id: "strong", personId: "alvarez", score: 0.91, centroid: a },
{ id: "also-him", personId: "alvarez", score: 0.88, centroid: same },
{ id: "other-face", personId: "alvarez", score: 0.7, centroid: b },
],
0.9,
);
expect([...keep].sort()).toEqual(["also-him", "strong"]);
});
});
+64
View File
@@ -0,0 +1,64 @@
import { cosine } from "./math.js";
/**
* How sure a name is, highest first. A sure face is never thrown away because a number was also read.
*
* 1. Face + number + kit colour of that player's team.
* 2. Face + number.
* 3. Face alone.
* 4. Number + kit, only when the face itself is not sure.
* 5. Number alone, only when the face itself is not sure.
*/
/** Face, the number, and the shirt colour of that player's team. */
export function faceNumberKitScore(face: number, jersey: number, kitSure: number): number {
return Math.round(Math.min(0.99, face + 0.15 * jersey + 0.04 * kitSure) * 1000) / 1000;
}
/** Face and the number on the kit are the same person. */
export function faceAndNumberScore(face: number, jersey: number): number {
return Math.round(Math.min(0.99, face + 0.15 * jersey) * 1000) / 1000;
}
/** Shirt number, and the kit colour matches the team we already know from a trusted player. */
export function numberAndKitScore(jersey: number, kitSure: number): number {
return Math.round(Math.min(0.82, jersey * 0.85 * kitSure) * 1000) / 1000;
}
/** Shirt number alone (one wearer, kit not known yet). Stays under a real face match. */
export function numberOnlyScore(jersey: number): number {
return Math.round(Math.min(0.72, jersey * 0.72) * 1000) / 1000;
}
export interface Claim {
id: string;
personId: string;
score: number;
centroid: number[];
}
/**
* One person, several face groups. Groups that look like the same face all keep the name.
* Groups that do not look like each other: only the cluster with the best score keeps it,
* so two different faces are not both "Manuel Alvarez #9".
*/
export function claimsToKeep(claims: Claim[], sameFace: number): Set<string> {
const keep = new Set<string>();
const byPerson = new Map<string, Claim[]>();
for (const c of claims) {
const list = byPerson.get(c.personId) ?? [];
list.push(c);
byPerson.set(c.personId, list);
}
for (const set of byPerson.values()) {
const ordered = [...set].sort((a, b) => b.score - a.score);
const clusters: Claim[][] = [];
for (const c of ordered) {
const hit = clusters.find((cluster) => cluster.some((o) => o.centroid.length > 0 && c.centroid.length > 0 && cosine(o.centroid, c.centroid) >= sameFace));
if (hit) hit.push(c);
else clusters.push([c]);
}
for (const c of clusters[0] ?? []) keep.add(c.id);
}
return keep;
}
+75 -23
View File
@@ -14,6 +14,11 @@ import type { JerseyReading } from "../jersey/model.js";
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
const STRONG_SUGGESTION = 0.85;
/** Outfield kit colour is not the goalkeeper's. Their shirt is a third colour on purpose. */
function isGoalkeeper(position: string | null | undefined): boolean {
return /guarda|\bgr\b|goal/i.test(position ?? "");
}
export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
export { eventSport, normSport } from "./sport.js";
@@ -24,6 +29,7 @@ import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext
import { samePlayer } from "../sports/identity.js";
import { eventSport, normSport } from "./sport.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js";
import { claimsToKeep, faceAndNumberScore, faceNumberKitScore, numberAndKitScore, numberOnlyScore } from "./rank.js";
import type { FaceEngine } from "./process.js";
import { FaceFollower } from "./track.js";
import { randomUUID } from "node:crypto";
@@ -600,20 +606,26 @@ export class FaceService {
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
.sort((a, b) => b.s - a.s);
const [first, second] = ranked;
const ok = first && first.s >= floor && (!second || first.s - second.s >= gap);
let suggestedPersonId = ok ? first.p.id : null;
let suggestionScore = ok ? first.s : null;
const ok = !!(first && first.s >= floor && (!second || first.s - second.s >= gap));
let suggestedPersonId: string | null = null;
let suggestionScore: number | null = null;
const read = await this.groupNumber(g.id);
const firstNumber = ok && read ? (await numberOf([first.p.id])).get(first.p.id) : null;
if (ok && read && firstNumber && firstNumber !== 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 && firstNumber === 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 && allowNumber) {
// 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.
const firstNumber = first && read ? (await numberOf([first.p.id])).get(first.p.id) ?? null : null;
if (ok && first) {
// A face we already recognise stays. The number and the kit only make that guess stronger.
// They must not replace it: that is what dropped the #9 whose face was already right.
suggestedPersonId = first.p.id;
suggestionScore = first.s;
if (read && firstNumber === read.number) {
const team = await this.teamByKit(g.id, eventId);
const onTeam = team ? await this.playersOfTeam([first.p], team.teamId) : null;
if (team && onTeam?.has(first.p.id)) suggestionScore = faceNumberKitScore(first.s, read.score, team.sure);
else suggestionScore = faceAndNumberScore(first.s, read.score);
} else if (read && firstNumber && firstNumber !== read.number && read.votes >= 2) {
suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000;
}
} else if (read && allowNumber) {
// No sure face. The number decides, and the kit colour keeps the other team out.
const close = ranked.filter((r) => r.s >= (bounded ? match * 0.8 : floor));
const nums = await numberOf(close.map((r) => r.p.id));
let near = close.filter((r) => nums.get(r.p.id) === read.number);
@@ -624,9 +636,8 @@ export class FaceService {
}
if (near.length === 1) {
suggestedPersonId = near[0]!.p.id;
suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000;
suggestionScore = Math.max(near[0]!.s, numberOnlyScore(read.score));
} else {
// No face to go by: the number (and, when both teams have it, the colour of the kit).
const byNumber = ctx ? await this.suggestByNumber(g.id, ctx, read) : null;
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
}
@@ -643,9 +654,32 @@ export class FaceService {
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
}
}
await this.dropWeakerDuplicateClaims(eventId);
if (ctx && !ctx.national && ctx.teamIds.length) await this.nameLineupPhotos(eventId, ctx, notThem, off);
}
/**
* Two face groups suggested as the same player, but the faces do not match: keep the stronger guess
* (face+number beats number-only). The other group is left unnamed so it is not a second "Manuel Alvarez".
*/
private async dropWeakerDuplicateClaims(eventId: string): Promise<void> {
const { db } = this.deps;
const rows = await db.faceGroup.findMany({
where: { eventId, personId: null, suggestedPersonId: { not: null } },
select: { id: true, suggestedPersonId: true, suggestionScore: true, centroid: true, model: true },
});
if (rows.length < 2) return;
const model = rows[0]!.model;
const keep = claimsToKeep(
rows.map((g) => ({ id: g.id, personId: g.suggestedPersonId!, score: g.suggestionScore ?? 0, centroid: g.centroid })),
this.thresholds(model).group,
);
for (const g of rows) {
if (keep.has(g.id)) continue;
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId: null, suggestionScore: null } });
}
}
/**
* A team lined up for the photograph: each clear shirt number belongs to one player of that squad.
* Those faces are suggested from the number. A group that already spans other photographs keeps a
@@ -794,7 +828,7 @@ export class FaceService {
// (`numbersIn` reads that competition first, unless this event is the official fixture).
const teamIds = ctx.teamIds;
if (teamIds.length) {
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, season: ctx.season, number: read.number }, select: { id: true, teamId: true, name: true, externalId: true } });
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, season: ctx.season, number: read.number }, select: { id: true, teamId: true, name: true, externalId: true, position: true } });
// The person may have been made from another season's entry of the same player.
const same = players.length
? await db.sportsPlayer.findMany({
@@ -810,12 +844,30 @@ export class FaceService {
const people = teamOf.size
? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: [...teamOf.keys()] } }, select: { id: true, sportsPlayerId: true } })
: [];
if (people.length === 1) return { personId: people[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
const team = await this.teamByKit(groupId, eventId);
const onKit = (sportsPlayerId: string | null) => {
if (!team || !sportsPlayerId) return team ? false : true;
return teamOf.get(sportsPlayerId) === team.teamId;
};
const keeperSide = (sportsPlayerId: string | null) => {
const side = sportsPlayerId ? teamOf.get(sportsPlayerId) : undefined;
const season = players.find((p) => p.teamId === side);
return isGoalkeeper(season?.position);
};
if (people.length === 1) {
const one = people[0]!;
const keeper = keeperSide(one.sportsPlayerId);
// Outfield kit says the other team: this number is not him. A goalkeeper wears neither outfield kit, so that does not rule him out.
if (!keeper && team && one.sportsPlayerId && !onKit(one.sportsPlayerId)) return null;
const score = !keeper && team && one.sportsPlayerId && onKit(one.sportsPlayerId) ? numberAndKitScore(read.score, team.sure) : numberOnlyScore(read.score);
return { personId: one.id, score };
}
if (people.length === 2) {
// One in each team: the kit colour of this group against each team's (from players already confirmed here).
const team = await this.teamByKit(groupId, eventId);
const pick = team ? people.find((p) => p.sportsPlayerId && teamOf.get(p.sportsPlayerId) === team.teamId) : undefined;
if (pick && team) return { personId: pick.id, score: Math.round(read.score * 0.85 * team.sure * 1000) / 1000 };
// One in each team: only the kit colour (learnt from a trusted teammate) may pick.
// Two goalkeepers share a number and neither wears the outfield colour, so that colour cannot choose.
const bothKeepers = people.every((p) => keeperSide(p.sportsPlayerId));
const pick = !bothKeepers && team ? people.find((p) => onKit(p.sportsPlayerId) && !keeperSide(p.sportsPlayerId)) : undefined;
if (pick && team) return { personId: pick.id, score: numberAndKitScore(read.score, team.sure) };
}
if (players.length) return null; // two players with that number and no clear kit, or not people yet: no guess
}
@@ -829,7 +881,7 @@ export class FaceService {
const nums = await numbersIn(db, ctx, candidates.map((p) => p.id));
const wearing = candidates.filter((p) => nums.get(p.id) === read.number);
if (wearing.length !== 1) return null;
return { personId: wearing[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
return { personId: wearing[0]!.id, score: numberOnlyScore(read.score) };
}
/** Which of these people play for the team (by their squad entry). */
@@ -871,7 +923,7 @@ export class FaceService {
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;
if (!sp || isGoalkeeper(sp.position)) continue;
byTeam.set(sp.teamId, [...(byTeam.get(sp.teamId) ?? []), f.kitColour]);
}
const home = median(byTeam.get(event.homeTeamId) ?? []);
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { colourDistance } from "./crop.js";
describe("kit colour distance", () => {
it("treats the same shirt in sun and shade as one colour, and a goalkeeper's yellow as neither team", () => {
const sky = [140, 190, 220];
const red = [200, 30, 30];
const blue = [30, 40, 190];
const keeper = [230, 210, 40];
expect(colourDistance(sky, [75, 110, 145])).toBeLessThan(60);
expect(colourDistance(red, [110, 18, 18])).toBeLessThan(60);
expect(colourDistance(red, blue)).toBeGreaterThan(90);
expect(colourDistance([245, 245, 245], [15, 15, 15])).toBeGreaterThan(90);
expect(colourDistance(keeper, red)).toBeGreaterThan(90);
expect(colourDistance(keeper, blue)).toBeGreaterThan(90);
expect(colourDistance(keeper, sky)).toBeGreaterThan(90);
});
});
+35 -3
View File
@@ -117,7 +117,39 @@ export function kitColour(img: SmallImage, chest: Box): number[] | null {
});
}
/** 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]!);
/** Hue 0–1, saturation and value 0–1. Value is how light the shirt is; shade changes it, not the hue. */
function hsv(rgb: number[]): { h: number; s: number; v: number } {
const r = rgb[0]! / 255;
const g = rgb[1]! / 255;
const b = rgb[2]! / 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const d = max - min;
const s = max === 0 ? 0 : d / max;
let h = 0;
if (d !== 0) {
if (max === r) h = ((g - b) / d) % 6;
else if (max === g) h = (b - r) / d + 2;
else h = (r - g) / d + 4;
h /= 6;
if (h < 0) h += 1;
}
return { h, s, v: max };
}
/**
* How far two kit colours are. Hue counts more than brightness, so the same shirt in sun and in shade
* stays close, while a goalkeeper's yellow stays far from both outfield kits. White and black still differ:
* with no hue to go on, lightness is what separates them. Roughly 0–400.
*/
export function colourDistance(a: number[], b: number[]): number {
const left = hsv(a);
const right = hsv(b);
let dh = Math.abs(left.h - right.h);
if (dh > 0.5) dh = 1 - dh;
const satMin = Math.min(left.s, right.s);
const hueTerm = (dh / 0.5) * 380 * (0.35 + 0.65 * satMin);
const lightScale = 200 * (1 - satMin) + 140 * satMin;
const lightTerm = Math.abs(left.v - right.v) * lightScale;
return Math.hypot(hueTerm, lightTerm);
}
+7
View File
@@ -11,6 +11,7 @@ import { badRequest, conflict, forbidden, notFound } from "../lib/errors.js";
import type { Broadcaster } from "../realtime.js";
import type { SportsService } from "../sports/service.js";
import { officialSigla } from "../sports/fpa-siglas.js";
import { splitStoredPlace } from "../sports/providers.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
@@ -173,6 +174,12 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
if (body.photographerIds?.length) await assertMembers(orgId, body.photographerIds);
const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, autopilot, fixtureId, homeTeamId, awayTeamId, ...fields } = body;
const match = await resolveMatch({ fixtureId, homeTeamId, awayTeamId });
if (match.fixtureId && (!fields.venue || !fields.city)) {
const fixture = await db.sportsFixture.findUnique({ where: { id: match.fixtureId }, include: { homeTeam: { select: { venue: true, city: true } } } });
const place = splitStoredPlace(fixture?.venue ?? fixture?.homeTeam.venue ?? null, fixture?.city ?? fixture?.homeTeam.city ?? null);
if (!fields.venue && place.venue) fields.venue = place.venue;
if (!fields.city && place.city) fields.city = place.city;
}
// A second click (the first answer never arrived) must not create the game twice.
if (match.fixtureId) {
const existing = await db.event.findFirst({ where: { organizationId: orgId, fixtureId: match.fixtureId, archivedAt: null }, include, orderBy: { createdAt: "asc" } });
+3 -5
View File
@@ -47,11 +47,10 @@ export async function registerUploadRoutes(
app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params);
const query = UploadQuery.parse(req.query);
const { eventId } = query;
// A computer can still name an event that was removed or belongs to somewhere else. Refusing the file
// drops the photo. Ingest keeps the event only when it is this organization's, and otherwise uses the clock.
const eventId = query.eventId;
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) {
throw badRequest("event_not_in_organization");
}
let uploaderId = currentUserId(req);
if (query.uploaderUserId && query.uploaderUserId !== uploaderId) {
if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden");
@@ -191,7 +190,6 @@ export async function registerUploadRoutes(
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const name = path.basename(body.name);
if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) throw new AppError(415, "unsupported_type", "JPEG only for now");
if (body.eventId && !(await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } }))) throw badRequest("event_not_in_organization");
const userId = currentUserId(req);
let uploaderUserId: string | null = null;
if (body.uploaderUserId && body.uploaderUserId !== userId) {
+2 -1
View File
@@ -28,7 +28,8 @@ describe("EHF matches", () => {
away: { name: "FC Porto" },
startsAt: new Date("2026-10-21T16:45:00Z"),
round: "Group Phase A",
venue: "Hala Aleksandar Nikolic, Belgrade",
venue: "Hala Aleksandar Nikolic",
city: "Belgrade",
homeScore: null,
awayScore: 28,
});
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { clubCity, fpaClubPlace, splitStoredPlace } from "./providers.js";
describe("home club place", () => {
it("reads the town from the club's own name or from a stadium that names the town", () => {
expect(clubCity({ fullName: "Associação Académica de Coimbra/OAF, SDUQ, Lda", stadium: "Estádio Cidade de Coimbra" })).toBe("Coimbra");
expect(clubCity({ fullName: "Amarante Futebol Clube SDUQ, Lda", stadium: "Estádio Municipal de Amarante" })).toBe("Amarante");
expect(clubCity({ fullName: "Futebol Clube de Vizela – Futebol, SAD", stadium: "Estádio Futebol Clube de Vizela" })).toBe("Vizela");
expect(clubCity({ fullName: "Futebol Clube do Porto - Futebol, SAD", stadium: "Estádio do Dragão" })).toBe("Porto");
expect(clubCity({ fullName: "Sport Lisboa e Benfica - Futebol, SAD", stadium: "Estádio do Sport Lisboa e Benfica" })).toBe("Lisboa");
expect(clubCity({ fullName: "UDL - União de Leiria - Futebol, SAD", stadium: "Estádio Dr. Magalhães Pessoa" })).toBe("Leiria");
expect(clubCity({ fullName: "Portimonense - Futebol, SAD", stadium: "Portimão Estádio" })).toBe("Portimão");
});
it("does not turn a person's name or the word Portugal into a town", () => {
expect(clubCity({ fullName: "Futebol Clube de Felgueiras - Futebol SAD", stadium: "Estádio Municipal Dr. Machado de Matos" })).toBe("Felgueiras");
expect(clubCity({ fullName: "Sporting Clube de Portugal - Futebol, SAD", stadium: "Estádio José Alvalade" })).toBeNull();
expect(clubCity({ fullName: "Leixões Sport Clube - Futebol, SAD", stadium: "Estádio do Mar" })).toBeNull();
expect(clubCity({ fullName: "Clube Desportivo Feirense - Futebol, SAD", stadium: "Estádio Marcolino Castro" })).toBeNull();
});
it("takes the handball club's town, and not the federation's address", () => {
expect(fpaClubPlace({ CLU_NOME: "Clube Oriental Lisboa", CLU_ABREV: "CLUBE ORIENTAL LISBOA", REC_NOME: "PAV. LOIOS", CLUBE_LOCALIDADE: "Lisboa" })).toEqual({ venue: "PAV. LOIOS", city: "Lisboa" });
expect(fpaClubPlace({ CLU_NOME: "Associacao Desportiva Albicastrense", CLU_ABREV: "AD ALBICASTRENSE", REC_NOME: "MUN. CASTELO BRANCO", CLUBE_LOCALIDADE: "Castelo Branco" })).toEqual({ venue: "MUN. CASTELO BRANCO", city: "Castelo Branco" });
expect(fpaClubPlace({ CLU_NOME: "Federacao Andebol Portugal", CLU_ABREV: "F.A.P.", CLUBE_LOCALIDADE: "Lisboa" })).toBeNull();
expect(fpaClubPlace({ CLU_NOME: "Vitória Sport Clube", CLU_ABREV: "VITÓRIA SC", REC_NOME: "DESP. UNIDADE VIMARANENSE", CLUBE_LOCALIDADE: null })).toEqual({ venue: "DESP. UNIDADE VIMARANENSE", city: null });
});
it("splits a venue that was stored with the town after a comma", () => {
expect(splitStoredPlace("Estádio Dr. Magalhães Pessoa, Leiria", null)).toEqual({ venue: "Estádio Dr. Magalhães Pessoa", city: "Leiria" });
expect(splitStoredPlace("Estádio Cidade de Coimbra", null)).toEqual({ venue: "Estádio Cidade de Coimbra", city: null });
expect(splitStoredPlace("Estádio do Dragão", "Porto")).toEqual({ venue: "Estádio do Dragão", city: "Porto" });
});
});
+137 -8
View File
@@ -19,7 +19,10 @@ export interface TeamData {
name: string;
abbreviation?: string | null;
logoUrl?: string | null;
/** The hall or stadium this club plays at. */
venue?: string | null;
/** The home club's town. Separate from the stadium name: captions use both. */
city?: string | null;
/** FPA: the club the team belongs to (its games and levels are listed per club). Not stored. */
clubId?: string | null;
}
@@ -50,7 +53,10 @@ export interface FixtureData {
timeKnown: boolean;
round?: string | null;
matchNumber?: string | null;
/** Stadium or hall, without the town. */
venue?: string | null;
/** Town of the home club, when the source names it. */
city?: string | null;
homeScore?: number | null;
awayScore?: number | null;
/** The referee team (UEFA publishes it before the match). */
@@ -111,6 +117,55 @@ export function lisbonTime(day: string, time?: string | null): { at: Date; timeK
}
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : typeof v === "number" ? String(v) : null);
/** A city named by the club itself: "de Vizela", "Municipal de Amarante", "Sport Lisboa". Not a person's name. */
const PLACE_STOP = new Set(["portugal", "futebol", "sad", "sduq", "lda", "clube", "sport", "sporting", "mar", "campo"]);
function tidyPlace(value: string): string | null {
const place = value.replace(/[/,].*$/, "").replace(/\s+(futebol|sad|sduq|lda)\b.*$/i, "").trim();
if (!place || place.length > 40) return null;
const key = place.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
if (PLACE_STOP.has(key)) return null;
return place;
}
export function clubCity(input: { fullName?: string | null; stadium?: string | null }): string | null {
const stadium = (input.stadium ?? "").replace(/\s+/g, " ").trim();
const municipal = /^estádio municipal de\s+(.+)$/i.exec(stadium);
if (municipal && !/^(dr\.?|eng\.?º?|engenheiro|25 de )\b/i.test(municipal[1]!)) {
const city = tidyPlace(municipal[1]!);
if (city) return city;
}
const cidadeDe = /^estádio cidade de\s+(.+)$/i.exec(stadium);
if (cidadeDe) {
const city = tidyPlace(cidadeDe[1]!);
if (city) return city;
}
const leading = /^(.+?)\s+estádio$/i.exec(stadium);
if (leading) {
const city = tidyPlace(leading[1]!);
if (city) return city;
}
const full = input.fullName ?? "";
if (/\bsport lisboa\b/i.test(full) || /\bsport lisboa\b/i.test(stadium)) return "Lisboa";
const matches = [...full.matchAll(/\b(?:de|do|das|dos)\s+([A-ZÁÉÍÓÚÂÊÔÃÕÇÀ][\p{L}'’.-]+)/gu)];
for (let i = matches.length - 1; i >= 0; i--) {
const city = tidyPlace(matches[i]![1]!);
if (city) return city;
}
return null;
}
/** Older rows stored "Estádio, Leiria" in the venue. The comma splits them back into stadium and city. */
export function splitStoredPlace(venue: string | null, city: string | null): { venue: string | null; city: string | null } {
if (city || !venue) return { venue, city };
const cut = venue.lastIndexOf(",");
if (cut < 0) return { venue, city: null };
const left = venue.slice(0, cut).trim();
const right = venue.slice(cut + 1).trim();
if (!left || !right || right.length > 40 || right.split(/\s+/).length > 4) return { venue, city: null };
return { venue: left, city: right };
}
const url = (...vs: unknown[]): string | null => {
for (const v of vs) {
if (typeof v === "string" && /^https:\/\//.test(v.trim())) return v.trim();
@@ -176,9 +231,30 @@ export function clubSeasons(payload: unknown): LigaClubSeason[] {
export class LigaProvider {
static readonly BASE = "https://www.ligaportugal.pt/api/v1";
private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" };
/** Stadium and town, once per club. The calendar and the teams list leave both empty; team/info has the stadium. */
private readonly places = new Map<string, Promise<{ venue: string | null; city: string | null } | null>>();
constructor(private readonly fetcher: Fetch) {}
/** The club's stadium and town. Null when Liga has not published the page. Never throws. */
place(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> {
const cached = this.places.get(externalId);
if (cached) return cached;
const pending = this.readPlace(externalId, season).catch(() => null);
this.places.set(externalId, pending);
return pending;
}
private async readPlace(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> {
const data = (await this.api("team/info", { id: externalId, season })) as Record<string, unknown>;
const stadium = data.stadium && typeof data.stadium === "object" ? (data.stadium as { name?: unknown }) : null;
const venue = str(stadium?.name);
const named = str(data.city);
const city = named || clubCity({ fullName: str(data.fullName), stadium: venue });
if (!venue && !city) return null;
return { venue, city };
}
/** Every season the federation still publishes, with that year's club competitions. */
async seasons(): Promise<LigaClubSeason[]> {
return clubSeasons(await this.api("seasons", {}));
@@ -194,7 +270,15 @@ export class LigaProvider {
async teams(competition: string, season: string): Promise<TeamData[]> {
const list = await this.api("competition/teams", { season, competition });
if (!Array.isArray(list)) throw new Error("liga: unexpected competition/teams");
return list.map(ligaTeam).filter((t): t is TeamData => !!t);
const teams = list.map(ligaTeam).filter((t): t is TeamData => !!t);
for (const team of teams) {
if (team.venue && team.city) continue;
const place = await this.place(team.externalId, season);
if (!place) continue;
team.venue = team.venue ?? place.venue;
team.city = team.city ?? place.city;
}
return teams;
}
/** The players, then the first team's coaching staff (head coach, assistants; the B team's staff is left out). */
@@ -306,6 +390,7 @@ export class LigaProvider {
round: str(f.round) ?? str(f.matchweekNumber),
matchNumber: str(f.fixtureNumber),
venue: str((f.stadium as { name?: unknown } | undefined)?.name) ?? home.venue ?? null,
city: str((f.stadium as { city?: unknown } | undefined)?.city) ?? home.city ?? null,
homeScore: finished && typeof f.homeTeamGoals === "number" ? f.homeTeamGoals : null,
awayScore: finished && typeof f.awayTeamGoals === "number" ? f.awayTeamGoals : null,
});
@@ -326,7 +411,8 @@ function ligaTeam(t: unknown): TeamData | null {
name,
abbreviation: str(o.abbreviation),
logoUrl: url(o.logo, o.image),
venue: str(o.venue) ?? str(o.venueName) ?? str(o.stadium),
venue: (typeof o.stadium === "object" && o.stadium ? str((o.stadium as { name?: unknown }).name) : null) ?? str(o.venue) ?? str(o.venueName) ?? (typeof o.stadium === "string" ? str(o.stadium) : null),
city: str(o.city) || null,
};
}
@@ -364,6 +450,23 @@ export class FpaProvider {
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
}
/** The club's hall and town (CLUBE_LOCALIDADE is often empty; the hall is REC_NOME). Never throws. */
async club(clubId: string): Promise<{ venue: string | null; city: string | null } | null> {
const cached = this.clubs.get(clubId);
if (cached) return cached;
const pending = this.readClub(clubId).catch(() => null);
this.clubs.set(clubId, pending);
return pending;
}
private readonly clubs = new Map<string, Promise<{ venue: string | null; city: string | null } | null>>();
private async readClub(clubId: string): Promise<{ venue: string | null; city: string | null } | null> {
const data = await get(this.fetcher, `${FpaProvider.WS}/getClube/${encodeURIComponent(clubId)}`, { accept: "application/json" }, "json");
const row = (Array.isArray(data) ? data[0] : data) as Record<string, unknown> | undefined;
return fpaClubPlace(row);
}
/** 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) });
@@ -744,6 +847,21 @@ export function fpaProva(prova: string): { code: string; name: string } | null {
return m ? { code: m[1]!, name: m[2]!.replace(/\s{2,}/g, " ") } : null;
}
/**
* The club card (`getClube`): the hall is REC_NOME, the town is CLUBE_LOCALIDADE.
* The federation's own card (F.A.P., Lisboa) is not a home club, so a seleção does not inherit that town.
*/
export function fpaClubPlace(row: Record<string, unknown> | null | undefined): { venue: string | null; city: string | null } | null {
if (!row) return null;
const abbrev = str(row.CLU_ABREV) ?? "";
const name = str(row.CLU_NOME) ?? "";
const federation = /^f\.?a\.?p\.?$/i.test(abbrev) || /federa[cç][aã]o/i.test(name);
const venue = str(row.REC_NOME);
const city = federation ? null : str(row.CLUBE_LOCALIDADE);
if (!venue && !city) return null;
return { venue, city };
}
function fpaFixture(r: Record<string, unknown>): FixtureData | null {
const prova = fpaProva(str(r.PROVA) ?? "");
const day = str(r.JOG_DATA);
@@ -768,6 +886,7 @@ function fpaFixture(r: Record<string, unknown>): FixtureData | null {
round: str(r.FASE),
matchNumber: str(r.JOG_NUM_JOGO),
venue: str(r.LOCAL),
city: str(r.CLUBE_LOCALIDADE),
homeScore: goals(r.GOLOS_CASA ?? r.JOG_GOLOS_CASA),
awayScore: goals(r.GOLOS_FORA ?? r.JOG_GOLOS_FORA),
};
@@ -790,6 +909,13 @@ export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean
return candidates[0]!;
}
/** FPF prints the stadium, sometimes "Estádio, Cidade". */
function fpfPlace(text: string): { venue: string | null; city: string | null } {
const raw = text.replace(/\s+/g, " ").trim();
if (!raw) return { venue: null, city: null };
return splitStoredPlace(raw, null);
}
export class FpfProvider {
static readonly BASE = "https://resultados.fpf.pt";
private static readonly HEADERS = { accept: "text/html", "accept-language": "pt-PT,pt;q=0.9", "user-agent": "PhotoReport/2 (sports data)" };
@@ -850,7 +976,7 @@ export class FpfProvider {
startsAt: when.at,
timeKnown: when.timeKnown,
round: roundLabel,
venue: r(link).next(".game-list-stadium").find("small").text().trim() || null,
...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()),
homeScore: score ? Number(score[1]) : null,
awayScore: score ? Number(score[2]) : null,
});
@@ -964,7 +1090,8 @@ export function uefaFixture(m: Json, competitionId: string, season: string): Fix
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,
venue: stadium,
city,
homeScore: goals(total.home),
awayScore: goals(total.away),
officials,
@@ -1131,7 +1258,8 @@ export function ehfFixture(row: unknown, competition: string, season: string): F
startsAt: at,
timeKnown: when.hasTime !== false,
round: round && group ? `${round} ${group}` : round,
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
venue: hall,
city,
homeScore: goals(obj(m.homeTeam)),
awayScore: goals(obj(m.guestTeam)),
};
@@ -1240,7 +1368,7 @@ export class EhfProvider {
async euroCupMenMatches(
competitionId: string,
contentId: string,
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1248,7 +1376,7 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1264,7 +1392,8 @@ export class EhfProvider {
startsAt: at,
homeNation: str(obj(obj(m.homeTeam).team).nationAbbreviation) ?? str(obj(obj(m.homeTeam).team).countryAbbreviation),
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
venue: hall,
city,
});
}
return out;
+10 -4
View File
@@ -7,6 +7,7 @@ import type { Db } from "../db.js";
import { forbidden, notFound } from "../lib/errors.js";
import { toCsv, toTsv } from "./codegen.js";
import { fixtureTextFilter } from "./fixture-search.js";
import { splitStoredPlace } from "./providers.js";
import type { SportsService } from "./service.js";
const OrgParams = z.object({ orgId: z.uuid() });
@@ -81,6 +82,7 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db;
slug: t.slug,
logoUrl: t.logoUrl,
venue: t.venue,
city: t.city,
players: t._count.players,
})),
};
@@ -120,20 +122,24 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db;
include: { homeTeam: true, awayTeam: true, competition: true },
});
return {
fixtures: fixtures.map((f) => ({
fixtures: fixtures.map((f) => {
const place = splitStoredPlace(f.venue ?? f.homeTeam.venue, f.city ?? f.homeTeam.city);
return {
id: f.id,
startsAt: f.startsAt,
timeKnown: f.timeKnown,
round: f.round,
matchNumber: f.matchNumber,
venue: f.venue,
venue: place.venue,
city: place.city,
homeScore: f.homeScore,
awayScore: f.awayScore,
sport: f.competition.sport,
competition: { id: f.competition.id, name: f.competition.name, provider: f.competition.provider, code: f.competition.externalId, gender: f.competition.gender },
home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue },
home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue, city: f.homeTeam.city },
away: { id: f.awayTeam.id, name: f.awayTeam.name, abbreviation: f.awayTeam.abbreviation },
})),
};
}),
};
});
+25 -6
View File
@@ -42,6 +42,7 @@ import {
type OfficialData,
type PlayerData,
ProviderHttpError,
splitStoredPlace,
type TeamData,
EHF_COMPETITIONS,
EhfProvider,
@@ -595,7 +596,8 @@ export class SportsService {
startsAt: lisbonTime("2026-11-05", "20:00").at,
timeKnown: true,
round: "Particular",
venue: "Pavilhão Municipal Fernando Lima, Caminha",
venue: "Pavilhão Municipal Fernando Lima",
city: "Caminha",
},
{
externalId: "m19-esp-por-20261107",
@@ -606,7 +608,8 @@ export class SportsService {
startsAt: lisbonTime("2026-11-07", "17:30").at,
timeKnown: true,
round: "Particular",
venue: "Pavilhão Municipal, Salceda de Caselas",
venue: "Pavilhão Municipal",
city: "Salceda de Caselas",
},
];
let n = 0;
@@ -685,7 +688,7 @@ export class SportsService {
*/
private async applyEuroCupSheets(now: Date, season: string, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[];
let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[];
try {
matches = await this.ehf.euroCupMenMatches(EHF_EURO_CUP_MEN.competitionId, EHF_EURO_CUP_MEN.contentId);
} catch (err) {
@@ -717,6 +720,7 @@ export class SportsService {
timeKnown: true,
round: "EHF Euro Cup",
venue: m.venue,
city: m.city,
});
}
const due = matches.filter((m) => Math.abs(m.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
@@ -1244,6 +1248,7 @@ export class SportsService {
...(t.abbreviation ? { abbreviation: t.abbreviation } : {}),
...(t.logoUrl ? { logoUrl: t.logoUrl } : {}),
...(t.venue ? { venue: t.venue } : {}),
...(t.city ? { city: t.city } : {}),
};
const team = await this.deps.db.sportsTeam.upsert({
where,
@@ -1304,6 +1309,21 @@ export class SportsService {
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);
let place = splitStoredPlace(f.venue ?? null, f.city ?? null);
if (provider === "FPA" && f.home.clubId && !place.city) {
const club = await this.fpa.club(f.home.clubId);
if (club?.city) {
place = { ...place, city: club.city };
await this.deps.db.sportsTeam.updateMany({ where: { id: homeTeamId, OR: [{ city: null }, { city: "" }] }, data: { city: club.city } });
}
if (club?.venue) {
await this.deps.db.sportsTeam.updateMany({ where: { id: homeTeamId, venue: null }, data: { venue: club.venue } });
}
}
if (!place.venue || !place.city) {
const home = await this.deps.db.sportsTeam.findUnique({ where: { id: homeTeamId }, select: { venue: true, city: true } });
place = { venue: place.venue ?? home?.venue ?? null, city: place.city ?? home?.city ?? null };
}
const data = {
season: f.season,
homeTeamId,
@@ -1317,11 +1337,10 @@ export class SportsService {
...(f.officials?.length ? { officials: f.officials as unknown as object } : {}),
};
// A sheet that does not name a hall must not wipe a venue we already stored (the youth article has none).
const venue = f.venue ?? null;
await this.deps.db.sportsFixture.upsert({
where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } },
create: { competitionId: c.id, externalId: f.externalId, ...data, venue },
update: { ...data, ...(venue ? { venue } : {}) },
create: { competitionId: c.id, externalId: f.externalId, ...data, venue: place.venue, city: place.city },
update: { ...data, ...(place.venue ? { venue: place.venue } : {}), ...(place.city ? { city: place.city } : {}) },
});
return 1;
}
+57 -1
View File
@@ -397,10 +397,66 @@ describe("faces", () => {
expect(groups[0]!.number).toMatchObject({ value: "10", votes: 2 });
// Benfica's 10 isn't playing; the suggestion waits for someone to confirm it.
expect(groups[0]!.suggestion).toMatchObject({ name: "Rui Costa" });
expect(groups[0]!.suggestion!.score).toBeCloseTo(0.855, 3);
// Number alone, kit not known yet: quieter than face+number (that tops out at 0.99).
expect(groups[0]!.suggestion!.score).toBeCloseTo(0.684, 2);
expect(groups[0]!.person).toBeNull();
expect((await ctx.db.photo.findMany({ select: { players: true } })).every((p) => p.players.length === 0)).toBe(true);
});
it("names from a clear shirt number when the face has nobody close (the #9 on the shorts)", async () => {
const { token, day1, orgId } = await setup();
await ctx.db.person.createMany({
data: [
{ organizationId: orgId, name: "Avançado Nove", club: "VSC", number: "9" },
{ organizationId: orgId, name: "Rui Costa", club: "VSC", number: "10" },
],
});
// Face of someone never confirmed (no similar person); the shorts clearly read 9.
const reader = {
read: async (_file: string, box: { y0: number }) =>
box.y0 > 0.4 ? { number: "9", score: 0.92 } : { number: null, score: 0.9 },
};
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:05:00", [42]);
for (let ids = await withNumbers.claim(10); ids.length; ids = await withNumbers.claim(10)) for (const id of ids) await withNumbers.process(id);
const { groups } = (await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) })).json() as {
groups: { suggestion: { name: string } | null; number: { value: string } | null; person: unknown }[];
};
expect(groups[0]!.number).toMatchObject({ value: "9" });
expect(groups[0]!.suggestion).toMatchObject({ name: "Avançado Nove" });
expect(groups[0]!.person).toBeNull();
});
it("keeps a sure face when the shirt reads another number", async () => {
const { token, day1, day2, orgId } = 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; 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: "ABC", number: "7" },
});
// Same club as day2's home so suggestByNumber can find them on that game.
await ctx.db.person.create({ data: { organizationId: orgId, name: "Avançado Nove", club: "ABC", number: "9" } });
// A week later the face is Miguel. The shirt reads 9: the face stays. The number does not replace him.
await photo("2026:09:30 21:00:00", [1]);
await drain();
const later = (await listed(day2.id)).groups[0]!;
expect(later.suggestion!.name).toBe("Miguel Silva");
const byFace = later.suggestion!;
await ctx.db.face.updateMany({ where: { groupId: later.id }, data: { jerseyNumber: "9", jerseyScore: 0.93 } });
await faces.refreshSuggestions(day2.id);
const after = (await listed(day2.id)).groups[0]!.suggestion!;
expect(after).toMatchObject({ name: "Miguel Silva" });
expect(after.score).toBeLessThan(byFace.score);
});
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() } });
+3 -2
View File
@@ -693,7 +693,7 @@ describe("sports data service", () => {
]);
// 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).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa", city: "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;
@@ -839,7 +839,8 @@ describe("sports data service", () => {
expect(friendly?.homeTeam.externalId).toBe("M19");
expect(friendly?.awayTeam.externalId).toBe("ESP-M19");
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima, Caminha");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
expect(friendly?.city).toBe("Caminha");
});
});
+6 -3
View File
@@ -8,9 +8,10 @@ const EVERY_MS = 4_000;
/**
* Desktop only: while signed in, notice Lightroom / Photo Mechanic soft-crop writes on local originals
* and apply them as develop crops (same path as cropping in Revelar — including autopilot learning).
* A colour class Photo Mechanic paints on the same file is copied onto the library photo.
*/
export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { enabled?: boolean; everyMs?: number }) {
const { organization } = useAuth();
const { api, organization } = useAuth();
const orgId = organization?.id;
useEffect(() => {
if (!enabled || !orgId) return;
@@ -18,7 +19,9 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
await reconcileSoftCrops();
await reconcileSoftCrops(async (id, photoId, color) => {
await api.updatePhotos(id, [photoId], { colorLabel: color });
});
} catch {
/* older desktop without local_stat, or offline index miss */
}
@@ -29,6 +32,6 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
alive = false;
clearTimeout(timer);
};
}, [orgId, enabled, everyMs]);
}, [api, orgId, enabled, everyMs]);
return null;
}
+14 -2
View File
@@ -1,4 +1,4 @@
import { libraryMarksFromXmp, xmpPacketFromJpeg } from "@photoreport/metadata";
import { colorClassFromXmp, libraryMarksFromXmp, xmpPacketFromJpeg } from "@photoreport/metadata";
import type { ApiClient } from "@photoreport/sdk";
import { desktopInvoke, isDesktop } from "../platform.js";
@@ -15,6 +15,8 @@ export interface WatchedDelivery {
orgId: string;
/** Last mtime we already reconciled (ms). */
seenAt: number;
/** Colour last copied from this file. */
color?: string | undefined;
}
function load(): WatchedDelivery[] {
@@ -96,6 +98,16 @@ export async function reconcileLightroomMarks(api: ApiClient): Promise<number> {
continue;
}
const marks = libraryMarksFromXmp(xmp);
const color = colorClassFromXmp(xmp);
if (color && color !== row.color) {
try {
await api.updatePhotos(row.orgId, [row.photoId], { colorLabel: color });
row.color = color;
} catch {
next.push(row);
continue;
}
}
if (marks.flag === "REJECT") {
try {
await deleteDeliveredFile(row.path);
@@ -107,7 +119,7 @@ export async function reconcileLightroomMarks(api: ApiClient): Promise<number> {
continue;
}
}
next.push({ ...row, seenAt: Date.now() });
next.push({ ...row, seenAt: Date.now(), color: row.color });
}
save(next);
return rejected;
+16 -8
View File
@@ -12,6 +12,21 @@ function asBytes(data: unknown): Uint8Array | null {
return null;
}
/** The XMP text of a local original (sidecar, else the packet in the JPEG). Null when this computer has no file. */
export async function localXmpText(sha256: string): Promise<string | null> {
if (!isDesktop() || !sha256) return null;
try {
const raw = await desktopInvoke<unknown>("local_xmp", { sha256 });
const bytes = asBytes(raw);
if (!bytes?.length) return null;
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
if (text.includes("<x:xmpmeta") || text.includes("crs:Crop") || text.includes("ColorClass") || text.includes("xmp:Label")) return text;
return xmpPacketFromJpeg(bytes);
} catch {
return null;
}
}
/**
* Soft crop embedded in the original on this computer (crs:Crop*), the same block Photo Mechanic reads.
* Cached per SHA-256. Null in the browser, when the file is missing, or when there is no crop.
@@ -23,14 +38,7 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
if (pending) return pending;
const work = (async () => {
try {
const raw = await desktopInvoke<unknown>("local_xmp", { sha256 });
const bytes = asBytes(raw);
if (!bytes?.length) {
cache.set(sha256, null);
return null;
}
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
const xmp = text.includes("<x:xmpmeta") || text.includes("crs:Crop") ? text : xmpPacketFromJpeg(bytes);
const xmp = await localXmpText(sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
cache.set(sha256, crop);
return crop;
+28 -7
View File
@@ -1,7 +1,7 @@
import type { SoftCrop } from "@photoreport/metadata";
import { colorClassFromXmp, cropFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
import { desktopInvoke, isDesktop } from "../platform.js";
import { offlineQueue } from "../offline/queue.js";
import { forgetSoftCrop, softCropFor } from "./softCrop.js";
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
/**
* Watch local originals for soft-crop changes written outside this app (Lightroom / Photo Mechanic).
@@ -22,6 +22,8 @@ export interface WatchedSoftCrop {
fingerprint: string;
/** Ignore file changes until this instant (our own sidecar write). */
ownWriteUntil: number;
/** Colour last copied from this file, so a repaint in Photo Mechanic is applied once. "" means the file named none. */
color?: string | undefined;
}
/** Return true when the crop was applied into an open develop session (skip a second queue write). */
@@ -97,11 +99,15 @@ function cropsEqual(a: SoftCrop, b: SoftCrop): boolean {
return softCropFingerprint(a) === softCropFingerprint(b);
}
/** Apply a colour Photo Mechanic wrote into the original. */
export type ApplyExternalColor = (orgId: string, photoId: string, color: XmpColor) => Promise<void>;
/**
* One pass: re-read soft crops whose file (or sidecar) mtime moved, apply as develop crop when the
* rectangle changed. Returns how many photos received a new crop.
* rectangle changed, and copy a colour class Photo Mechanic wrote onto the library photo.
* Returns how many photos received a new crop.
*/
export async function reconcileSoftCrops(): Promise<number> {
export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promise<number> {
if (!isDesktop()) return 0;
const rows = load();
if (!rows.length) return 0;
@@ -114,7 +120,9 @@ export async function reconcileSoftCrops(): Promise<number> {
next.push(row);
continue;
}
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs) {
// A row saved before colours were copied has no `color`. Read it once even if the mtime is already known,
// so a colour painted earlier still arrives. "" means we looked and the file names no colour.
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && row.color !== undefined) {
next.push(row);
continue;
}
@@ -123,10 +131,22 @@ export async function reconcileSoftCrops(): Promise<number> {
continue;
}
forgetSoftCrop(row.sha256);
const crop = await softCropFor(row.sha256);
const xmp = await localXmpText(row.sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const color = xmp ? colorClassFromXmp(xmp) : null;
let colorApplied = color ? row.color : (row.color ?? "");
if (color && color !== row.color && applyColor) {
try {
await applyColor(row.orgId, row.photoId, color);
colorApplied = color;
} catch {
next.push(row);
continue;
}
}
const fingerprint = softCropFingerprint(crop);
if (!crop || fingerprint === row.fingerprint) {
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint });
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint, color: colorApplied });
continue;
}
const command = {
@@ -147,6 +167,7 @@ export async function reconcileSoftCrops(): Promise<number> {
...row,
mtimeMs: stat.mtimeMs || row.mtimeMs,
fingerprint,
color: colorApplied,
ownWriteUntil: now + OWN_WRITE_GRACE_MS,
});
}
+9
View File
@@ -52,6 +52,15 @@ export const t = {
},
removeFromEventHelp: "Ficam em Sem evento. Não são apagadas da biblioteca. O que já foi enviado sai desse destino.",
removedFromEvent: (n: number) => (n === 1 ? "1 foto retirada do evento" : `${n} fotos retiradas do evento`),
photoMenu: "Fotografia",
photoMenuPick: "Escolher",
photoMenuReject: "Rejeitar",
photoMenuClear: "Limpar marca",
photoMenuInfo: "Informação",
photoMenuRemove: "Tirar do evento",
photoMenuDevelop: "Revelar",
photoMenuLoupe: "Lupa",
photoMenuGrid: "Grelha",
folderSheet: {
opening: "A abrir a pasta…",
close: "Fechar",
+1
View File
@@ -89,6 +89,7 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
home: teamDisplayName(f.home.name),
away: teamDisplayName(f.away.name),
venue: f.venue ?? f.home.venue ?? values.venue ?? "",
city: f.city ?? f.home.city ?? values.city ?? "",
sport: f.sport,
competition: f.competition.name,
competitionCode: f.competition.provider === "FPA" ? f.competition.code : (values.competitionCode ?? ""),
+61 -6
View File
@@ -26,9 +26,10 @@ interface CellProps {
focused: boolean;
onPick: (id: string, e: React.MouseEvent) => void;
onOpen: (id: string) => void;
onMenu?: (id: string, e: React.MouseEvent) => void;
}
const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, onPick, onOpen }: CellProps) {
const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, onPick, onOpen, onMenu }: CellProps) {
const ref = useRef<HTMLButtonElement>(null);
useEffect(() => {
if (focused) ref.current?.scrollIntoView({ block: "nearest" });
@@ -60,6 +61,12 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
data-photo-id={photo.id}
onClick={(e) => onPick(photo.id, e)}
onDoubleClick={() => onOpen(photo.id)}
onContextMenu={(e) => {
if (!onMenu) return;
e.preventDefault();
e.stopPropagation();
onMenu(photo.id, e);
}}
aria-pressed={selected}
aria-label={`${photo.name}${photo.flag === "PICK" ? ", escolhida" : photo.flag === "REJECT" ? ", rejeitada" : ""}${photo.rating ? `, ${photo.rating} estrelas` : ""}`}
className={`relative flex aspect-square flex-col items-center justify-between gap-1 border px-2 pb-1 pt-4 ${
@@ -75,7 +82,15 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
<span className="font-mono text-[10px] uppercase text-faint">erro</span>
) : shown ? (
<span className="relative inline-block max-h-full max-w-full">
<img src={shown} onError={() => setImgFailed(true)} alt="" loading="lazy" decoding="async" draggable={false} className="block max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
<img
src={shown}
onError={() => setImgFailed(true)}
alt=""
loading="lazy"
decoding="async"
draggable={false}
className="pointer-events-none block max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]"
/>
{softCrop && <SoftCropGuide crop={softCrop} />}
</span>
) : (
@@ -118,9 +133,15 @@ export function Grid(props: {
srcFor: (photo: PhotoSummary) => string;
onPick: (id: string, e: React.MouseEvent) => void;
onOpen: (id: string) => void;
onMenu?: (id: string, e: React.MouseEvent) => void;
}) {
return (
<section aria-label="Grelha" className="grid content-start gap-1 p-1.5" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(168px, 1fr))" }}>
<section
aria-label="Grelha"
className="grid content-start gap-1 p-1.5"
style={{ gridTemplateColumns: "repeat(auto-fill, minmax(168px, 1fr))" }}
onContextMenu={(e) => e.preventDefault()}
>
{props.photos.map((photo, index) => (
<Cell
key={photo.id}
@@ -132,6 +153,7 @@ export function Grid(props: {
focused={props.focus === photo.id}
onPick={props.onPick}
onOpen={props.onOpen}
{...(props.onMenu ? { onMenu: props.onMenu } : {})}
/>
))}
</section>
@@ -148,7 +170,23 @@ export interface LoupeFace {
suggested: boolean;
}
export function Loupe({ photo, src, fallback, index, total, faces = [] }: { photo: PhotoSummary; src: string; fallback?: string; index: number; total: number; faces?: LoupeFace[] }) {
export function Loupe({
photo,
src,
fallback,
index,
total,
faces = [],
onMenu,
}: {
photo: PhotoSummary;
src: string;
fallback?: string;
index: number;
total: number;
faces?: LoupeFace[];
onMenu?: (id: string, e: React.MouseEvent) => void;
}) {
// 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);
@@ -170,9 +208,26 @@ export function Loupe({ photo, src, fallback, index, total, faces = [] }: { phot
}, [photo.sha256]);
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">
<section
aria-label="Lupa"
className="relative flex h-full min-h-[420px] items-center justify-center bg-[#121213] p-6"
onContextMenu={(e) => {
if (!onMenu) {
e.preventDefault();
return;
}
e.preventDefault();
onMenu(photo.id, e);
}}
>
<span className="relative inline-block max-h-full max-w-full">
<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)]" />
<img
src={shown}
onError={() => setFailed(true)}
alt={photo.name}
draggable={false}
className="pointer-events-none block max-h-[calc(100vh-14rem)] max-w-full object-contain shadow-[0_2px_12px_rgba(0,0,0,0.7)]"
/>
{softCrop && <SoftCropGuide crop={softCrop} />}
{faces.map((f) => (
<span
+69
View File
@@ -0,0 +1,69 @@
import { useEffect, useRef } from "react";
import { t } from "../i18n.js";
export interface PhotoMenuAction {
id: string;
label: string;
danger?: boolean;
disabled?: boolean;
onSelect: () => void;
}
/** PhotoReport's own right-click menu — replaces the webview's "Open Image / Download / Copy". */
export function PhotoContextMenu(props: {
x: number;
y: number;
actions: PhotoMenuAction[];
onClose: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
props.onClose();
}
};
const onDown = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) props.onClose();
};
window.addEventListener("keydown", onKey, true);
window.addEventListener("mousedown", onDown, true);
return () => {
window.removeEventListener("keydown", onKey, true);
window.removeEventListener("mousedown", onDown, true);
};
}, [props.onClose]);
// Keep the menu on screen.
const left = Math.min(props.x, typeof window !== "undefined" ? window.innerWidth - 220 : props.x);
const top = Math.min(props.y, typeof window !== "undefined" ? window.innerHeight - props.actions.length * 32 - 16 : props.y);
return (
<div
ref={ref}
role="menu"
aria-label={t.photoMenu}
className="fixed z-[60] min-w-[200px] border border-line bg-panel py-1 shadow-xl"
style={{ left, top }}
>
{props.actions.map((a) => (
<button
key={a.id}
type="button"
role="menuitem"
disabled={a.disabled}
className={`flex w-full px-3 py-1.5 text-left text-[13px] disabled:opacity-40 ${
a.danger ? "text-danger hover:bg-[#3a2020]" : "text-ink hover:bg-cell-on"
}`}
onClick={() => {
if (a.disabled) return;
a.onSelect();
props.onClose();
}}
>
{a.label}
</button>
))}
</div>
);
}
+14
View File
@@ -16,6 +16,20 @@ describe("folder drop", () => {
expect(opened).toEqual(["/tmp/job"]);
});
it("uploads every loose file the shell can read", async () => {
const sent: string[] = [];
const wait = beginDropWait();
nativePaths(
["/tmp/a.jpg", "/tmp/b.jpg"],
async () => null,
() => {},
async (paths) => paths.map((path) => new File([path], path.split("/").pop()!)),
(files) => sent.push(...files.map((file) => file.name)),
);
await expect(wait).resolves.toBe("native");
expect(sent).toEqual(["a.jpg", "b.jpg"]);
});
it("leaves loose files to the upload", async () => {
const opened: string[] = [];
const wait = beginDropWait();
+32 -4
View File
@@ -11,7 +11,7 @@ export interface FolderListing {
files: FolderFile[];
}
type Kind = "folder" | "files";
type Kind = "folder" | "files" | "native";
interface Gate {
promise: Promise<Kind>;
@@ -66,18 +66,34 @@ export function nativePaths(
paths: string[],
isFolder: (paths: string[]) => Promise<string | null>,
open: (path: string) => void,
/**
* Loose files. Return the photos to upload. An empty list (an older shell that cannot read the drop)
* falls back to the page's own file list, which may contain only a few of them.
*/
readFiles?: (paths: string[]) => Promise<File[]>,
upload?: (files: File[]) => void,
): void {
nativeSeen = true;
const current = takeGate();
clearTimeout(current.timer);
void isFolder(paths)
.then((folder) => {
.then(async (folder) => {
if (folder) {
finish("folder");
open(folder);
} else {
finish("files");
return;
}
if (!readFiles) {
finish("files");
return;
}
const files = await readFiles(paths).catch(() => [] as File[]);
if (!files.length) {
finish("files");
return;
}
finish("native");
upload?.(files);
})
.catch(() => finish("files"));
}
@@ -104,6 +120,18 @@ export function folderDropPath(paths: string[], invoke: Invoke = desktopInvoke):
return invoke<string | null>("folder_drop", { paths });
}
/** Bytes of one photo from the latest drop of loose files. Null when this shell cannot read drops yet. */
export async function readDroppedFile(path: string, invoke: Invoke = desktopInvoke): Promise<ArrayBuffer | null> {
if (!/\.jpe?g$/i.test(path)) return null;
try {
return asArrayBuffer(await invoke<unknown>("drop_read", { path }));
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (/not found|unknown command/i.test(message)) return null;
return null;
}
}
export async function openFolder(path: string, invoke: Invoke = desktopInvoke): Promise<FolderListing> {
try {
return await invoke<FolderListing>("folder_open", { path });
+14 -5
View File
@@ -174,10 +174,12 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
eventId: string | undefined;
original?: DesktopOrigin;
uploaderUserId?: string;
sha256?: string | null;
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
}[]
>([]);
sha256?: string | null;
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
/** The named event was refused once. The next try lets the server place the photo by its clock. */
eventStripped?: boolean;
}[]
>([]);
const running = useRef(0);
/** No network: the queue waits (nothing fails) and carries on when the connection is back. */
const paused = useRef(false);
@@ -222,7 +224,14 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
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}` });
const errorCode = (res.body as { error?: string } | null)?.error;
if (final === "failed" && errorCode === "event_not_in_organization" && next.eventId && !next.eventStripped) {
next.eventId = undefined;
next.eventStripped = true;
waiting = true;
update(item.id, { status: "queued", progress: 0, error: undefined });
queue.current.unshift(next);
} else if (final === "failed") update(item.id, { status: "failed", error: errorCode ?? `http_${res.status}` });
else update(item.id, { status: final, progress: 1 });
} catch (err) {
if (isNetworkError(err)) {
+95 -21
View File
@@ -14,7 +14,7 @@ import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { FolderDevelop } from "../library/FolderDevelop.js";
import { FolderSheet } from "../library/FolderSheet.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, readDroppedFile, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { finishMergedJpeg } from "../library/finishMergedJpeg.js";
import { mergeFolderNative } from "../library/folderMerge.js";
import { MERGE_EDGE } from "../library/mergeStacks.js";
@@ -30,6 +30,7 @@ import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
import { PhotoContextMenu, type PhotoMenuAction } from "../library/PhotoContextMenu.js";
import { RemoveFromEventDialog } from "../library/RemoveFromEvent.js";
import { isEventScope, isRemoveKey, removeFromEvent } from "../library/remove.js";
import { initialLibrary, isMac, type LibraryFilter, libraryReducer, matchesFilter, patchForKey, pmPatchForKey } from "../library/store.js";
@@ -60,6 +61,7 @@ export function LibraryPage() {
const [inboxCount, setInboxCount] = useState(0);
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false);
const [photoMenu, setPhotoMenu] = useState<{ x: number; y: number; id: string } | null>(null);
const { open: openFolderScan, syncGames } = useFolderScan();
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
@@ -277,6 +279,11 @@ export function LibraryPage() {
const [developPath, setDevelopPath] = useState<string | null>(null);
const [openingFolder, setOpeningFolder] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const uploadAddRef = useRef(uploads.add);
const uploadIntoRef = useRef(uploadInto);
uploadAddRef.current = uploads.add;
uploadIntoRef.current = uploadInto;
useEffect(() => {
if (!isDesktop()) return;
let dead = false;
@@ -287,23 +294,38 @@ export function LibraryPage() {
else if (event.payload.type === "leave") setDragging(false);
else if (event.payload.type === "drop") {
setDragging(false);
nativePaths(event.payload.paths, folderDropPath, (path) => {
setOpeningFolder(true);
setLoupe(false);
void openFolder(path).then(
(listing) => {
if (dead) return;
setOpeningFolder(false);
setDevelopPath(null);
setSheet(listing);
},
() => {
if (dead) return;
setOpeningFolder(false);
setError(t.folderSheet.failed);
},
);
});
nativePaths(
event.payload.paths,
folderDropPath,
(path) => {
setOpeningFolder(true);
setLoupe(false);
void openFolder(path).then(
(listing) => {
if (dead) return;
setOpeningFolder(false);
setDevelopPath(null);
setSheet(listing);
},
() => {
if (dead) return;
setOpeningFolder(false);
setError(t.folderSheet.failed);
},
);
},
async (paths) => {
const files: File[] = [];
for (const path of paths) {
const bytes = await readDroppedFile(path);
if (!bytes) continue;
const name = path.split(/[/\\]/).pop() || "photo.jpg";
files.push(new File([bytes], name, { type: "image/jpeg" }));
}
return files;
},
(files) => uploadAddRef.current(files, uploadIntoRef.current),
);
}
}),
).then((stop) => {
@@ -315,7 +337,6 @@ export function LibraryPage() {
unlisten();
};
}, []);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto);
useEffect(() => {
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
@@ -444,6 +465,13 @@ export function LibraryPage() {
dispatch({ type: "select", id, mode: "single", visible: [] });
setLoupe(true);
}, []);
const onPhotoMenu = useCallback(
(id: string, e: React.MouseEvent) => {
if (!state.selected.has(id)) dispatch({ type: "select", id, mode: "single", visible: visibleIds });
setPhotoMenu({ x: e.clientX, y: e.clientY, id });
},
[state.selected, visibleIds],
);
// Face boxes and names over the loupe.
useEffect(() => {
setLoupeFaces([]);
@@ -463,6 +491,32 @@ export function LibraryPage() {
const srcFor = useCallback((p: PhotoSummary) => api.absolute(p.urls.thumb), [api]);
const photoMenuActions = useMemo((): PhotoMenuAction[] => {
if (!photoMenu || !canCull) return [];
const ids = selection.map((p) => p.id);
const inEvent = isEventScope(state.scope);
const actions: PhotoMenuAction[] = [
{ id: "pick", label: t.photoMenuPick, onSelect: () => void patch(ids, { flag: "PICK" }) },
{ id: "reject", label: t.photoMenuReject, onSelect: () => void patch(ids, { flag: "REJECT" }) },
{ id: "clear", label: t.photoMenuClear, onSelect: () => void patch(ids, { flag: "NONE" }) },
{ id: "info", label: t.photoMenuInfo, onSelect: () => setIptcOpen(true) },
];
if (loupe) {
actions.push({ id: "grid", label: t.photoMenuGrid, onSelect: () => setLoupe(false) });
} else if (focus) {
actions.push({ id: "loupe", label: t.photoMenuLoupe, onSelect: () => setLoupe(true) });
actions.push({
id: "develop",
label: t.photoMenuDevelop,
onSelect: () => navigate(`/develop/${focus.id}`),
});
}
if (inEvent) {
actions.push({ id: "remove", label: t.photoMenuRemove, danger: true, onSelect: () => setRemoveOpen(true) });
}
return actions;
}, [photoMenu, canCull, selection, state.scope, loupe, focus, patch, navigate]);
if (!organization) return <p className="p-6 text-sm text-muted">{t.noAccess}</p>;
const picks = state.photos.filter((p) => p.flag === "PICK").length;
@@ -753,10 +807,27 @@ export function LibraryPage() {
) : view === "faces" && state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? (
<FacesView api={api} orgId={orgId} eventId={state.scope} canAnalyse={canCreate} refreshKey={facesTick} />
) : loupe && focus ? (
<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} />
<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}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
/>
) : visible.length || suggested.length ? (
<>
<Grid photos={visible} selected={state.selected} focus={state.focus} orgId={orgId} srcFor={srcFor} onPick={onPick} onOpen={onOpenLoupe} />
<Grid
photos={visible}
selected={state.selected}
focus={state.focus}
orgId={orgId}
srcFor={srcFor}
onPick={onPick}
onOpen={onOpenLoupe}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
/>
{suggested.length > 0 && (
<div className="border-t border-line">
<p className="px-3 pt-3 text-[12px] text-muted">{state.scope === "face:" ? t.lookup.possible(suggested.length) : t.searchSuggested(suggested.length)}</p>
@@ -783,6 +854,9 @@ export function LibraryPage() {
onPlayers={(ids, players) => patch(ids, { players })}
/>
{photoMenu && photoMenuActions.length > 0 && (
<PhotoContextMenu x={photoMenu.x} y={photoMenu.y} actions={photoMenuActions} onClose={() => setPhotoMenu(null)} />
)}
{removeOpen && isEventScope(state.scope) && (
<RemoveFromEventDialog
count={selection.length}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.28",
"version": "0.3.30",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.28"
version = "0.3.30"
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."
+1
View File
@@ -38,6 +38,7 @@ fn main() {
"local_original_changed",
"local_film_thumb",
"folder_drop",
"drop_read",
"folder_open",
"folder_thumb",
"folder_read",
@@ -35,6 +35,7 @@
"allow-local-original-changed",
"allow-local-film-thumb",
"allow-folder-drop",
"allow-drop-read",
"allow-folder-open",
"allow-folder-thumb",
"allow-folder-read",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-drop-read"
description = "Enables the drop_read command without any pre-configured scope."
commands.allow = ["drop_read"]
[[permission]]
identifier = "deny-drop-read"
description = "Denies the drop_read command without any pre-configured scope."
commands.deny = ["drop_read"]
+42 -3
View File
@@ -17,6 +17,9 @@ use crate::local::read_film_thumb;
pub struct OpenFolders {
/// Canonical paths of folders the user actually dropped on the window.
dropped: Mutex<HashSet<PathBuf>>,
/// Photos dropped as files (not inside a folder). Readable until the next drop. The page's file list
/// often receives only a few of them.
files: Mutex<HashSet<PathBuf>>,
/// Folders opened as a contact sheet this session. Thumbnails stay inside these.
open: Mutex<Vec<PathBuf>>,
}
@@ -36,19 +39,40 @@ pub struct FolderFile {
}
impl OpenFolders {
/// Remember folders from a drop on this window. Files in the same drop are ignored.
/// Remember what was dropped on this window. Folders can be opened. Loose photos can be read back,
/// because the page's own file list keeps only a few of a large drop.
pub fn note(&self, paths: &[PathBuf]) {
let mut dropped = self.dropped.lock().unwrap();
let mut files = self.files.lock().unwrap();
files.clear();
for path in paths {
if !path.is_dir() {
if path.is_dir() {
if let Ok(canon) = path.canonicalize() {
dropped.insert(canon);
}
continue;
}
if !path.is_file() || !is_photo(path) {
continue;
}
if let Ok(canon) = path.canonicalize() {
dropped.insert(canon);
files.insert(canon);
}
}
}
/// A photo from the latest drop, canonical. Anything else is refused.
pub fn allow_dropped_file(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|_| "not_found".to_string())?;
if !canon.is_file() || !is_photo(&canon) {
return Err("not_a_photo".to_string());
}
if !self.files.lock().unwrap().contains(&canon) {
return Err("not_allowed".to_string());
}
Ok(canon)
}
/// The dropped folder, canonical, or an error when it was not dropped here or is not a folder.
pub fn open(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|e| e.to_string())?;
@@ -296,6 +320,21 @@ fn listing(root: PathBuf) -> FolderListing {
}
}
/// One photo from the latest drop of loose files. The page uploads it. A path from anywhere else is refused.
#[tauri::command]
pub async fn drop_read(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<tauri::ipc::Response, String> {
let p = folders.allow_dropped_file(Path::new(&path))?;
let meta = tokio::fs::metadata(&p).await.map_err(|e| e.to_string())?;
if meta.len() == 0 || meta.len() > 200 * 1024 * 1024 {
return Err("bad_file".to_string());
}
let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?;
Ok(tauri::ipc::Response::new(bytes))
}
/// The first dropped path that is a folder, so the page can open it instead of uploading the files inside.
#[tauri::command]
pub fn folder_drop(paths: Vec<String>) -> Option<String> {
+1
View File
@@ -150,6 +150,7 @@ pub fn run() {
local::local_stat,
local::local_xmp,
browse::folder_drop,
browse::drop_read,
browse::folder_open,
browse::folder_thumb,
browse::folder_read,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.28",
"version": "0.3.30",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+23 -10
View File
@@ -219,18 +219,22 @@ group.
Face and number are used together:
- **Face sure, number agrees:** the face's suggestion, surer (score + 0.15 × the reading, at most 0.99).
- **Face + number + kit colour** of that player's team is the strongest guess. **Face + number** is next.
A face that already matches is never replaced because a number was also read — that dropped players whose face
was right and whose shorts number was visible. The number only raises the score when it is the same player's.
- **Face sure, no number read:** the face's suggestion. Faces come from confirmed groups and from the official
headshots (Liga, UEFA, FPA licence photos) that squads bring as reference photos, so even a first match has faces to go by.
- **Face sure, number clearly another (two or more readings):** still the face's suggestion, at 0.8 × its score.
- **Face not sure (weak, or two people too close):** among the people the face is near to, the one whose number was
read; else the squad player who wears that number in either team of the event (0.9 × the mean reading).
- **No sure face, clear number:** the squad player who wears it, but only if the kit colour matches a teammate already
trusted. The other team's kit never takes the name. Club crests are not a separate model: chest sponsors are not the
badge, and the shirt colour already separates two kits.
- Two face groups that do not look like the same person never both keep that name: the stronger guess wins.
- **Both teams have that number:** the kit colour decides. Each face keeps the median colour of the middle of its
chest; each team's colour is the median of its players already confirmed in the event, or suggested with face and
shirt agreeing (score 0.85 and up), goalkeepers left out. The same colour also decides between two people the
face is near to who both wear the number read.
The group goes to the team whose colour is clearly closer, never when the two kits are alike or the group's
colour sits in between.
shirt agreeing (score 0.85 and up), goalkeepers left out — a goalkeeper's shirt is a third colour and never
teaches the team's kit, and it does not rule him out when it fails to match either outfield shirt.
Comparison is by hue first, so the same shirt in sun and in shade still matches; white and black still differ.
The group goes to the team whose colour is clearly closer, never when the two kits are alike, the group's
colour sits in between, or it is far from both (the goalkeeper, a referee).
Suggestions still never name anyone on their own.
@@ -278,7 +282,15 @@ hand-drawn boxes.
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh.
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. On start the worker reads
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. The calendar does not
name the ground: `team/info` does (the stadium). The town is that page's city when Liga fills it, otherwise the
town written in the club's own name or in a stadium that names it ("Municipal de Amarante", "Cidade de Coimbra").
A person's name in the stadium ("Dr. Machado de Matos") is not a town. Stadium and town are stored apart
(`venue` and `city`) on the club and on the match, and choosing the match fills both on the event. The same
split is what UEFA (`stadium.city`) and the EHF (`cityName`) already publish. Handball keeps the hall from the
agenda (`LOCAL`, the same line as Recinto on the match sheet). The town is the home club's `CLUBE_LOCALIDADE`
(`getClube`: Oriental → Lisboa, Albicastrense → Castelo Branco). The federation's own card is not a club, so a
seleção does not take Lisboa from F.A.P. A club that leaves the locality blank stays without a city. On start the worker reads
every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro),
so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest
photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list
@@ -452,7 +464,8 @@ credentials, another name and folder).
for Lightroom Classic ≥ 13.2 Attribute filters: `XMP-xmpDM:Pick` (1 / 0 / −1) + `Good`, `XMP-xmp:Rating`,
`XMP-xmp:Label`, plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic. When the desktop app is open it
watches local delivery folders; a Reject written back by Lightroom (XMP auto-write) sets the photo to REJECT
and retracts any delivery of that file.
and retracts any delivery of that file. A colour Photo Mechanic paints on a local original, or on a delivered
file, is copied back (`photomechanic:ColorClass`: 1 red, 3 yellow, 4 green, 5 blue, 7 purple).
**Colour ↔ destination.** A delivery target may own one library colour. Painting that colour queues the photo
only there; enqueue skips `color_mismatch` otherwise. The library colour is how you see what went where.
+61 -8
View File
@@ -197,12 +197,29 @@ function fill(template: string, vars: TemplateVars, codes: CodeList | undefined,
return expanded.text;
}
/** Collapse the spaces an empty variable leaves behind. Missing variables are always reported as issues. */
/**
* Collapse the holes an empty variable leaves behind. Missing variables are always reported as issues.
* The newsroom caption is "{event}, em {city}, no {venue}": without city/venue that must not become
* "AFS x FC Vizela, em , no" on a client delivery.
*/
function tidy(value: string): string {
// A match template on an event without an away team: "Gala x , em Braga" → "Gala, em Braga".
return value
.replace(/\s{2,}/g, " ")
// Match template on an event without an away team: "Gala x , em Braga" → "Gala, em Braga".
.replace(/\s+x\s*(?=,|$)/g, "")
// City missing, venue kept: ", em , no Estádio" → ", no Estádio" (keep the article).
.replace(/,\s*em\s*,\s*(n[oa]s?\s+)/gi, ", $1")
// Both city and venue missing: trailing ", em , no" / ", em , na".
.replace(/,\s*em\s*,\s*n[oa]s?\s*$/gi, "")
// Leftover empty city slot: ", em ,".
.replace(/,\s*em\s*,/gi, ",")
// Venue missing at the end: ", em Braga, no" → ", em Braga".
.replace(/,\s*n[oa]s?\s*$/gi, "")
// Orphan "em" at the end: ", em".
.replace(/,\s*em\s*$/gi, "")
.replace(/\s{2,}/g, " ")
.replace(/,\s*$/g, "")
.replace(/^\s*,\s*/g, "")
.trim();
}
@@ -306,21 +323,57 @@ export function marksToExiftoolArgs(marks: LibraryMarks): string[] {
/**
* Read cull marks from an XMP packet (sidecar or embedded). Used when Lightroom writes Pick back to a delivered file.
*/
/**
* Photo Mechanic's colour class (the number it writes, not the English name). Same map as the IPTC variables:
* 1 red, 3 yellow, 4 green, 5 blue, 7 purple. 0 clears the colour. 2 and 6 are unused in that set.
*/
export type XmpColor = "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
const PM_COLOR_CLASS: Record<number, XmpColor> = {
0: "NONE",
1: "RED",
3: "YELLOW",
4: "GREEN",
5: "BLUE",
7: "PURPLE",
};
const LABEL_NAME: Record<string, XmpColor> = {
red: "RED",
winner: "RED",
yellow: "YELLOW",
superior: "YELLOW",
green: "GREEN",
"superior alt": "GREEN",
blue: "BLUE",
typical: "BLUE",
purple: "PURPLE",
extra: "PURPLE",
none: "NONE",
};
/**
* The colour Photo Mechanic or Lightroom wrote. Null when the packet does not mention a colour, so a file
* that only has a crop does not wipe a colour set in the library. Colour class wins over the label name.
*/
export function colorClassFromXmp(xmp: string): XmpColor | null {
const klass = xmpMatchNum(xmp, /(?:photomechanic:)?ColorClass\s*(?:=|:|>)\s*"?(\d+)/i) ?? xmpMatchNum(xmp, /<(?:photomechanic:)?ColorClass>(\d+)<\/(?:photomechanic:)?ColorClass>/i);
if (klass !== null) return PM_COLOR_CLASS[klass] ?? null;
const labelRaw = xmpMatchStr(xmp, /(?:xmp:Label|Label)\s*(?:=|:|>)\s*"?([A-Za-z]+(?: [A-Za-z]+)?)/i) ?? xmpMatchStr(xmp, /<xmp:Label>([^<]+)<\/xmp:Label>/i);
if (labelRaw === null) return null;
return LABEL_NAME[labelRaw.trim().toLowerCase()] ?? null;
}
export function libraryMarksFromXmp(xmp: string): LibraryMarks {
const pick = xmpMatchNum(xmp, /(?:xmpDM:pick|xmp:Pick|Pick)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmpDM:pick>(-?\d+)<\/xmpDM:pick>/i);
const rating = xmpMatchNum(xmp, /(?:xmp:Rating|Rating)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmp:Rating>(-?\d+)<\/xmp:Rating>/i);
const labelRaw = xmpMatchStr(xmp, /(?:xmp:Label|Label)\s*(?:=|:|>)\s*"?([A-Za-z]+)/i) ?? xmpMatchStr(xmp, /<xmp:Label>([^<]+)<\/xmp:Label>/i);
let flag: LibraryMarks["flag"] = "NONE";
if (pick === -1 || rating === -1) flag = "REJECT";
else if (pick === 1) flag = "PICK";
const colorLabel =
labelRaw && ["Red", "Yellow", "Green", "Blue", "Purple"].includes(labelRaw)
? (labelRaw.toUpperCase() as "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE")
: "NONE";
return {
flag,
rating: rating !== null && rating > 0 ? Math.min(5, rating) : 0,
colorLabel,
colorLabel: colorClassFromXmp(xmp) ?? "NONE",
};
}
+32
View File
@@ -15,6 +15,7 @@ import {
renderFileName,
renderFolder,
seasonOf,
colorClassFromXmp,
cropFromXmp,
libraryMarksFromXmp,
marksToExiftoolArgs,
@@ -99,6 +100,30 @@ describe("IPTC template", () => {
expect(old.event).toBe("Conferência de imprensa do FC Porto");
});
it("does not send a broken Portuguese caption when city and venue are missing", () => {
// Delivered to Cofina as "AFS x FC Vizela, em , no" — unusable in the newsroom.
const game = { home: "AFS", away: "FC Vizela", venue: "", city: "", sport: "futebol", startsAt: new Date("2026-11-04T20:00:00Z") };
const { values, issues } = applyTemplate(NEWSROOM_TEMPLATE, buildVars(game, { players: ["Rodrigo Pinho"] }, "MovePhoto"));
expect(values.caption).toBe("AFS x FC Vizela");
expect(values.headline).toBe("AFS x FC Vizela");
expect(values.event).toBe("AFS x FC Vizela");
expect(values.city).toBeUndefined();
expect(values.location).toBeUndefined();
expect(issues.filter((i) => i.kind === "missing_variable").map((i) => i.detail).sort()).toEqual([
"city",
"city",
"city",
"venue",
"venue",
"venue",
]);
// Only one of city / venue filled: keep the clause that still makes sense.
expect(applyTemplate(NEWSROOM_TEMPLATE, buildVars({ ...game, city: "Vizela" }, {}, "P")).values.caption).toBe("AFS x FC Vizela, em Vizela");
expect(applyTemplate(NEWSROOM_TEMPLATE, buildVars({ ...game, venue: "Estádio do FC Vizela" }, {}, "P")).values.caption).toBe(
"AFS x FC Vizela, no Estádio do FC Vizela",
);
});
it("expands codes typed by an editor and keeps long venues whole", () => {
const { values, issues } = applyTemplate({ title: "\\v7\\", location: "{venue}" }, buildVars(braga), codeList({ v7: "Miguel Silva (VSC)" }));
expect(values.title).toBe("Miguel Silva (VSC)");
@@ -146,6 +171,13 @@ describe("IPTC template", () => {
colorLabel: "BLUE",
});
expect(libraryMarksFromXmp(`xmpDM:pick="-1"`).flag).toBe("REJECT");
expect(colorClassFromXmp(`photomechanic:ColorClass="1"`)).toBe("RED");
expect(colorClassFromXmp(`photomechanic:ColorClass="3"`)).toBe("YELLOW");
expect(colorClassFromXmp(`photomechanic:ColorClass="4"`)).toBe("GREEN");
expect(colorClassFromXmp(`photomechanic:ColorClass="7"`)).toBe("PURPLE");
expect(colorClassFromXmp(`photomechanic:ColorClass="0"`)).toBe("NONE");
expect(colorClassFromXmp(`photomechanic:ColorClass="1" xmp:Label="Blue"`)).toBe("RED");
expect(colorClassFromXmp(`crs:CropTop="0.1"`)).toBeNull();
});
it("reads the soft crop Photo Mechanic and Lightroom draw from crs attributes", () => {
+2 -1
View File
@@ -198,11 +198,12 @@ export interface SportsFixture {
round: string | null;
matchNumber: string | null;
venue: string | null;
city: string | null;
homeScore: number | null;
awayScore: number | null;
sport: string;
competition: { id: string; name: string; provider: SportsProvider; code: string; gender: string | null };
home: { id: string; name: string; abbreviation: string | null; venue: string | null };
home: { id: string; name: string; abbreviation: string | null; venue: string | null; city: string | null };
away: { id: string; name: string; abbreviation: string | null };
}