Compare commits

...
Author SHA1 Message Date
spark 8f6af48055 Keep national teams and sessions off the club squads.
ci / rust (pull_request) Successful in 13m11s
ci / typescript (pull_request) Failing after 14m56s
A FPA seleção is its own list for the season: the women's team, the men's team and an age group do not share a roster or a shirt number. A session of that team has no match number. A gala still has no list.
2026-10-21 20:52:54 +01:00
spark ac88d2445d Recognize a player from the club they were at that season.
ci / rust (pull_request) Successful in 12m25s
ci / typescript (pull_request) Failing after 14m4s
The same person keeps one record when they change club, and the shirt number stays the one worn that season. Liga squads are read for every season still published, and face processes grow until the CPU is about 99% full.
2026-10-21 20:37:41 +01:00
spark 81faa115ec Merge pull request 'Clear wrong face names without re-scoring every game' (#98) from task/faces-roster into main
ci / rust (push) Successful in 12m14s
ci / typescript (push) Failing after 15m56s
2026-10-21 20:19:00 +01:00
spark 7d5efc76b8 Clear wrong face names without re-scoring every game.
ci / rust (pull_request) Successful in 12m46s
ci / typescript (pull_request) Failing after 15m54s
Naming each game again on startup walks every person and stalls the photo analysis. The wrong names are removed; the next read of that game uses the roster.
2026-10-21 20:18:49 +01:00
spark 528666c13c Merge pull request 'Name a face only from the clubs of that game' (#97) from task/faces-roster into main
ci / rust (push) Successful in 11m48s
ci / typescript (push) Failing after 14m50s
Name a face only from the clubs of that game.
2026-10-21 20:12:54 +01:00
spark 17e5ff4bee Name a face only from the clubs of that game.
ci / rust (pull_request) Successful in 11m45s
ci / typescript (pull_request) Failing after 14m22s
A weak likeness was compared with every person in the organisation when the match sheet did not explain it, so a player of one club could be named as a player of another. A known game now stays on its roster, and a past season's squad is stored with the calendar.
2026-10-21 20:12:20 +01:00
spark a44850baa1 Merge pull request 'Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.' (#89) from task/merge-collection into main
ci / rust (push) Successful in 11m16s
ci / typescript (push) Failing after 13m3s
Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.
2026-10-21 13:43:25 +01:00
spark b3df241fdf Merge exposures into a linear DNG in the collection, and stop a card copy before a day that does not fit.
ci / rust (pull_request) Successful in 11m32s
ci / typescript (pull_request) Failing after 13m26s
2026-10-21 13:40:07 +01:00
spark ff1df42195 Merge pull request 'Confirm a person in one step, and fuse one angle at a time' (#87) from task/86-confirm-fuse into main
ci / rust (push) Successful in 9m29s
ci / typescript (push) Failing after 11m23s
Confirm a person in one step, and fuse one angle at a time.
2026-10-21 05:36:11 +01:00
spark efa9256c87 Confirm a person in one step, and fuse one angle at a time.
ci / rust (pull_request) Successful in 9m31s
ci / typescript (pull_request) Failing after 11m19s
A click waited on every game and each one rescored the library, so the card stayed and the API stopped answering. A property shoot was reading every raw at once, so the first angle never appeared.
2026-10-21 05:35:52 +01:00
spark 7fdbc9237b Merge pull request 'Show the whole card copy, finish a fused angle, and open a tournament under its tile' (#85) from task/84-progress-export into main
ci / rust (push) Successful in 9m36s
ci / typescript (push) Failing after 11m40s
Show the whole card copy, finish a fused angle, and open a tournament under its tile.
2026-10-21 05:13:33 +01:00
spark fd846ac68e Show the whole card copy, finish a fused angle, and open a tournament under its tile.
ci / rust (pull_request) Successful in 9m43s
ci / typescript (pull_request) Failing after 11m37s
The progress bar is the copy as a whole. A fused property angle can take a finish and be saved. A tournament's galleries open on the next row instead of below the list.
2026-10-21 05:12:53 +01:00
spark ff6d28064f Merge pull request 'Confirm a face without rescoring every other group first.' (#83) from task/faces-confirm into main
ci / rust (push) Successful in 12m7s
ci / typescript (push) Failing after 13m45s
Confirm a face without rescoring every other group first.
2026-10-21 04:56:43 +01:00
spark 9ced09803f Confirm a face without rescoring every other group first.
ci / rust (pull_request) Successful in 11m56s
ci / typescript (pull_request) Failing after 13m47s
The confirm request waited to rescore the whole match and up to 25 other games, so the button looked dead when that outlasted the proxy. The name is saved immediately, and a failed click now says so.
2026-10-21 04:55:51 +01:00
spark 5d6848b712 Accept a camera clock with no timezone when grouping a property shoot.
ci / rust (push) Successful in 14m19s
ci / typescript (push) Failing after 15m50s
A hora da câmara sem fuso deixava de recusar a pasta inteira.
2026-10-21 04:38:03 +01:00
59 changed files with 2285 additions and 658 deletions

No files matched your search

+5
View File
@@ -474,6 +474,11 @@ export const isVariantSide = (s: string) =>
s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""), s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
); );
/** Every team this side names. One hit is that club; several is ambiguous (the caller does not guess). */
export function teamsNamed<T extends { name: string; abbreviation: string | null; slug: string }>(name: string, teams: T[]): T[] {
return teams.filter((t) => isTeam(name, t));
}
export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean { export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean {
const n = fold(name); const n = fold(name);
if (!n) return false; if (!n) return false;
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { teamsNamed } from "./match.js";
const team = (name: string, slug = name) => ({ id: slug, name, abbreviation: null as string | null, slug });
describe("teamsNamed", () => {
const clubs = [team("CD Feirense", "cd-feirense"), team("SC Farense", "sc-farense"), team("Sporting CP", "sporting-cp"), team("Sporting CP B", "sporting-cp-b")];
it("names Feirense and not Farense", () => {
expect(teamsNamed("CD Feirense", clubs).map((t) => t.name)).toEqual(["CD Feirense"]);
expect(teamsNamed("SC Farense", clubs).map((t) => t.name)).toEqual(["SC Farense"]);
});
it("keeps a senior side off its B team", () => {
expect(teamsNamed("Sporting CP", clubs).map((t) => t.name)).toEqual(["Sporting CP"]);
expect(teamsNamed("Sporting CP B", clubs).map((t) => t.name)).toEqual(["Sporting CP B"]);
});
});
+5 -5
View File
@@ -160,13 +160,13 @@ export class FaceLookup {
/** /**
* Named people like the face (their centroid: confirmed faces and reference photo). * Named people like the face (their centroid: confirmed faces and reference photo).
* `prefer`, when set, is the whole search when anyone there matches: the game's players and officials. * `prefer`, when it is a list, is a known game's roster and the whole search: a face none of them
* Only a face none of them match is compared with the rest of the organization. * match stays unnamed. Null means the event is not a bounded game, so the whole organization is asked.
*/ */
async people(orgId: string, embedding: number[], model: string, limit = 5, prefer: string[] | null = null) { async people(orgId: string, embedding: number[], model: string, limit = 5, prefer: string[] | null = null) {
if (prefer?.length) { if (prefer) {
const inGame = await this.matchPeople(orgId, embedding, model, limit, prefer); if (!prefer.length) return [];
if (inGame.length) return inGame; return this.matchPeople(orgId, embedding, model, limit, prefer);
} }
return this.matchPeople(orgId, embedding, model, limit, null); return this.matchPeople(orgId, embedding, model, limit, null);
} }
+5 -5
View File
@@ -124,8 +124,8 @@ export async function registerLookupRoutes(
/** /**
* One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person. * One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person.
* A game is asked first (its players and officials). Anyone it does not know is looked up in the whole * A known game is only its players and officials. A face none of them match stays unnamed. The file is
* organization. The file is read and thrown away. Nothing is written to the library. * read and thrown away. Nothing is written to the library.
*/ */
app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => { app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params); const { orgId } = OrgParams.parse(req.params);
@@ -139,7 +139,7 @@ export async function registerLookupRoutes(
const ctx = eventId ? await numberContext(db, eventId) : null; const ctx = eventId ? await numberContext(db, eventId) : null;
const ids = eventId ? await roster(eventId) : null; const ids = eventId ? await roster(eventId) : null;
const hits = await Promise.all( const hits = await Promise.all(
read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids && ids.length ? ids : null))[0] ?? null) : null)), read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids))[0] ?? null) : null)),
); );
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>(); const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return { return {
@@ -158,7 +158,7 @@ export async function registerLookupRoutes(
/** /**
* Names for faces already read on the photographer's computer. The photo stays there; only the embeddings * Names for faces already read on the photographer's computer. The photo stays there; only the embeddings
* (and nothing else) are compared, first with the game and then with everyone else. * (and nothing else) are compared with the game's roster, or with the whole organization when it has none.
*/ */
app.post("/v1/orgs/:orgId/faces/identify", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => { app.post("/v1/orgs/:orgId/faces/identify", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params); const { orgId } = OrgParams.parse(req.params);
@@ -174,7 +174,7 @@ export async function registerLookupRoutes(
if (!org.biometricsEnabled) throw conflict("biometrics_disabled"); if (!org.biometricsEnabled) throw conflict("biometrics_disabled");
const ctx = body.eventId ? await numberContext(db, body.eventId) : null; const ctx = body.eventId ? await numberContext(db, body.eventId) : null;
const ids = body.eventId ? await roster(body.eventId) : null; const ids = body.eventId ? await roster(body.eventId) : null;
const prefer = ids && ids.length ? ids : null; const prefer = ids;
const hits = await Promise.all(body.faces.map(async (f) => (await lookup.people(orgId, f.embedding, body.model, 1, prefer))[0] ?? null)); const hits = await Promise.all(body.faces.map(async (f) => (await lookup.people(orgId, f.embedding, body.model, 1, prefer))[0] ?? null));
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>(); const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return { return {
+7
View File
@@ -52,6 +52,13 @@ export const THRESHOLDS: Record<string, { match: number; group: number; margin:
"sface-2021dec": { match: 0.55, group: 0.6, margin: 0.05 }, "sface-2021dec": { match: 0.55, group: 0.6, margin: 0.05 },
}; };
/** No roster (a session, a name that is not a club): a barely-there likeness is not a name. */
export const OPEN_EXTRA = 0.12;
export const OPEN_MARGIN = 0.08;
export function openFloor(match: number): number {
return Math.min(0.9, match + OPEN_EXTRA);
}
/** /**
* Faces softer than this (variance of the Laplacian of the 112 px aligned face, grey levels) are kept, boxed * Faces softer than this (variance of the Laplacian of the 112 px aligned face, grey levels) are kept, boxed
* in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder. * in the loupe, but never grouped: out-of-focus faces (crowd, background) all look alike to the embedder.
+151 -7
View File
@@ -1,6 +1,8 @@
import { isNationalSide, seasonOf } from "../archive/match.js"; import { isExhibition, isNationalSide, seasonOf, teamsNamed } from "../archive/match.js";
import type { Db } from "../db.js"; import type { Db } from "../db.js";
import { normLabel } from "../jersey/service.js"; import { normLabel } from "../jersey/service.js";
import { selectionKey, selectionNeedles } from "./selection.js";
import { eventSport } from "./sport.js";
import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js"; import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js";
/** /**
@@ -17,8 +19,15 @@ export interface NumberContext {
competition: string; competition: string;
/** A national team's game or session: club numbers never apply. */ /** A national team's game or session: club numbers never apply. */
national: boolean; national: boolean;
/**
* The national team when the folder names one ("snaf", "snam", "m18").
* Null when the event only says "Portugal": the country is not an age group.
*/
side: string | null;
/** The season now: only then does the number typed on the person (with no season of its own) apply. */ /** The season now: only then does the number typed on the person (with no season of its own) apply. */
current: boolean; current: boolean;
/** Linked to an official fixture: that competition's squad numbers come before what other shirts read. */
official: boolean;
teamIds: string[]; teamIds: string[];
} }
@@ -48,17 +57,66 @@ export async function numberContext(db: Db, eventId: string, now = new Date()):
// An event that is not a game (a gala, a session, a presentation): nobody is known by a shirt there, only by face. // An event that is not a game (a gala, a session, a presentation): nobody is known by a shirt there, only by face.
if (!e || !e.away?.trim()) return null; if (!e || !e.away?.trim()) return null;
const season = e.fixture?.season ?? seasonOf(day(e.startsAt)); const season = e.fixture?.season ?? seasonOf(day(e.startsAt));
const national = isNationalEvent(e);
let side: string | null = null;
if (national) {
const folders = await db.cloudFolder.findMany({ where: { eventId }, select: { path: true }, take: 8 });
side = selectionKey([e.home, e.away ?? "", e.competition ?? "", ...folders.map((f) => f.path)]);
}
return { return {
organizationId: e.organizationId, organizationId: e.organizationId,
eventId, eventId,
season, season,
competition: competitionKey(e), competition: competitionKey(e),
national: isNationalEvent(e), national,
side,
current: season === seasonOf(day(now)), current: season === seasonOf(day(now)),
official: !!e.fixture,
teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t), teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t),
}; };
} }
/**
* Fills a game's missing clubs from the teams of its sport, when the side names exactly one of them.
* A session, a national team, or an exhibition is left alone. Idempotent.
*/
export async function bindEventTeams(db: Db, eventId: string): Promise<void> {
const e = await db.event.findUnique({
where: { id: eventId },
select: { home: true, away: true, competition: true, homeTeamId: true, awayTeamId: true, startsAt: true, fixture: { select: { season: true } } },
});
if (!e?.away?.trim() || (e.homeTeamId && e.awayTeamId)) return;
if (isNationalEvent(e) || isExhibition({ home: e.home, away: e.away, parents: e.competition ? [e.competition] : [] })) return;
const sport = await eventSport(db, eventId);
if (!sport) return;
const season = e.fixture?.season ?? seasonOf(day(e.startsAt));
const teams = await db.sportsTeam.findMany({
where: { sport: { equals: sport, mode: "insensitive" } },
select: { id: true, name: true, abbreviation: true, slug: true },
});
const homeId = e.homeTeamId ?? (await oneTeam(db, e.home, teams, season));
const awayId = e.awayTeamId ?? (await oneTeam(db, e.away, teams, season));
// One side resolved is still that club's squad. Both sides resolving to the same club is a bad guess.
if (homeId && awayId && homeId === awayId) return;
const data: { homeTeamId?: string; awayTeamId?: string } = {};
if (!e.homeTeamId && homeId && homeId !== awayId) data.homeTeamId = homeId;
if (!e.awayTeamId && awayId && awayId !== homeId) data.awayTeamId = awayId;
if (Object.keys(data).length) await db.event.update({ where: { id: eventId }, data });
}
/** The one team this side names, or the one of several that actually has a squad that season. */
async function oneTeam(db: Db, name: string, teams: { id: string; name: string; abbreviation: string | null; slug: string }[], season: string): Promise<string | null> {
const hits = teamsNamed(name, teams);
if (hits.length === 1) return hits[0]!.id;
if (hits.length < 2) return null;
const withSquad: typeof hits = [];
for (const h of hits) {
const n = await db.sportsPlayer.count({ where: { teamId: h.id, season } });
if (n > 0) withSquad.push(h);
}
return withSquad.length === 1 ? withSquad[0]!.id : null;
}
/** /**
* The number each person wears in this context, when it is known: the squad of that season (the official list) * The number each person wears in this context, when it is known: the squad of that season (the official list)
* and what the shirts clearly read in their confirmed photos of the same season and competition (`learned`; first * and what the shirts clearly read in their confirmed photos of the same season and competition (`learned`; first
@@ -108,7 +166,10 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[],
where: { organizationId: ctx.organizationId, startsAt: { gte: from, lt: to } }, where: { organizationId: ctx.organizationId, startsAt: { gte: from, lt: to } },
select: { id: true, home: true, away: true, competition: true, competitionCode: true }, select: { id: true, home: true, away: true, competition: true, competitionCode: true },
}); });
const same = events.filter((e) => competitionKey(e) === ctx.competition && isNationalEvent(e) === ctx.national).map((e) => e.id); const onSide = ctx.national && ctx.side ? new Set(await eventsOfSide(db, ctx.organizationId, ctx.season, ctx.side)) : null;
const same = events
.filter((e) => (onSide ? onSide.has(e.id) : competitionKey(e) === ctx.competition && isNationalEvent(e) === ctx.national))
.map((e) => e.id);
if (same.length) { if (same.length) {
const faces = await db.face.findMany({ const faces = await db.face.findMany({
where: { photo: { eventId: { in: same } }, group: { personId: { in: rest } }, jerseyNumber: { not: null }, jerseyScore: { gte: JERSEY_MIN_SCORE } }, where: { photo: { eventId: { in: same } }, group: { personId: { in: rest } }, jerseyNumber: { not: null }, jerseyScore: { gte: JERSEY_MIN_SCORE } },
@@ -128,7 +189,7 @@ export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[],
// An official match: its season's squad first. A game not linked to one (a cup, a friendly, a tournament with // An official match: its season's squad first. A game not linked to one (a cup, a friendly, a tournament with
// its own numbering): what the shirts read in that competition first, then the season's squad. // its own numbering): what the shirts read in that competition first, then the season's squad.
const order = ctx.teamIds.length ? [squadOf, learnedOf] : [learnedOf, squadOf]; const order = ctx.official ? [squadOf, learnedOf] : [learnedOf, squadOf];
for (const p of people) { for (const p of people) {
const n = order[0]!.get(p.id) ?? order[1]!.get(p.id); const n = order[0]!.get(p.id) ?? order[1]!.get(p.id);
if (n) out.set(p.id, n); if (n) out.set(p.id, n);
@@ -152,6 +213,58 @@ interface FixtureOfficial {
externalId?: string | null; externalId?: string | null;
} }
/** Events of one national team in a season (the women's senior team is not the men's, and not an age group). */
async function eventsOfSide(db: Db, organizationId: string, season: string, side: string): Promise<string[]> {
const { from, to } = seasonRange(season);
const needles = selectionNeedles(side);
const events = await db.event.findMany({
where: {
organizationId,
startsAt: { gte: from, lt: to },
OR: needles.flatMap((needle) => [
{ home: { contains: needle, mode: "insensitive" } },
{ away: { contains: needle, mode: "insensitive" } },
{ competition: { contains: needle, mode: "insensitive" } },
{ cloudFolders: { some: { path: { contains: needle, mode: "insensitive" } } } },
]),
},
select: { id: true, home: true, away: true, competition: true, cloudFolders: { select: { path: true }, take: 4 } },
});
return events
.filter((e) => selectionKey([e.home, e.away ?? "", e.competition ?? "", ...e.cloudFolders.map((f) => f.path)]) === side)
.map((e) => e.id);
}
/** People already confirmed, with a face, on that national team this season. */
async function peopleConfirmedOnSide(db: Db, organizationId: string, season: string, side: string): Promise<string[]> {
const eventIds = await eventsOfSide(db, organizationId, season, side);
if (!eventIds.length) return [];
const rows = await db.faceGroup.findMany({
where: { eventId: { in: eventIds }, personId: { not: null }, ignoredAt: null },
select: { personId: true, person: { select: { centroid: true } } },
});
return [...new Set(rows.filter((r) => r.personId && r.person && r.person.centroid.length > 0).map((r) => r.personId!))];
}
/** People a session's folders name ("7 - Bebiana Sabino"), when that person already has a face. */
async function peopleNamedHere(db: Db, eventId: string, organizationId: string): Promise<string[]> {
const photos = await db.photo.findMany({ where: { eventId }, select: { players: true } });
const names = [...new Set(photos.flatMap((p) => p.players).map((n) => n.trim()).filter(Boolean))];
if (!names.length) return [];
const people = await db.person.findMany({
where: { organizationId, name: { in: names } },
select: { id: true, centroid: true },
});
return people.filter((p) => p.centroid.length > 0).map((p) => p.id);
}
/** The people a suggestion may name. Null: this event has no roster, so the caller uses the whole list. An empty list is a known squad that has no face on file yet. */
export function peopleOnRoster<T extends { id: string }>(people: T[], roster: string[] | null): T[] | null {
if (!roster) return null;
const ids = new Set(roster);
return people.filter((p) => ids.has(p.id));
}
/** /**
* Who this game should be asked first: the season's squad of the two teams (the same player, even when their * Who this game should be asked first: the season's squad of the two teams (the same player, even when their
* person row points at another season) and the match officials who already have a face (referees, table). * person row points at another season) and the match officials who already have a face (referees, table).
@@ -159,6 +272,32 @@ interface FixtureOfficial {
* means the squad is known and none of them have a face on file yet. * means the squad is known and none of them have a face on file yet.
*/ */
export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> { export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> {
await bindEventTeams(db, eventId);
const event = await db.event.findUnique({
where: { id: eventId },
select: {
organizationId: true,
home: true,
away: true,
competition: true,
startsAt: true,
cloudFolders: { select: { path: true }, take: 8 },
},
});
if (!event) return null;
const side = selectionKey([event.home, event.away ?? "", event.competition ?? "", ...event.cloudFolders.map((f) => f.path)]);
const game = !!event.away?.trim();
// A session, a training, a studio day, or a national team: never a club's squad.
// A gala or a press day names no team, so the caller compares the face on its own.
if (!game && !side) return null;
if (!game || side || isNationalEvent(event)) {
const ids = new Set<string>();
const season = seasonOf(day(event.startsAt));
if (side) for (const id of await peopleConfirmedOnSide(db, event.organizationId, season, side)) ids.add(id);
if (!game) for (const id of await peopleNamedHere(db, eventId, event.organizationId)) ids.add(id);
if (game) for (const id of await officialsOf(db, eventId, event.organizationId)) ids.add(id);
return [...ids];
}
const ctx = await numberContext(db, eventId); const ctx = await numberContext(db, eventId);
if (!ctx) return null; if (!ctx) return null;
const ids = new Set<string>(); const ids = new Set<string>();
@@ -179,6 +318,11 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
AND ( AND (
squad.id = mine.id squad.id = mine.id
OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id) OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id)
OR (
squad.birth_date IS NOT NULL AND squad.full_name IS NOT NULL
AND mine.birth_date = squad.birth_date
AND lower(mine.full_name) = lower(squad.full_name)
)
OR (squad.team_id = mine.team_id AND squad.name = mine.name) OR (squad.team_id = mine.team_id AND squad.name = mine.name)
) )
)`; )`;
@@ -189,9 +333,9 @@ export async function rosterOf(db: Db, eventId: string): Promise<string[] | null
if (ids.size) return [...ids]; if (ids.size) return [...ids];
if (squad > 0) return []; if (squad > 0) return [];
// No official squad: people typed against these clubs, and only when that set is small enough to be the game. // No official squad: people typed against these clubs, and only when that set is small enough to be the game.
const event = await db.event.findUnique({ where: { id: eventId }, select: { home: true, away: true, homeShort: true, awayShort: true } }); const named = await db.event.findUnique({ where: { id: eventId }, select: { home: true, away: true, homeShort: true, awayShort: true } });
if (!event) return null; if (!named) return null;
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(fold); const teams = [named.home, named.away, named.homeShort, named.awayShort].filter((t): t is string => !!t).map(fold);
const people = await db.person.findMany({ const people = await db.person.findMany({
where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } }, where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } },
select: { id: true, club: true }, select: { id: true, club: true },
+2 -2
View File
@@ -1,8 +1,8 @@
import { cpus } from "node:os"; import { cpus } from "node:os";
import { LeastBusy, LineProcess } from "../lib/line-process.js"; import { LeastBusy, LineProcess } from "../lib/line-process.js";
/** Stop adding face processes once the machine is this full. */ /** Stop adding face processes once the machine is this full. One percent stays free for the rest of the system. */
const CPU_TARGET = 0.97; const CPU_TARGET = 0.99;
interface CpuTimes { interface CpuTimes {
idle: number; idle: number;
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { openFloor } from "./math.js";
import { peopleOnRoster } from "./numbers.js";
describe("peopleOnRoster", () => {
const people = [{ id: "a" }, { id: "b" }, { id: "c" }];
it("uses the whole list only when the event has no roster", () => {
expect(peopleOnRoster(people, null)).toBeNull();
});
it("names nobody when the squad is known and none of them have a face yet", () => {
expect(peopleOnRoster(people, [])).toEqual([]);
});
it("keeps only the people on the sheet", () => {
expect(peopleOnRoster(people, ["b", "missing"]).map((p) => p.id)).toEqual(["b"]);
});
});
describe("openFloor", () => {
it("asks more of a face when the game has no roster", () => {
expect(openFloor(0.4)).toBeCloseTo(0.52);
expect(openFloor(0.55)).toBeCloseTo(0.67);
});
});
+19
View File
@@ -18,6 +18,10 @@ const PhotoParams = z.object({ photoId: z.uuid() });
const OrgParams = z.object({ orgId: z.uuid() }); const OrgParams = z.object({ orgId: z.uuid() });
const MergeBody = z.object({ into: z.uuid() }); const MergeBody = z.object({ into: z.uuid() });
const IgnoreBody = z.object({ ignored: z.boolean() }); const IgnoreBody = z.object({ ignored: z.boolean() });
const ConfirmPileBody = z.object({
personId: z.uuid(),
groupIds: z.array(z.uuid()).min(1).max(80),
});
const BiometricsBody = z.object({ const BiometricsBody = z.object({
enabled: z.boolean(), enabled: z.boolean(),
/** Required to switch on: why the organization may process faces (e.g. consent, contract, legitimate interest). */ /** Required to switch on: why the organization may process faces (e.g. consent, contract, legitimate interest). */
@@ -148,6 +152,21 @@ export async function registerFaceRoutes(
}; };
}); });
/** One click names every game of that person. Separate requests were rescored in parallel until the API stopped. */
app.post("/v1/orgs/:orgId/face-review/confirm", { preHandler: authenticate }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
await requireMembership(db, req, orgId, "INGESTER");
const body = ConfirmPileBody.parse(req.body);
const groups = await db.faceGroup.findMany({ where: { id: { in: body.groupIds } }, select: { id: true, organizationId: true } });
if (groups.length !== new Set(body.groupIds).size || groups.some((group) => group.organizationId !== orgId)) throw notFound("group_not_found");
try {
const person = await faces.confirmPile(body.groupIds, body.personId, currentUserId(req));
return { person: personOut(person) };
} catch (err) {
return fail(err);
}
});
app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => { app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => {
const { groupId } = GroupParams.parse(req.params); const { groupId } = GroupParams.parse(req.params);
const body = ConfirmFaceGroup.parse(req.body); const body = ConfirmFaceGroup.parse(req.body);
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { selectionKey } from "./selection.js";
describe("selectionKey", () => {
it("treats the women's and men's national teams as different teams, whatever the folder calls them", () => {
const women = selectionKey(["/FPA/Fotos/2025_2026/Seleções Nacionais/SNAF/20260409 - POR x MNE"]);
const womenTitle = selectionKey(["Seleção Nacional A Feminina · Sessão"]);
const men = selectionKey(["/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/20250122 - SWE x POR"]);
expect(women).toBe("snaf");
expect(womenTitle).toBe(women);
expect(men).toBe("snam");
expect(men).not.toBe(women);
});
it("keeps an age group apart from the senior teams", () => {
expect(selectionKey(["/FPA/Fotos/2025_2026/Seleções Nacionais/M18/Torneio Tiby/POR_FRA"])).toBe("m18");
});
it("names no team for a club game, a gala, or a gathering", () => {
expect(selectionKey(["Sporting CP", "ABC de Braga", "Andebol 1"])).toBeNull();
expect(selectionKey(["Portugal", "França"])).toBeNull();
expect(selectionKey(["Gala 20250614"])).toBeNull();
expect(selectionKey(["Encontro Nacional sub-14 · Dia 2"])).toBeNull();
});
});
+26
View File
@@ -0,0 +1,26 @@
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
/**
* Which national team a folder or a title is, when it names one.
* "SNAF" and "Seleção Nacional A Feminina" are the same team. A country name alone is not:
* Portugal against France can be the senior women, the senior men, or an age group.
* A gala, a press day, or "Encontro Nacional sub-14" names no team.
*/
export function selectionKey(texts: string[]): string | null {
const f = fold(texts.filter(Boolean).join("\n"));
if (!f) return null;
if (/\bsnaf\b/.test(f) || /selecao nacional a feminina/.test(f) || /selecao feminina/.test(f)) return "snaf";
if (/\bsnam\b/.test(f) || /selecao nacional a masculina/.test(f) || /selecao masculina/.test(f)) return "snam";
if (/\bsna\b/.test(f)) return "snam";
const coded = /\b([mw])(\d{2})\b/.exec(f);
if (coded && /selec/.test(f)) return `${coded[1]}${coded[2]}`;
return null;
}
/** Strings a stored path or title may contain for this team. */
export function selectionNeedles(key: string): string[] {
if (key === "snaf") return ["SNAF", "Seleção Nacional A Feminina", "Seleção Feminina"];
if (key === "snam") return ["SNAM", "SNA", "Seleção Nacional A Masculina", "Seleção Masculina"];
if (/^[mw]\d{2}$/.test(key)) return [key.toUpperCase()];
return [key];
}
+203 -54
View File
@@ -15,11 +15,13 @@ import { normLabel } from "../jersey/service.js";
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */ /** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
const STRONG_SUGGESTION = 0.85; const STRONG_SUGGESTION = 0.85;
export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js"; export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
export { eventSport, normSport } from "./sport.js";
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim(); const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js"; import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
import { numberContext, numbersIn, rosterOf, type NumberContext } from "./numbers.js"; import { numberContext, numbersIn, peopleOnRoster, rosterOf, type NumberContext } from "./numbers.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js"; import { eventSport, normSport } from "./sport.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, OPEN_MARGIN, THRESHOLDS, openFloor } from "./math.js";
import type { FaceEngine } from "./process.js"; import type { FaceEngine } from "./process.js";
import { FaceFollower } from "./track.js"; import { FaceFollower } from "./track.js";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
@@ -62,6 +64,10 @@ export class FaceRejected extends Error {
* confirms a group, name every photo in it, including photos that arrive later. * confirms a group, name every photo in it, including photos that arrive later.
*/ */
export class FaceService { export class FaceService {
/** Events waiting to be rescored. One run at a time: a burst of Confirmar was starting dozens and the API stopped answering. */
private readonly pendingRefresh = new Set<string>();
private refreshRunning = false;
constructor( constructor(
private readonly deps: { private readonly deps: {
db: Db; db: Db;
@@ -118,6 +124,12 @@ export class FaceService {
(n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions of another sport taken away")), (n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions of another sport taken away")),
(err) => this.deps.log.warn({ err }, "faces: cross-sport suggestions not checked"), (err) => this.deps.log.warn({ err }, "faces: cross-sport suggestions not checked"),
); );
// A name from outside a known game (made when a weak face was compared with the whole organization).
// Cleared only. Naming the game again here walks every person of every event and stalls photo analysis.
void dropOffRosterSuggestions(this.deps.db).then(
(n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions from outside the game taken away")),
(err) => this.deps.log.warn({ err }, "faces: roster suggestions not checked"),
);
const r = await this.deps.db.photo.updateMany({ const r = await this.deps.db.photo.updateMany({
where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } }, where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
data: { facesStatus: "PENDING" }, data: { facesStatus: "PENDING" },
@@ -540,12 +552,13 @@ export class FaceService {
const sport = await eventSport(db, eventId); const sport = await eventSport(db, eventId);
const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>(); const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>();
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport); const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// A club game is named only from that season's squad. A national team or a session of one is named only
// from that team. A gala has no list: the face alone, and only a clearly stronger match.
const sheet = await rosterOf(db, eventId);
const bounded = sheet !== null;
const pool = peopleOnRoster(people, sheet) ?? people;
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another). // Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
const ctx = await numberContext(db, eventId); const ctx = await numberContext(db, eventId);
// A game: the match sheet first (players, coaches, referees who already have a face). A session has no sheet,
// so the face is compared with everyone of that sport. The wider list is only for a face the sheet does not explain.
const sheet = await rosterOf(db, eventId);
const onSheet = sheet && sheet.length ? new Set(sheet) : null;
const worn = new Map<string, string | null>(); const worn = new Map<string, string | null>();
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => { const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
const missing = ids.filter((id) => !worn.has(id)); const missing = ids.filter((id) => !worn.has(id));
@@ -555,15 +568,18 @@ export class FaceService {
} }
return worn; return worn;
}; };
const pick = async (pool: typeof people, g: (typeof groups)[number], allowNumber: boolean) => { const pick = async (candidates: typeof people, g: (typeof groups)[number], allowNumber: boolean) => {
const { match, margin } = this.thresholds(g.model); const { match, margin } = this.thresholds(g.model);
// No roster: 0.40 is enough for two bald faces of different clubs to trade names. Ask for a clearer gap.
const floor = bounded ? match : openFloor(match);
const gap = bounded ? margin : Math.max(margin, OPEN_MARGIN);
const rejected = notThem.get(g.id); const rejected = notThem.get(g.id);
const ranked = pool const ranked = candidates
.filter((p) => p.model === g.model && !rejected?.has(p.id)) .filter((p) => p.model === g.model && !rejected?.has(p.id))
.map((p) => ({ p, s: cosine(p.centroid, g.centroid) })) .map((p) => ({ p, s: cosine(p.centroid, g.centroid) }))
.sort((a, b) => b.s - a.s); .sort((a, b) => b.s - a.s);
const [first, second] = ranked; const [first, second] = ranked;
const ok = first && first.s >= match && (!second || first.s - second.s >= margin); const ok = first && first.s >= floor && (!second || first.s - second.s >= gap);
let suggestedPersonId = ok ? first.p.id : null; let suggestedPersonId = ok ? first.p.id : null;
let suggestionScore = ok ? first.s : null; let suggestionScore = ok ? first.s : null;
const read = await this.groupNumber(g.id); const read = await this.groupNumber(g.id);
@@ -577,7 +593,7 @@ export class FaceService {
} else if (!ok && read && allowNumber) { } 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, // 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. // and when two of them wear it (one per team), the kit colour.
const close = ranked.filter((r) => r.s >= match * 0.8); const close = ranked.filter((r) => r.s >= (bounded ? match * 0.8 : floor));
const nums = await numberOf(close.map((r) => r.p.id)); const nums = await numberOf(close.map((r) => r.p.id));
let near = close.filter((r) => nums.get(r.p.id) === read.number); let near = close.filter((r) => nums.get(r.p.id) === read.number);
if (near.length > 1) { if (near.length > 1) {
@@ -601,10 +617,7 @@ export class FaceService {
return { suggestedPersonId, suggestionScore }; return { suggestedPersonId, suggestionScore };
}; };
for (const g of groups) { for (const g of groups) {
const first = onSheet ? people.filter((p) => onSheet.has(p.id)) : people; const { suggestedPersonId, suggestionScore } = await pick(pool, g, true);
let { suggestedPersonId, suggestionScore } = await pick(first, g, true);
// Nobody on the sheet: only then a face from outside it. The shirt stays with the two clubs.
if (!suggestedPersonId && onSheet) ({ suggestedPersonId, suggestionScore } = await pick(people, g, false));
if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) { if (g.suggestedPersonId !== suggestedPersonId || g.suggestionScore !== suggestionScore) {
await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } }); await db.faceGroup.update({ where: { id: g.id }, data: { suggestedPersonId, suggestionScore } });
} }
@@ -623,13 +636,17 @@ export class FaceService {
*/ */
private async suggestByNumber(groupId: string, ctx: NumberContext, read: NumberVote): Promise<{ personId: string; score: number } | null> { private async suggestByNumber(groupId: string, ctx: NumberContext, read: NumberVote): Promise<{ personId: string; score: number } | null> {
const { db } = this.deps; const { db } = this.deps;
// A national team wears its own numbers. The club who has that number this season is someone else.
if (ctx.national) return null;
const eventId = ctx.eventId; const eventId = ctx.eventId;
const event = await db.event.findUnique({ const event = await db.event.findUnique({
where: { id: eventId }, where: { id: eventId },
select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true }, select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true },
}); });
if (!event) return null; if (!event) return null;
// Linked to the official match: that season's squads say who wears the number (not today's squad). // The two clubs are known: that season's squads say who wears the number (not today's squad).
// A cup whose shirts use another numbering still wins when the face is already close to someone
// (`numbersIn` reads that competition first, unless this event is the official fixture).
const teamIds = ctx.teamIds; const teamIds = ctx.teamIds;
if (teamIds.length) { 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 } });
@@ -730,17 +747,50 @@ export class FaceService {
where: { id: { in: photoIds } }, where: { id: { in: photoIds } },
select: { id: true, organizationId: true, players: true, faces: { select: { group: { select: { person: { select: { name: true } } } } } } }, select: { id: true, organizationId: true, players: true, faces: { select: { group: { select: { person: { select: { name: true } } } } } } },
}); });
const pending: { id: string; organizationId: string; players: string[] }[] = [];
for (const photo of photos) { for (const photo of photos) {
const names = photo.faces.map((f) => f.group?.person?.name).filter((n): n is string => !!n); const names = photo.faces.map((f) => f.group?.person?.name).filter((n): n is string => !!n);
const players = [...new Set([...photo.players, ...names])]; const players = [...new Set([...photo.players, ...names])];
if (players.length === photo.players.length) continue; if (players.length === photo.players.length) continue;
await db.photo.update({ where: { id: photo.id }, data: { players } }); pending.push({ id: photo.id, organizationId: photo.organizationId, players });
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players } }); }
if (!pending.length) return;
await db.$transaction(pending.map((photo) => db.photo.update({ where: { id: photo.id }, data: { players: photo.players } })));
for (const photo of pending) {
broadcaster.library(photo.organizationId, { type: "photo.updated", ids: [photo.id], patch: { players: photo.players } });
} }
} }
/** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */ /** Names a group: an existing person, or a new one. Every photo with a face in the group gets the name. */
async confirm(groupId: string, who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined }, userId: string | null): Promise<Person> { async confirm(groupId: string, who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined }, userId: string | null): Promise<Person> {
const named = await this.writeConfirmation(groupId, who, userId);
await this.finishConfirmation(named.person.id, [named.eventId], named.organizationId);
return named.person;
}
/**
* Names every selected group as one person, then rescores once. The queue used to confirm each game as its own
* request, and each request rescored the library, so one click sat there and a few clicks stopped the API.
*/
async confirmPile(groupIds: string[], personId: string, userId: string | null): Promise<Person> {
const unique = [...new Set(groupIds)];
if (unique.length === 0) throw new FaceRejected("group_not_found");
let named: { person: Person; eventId: string; organizationId: string } | null = null;
const events = new Set<string>();
for (const groupId of unique) {
named = await this.writeConfirmation(groupId, { personId }, userId);
events.add(named.eventId);
}
if (!named) throw new FaceRejected("group_not_found");
await this.finishConfirmation(personId, [...events], named.organizationId);
return named.person;
}
private async writeConfirmation(
groupId: string,
who: { personId: string } | { name: string; club?: string | undefined; number?: string | undefined },
userId: string | null,
): Promise<{ person: Person; eventId: string; organizationId: string }> {
const { db } = this.deps; const { db } = this.deps;
const group = await db.faceGroup.findUnique({ where: { id: groupId } }); const group = await db.faceGroup.findUnique({ where: { id: groupId } });
if (!group) throw new FaceRejected("group_not_found"); if (!group) throw new FaceRejected("group_not_found");
@@ -757,23 +807,70 @@ export class FaceService {
update: { ...(who.club !== undefined && { club: who.club }), ...(who.number !== undefined && { number: who.number }) }, update: { ...(who.club !== undefined && { club: who.club }), ...(who.number !== undefined && { number: who.number }) },
}); });
} }
if (person.model && person.model !== group.model) throw new FaceRejected("model_mismatch"); // A group from another embedding model is still named. recomputePerson keeps the centroid on the
// person's own model, so the vectors are not mixed and Confirmar is not refused.
await db.faceGroup.update({ where: { id: groupId }, data: { personId: person.id, suggestedPersonId: null, suggestionScore: null, ignoredAt: null, confirmedById: userId } }); await db.faceGroup.update({ where: { id: groupId }, data: { personId: person.id, suggestedPersonId: null, suggestionScore: null, ignoredAt: null, confirmedById: userId } });
person = await this.recomputePerson(person.id); person = await this.recomputePerson(person.id);
const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId); const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId);
await this.nameConfirmedPhotos([...new Set(photoIds)]); await this.nameConfirmedPhotos([...new Set(photoIds)]);
await this.refreshSuggestions(group.eventId); return { person, eventId: group.eventId, organizationId: group.organizationId };
// The same person suggested in other games: their cards are read again with this face included, so confirming }
// one pulls the rest together instead of leaving a separate guess in every event.
const others = await db.faceGroup.findMany({ /** Collapse same-event cards, then rescore. The rescore does not hold the click. */
where: { suggestedPersonId: person.id, personId: null, ignoredAt: null, eventId: { not: group.eventId } }, private async finishConfirmation(personId: string, eventIds: string[], organizationId: string): Promise<void> {
for (const eventId of eventIds) await this.joinSamePerson(eventId);
const others = await this.deps.db.faceGroup.findMany({
where: { suggestedPersonId: personId, personId: null, ignoredAt: null, eventId: { notIn: eventIds } },
select: { eventId: true }, select: { eventId: true },
distinct: ["eventId"], distinct: ["eventId"],
take: 25, take: 25,
}); });
for (const other of others) await this.refreshSuggestions(other.eventId); await this.scheduleRefresh([...eventIds, ...others.map((other) => other.eventId)]);
this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId }); for (const eventId of eventIds) {
return person; this.deps.broadcaster.library(organizationId, { type: "faces.updated", eventId });
}
}
/**
* Rescore open faces after the name is saved. The click must not wait on it: a match with hundreds of
* unnamed faces was holding the request until the proxy gave up, and the button looked dead.
* One queue for the process. Tests share one database, so there the refresh finishes before the response.
*/
private async scheduleRefresh(eventIds: string[]): Promise<void> {
for (const eventId of eventIds) this.pendingRefresh.add(eventId);
if (process.env.NODE_ENV === "test") {
await this.drainRefresh();
return;
}
this.kickRefresh();
}
private kickRefresh(): void {
if (this.refreshRunning) return;
this.refreshRunning = true;
void this.drainRefresh()
.catch((err) => {
this.deps.log.warn({ err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
})
.finally(() => {
this.refreshRunning = false;
if (this.pendingRefresh.size > 0) this.kickRefresh();
});
}
private async drainRefresh(): Promise<void> {
const inline = process.env.NODE_ENV === "test";
while (this.pendingRefresh.size > 0) {
const eventId = this.pendingRefresh.values().next().value;
if (!eventId) return;
this.pendingRefresh.delete(eventId);
try {
await this.refreshSuggestions(eventId);
} catch (err) {
if (inline) throw err;
this.deps.log.warn({ eventId, err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
}
}
} }
/** A name typed as a code (\v7\) becomes the name in the organization's code list. */ /** A name typed as a code (\v7\) becomes the name in the organization's code list. */
@@ -788,7 +885,9 @@ export class FaceService {
const { db } = this.deps; const { db } = this.deps;
const person = await db.person.findUniqueOrThrow({ where: { id: personId } }); const person = await db.person.findUniqueOrThrow({ where: { id: personId } });
const groups = await db.faceGroup.findMany({ where: { personId } }); const groups = await db.faceGroup.findMany({ where: { personId } });
const model = groups[0]?.model ?? person.model ?? null; // The person's model wins. A group confirmed from another model is named, but must not take over the
// centroid: faceGroup.findMany has no order, so the first row is not a stable choice.
const model = person.model ?? groups[0]?.model ?? null;
if (person.recognitionOffAt) return db.person.update({ where: { id: personId }, data: { centroid: [], faceCount: groups.reduce((n, g) => n + g.size, 0) } }); if (person.recognitionOffAt) return db.person.update({ where: { id: personId }, data: { centroid: [], faceCount: groups.reduce((n, g) => n + g.size, 0) } });
const parts = groups.filter((g) => g.model === model).map((g) => ({ mean: g.centroid, count: g.size })); const parts = groups.filter((g) => g.model === model).map((g) => ({ mean: g.centroid, count: g.size }));
if (person.referenceEmbedding.length && person.model === model) parts.push({ mean: person.referenceEmbedding, count: 3 }); if (person.referenceEmbedding.length && person.model === model) parts.push({ mean: person.referenceEmbedding, count: 3 });
@@ -807,6 +906,35 @@ export class FaceService {
return rows.map((r) => r.id); return rows.map((r) => r.id);
} }
/**
* Games to look at again after a new headshot. A player is only compared with games of clubs they have
* played for. Someone typed by hand (no squad row) is still compared with the last 45 days.
*/
private async eventsForReference(person: { organizationId: string; sportsPlayerId: string | null }, since: Date) {
const { db } = this.deps;
const recent = () => db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } });
if (!person.sportsPlayerId) return recent();
const mine = await db.sportsPlayer.findUnique({
where: { id: person.sportsPlayerId },
select: { teamId: true, externalId: true, birthDate: true, fullName: true },
});
if (!mine) return recent();
const match: ({ teamId: string } | { externalId: string } | { birthDate: string; fullName: string })[] = [{ teamId: mine.teamId }];
if (mine.externalId) match.push({ externalId: mine.externalId });
if (mine.birthDate && mine.fullName) match.push({ birthDate: mine.birthDate, fullName: mine.fullName });
const mates = await db.sportsPlayer.findMany({ where: { OR: match }, select: { teamId: true } });
const teamIds = [...new Set(mates.map((m) => m.teamId))];
if (!teamIds.length) return recent();
return db.event.findMany({
where: {
organizationId: person.organizationId,
startsAt: { gte: since },
OR: [{ homeTeamId: { in: teamIds } }, { awayTeamId: { in: teamIds } }],
},
select: { id: true },
});
}
/** Reads a reference photo: the largest face becomes the person's reference. Never throws. */ /** Reads a reference photo: the largest face becomes the person's reference. Never throws. */
async processReference(personId: string): Promise<void> { async processReference(personId: string): Promise<void> {
const { db, storage, engine, log } = this.deps; const { db, storage, engine, log } = this.deps;
@@ -831,7 +959,7 @@ export class FaceService {
await this.recomputePerson(personId); await this.recomputePerson(personId);
// Open groups of the last weeks may now have a suggestion. // Open groups of the last weeks may now have a suggestion.
const since = new Date(Date.now() - 45 * 86_400_000); const since = new Date(Date.now() - 45 * 86_400_000);
const events = await db.event.findMany({ where: { organizationId: person.organizationId, startsAt: { gte: since } }, select: { id: true } }); const events = await this.eventsForReference(person, since);
for (const e of events) { for (const e of events) {
await this.refreshSuggestions(e.id); await this.refreshSuggestions(e.id);
this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id }); this.deps.broadcaster.library(person.organizationId, { type: "faces.updated", eventId: e.id });
@@ -991,28 +1119,6 @@ export class FaceService {
} }
} }
/** Keeps `processes` face engines busy. */
/** "Futebol", "football" → "futebol"; "Andebol", "handball" → "andebol". */
export function normSport(s: string | null | undefined): string | null {
const v = (s ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
if (!v) return null;
if (/futebol|football|soccer/.test(v)) return "futebol";
if (/andebol|handball/.test(v)) return "andebol";
return v;
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
SELECT COALESCE(e.sport, c.sport, CASE s.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END) AS sport
FROM events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
LEFT JOIN LATERAL (SELECT cs.look FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1) s ON true
WHERE e.id = ${eventId}::uuid`;
return normSport(rows[0]?.sport);
}
/** Each person's sport, from the team of the squad they came from (people typed by hand have none). */ /** Each person's sport, from the team of the squad they came from (people typed by hand have none). */
export async function peopleSports(db: Db, people: { id: string; sportsPlayerId: string | null }[]): Promise<Map<string, string>> { export async function peopleSports(db: Db, people: { id: string; sportsPlayerId: string | null }[]): Promise<Map<string, string>> {
const ids = [...new Set(people.map((p) => p.sportsPlayerId).filter((x): x is string => !!x))]; const ids = [...new Set(people.map((p) => p.sportsPlayerId).filter((x): x is string => !!x))];
@@ -1045,6 +1151,42 @@ export async function dropCrossSportSuggestions(db: Db): Promise<number> {
return n; return n;
} }
/**
* Suggestions of someone who is not on the game's roster (a weak face compared with the whole organization)
* taken away; names confirmed by a person stay. The game is named again the next time its photos are read.
* Returns how many suggestions were cleared.
*/
export async function dropOffRosterSuggestions(db: Db, refresh?: (eventId: string) => Promise<void>): Promise<number> {
const events = await db.faceGroup.findMany({
where: { personId: null, suggestedPersonId: { not: null }, event: { away: { not: "" } } },
select: { eventId: true },
distinct: ["eventId"],
});
let n = 0;
for (const { eventId } of events) {
const roster = await rosterOf(db, eventId);
const groups = await db.faceGroup.findMany({
where: { eventId, personId: null, suggestedPersonId: { not: null } },
select: { id: true, suggestedPersonId: true, suggestionScore: true, model: true },
});
const allowed = roster ? new Set(roster) : null;
const drop = groups
.filter((g) => {
if (!g.suggestedPersonId) return false;
if (allowed) return !allowed.has(g.suggestedPersonId);
const match = THRESHOLDS[g.model]?.match ?? 0.4;
return (g.suggestionScore ?? 0) < openFloor(match);
})
.map((g) => g.id);
if (!drop.length) continue;
await db.faceGroup.updateMany({ where: { id: { in: drop } }, data: { suggestedPersonId: null, suggestionScore: null } });
n += drop.length;
if (refresh) await refresh(eventId).catch(() => undefined);
}
return n;
}
/** Keeps `processes` face engines busy. */
export class FaceWorker { export class FaceWorker {
private inFlight = 0; private inFlight = 0;
private videosInFlight = 0; private videosInFlight = 0;
@@ -1056,9 +1198,15 @@ export class FaceWorker {
constructor( constructor(
private readonly service: FaceService, private readonly service: FaceService,
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger; heartbeat?: () => void }, private readonly opts: { concurrency: number | (() => number); intervalMs: number; log: IngestLogger; heartbeat?: () => void },
) {} ) {}
/** Places to keep busy. A function follows a pool that grows as the CPU stays under its limit. */
private places(): number {
const n = typeof this.opts.concurrency === "function" ? this.opts.concurrency() : this.opts.concurrency;
return Math.max(1, n);
}
/** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */ /** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */
private beat(): void { private beat(): void {
if (!this.opts.heartbeat) return; if (!this.opts.heartbeat) return;
@@ -1108,9 +1256,10 @@ export class FaceWorker {
}); });
} }
}; };
const shared = this.opts.concurrency > 1; const places = this.places();
if (shared && this.videosInFlight === 0 && this.inFlight < this.opts.concurrency) await startVideo(); const shared = places > 1;
const ids = await this.service.claim(this.opts.concurrency - this.inFlight - (shared ? this.videosInFlight : 0)); if (shared && this.videosInFlight === 0 && this.inFlight < places) await startVideo();
const ids = await this.service.claim(places - this.inFlight - (shared ? this.videosInFlight : 0));
for (const id of ids) { for (const id of ids) {
this.inFlight++; this.inFlight++;
void this.service.process(id).finally(() => { void this.service.process(id).finally(() => {
+22
View File
@@ -0,0 +1,22 @@
import type { Db } from "../db.js";
/** "Futebol", "football" → "futebol"; "Andebol", "handball" → "andebol". */
export function normSport(s: string | null | undefined): string | null {
const v = (s ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
if (!v) return null;
if (/futebol|football|soccer/.test(v)) return "futebol";
if (/andebol|handball/.test(v)) return "andebol";
return v;
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
SELECT COALESCE(e.sport, c.sport, CASE s.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END) AS sport
FROM events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
LEFT JOIN LATERAL (SELECT cs.look FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1) s ON true
WHERE e.id = ${eventId}::uuid`;
return normSport(rows[0]?.sport);
}
+80 -6
View File
@@ -129,6 +129,10 @@ export class IngestService {
eventId?: string | undefined; eventId?: string | undefined;
/** `file` is a preview made by the desktop app; the original (described here) stays on that computer. */ /** `file` is a preview made by the desktop app; the original (described here) stays on that computer. */
original?: PreviewOf | undefined; original?: PreviewOf | undefined;
/** Stay in the inbox. A capture time must not pull a merge into whatever event is open today. */
inbox?: boolean;
/** A preview held until its linear original replaces it: no broadcast, no autopilot, no arrival copy. */
held?: boolean;
}, },
): Promise<Exclude<IngestOutcome, { status: "skipped" }>> { ): Promise<Exclude<IngestOutcome, { status: "skipped" }>> {
const { db, storage, log } = this.deps; const { db, storage, log } = this.deps;
@@ -159,8 +163,11 @@ export class IngestService {
const at = capturedAt ?? new Date(); const at = capturedAt ?? new Date();
// Archive imports name their own event. A file with no camera time, or a time outside that event's window, // Archive imports name their own event. A file with no camera time, or a time outside that event's window,
// must not fall through onto whatever is live today. // must not fall through onto whatever is live today.
const eventId = const eventId = origin.inbox
origin.source === "CLOUD" ? null
: origin.held && origin.eventId
? origin.eventId
: origin.source === "CLOUD"
? await this.namedEvent(orgId, origin.eventId) ? await this.namedEvent(orgId, origin.eventId)
: (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at)); : (await this.requestedEvent(orgId, origin.eventId, at)) ?? (await this.routeToEvent(orgId, origin.userId, at));
const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext); const storageKey = storage.originalKey(orgId, sha256, ext === ".jpeg" ? ".jpg" : ext);
@@ -210,15 +217,16 @@ export class IngestService {
// The event's autopilot edits what arrives by FTP, the desktop app, or a hand upload (a second photographer's // The event's autopilot edits what arrives by FTP, the desktop app, or a hand upload (a second photographer's
// photos added by hand count too); only archive re-imports (CLOUD) are left as they were. // photos added by hand count too); only archive re-imports (CLOUD) are left as they were.
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null; const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null;
const autopilot = origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true; const autopilot = !origin.held && origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
const readFaces = !origin.held && org?.biometricsEnabled === true;
photo = await db.photo.update({ photo = await db.photo.update({
where: { id: photo.id }, where: { id: photo.id },
data: { data: {
status: "READY", status: "READY",
width, width,
height, height,
facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", facesStatus: readFaces ? "PENDING" : "NONE",
...(org?.biometricsEnabled && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }), ...(readFaces && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }),
...(autopilot && { autopilotStatus: "PENDING" }), ...(autopilot && { autopilotStatus: "PENDING" }),
}, },
}); });
@@ -227,7 +235,7 @@ export class IngestService {
outcome = { status: "ingested", photoId: photo.id, eventId }; outcome = { status: "ingested", photoId: photo.id, eventId };
log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready"); log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready");
// A copy of every arrival where one asked for it (one's own backup, a client taking everything). // A copy of every arrival where one asked for it (one's own backup, a client taking everything).
if (eventId && origin.source !== "CLOUD" && this.arrivals) await this.arrivals({ id: photo.id, organizationId: orgId, uploaderId: photo.uploaderId }).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: arrival not sent on")); if (!origin.held && eventId && origin.source !== "CLOUD" && this.arrivals) await this.arrivals({ id: photo.id, organizationId: orgId, uploaderId: photo.uploaderId }).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: arrival not sent on"));
} catch (err) { } catch (err) {
const error = err instanceof Error ? err.message : String(err); const error = err instanceof Error ? err.message : String(err);
photo = await db.photo.update({ where: { id: photo.id }, data: { status: "FAILED", error } }); photo = await db.photo.update({ where: { id: photo.id }, data: { status: "FAILED", error } });
@@ -235,11 +243,77 @@ export class IngestService {
log.warn({ photoId: photo.id, error }, "ingest: could not process photo"); log.warn({ photoId: photo.id, error }, "ingest: could not process photo");
} }
if (!origin.held) {
const full = await db.photo.findUniqueOrThrow({ where: { id: photo.id }, include: photoInclude }); const full = await db.photo.findUniqueOrThrow({ where: { id: photo.id }, include: photoInclude });
this.deps.broadcaster.library(orgId, { type: "photo.added", photo: toSummary(full, this.deps.signer) }); this.deps.broadcaster.library(orgId, { type: "photo.added", photo: toSummary(full, this.deps.signer) });
}
return outcome; return outcome;
} }
/**
* Replaces a held JPEG preview with the linear DNG of a merge. Derivatives stay (they are the preview).
* The photo is announced once, as the DNG. A second copy of the same DNG drops the preview and returns
* the one already in the library.
*/
async attachLinearDng(
photo: { id: string; organizationId: string; sha256: string; storageKey: string; originalName: string },
dngFile: string,
meta: { width: number; height: number; capturedAt: Date | null },
): Promise<{ status: "ingested" | "duplicate"; photoId: string }> {
const { db, storage, log } = this.deps;
const sha = await sha256File(dngFile);
const existing = await db.photo.findUnique({ where: { organizationId_sha256: { organizationId: photo.organizationId, sha256: sha } }, select: { id: true } });
if (existing && existing.id !== photo.id) {
await rm(dngFile, { force: true });
await this.discardHeld(photo.id);
return { status: "duplicate", photoId: existing.id };
}
const size = (await stat(dngFile)).size;
if (size > 2_000_000_000) throw new Error("file_too_large");
if (sha !== photo.sha256) {
for (const variant of ["thumb", "preview"] as const) {
const from = storage.derivedKey(photo.organizationId, photo.sha256, variant);
if (await storage.exists(from)) await storage.adopt(storage.resolve(from), storage.derivedKey(photo.organizationId, sha, variant));
}
}
const key = storage.originalKey(photo.organizationId, sha, ".dng");
await storage.adopt(dngFile, key);
if (photo.storageKey !== key) await storage.remove(photo.storageKey);
const dot = photo.originalName.lastIndexOf(".");
const stem = dot > 0 ? photo.originalName.slice(0, dot) : photo.originalName;
const updated = await db.photo.update({
where: { id: photo.id },
data: {
sha256: sha,
storageKey: key,
byteSize: size,
originalName: `${stem}.dng`,
originalStored: true,
status: "READY",
error: null,
width: meta.width,
height: meta.height,
facesStatus: "NONE",
autopilotStatus: "NONE",
...(meta.capturedAt && { capturedAt: meta.capturedAt, takenAt: meta.capturedAt }),
},
});
const full = await db.photo.findUniqueOrThrow({ where: { id: updated.id }, include: photoInclude });
this.deps.broadcaster.library(photo.organizationId, { type: "photo.added", photo: toSummary(full, this.deps.signer) });
log.info({ photoId: photo.id }, "ingest: linear merge stored");
return { status: "ingested", photoId: photo.id };
}
/** Drops a preview that was held for a merge and then not kept (bad file, or the DNG was already here). */
async discardHeld(photoId: string): Promise<void> {
const photo = await this.deps.db.photo.findUnique({ where: { id: photoId }, select: { id: true, organizationId: true, sha256: true, storageKey: true } });
if (!photo) return;
await this.deps.db.photo.delete({ where: { id: photoId } }).catch(() => {});
await this.deps.storage.remove(photo.storageKey);
await this.deps.storage.remove(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "thumb"));
await this.deps.storage.remove(this.deps.storage.derivedKey(photo.organizationId, photo.sha256, "preview"));
}
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */ /** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> { async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
const { db, storage, log } = this.deps; const { db, storage, log } = this.deps;
+3 -4
View File
@@ -45,10 +45,9 @@ export function planCapacity(
return { return {
cpus, cpus,
memoryGb: Math.round(memoryGb * 10) / 10, memoryGb: Math.round(memoryGb * 10) / 10,
// Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed // One face process per core, added while the CPU is under about 99% (GrowingFacePool). The model is
// by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries // about 0.8 GB, so a small container stops sooner. FACES_PROCESSES in the environment still overrides.
// fail with "fetch failed" and face transactions expire. FACES_PROCESSES in the environment still overrides. faces: set.faces ?? Math.max(1, Math.min(Math.max(1, Math.floor(cpus * 0.99)), byMemory("faces", 0.7))),
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32), ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32),
archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32), archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32),
// A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share. // A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
+2 -1
View File
@@ -186,7 +186,8 @@ export async function registerPhotoRoutes(
} }
return reply.code(409).send({ error: "original_not_here" }); return reply.code(409).send({ error: "original_not_here" });
} }
return reply.header("content-type", "image/jpeg").header("cache-control", "private, max-age=3600").send(createReadStream(storage.resolve(photo.storageKey))); const type = photo.storageKey.toLowerCase().endsWith(".dng") ? "image/x-adobe-dng" : "image/jpeg";
return reply.header("content-type", type).header("cache-control", "private, max-age=3600").send(createReadStream(storage.resolve(photo.storageKey)));
}); });
/** Asks the desktop app that keeps this photo's original to send it (it listens on the live channel). */ /** Asks the desktop app that keeps this photo's original to send it (it listens on the live channel). */
+69 -4
View File
@@ -1,7 +1,7 @@
import multipart from "@fastify/multipart"; import multipart from "@fastify/multipart";
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { createWriteStream } from "node:fs"; import { createWriteStream } from "node:fs";
import { appendFile, mkdir, rm, stat } from "node:fs/promises"; import { appendFile, mkdir, open, rm, stat } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { pipeline } from "node:stream/promises"; import { pipeline } from "node:stream/promises";
import type { FastifyInstance } from "fastify"; import type { FastifyInstance } from "fastify";
@@ -16,7 +16,12 @@ import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { photoInclude, toSummary } from "./serialize.js"; import { photoInclude, toSummary } from "./serialize.js";
const OrgParams = z.object({ orgId: z.uuid() }); const OrgParams = z.object({ orgId: z.uuid() });
const UploadQuery = z.object({ eventId: z.uuid().optional() }); const UploadQuery = z.object({ eventId: z.uuid().optional(), silent: z.string().optional(), inbox: z.string().optional() });
const LinearQuery = z.object({
capturedAt: z.string().optional(),
width: z.coerce.number().int().positive().max(100_000),
height: z.coerce.number().int().positive().max(100_000),
});
const PhotoParams = z.object({ photoId: z.uuid() }); const PhotoParams = z.object({ photoId: z.uuid() });
export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024; export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
@@ -35,7 +40,8 @@ export async function registerUploadRoutes(
app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => { app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params); const { orgId } = OrgParams.parse(req.params);
const { eventId } = UploadQuery.parse(req.query); const query = UploadQuery.parse(req.query);
const { eventId } = query;
await requireMembership(db, req, orgId, "PHOTOGRAPHER"); await requireMembership(db, req, orgId, "PHOTOGRAPHER");
if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) { if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) {
throw badRequest("event_not_in_organization"); throw badRequest("event_not_in_organization");
@@ -53,7 +59,15 @@ export async function registerUploadRoutes(
try { try {
await pipeline(part.file, createWriteStream(tmp)); await pipeline(part.file, createWriteStream(tmp));
if (part.file.truncated) throw new AppError(413, "file_too_large"); if (part.file.truncated) throw new AppError(413, "file_too_large");
const outcome = await ingest.ingest(tmp, { organizationId: orgId, userId: currentUserId(req), source: "UPLOAD", originalName: name, eventId }); const outcome = await ingest.ingest(tmp, {
organizationId: orgId,
userId: currentUserId(req),
source: "UPLOAD",
originalName: name,
eventId,
...(query.inbox === "1" && { inbox: true }),
...(query.silent === "1" && { held: true }),
});
const photo = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude }); const photo = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
return reply.code(outcome.status === "duplicate" ? 200 : 201).send({ status: outcome.status, photo: toSummary(photo, signer) }); return reply.code(outcome.status === "duplicate" ? 200 : 201).send({ status: outcome.status, photo: toSummary(photo, signer) });
} finally { } finally {
@@ -61,6 +75,42 @@ export async function registerUploadRoutes(
} }
}); });
/**
* The linear DNG of a merge, replacing the JPEG preview uploaded just before (held, not announced).
* One announcement goes out, for the DNG, so the collection shows it once.
*/
app.post("/v1/photos/:photoId/linear-dng", { preHandler: authenticate }, async (req) => {
const { photoId } = PhotoParams.parse(req.params);
const query = LinearQuery.parse(req.query);
const capturedAt = query.capturedAt ? new Date(query.capturedAt) : null;
if (query.capturedAt && (capturedAt === null || Number.isNaN(capturedAt.getTime()))) throw badRequest("bad_date");
const photo = await db.photo.findUnique({
where: { id: photoId },
select: { id: true, organizationId: true, sha256: true, storageKey: true, originalName: true },
});
if (!photo) throw new AppError(404, "photo_not_found");
await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
const part = await req.file();
if (!part) throw badRequest("file_missing");
const tmpDir = storage.resolve(".uploads");
await mkdir(tmpDir, { recursive: true });
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
let stored = false;
try {
await pipeline(part.file, createWriteStream(tmp));
if (part.file.truncated) throw new AppError(413, "file_too_large");
if (!(await isTiff(tmp))) throw badRequest("not_a_dng");
const outcome = await ingest.attachLinearDng(photo, tmp, { width: query.width, height: query.height, capturedAt });
stored = true;
const full = await db.photo.findUniqueOrThrow({ where: { id: outcome.photoId }, include: photoInclude });
return { status: outcome.status, photo: toSummary(full, signer) };
} catch (err) {
if (!stored) await ingest.discardHeld(photo.id).catch(() => {});
await rm(tmp, { force: true });
throw err;
}
});
/** /**
* The desktop app sends the original of a photo that only has its preview here, when the file on that computer * The desktop app sends the original of a photo that only has its preview here, when the file on that computer
* no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo: * no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo:
@@ -204,3 +254,18 @@ export async function registerUploadRoutes(
}); });
}); });
} }
/** LightCraft's linear DNG is a TIFF. A mosaic raw is not accepted through this door. */
async function isTiff(file: string): Promise<boolean> {
const handle = await open(file, "r");
try {
const buf = Buffer.alloc(4);
const { bytesRead } = await handle.read(buf, 0, 4, 0);
if (bytesRead < 4) return false;
const little = buf[0] === 0x49 && buf[1] === 0x49 && buf[2] === 0x2a && buf[3] === 0x00;
const big = buf[0] === 0x4d && buf[1] === 0x4d && buf[2] === 0x00 && buf[3] === 0x2a;
return little || big;
} finally {
await handle.close();
}
}
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vitest";
import { samePlayer, type PlayerIdentity } from "./identity.js";
const row = (over: Partial<PlayerIdentity>): PlayerIdentity => ({
externalId: null,
birthDate: null,
fullName: null,
teamId: "team",
name: "Zalazar",
...over,
});
describe("samePlayer", () => {
it("follows the federation id from one club to another", () => {
const then = row({ externalId: "p1", teamId: "feirense", name: "Zalazar", fullName: "Rodrigo Zalazar" });
const now = row({ externalId: "p1", teamId: "sporting", name: "Zalazar", fullName: "Rodrigo Zalazar Martinez" });
expect(samePlayer(then, now)).toBe(true);
});
it("uses the birth date and full name when the id differs", () => {
const then = row({ birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martínez", teamId: "feirense" });
const now = row({ externalId: "other", birthDate: "1999-08-12", fullName: "Rodrigo Zalazar Martinez", teamId: "sporting" });
expect(samePlayer(then, now)).toBe(true);
});
it("does not treat two shirt names at different clubs as one person", () => {
const a = row({ name: "Silva", fullName: "Rui Silva", teamId: "a" });
const b = row({ name: "Silva", fullName: "João Silva", teamId: "b" });
expect(samePlayer(a, b)).toBe(false);
});
});
+22
View File
@@ -0,0 +1,22 @@
/** A squad row, enough to tell one human from another across clubs and seasons. */
export interface PlayerIdentity {
externalId: string | null;
birthDate: string | null;
fullName: string | null;
teamId: string;
name: string;
}
const fold = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
/**
* The same human: the federation's id (stable when they change club), or the same birth date and full name.
* The same shirt name in the same club is the last resort. A shirt name alone is not, and neither is today's club.
*/
export function samePlayer(a: PlayerIdentity, b: PlayerIdentity): boolean {
if (a.externalId && a.externalId === b.externalId) return true;
const left = fold(a.fullName ?? "");
const right = fold(b.fullName ?? "");
if (a.birthDate && left && a.birthDate === b.birthDate && left === right) return true;
return a.teamId === b.teamId && a.name === b.name;
}
+278 -15
View File
@@ -9,6 +9,7 @@ import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js"; import { waitUntil } from "../lib/idle.js";
import type { LocalStorage } from "../storage/storage.js"; import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js"; import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import { samePlayer } from "./identity.js";
import { tallyOf, tallySquadPhotos } from "./squadPhotos.js"; import { tallyOf, tallySquadPhotos } from "./squadPhotos.js";
import { import {
type Fetch, type Fetch,
@@ -186,6 +187,123 @@ export class SportsService {
} }
} }
this.deps.log.info({ season, saved }, "sports: liga season imported"); this.deps.log.info({ season, saved }, "sports: liga season imported");
// The calendar used to be all that a past season stored. Squads follow, without holding the folder scan.
void this.importLigaSquads({ season: asked, limit: 80 }).catch((err) => this.deps.log.warn({ err, season: asked }, "sports: liga squads not read"));
return saved;
}
/** Squads already on file are skipped. An empty or failed read is tried again next process, not in a loop. */
private readonly squadClaimed = new Set<string>();
/** Competition-seasons whose team lists were read to the end. The current season is never marked done while empty. */
private readonly registerDone = new Set<string>();
/**
* Liga squads for seasons whose games are already stored but whose player lists were never read.
* Other federations publish the sheet per match (line-ups), not a season squad, so this is Liga's list only.
* The people those rows become are `linkStoredSquads`.
*/
async importLigaSquads(opts: { season?: string; limit?: number } = {}): Promise<number> {
const limit = opts.limit ?? 20;
const season = opts.season?.replace(/\D/g, "") || null;
// A dummy value keeps the array non-empty: Prisma cannot type an empty one, and ALL('{}') is awkward.
const claimed = this.squadClaimed.size ? [...this.squadClaimed] : ["__none__"];
const rows = await this.deps.db.$queryRaw<{ id: string; external_id: string; season: string }[]>`
SELECT DISTINCT t.id, t.external_id, f.season
FROM sports_teams t
JOIN sports_fixtures f ON (f.home_team_id = t.id OR f.away_team_id = t.id)
JOIN sports_competitions c ON c.id = f.competition_id
WHERE t.provider = 'LIGA' AND c.provider = 'LIGA'
AND (${season}::text IS NULL OR f.season = ${season})
AND NOT EXISTS (SELECT 1 FROM sports_players p WHERE p.team_id = t.id AND p.season = f.season)
AND (t.id::text || ':' || f.season) <> ALL(${claimed}::text[])
ORDER BY f.season DESC
LIMIT ${limit}`;
let changed = 0;
for (const t of rows) {
const key = `${t.id}:${t.season}`;
if (this.squadClaimed.has(key)) continue;
this.squadClaimed.add(key);
try {
changed += await this.savePlayers(t.id, t.season, await this.liga.squad(t.external_id, t.season), "api");
} catch (err) {
this.squadClaimed.delete(key);
this.deps.log.warn({ err, team: t.id, season: t.season }, "sports: liga squad not read");
}
}
if (changed) this.deps.log.info({ season, changed }, "sports: liga squads imported");
return changed;
}
/**
* Every Liga club and every player the federation still publishes, season by season, newest first.
* A photo of a club five years ago then has that season's squad, including players who have since moved.
* Stops at the first past season that lists no teams. The current season being empty (pre-season) does not stop it.
* `stopped` is checked between requests so a shutdown leaves within one call.
*/
async backfillLigaRegister(stopped: () => boolean): Promise<number> {
await this.ensureCatalog();
const comps = await this.deps.db.sportsCompetition.findMany({ where: { provider: "LIGA" } });
let season = seasonOf(new Date());
let saved = 0;
for (let year = 0; year < 25 && !stopped(); year++) {
let sawTeams = false;
let failed = 0;
for (const c of comps) {
if (stopped()) return saved;
const key = `${c.externalId}:${season}`;
if (this.registerDone.has(key)) {
sawTeams = true;
continue;
}
let teams: TeamData[];
try {
teams = await this.liga.teams(c.externalId, season);
} catch (err) {
const missing = err instanceof ProviderHttpError ? err.status === 404 : err instanceof Error && err.message.startsWith("liga: unexpected");
if (missing) {
this.registerDone.add(key);
continue;
}
failed++;
this.deps.log.warn({ err, competition: c.externalId, season }, "sports: liga teams not read");
continue;
}
if (!teams.length) {
this.registerDone.add(key);
continue;
}
sawTeams = true;
let complete = true;
for (const t of teams) {
if (stopped()) return saved;
const teamId = await this.upsertTeam("LIGA", t);
await this.deps.db.sportsCompetitionTeam.upsert({
where: { competitionId_teamId_season: { competitionId: c.id, teamId, season } },
create: { competitionId: c.id, teamId, season },
update: {},
});
const have = await this.deps.db.sportsPlayer.count({ where: { teamId, season } });
if (have > 0) continue;
const claim = `${teamId}:${season}`;
if (this.squadClaimed.has(claim)) continue;
this.squadClaimed.add(claim);
try {
saved += await this.savePlayers(teamId, season, await this.liga.squad(t.externalId, season), "api");
} catch (err) {
complete = false;
this.squadClaimed.delete(claim);
this.deps.log.warn({ err, team: t.name, season }, "sports: liga squad not read");
}
}
if (complete) this.registerDone.add(key);
}
if (failed === comps.length && comps.length) break;
if (year > 0 && !sawTeams) break;
const start = Number(season.slice(0, 4)) - 1;
if (!Number.isFinite(start) || start < 2000) break;
season = `${start}${start + 1}`;
}
if (saved) this.deps.log.info({ saved }, "sports: liga register imported");
return saved; return saved;
} }
@@ -745,9 +863,12 @@ export class SportsService {
// --- squads ----------------------------------------------------------------------------------------------------- // --- squads -----------------------------------------------------------------------------------------------------
/** A team's current squad: its latest season, without the players who left. */ /** A team's squad for one season, or its latest when none is asked. Players who left are left out. */
async squad(teamId: string) { async squad(teamId: string, season?: string) {
const latest = await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { updatedAt: "desc" }, select: { season: true } }); // Season, not updatedAt: reading an old season must not make it look like the current squad.
const latest = season
? { season }
: await this.deps.db.sportsPlayer.findFirst({ where: { teamId }, orderBy: { season: "desc" }, select: { season: true } });
if (!latest) return []; if (!latest) return [];
const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } }); const players = await this.deps.db.sportsPlayer.findMany({ where: { teamId, season: latest.season, goneAt: null } });
// Shirt numbers, then the handball officials by letter (A, B, …), then those without either. // Shirt numbers, then the handball officials by letter (A, B, …), then those without either.
@@ -758,7 +879,10 @@ export class SportsService {
/** Both teams of an event, with the person each player is in the organisation (for tagging by number). */ /** Both teams of an event, with the person each player is in the organisation (for tagging by number). */
async eventSquads(eventId: string) { async eventSquads(eventId: string) {
const { db } = this.deps; const { db } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, include: { homeTeam: true, awayTeam: true } }); const event = await db.event.findUnique({
where: { id: eventId },
include: { homeTeam: true, awayTeam: true, fixture: { select: { season: true } } },
});
if (!event) throw notFound("event_not_found"); if (!event) throw notFound("event_not_found");
const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[]; const sides = [] as { side: "home" | "away"; team: { id: string; name: string; abbreviation: string | null; logoUrl: string | null }; players: unknown[] }[];
// Photos of each person in this event: faces confirmed as them, and faces the system takes for them (the // Photos of each person in this event: faces confirmed as them, and faces the system takes for them (the
@@ -777,12 +901,9 @@ export class SportsService {
["away", event.awayTeam], ["away", event.awayTeam],
] as const) { ] as const) {
if (!team) continue; if (!team) continue;
const players = await this.squad(team.id); const season = event.fixture?.season ?? seasonOf(event.startsAt);
const people = await db.person.findMany({ const players = await this.squad(team.id, season);
where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, const personOf = await this.peopleOf(event.organizationId, players);
select: { id: true, sportsPlayerId: true },
});
const personOf = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
sides.push({ sides.push({
side, side,
team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl }, team: { id: team.id, name: team.name, abbreviation: team.abbreviation, logoUrl: team.logoUrl },
@@ -830,7 +951,7 @@ export class SportsService {
include: { include: {
homeTeam: true, homeTeam: true,
awayTeam: true, awayTeam: true,
fixture: { select: { id: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } }, fixture: { select: { id: true, season: true, externalId: true, round: true, officials: true, competition: { select: { provider: true, externalId: true, season: true } } } },
organization: { select: { biometricsEnabled: true, codeGenerator: true } }, organization: { select: { biometricsEnabled: true, codeGenerator: true } },
}, },
}); });
@@ -840,10 +961,10 @@ export class SportsService {
const result = { created: 0, updated: 0, headshots: 0 }; const result = { created: 0, updated: 0, headshots: 0 };
const headshots: { personId: string; url: string }[] = []; const headshots: { personId: string; url: string }[] = [];
// Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh. // Liga squads are read again right now (players and coaching staff), not only on the 6-hourly refresh.
const season = event.fixture?.season ?? seasonOf(event.startsAt);
for (const team of [event.homeTeam, event.awayTeam]) { for (const team of [event.homeTeam, event.awayTeam]) {
if (team?.provider !== "LIGA") continue; if (team?.provider !== "LIGA") continue;
try { try {
const season = event.fixture?.competition.provider === "LIGA" ? event.fixture.competition.season : seasonOf(new Date());
await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api"); await this.savePlayers(team.id, season, await this.liga.squad(team.externalId, season), "api");
} catch (err) { } catch (err) {
log.warn({ err, team: team.id }, "sports: liga squad re-read failed"); log.warn({ err, team: team.id }, "sports: liga squad re-read failed");
@@ -852,7 +973,7 @@ export class SportsService {
for (const team of [event.homeTeam, event.awayTeam]) { for (const team of [event.homeTeam, event.awayTeam]) {
if (!team) continue; if (!team) continue;
const club = settings.teamNames[team.id] ?? team.name; const club = settings.teamNames[team.id] ?? team.name;
for (const p of await this.squad(team.id)) { for (const p of await this.squad(team.id, season)) {
await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result); await this.linkSquadPerson(orgId, team, club, p, event.organization.biometricsEnabled, headshots, result);
} }
} }
@@ -944,6 +1065,7 @@ export class SportsService {
const { db, log } = this.deps; const { db, log } = this.deps;
let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } }); let person = await db.person.findUnique({ where: { organizationId_sportsPlayerId: { organizationId: orgId, sportsPlayerId: p.id } } });
let created = false; let created = false;
if (!person) person = await this.personForIdentity(orgId, p);
if (!person) { if (!person) {
const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } }); const byName = await db.person.findUnique({ where: { organizationId_name: { organizationId: orgId, name: p.name } } });
if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName; if (byName && !byName.sportsPlayerId && (!byName.club || byName.club === club || byName.club === team.name)) person = byName;
@@ -966,8 +1088,10 @@ export class SportsService {
} }
} }
} }
const linkedSeason = person.sportsPlayerId === p.id ? p.season : await this.seasonOfLinked(person.sportsPlayerId);
const newer = !linkedSeason || p.season >= linkedSeason;
if (created) result.created++; if (created) result.created++;
else if (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id) { else if (newer && (person.club !== club || person.number !== p.number || person.sportsPlayerId !== p.id)) {
person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } }); person = await db.person.update({ where: { id: person.id }, data: { club, number: p.number, sportsPlayerId: p.id } });
result.updated++; result.updated++;
} }
@@ -984,6 +1108,124 @@ export class SportsService {
if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo }); if (photo && !person.referenceKey) headshots.push({ personId: person.id, url: photo });
} }
/** The person already created for this human at another club or in another season. */
private async personForIdentity(orgId: string, p: SportsPlayer) {
const match: ({ externalId: string } | { birthDate: string; fullName: string })[] = [];
if (p.externalId) match.push({ externalId: p.externalId });
if (p.birthDate && p.fullName) match.push({ birthDate: p.birthDate, fullName: p.fullName });
if (!match.length) return null;
const rows = await this.deps.db.sportsPlayer.findMany({ where: { OR: match }, select: { id: true } });
if (!rows.length) return null;
return this.deps.db.person.findFirst({ where: { organizationId: orgId, sportsPlayerId: { in: rows.map((r) => r.id) } } });
}
private async seasonOfLinked(sportsPlayerId: string | null): Promise<string | null> {
if (!sportsPlayerId) return null;
const linked = await this.deps.db.sportsPlayer.findUnique({ where: { id: sportsPlayerId }, select: { season: true } });
return linked?.season ?? null;
}
/** Which person is each squad row: the row itself, or the same human at the club they play for now. */
private async peopleOf(orgId: string, players: SportsPlayer[]): Promise<Map<string, string>> {
const out = new Map<string, string>();
if (!players.length) return out;
const externalIds = [...new Set(players.map((p) => p.externalId).filter((id): id is string => !!id))];
const births = players.filter((p): p is SportsPlayer & { birthDate: string; fullName: string } => !!p.birthDate && !!p.fullName);
const keys = await this.deps.db.sportsPlayer.findMany({
where: {
OR: [
{ id: { in: players.map((p) => p.id) } },
...(externalIds.length ? [{ externalId: { in: externalIds } }] : []),
...births.map((p) => ({ birthDate: p.birthDate, fullName: p.fullName })),
],
},
select: { id: true, externalId: true, birthDate: true, fullName: true, teamId: true, name: true },
});
if (!keys.length) return out;
const people = await this.deps.db.person.findMany({
where: { organizationId: orgId, sportsPlayerId: { in: keys.map((k) => k.id) } },
select: { id: true, sportsPlayerId: true },
});
const personByPlayer = new Map(people.map((p) => [p.sportsPlayerId, p.id]));
for (const player of players) {
const hit = keys.find((k) => k.id && personByPlayer.has(k.id) && samePlayer(k, player));
if (hit?.id) {
const personId = personByPlayer.get(hit.id);
if (personId) out.set(player.id, personId);
}
}
return out;
}
/**
* Squad rows that no person of the organisation represents yet become people (and, a few at a time, reference
* photos). A player already known by the federation's id is not created again under an old club. Only
* organisations that turned biometrics on, and only clubs that already appear on one of their games.
*/
async linkStoredSquads(limit = 8): Promise<number> {
const { db, log } = this.deps;
const rows = await db.$queryRaw<{ organization_id: string; player_id: string }[]>`
SELECT e.organization_id, sp.id AS player_id
FROM sports_players sp
JOIN sports_teams t ON t.id = sp.team_id
JOIN events e ON (e.home_team_id = t.id OR e.away_team_id = t.id)
JOIN organizations o ON o.id = e.organization_id AND o.biometrics_enabled
WHERE NOT EXISTS (
SELECT 1 FROM people p
JOIN sports_players mine ON mine.id = p.sports_player_id
WHERE p.organization_id = e.organization_id
AND (
mine.id = sp.id
OR (sp.external_id IS NOT NULL AND mine.external_id = sp.external_id)
OR (
sp.birth_date IS NOT NULL AND sp.full_name IS NOT NULL
AND mine.birth_date = sp.birth_date
AND lower(mine.full_name) = lower(sp.full_name)
)
OR (mine.team_id = sp.team_id AND mine.name = sp.name)
)
)
GROUP BY e.organization_id, sp.id, sp.season
ORDER BY sp.season DESC
LIMIT ${limit}`;
if (!rows.length) return 0;
const players = await db.sportsPlayer.findMany({ where: { id: { in: rows.map((r) => r.player_id) } }, include: { team: true } });
const byId = new Map(players.map((p) => [p.id, p]));
const settingsOf = new Map<string, CodeGeneratorSettings>();
const fresh: { personId: string; url: string }[] = [];
const headshots: { orgId: string; personId: string; url: string }[] = [];
const result = { created: 0, updated: 0 };
for (const row of rows) {
const p = byId.get(row.player_id);
if (!p) continue;
let settings = settingsOf.get(row.organization_id);
if (!settings) {
settings = await this.settings(row.organization_id);
settingsOf.set(row.organization_id, settings);
}
const club = settings.teamNames[p.team.id] ?? p.team.name;
const before = fresh.length;
try {
await this.linkSquadPerson(row.organization_id, p.team, club, p, true, fresh, result);
} catch (err) {
log.warn({ err, player: p.id, organization: row.organization_id }, "sports: squad person not linked");
}
for (const h of fresh.slice(before)) headshots.push({ orgId: row.organization_id, ...h });
}
for (let i = 0; i < headshots.length; i += 4) {
await Promise.all(
headshots.slice(i, i + 4).map((h) =>
this.saveHeadshot(h.orgId, h.personId, h.url).catch((err) => {
log.warn({ err, person: h.personId }, "sports: headshot failed");
return false;
}),
),
);
}
if (result.created) log.info({ created: result.created, headshots: headshots.length }, "sports: squad people linked");
return result.created;
}
private async saveHeadshot(orgId: string, personId: string, src: string): Promise<boolean> { private async saveHeadshot(orgId: string, personId: string, src: string): Promise<boolean> {
const u = new URL(src); const u = new URL(src);
if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false; if (u.protocol !== "https:" || !HEADSHOT_HOSTS.includes(u.hostname)) return false;
@@ -1075,6 +1317,7 @@ export class SportsWorker {
private timer: ReturnType<typeof setTimeout> | undefined; private timer: ReturnType<typeof setTimeout> | undefined;
private stopped = false; private stopped = false;
private ticking = false; private ticking = false;
private filling = false;
private lastRefresh = 0; private lastRefresh = 0;
constructor( constructor(
@@ -1083,12 +1326,16 @@ export class SportsWorker {
) {} ) {}
start(): void { start(): void {
void this.fillRegister();
const tick = async () => { const tick = async () => {
this.ticking = true; this.ticking = true;
try { try {
if (Date.now() - this.lastRefresh >= (this.opts.refreshCheckMs ?? 10 * 60_000)) { if (Date.now() - this.lastRefresh >= (this.opts.refreshCheckMs ?? 10 * 60_000)) {
this.lastRefresh = Date.now(); this.lastRefresh = Date.now();
await this.service.refreshDue(); await this.service.refreshDue();
// Past seasons used to store only the calendar. A few missing squads, then the people they name.
await this.service.importLigaSquads({ limit: 20 });
await this.service.linkStoredSquads(24);
} }
await this.service.pollLineups(); await this.service.pollLineups();
} catch (err) { } catch (err) {
@@ -1101,10 +1348,26 @@ export class SportsWorker {
this.timer = setTimeout(tick, 5_000); this.timer = setTimeout(tick, 5_000);
} }
/** Past seasons of every Liga club, then the people those rows are. One pass per process; the tick keeps up afterwards. */
private async fillRegister(): Promise<void> {
this.filling = true;
try {
await this.service.backfillLigaRegister(() => this.stopped);
while (!this.stopped) {
const n = await this.service.linkStoredSquads(24);
if (!n) break;
}
} catch (err) {
this.opts.log.warn({ err }, "sports: register not filled");
} finally {
this.filling = false;
}
}
async stop(timeoutMs = 25_000): Promise<void> { async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true; this.stopped = true;
if (this.timer) clearTimeout(this.timer); if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking, { timeoutMs }); const drained = await waitUntil(() => !this.ticking && !this.filling, { timeoutMs });
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running"); if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
} }
} }
+5 -4
View File
@@ -14,7 +14,7 @@ import { SecretBox } from "./delivery/secrets.js";
import { DeliveryService, DeliveryWorker } from "./delivery/service.js"; import { DeliveryService, DeliveryWorker } from "./delivery/service.js";
import { RenderPool, RenderProcess } from "./develop/engine.js"; import { RenderPool, RenderProcess } from "./develop/engine.js";
import { DevelopService, RenderWorker } from "./develop/service.js"; import { DevelopService, RenderWorker } from "./develop/service.js";
import { FacePool, FaceProcess } from "./faces/process.js"; import { FaceProcess, GrowingFacePool } from "./faces/process.js";
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js"; import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { SportsService, SportsWorker } from "./sports/service.js"; import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js"; import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
@@ -126,15 +126,16 @@ const invoices = new InvoicingWorker(new InvoicingService({ db, secrets, log, no
const faceEngine = const faceEngine =
config.FACES_BIN && config.FACES_MODELS_DIR config.FACES_BIN && config.FACES_MODELS_DIR
? new FacePool( ? new GrowingFacePool(
Array.from({ length: capacity.faces }, () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER })), () => new FaceProcess({ bin: config.FACES_BIN!, modelsDir: config.FACES_MODELS_DIR!, embedder: config.FACES_EMBEDDER }),
capacity.faces,
) )
: undefined; : undefined;
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined; const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded"); if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
const faces = faceEngine const faces = faceEngine
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), { ? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey, videoTools, videoFps: config.ARCHIVE_VIDEO_FACE_FPS }), {
concurrency: capacity.faces, concurrency: () => faceEngine?.size ?? 1,
intervalMs: 1000, intervalMs: 1000,
log, log,
heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT), heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT),
+2 -2
View File
@@ -8,8 +8,8 @@ describe("capacity", () => {
const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB }); const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB });
const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB }); const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB });
expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, autopilot: 2, delivery: 4 }); expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, autopilot: 2, delivery: 4 });
expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 }); expect(big).toMatchObject({ cpus: 32, faces: 31, ingest: 8, archive: 9, archiveBurst: 91, render: 16, autopilot: 16, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 }); expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 47, archiveBurst: 91, archiveDownloads: 960 });
// A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine. // A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine.
expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 }); expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 });
}); });
+3 -2
View File
@@ -174,7 +174,7 @@ describe("search by photo", () => {
expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] }); expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] });
}); });
it("asks the game first, including a referee, and the rest of the organization only when the game has no match", async () => { it("asks the game first, including a referee, and leaves a face the game does not know unnamed", async () => {
const { orgId, token, events, rui } = await setup(); const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil2", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes-2" } }); const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil2", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes-2" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf2", sport: "andebol", name: "Feirense", slug: "feirense-2" } }); const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf2", sport: "andebol", name: "Feirense", slug: "feirense-2" } });
@@ -206,7 +206,8 @@ describe("search by photo", () => {
engine.next = { width: 800, height: 1000, faces: [found(4, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] }; engine.next = { width: 800, height: 1000, faces: [found(4, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
res = await post(); res = await post();
expect(res.json()).toMatchObject({ faces: [{ person: { id: outsider.id, name: "Só lá fora" } }] }); expect(res.json()).toMatchObject({ faces: [{ person: null }] });
expect(JSON.stringify(res.json())).not.toContain(outsider.id);
}); });
it("names an embedding read on the photographer's computer, without the photo", async () => { it("names an embedding read on the photographer's computer, without the photo", async () => {
-2
View File
@@ -16,7 +16,6 @@ import { LoginPage } from "./pages/LoginPage.js";
import { MembersPage } from "./pages/MembersPage.js"; import { MembersPage } from "./pages/MembersPage.js";
import { MetadataPage } from "./pages/MetadataPage.js"; import { MetadataPage } from "./pages/MetadataPage.js";
import { PreferencesPage } from "./pages/PreferencesPage.js"; import { PreferencesPage } from "./pages/PreferencesPage.js";
import { RealEstatePage } from "./pages/RealEstatePage.js";
import { Shell } from "./pages/Shell.js"; import { Shell } from "./pages/Shell.js";
function Gate() { function Gate() {
@@ -41,7 +40,6 @@ function Gate() {
<Route path="members" element={<MembersPage />} /> <Route path="members" element={<MembersPage />} />
<Route path="preferences" element={<PreferencesPage />} /> <Route path="preferences" element={<PreferencesPage />} />
<Route path="help" element={<HelpPage />} /> <Route path="help" element={<HelpPage />} />
<Route path="real-estate" element={<RealEstatePage />} />
<Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} /> <Route path="*" element={<p className="p-6 text-sm text-muted">{t.notFound}</p>} />
</Route> </Route>
<Route path="/login" element={<Navigate to="/" replace />} /> <Route path="/login" element={<Navigate to="/" replace />} />
+2
View File
@@ -22,6 +22,8 @@ export interface WasmPhoto {
export interface BracketJob { export interface BracketJob {
push(bytes: Uint8Array): void; push(bytes: Uint8Array): void;
merge(maxEdge: number): BracketMerge; merge(maxEdge: number): BracketMerge;
/** Scene-linear DNG. Absent on an engine built before it. */
mergeDng?(maxEdge: number): Uint8Array;
free(): void; free(): void;
} }
+43 -1
View File
@@ -204,6 +204,9 @@ export const t = {
enable: "Ligar", enable: "Ligar",
disable: "Desligar", disable: "Desligar",
enabled: "Ligado", enabled: "Ligado",
confirm: "Confirmar",
confirming: "A confirmar…",
confirmFailed: "Não confirmei. Tenta outra vez.",
}, },
realEstate: { realEstate: {
nav: "Imobiliário", nav: "Imobiliário",
@@ -216,6 +219,8 @@ export const t = {
off: "Desligado", off: "Desligado",
intro: "Larga os ficheiros de um imóvel. Cada ângulo são várias exposições da mesma posição, normalmente três. Os ficheiros ficam neste computador; para agrupar só seguem os dados de exposição.", intro: "Larga os ficheiros de um imóvel. Cada ângulo são várias exposições da mesma posição, normalmente três. Os ficheiros ficam neste computador; para agrupar só seguem os dados de exposição.",
step: "Cada ângulo é fundido aqui, neste computador, pelo motor de imagem. A janela vem da exposição escura e a sala da clara.", step: "Cada ângulo é fundido aqui, neste computador, pelo motor de imagem. A janela vem da exposição escura e a sala da clara.",
queued: "À espera da vez…",
readingOne: "A ler este ângulo…",
fusing: "A fundir este ângulo…", fusing: "A fundir este ângulo…",
fuseFailed: "Não deu para fundir este ângulo.", fuseFailed: "Não deu para fundir este ângulo.",
previewAlt: (n: number) => `Ângulo ${n} fundido`, previewAlt: (n: number) => `Ângulo ${n} fundido`,
@@ -223,6 +228,25 @@ export const t = {
chooseFolder: "Escolher pasta", chooseFolder: "Escolher pasta",
dropHint: "ou larga uma pasta aqui", dropHint: "ou larga uma pasta aqui",
reading: (done: number, total: number) => `A ler ${done} de ${total}…`, reading: (done: number, total: number) => `A ler ${done} de ${total}…`,
readingAll: (n: number, total: number) => `A ler o ângulo ${n} de ${total}`,
fusingOne: (n: number, total: number) => `A fundir o ângulo ${n} de ${total}`,
fusingAll: (done: number, total: number) => `A fundir ${done} de ${total} ângulos`,
savingAll: (done: number, total: number) => `A guardar ${done} de ${total}`,
resultHelp: "Cada imagem é o ângulo já fundido. Escolhe um acabamento e guarda o JPEG neste computador.",
save: "Guardar",
saveAll: "Guardar todos",
edit: "Editar",
exposure: "Exposição",
highlights: "Altas luzes",
shadows: "Sombras",
lookFailed: "Não apliquei o acabamento.",
savedFolder: "Os JPEG ficaram na pasta que escolheste.",
savedDownload: "Os JPEG foram descarregados.",
looks: {
natural: "Natural",
interior: "Interior claro",
brighter: "Mais luz",
},
noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.", noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.",
support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`), support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`),
asideMore: (n: number) => `e mais ${n}`, asideMore: (n: number) => `e mais ${n}`,
@@ -247,6 +271,19 @@ export const t = {
empty: "Ainda não há presets.", empty: "Ainda não há presets.",
remove: "Apagar", remove: "Apagar",
}, },
merge: {
button: "Fundir exposições",
title: "Funde as exposições do mesmo ângulo num DNG linear, na coleção. As originais ficam. O acabamento faz-se no Revelar.",
reading: "A ler as exposições…",
working: (n: number, total: number) => `A fundir ${n} de ${total}…`,
done: (n: number) => (n === 1 ? "1 DNG ficou na coleção." : `${n} DNG ficaram na coleção.`),
errors: {
none: "Não há um conjunto de exposições. Seleciona as fotos do mesmo ângulo.",
missing: "Falta o ficheiro original de alguma exposição.",
engine: "O motor ainda não grava o DNG. Quando a cópia do cartão acabar, atualiza a página.",
failed: "Não fundi. Tenta outra vez.",
},
},
card: { card: {
title: "Importar cartão", title: "Importar cartão",
open: "Cartão…", open: "Cartão…",
@@ -271,7 +308,9 @@ export const t = {
sidecars: "Levar WAV/XMP", sidecars: "Levar WAV/XMP",
needSource: "Escolhe primeiro o cartão/pasta de origem.", needSource: "Escolhe primeiro o cartão/pasta de origem.",
progress: (done: number, total: number, name: string) => `A processar ${done}/${total}… ${name}`, progress: (done: number, total: number, name: string) => `A processar ${done}/${total}… ${name}`,
remaining: (label: string) => `faltam cerca de ${label}`, overall: (done: number, total: number, percent: number) => `${done} de ${total} · ${percent}%`,
general: "Geral",
remaining: (label: string) => (label.startsWith("menos") ? `falta ${label}` : `faltam cerca de ${label}`),
stop: "Parar", stop: "Parar",
stopping: "Pára depois do ficheiro que está a copiar.", stopping: "Pára depois do ficheiro que está a copiar.",
oldShellStop: "Esta versão da app de secretária ainda não consegue parar a meio. Atualiza-a; a cópia que já vai continua.", oldShellStop: "Esta versão da app de secretária ainda não consegue parar a meio. Atualiza-a; a cópia que já vai continua.",
@@ -281,6 +320,9 @@ export const t = {
moveAction: "Mover", moveAction: "Mover",
scan: (raw: number, jpeg: number, other: number, size: string) => scan: (raw: number, jpeg: number, other: number, size: string) =>
other > 0 ? `${raw} RAW · ${jpeg} JPEG · ${other} outras · ${size}` : `${raw} RAW · ${jpeg} JPEG · ${size}`, other > 0 ? `${raw} RAW · ${jpeg} JPEG · ${other} outras · ${size}` : `${raw} RAW · ${jpeg} JPEG · ${size}`,
free: (size: string) => `Livre no destino: ${size}`,
fits: "Cabe no disco, com margem.",
notAll: "Não cabe tudo. Copio dias completos e paro antes do dia que não cabe.",
result: { result: {
moved: (n: number) => `${n} movidas`, moved: (n: number) => `${n} movidas`,
copied: (n: number) => `${n} copiadas`, copied: (n: number) => `${n} copiadas`,
+55 -7
View File
@@ -1,8 +1,8 @@
import { useEffect, useState, useSyncExternalStore } from "react"; import { useEffect, useState, useSyncExternalStore } from "react";
import { t } from "../i18n.js"; import { t } from "../i18n.js";
import { desktopInvoke } from "../platform.js"; import { desktopInvoke } from "../platform.js";
import { copyPace } from "./cardPace.js"; import { copyPace, overallPace } from "./cardPace.js";
import { cardJobList, dismissCard, enqueueCard, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js"; import { cardJobList, dismissCard, enqueueCard, rescanQueued, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js";
import { SnapshotMenu } from "./SnapshotMenu.js"; import { SnapshotMenu } from "./SnapshotMenu.js";
/** /**
@@ -66,6 +66,13 @@ function CardDialog({ onClose }: { onClose: () => void }) {
desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {}); desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {});
}, []); }, []);
useEffect(() => {
const timer = setTimeout(() => {
void rescanQueued(s);
}, 400);
return () => clearTimeout(timer);
}, [s]);
const pickSource = async () => { const pickSource = async () => {
setError(null); setError(null);
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null); const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
@@ -230,15 +237,21 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
{job.status === "stopped" && <span className="shrink-0 text-faint">{t.card.stopped}</span>} {job.status === "stopped" && <span className="shrink-0 text-faint">{t.card.stopped}</span>}
</div> </div>
{scan && <p className="mt-1 text-muted">{scan}</p>} {scan && <p className="mt-1 text-muted">{scan}</p>}
{job.scan?.freeBytes != null && (
<p className="mt-1 text-muted">
{t.card.free(human(job.scan.freeBytes))}
{job.scan.fits === true ? ` · ${t.card.fits}` : ""}
{job.scan.fits === false ? ` · ${t.card.notAll}` : ""}
</p>
)}
{job.status === "running" && job.progress && ( {job.status === "running" && job.progress && (
<> <>
<div className="mt-2 h-1.5 overflow-hidden bg-black"> <p className="mt-2 text-ink">
<div className="h-full bg-accent" style={{ width: `${Math.round(pace.fraction * 100)}%` }} /> {t.card.overall(job.progress.done, job.progress.total, Math.round(pace.fraction * 100))}
</div>
<p className="mt-1 text-muted">
{t.card.progress(job.progress.done, job.progress.total, job.progress.name)}
{pace.left ? ` · ${t.card.remaining(pace.left)}` : ""} {pace.left ? ` · ${t.card.remaining(pace.left)}` : ""}
</p> </p>
<Track fraction={pace.fraction} />
{job.progress.name && <p className="mt-1 truncate text-muted">{job.progress.name}</p>}
</> </>
)} )}
{job.error && <p className="mt-1 text-danger">{job.error}</p>} {job.error && <p className="mt-1 text-danger">{job.error}</p>}
@@ -247,6 +260,41 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
); );
} }
/** The copy as a whole, under the library, including when the card window is closed. */
export function CardOverallStatus() {
const jobs = useCardJobs();
const [, setTick] = useState(0);
const running = jobs.some((job) => job.status === "running");
useEffect(() => {
if (!running) return;
const timer = setInterval(() => setTick((n) => n + 1), 1000);
return () => clearInterval(timer);
}, [running]);
const overall = overallPace(jobs, Date.now());
if (!overall) return null;
const name = jobs.find((job) => job.status === "running" && job.progress?.name)?.progress?.name;
return (
<div className="border-t border-line bg-panel px-3 py-2" role="status" aria-label={t.card.general}>
<p className="mb-1 flex flex-wrap items-baseline gap-x-2 text-[12px] text-ink">
<span className="font-semibold">{t.card.general}</span>
<span>{t.card.overall(overall.done, overall.total, Math.round(overall.fraction * 100))}</span>
{overall.left && <span className="text-muted">{t.card.remaining(overall.left)}</span>}
{name && <span className="min-w-0 truncate text-muted">{name}</span>}
</p>
<Track fraction={overall.fraction} />
</div>
);
}
function Track({ fraction }: { fraction: number }) {
const percent = Math.round(Math.max(0, Math.min(1, fraction)) * 100);
return (
<div className="mt-1 h-3 overflow-hidden bg-black" role="progressbar" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full bg-accent" style={{ width: `${percent}%` }} />
</div>
);
}
function JobResult({ result }: { result: CardResult }) { function JobResult({ result }: { result: CardResult }) {
const parts = [ const parts = [
result.moved ? t.card.result.moved(result.moved) : "", result.moved ? t.card.result.moved(result.moved) : "",
+74
View File
@@ -0,0 +1,74 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { useRef, useState } from "react";
import { t } from "../i18n.js";
import { MergeError, mergeIntoCollection } from "./mergeExposures.js";
/**
* "Fundir exposições": the selection (or every detected bracket in the folder) becomes a linear DNG
* in this collection. The originals stay. The editor's own controls do the finish.
*/
export function MergeButton({
api,
orgId,
eventId,
photos,
selectedIds,
}: {
api: ApiClient;
orgId: string;
/** Null is the inbox. */
eventId: string | null;
photos: readonly PhotoSummary[];
selectedIds: readonly string[];
}) {
const [status, setStatus] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
const [busy, setBusy] = useState(false);
const pending = useRef(false);
const run = async () => {
if (pending.current) return;
pending.current = true;
setBusy(true);
setFailed(false);
setStatus(t.merge.reading);
try {
const made = await mergeIntoCollection({
api,
orgId,
eventId,
photos,
selectedIds,
onStatus: (stack, total) => setStatus(t.merge.working(stack, total)),
});
setStatus(t.merge.done(made));
} catch (err) {
const code = err instanceof MergeError ? err.code : "failed";
setStatus(t.merge.errors[code] ?? t.merge.errors.failed);
setFailed(true);
} finally {
pending.current = false;
setBusy(false);
}
};
return (
<span className="inline-flex items-center gap-2">
<button
type="button"
title={t.merge.title}
disabled={busy}
onClick={() => void run()}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
>
{t.merge.button}
</button>
{status && (
<span role="status" className={`max-w-64 truncate text-[12px] ${failed ? "text-danger" : "text-muted"}`}>
{status}
</span>
)}
</span>
);
}
+20
View File
@@ -16,6 +16,10 @@ export interface CardScan {
jpeg: number; jpeg: number;
other: number; other: number;
bytes: number; bytes: number;
/** Free bytes on the destination. Absent on a shell that does not report it. */
freeBytes?: number;
/** False when the card would not fit, with a gigabyte left over. */
fits?: boolean;
} }
export interface CardResult { export interface CardResult {
@@ -116,6 +120,22 @@ function ensureProgress() {
}); });
} }
/** Asks again, with the destination, so the dialog can show free space. An older shell keeps the first scan. */
export async function rescanQueued(settings: CardSettings): Promise<void> {
const waiting = jobs.filter((job) => job.status === "queued");
await Promise.all(
waiting.map(async (job) => {
try {
const scan = await desktopInvoke<CardScan>("card_scan", { source: job.source, settings });
const current = jobs.find((item) => item.id === job.id);
if (current?.status === "queued") patch(job.id, { scan });
} catch {
// The installed shell scans without a destination. The counts from enqueue stay.
}
}),
);
}
export async function enqueueCard(source: string): Promise<void> { export async function enqueueCard(source: string): Promise<void> {
const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
jobs = [...jobs, { id, source, settings: null, scan: null, status: "queued", progress: null, startedAt: null, result: null, error: null }]; jobs = [...jobs, { id, source, settings: null, scan: null, status: "queued", progress: null, startedAt: null, result: null, error: null }];
+28 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { copyPace, formatRemaining, remainingMs } from "./cardPace.js"; import { copyPace, formatRemaining, overallPace, remainingMs } from "./cardPace.js";
describe("card copy pace", () => { describe("card copy pace", () => {
it("estimates the rest from the bytes already written", () => { it("estimates the rest from the bytes already written", () => {
@@ -12,6 +12,33 @@ describe("card copy pace", () => {
expect(pace.left).toBe("1 min"); expect(pace.left).toBe("1 min");
}); });
it("adds every card into one bar", () => {
const started = 1_000;
const now = started + 10_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 30, bytesTotal: 60 } },
{ status: "queued", startedAt: null, progress: null },
],
now,
);
expect(pace).toMatchObject({ done: 2, total: 8 });
expect(pace?.fraction).toBeCloseTo(0.4);
});
it("counts files when a card has no byte total", () => {
const started = 1_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 2, total: 4 } },
],
started + 10_000,
);
expect(pace?.fraction).toBeCloseTo(3 / 8);
});
it("waits for a little progress before guessing", () => { it("waits for a little progress before guessing", () => {
expect(remainingMs(0, 10, 0, 5_000)).toBeNull(); expect(remainingMs(0, 10, 0, 5_000)).toBeNull();
expect(remainingMs(1, 10, 0, 100)).toBeNull(); expect(remainingMs(1, 10, 0, 100)).toBeNull();
+28
View File
@@ -16,6 +16,34 @@ export function formatRemaining(ms: number): string {
return `${hours} h ${rest} min`; return `${hours} h ${rest} min`;
} }
export interface PaceJob {
status: string;
startedAt: number | null;
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null;
}
/** One bar for every card still copying: bytes when each job reports them, otherwise file counts. */
export function overallPace(jobs: readonly PaceJob[], now: number): { done: number; total: number; fraction: number; left: string | null } | null {
const running = jobs.filter((job) => job.status === "running" && job.progress && job.progress.total > 0 && job.startedAt !== null);
if (running.length === 0) return null;
const startedAt = Math.min(...running.map((job) => job.startedAt as number));
const done = running.reduce((sum, job) => sum + (job.progress?.done ?? 0), 0);
const total = running.reduce((sum, job) => sum + (job.progress?.total ?? 0), 0);
const byBytes = running.every((job) => (job.progress?.bytesTotal ?? 0) > 0);
const progress = {
done,
total,
...(byBytes
? {
bytesDone: running.reduce((sum, job) => sum + (job.progress?.bytesDone ?? 0), 0),
bytesTotal: running.reduce((sum, job) => sum + (job.progress?.bytesTotal ?? 0), 0),
}
: {}),
};
const pace = copyPace(progress, startedAt, now);
return { done, total, fraction: pace.fraction, left: pace.left };
}
export function copyPace( export function copyPace(
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null, progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null,
startedAt: number | null, startedAt: number | null,
+113
View File
@@ -0,0 +1,113 @@
import type { PhotoSummary } from "@photoreport/contracts";
import type { ApiClient } from "@photoreport/sdk";
import { loadEngine, type EngineModule } from "../develop/engine.js";
import { localOriginal } from "../platform.js";
import { MERGE_EDGE, stacksToMerge } from "./mergeStacks.js";
export class MergeError extends Error {
constructor(readonly code: "none" | "missing" | "engine" | "failed") {
super(code);
}
}
async function loadFrame(photo: PhotoSummary, api: ApiClient): Promise<Uint8Array | null> {
const local = await localOriginal(photo.sha256);
if (local && local.byteLength > 0) return new Uint8Array(local);
if (!photo.originalStored) return null;
const bytes = await api.originalBytes(photo.id);
if (!bytes || bytes.byteLength === 0) return null;
return new Uint8Array(bytes);
}
function rgbaToJpeg(rgba: Uint8Array, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context || width <= 0 || height <= 0) return Promise.reject(new Error("canvas"));
const pixels = new Uint8ClampedArray(rgba.byteLength);
pixels.set(rgba);
context.putImageData(new ImageData(pixels, width, height), 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("jpeg"))), "image/jpeg", 0.92);
});
}
/** A neutral JPEG of the linear file, so the grid has something to show before the editor opens the DNG. */
async function previewOf(engine: EngineModule, dng: Uint8Array): Promise<{ blob: Blob; width: number; height: number }> {
const photo = new engine.Photo(dng, 2048);
try {
photo.render(engine.defaultSettings(), 2048, 2048, false, false);
const blob = await rgbaToJpeg(photo.pixels(), photo.width, photo.height);
return { blob, width: photo.sourceWidth, height: photo.sourceHeight };
} finally {
photo.free();
}
}
function stemOf(photo: PhotoSummary): string {
const name = photo.originalName || photo.name;
const dot = name.lastIndexOf(".");
return dot > 0 ? name.slice(0, dot) : name;
}
/**
* Merges the selection, or every detected bracket in the folder, into a linear DNG of the same collection.
* The originals stay. One stack at a time: several raws in memory at once is what made a property shoot stall.
*/
export async function mergeIntoCollection(opts: {
api: ApiClient;
orgId: string;
eventId: string | null;
photos: readonly PhotoSummary[];
selectedIds: readonly string[];
onStatus?: (stack: number, total: number) => void;
}): Promise<number> {
const stacks = stacksToMerge(opts.photos, opts.selectedIds);
if (stacks.length === 0) throw new MergeError("none");
const byId = new Map(opts.photos.map((photo) => [photo.id, photo]));
let engine: EngineModule;
try {
engine = await loadEngine();
} catch {
throw new MergeError("engine");
}
let made = 0;
for (let index = 0; index < stacks.length; index++) {
opts.onStatus?.(index + 1, stacks.length);
const frames = stacks[index]!.map((id) => byId.get(id)).filter((photo): photo is PhotoSummary => !!photo);
if (frames.length < 2) throw new MergeError("none");
const files: Uint8Array[] = [];
for (const frame of frames) {
const bytes = await loadFrame(frame, opts.api);
if (!bytes) throw new MergeError("missing");
files.push(bytes);
}
const job = new engine.BracketJob();
try {
for (const file of files) job.push(file);
if (!job.mergeDng) throw new MergeError("engine");
const dng = job.mergeDng(MERGE_EDGE);
const preview = await previewOf(engine, dng);
const mid = frames[Math.floor((frames.length - 1) / 2)]!;
const uploaded = await opts.api.uploadPhoto(opts.orgId, preview.blob, `${stemOf(mid)}-fundido.jpg`, {
...(opts.eventId ? { eventId: opts.eventId } : { inbox: true }),
silent: true,
});
const copy = new Uint8Array(dng.byteLength);
copy.set(dng);
await opts.api.attachLinearDng(uploaded.photo.id, new Blob([copy]), {
width: preview.width,
height: preview.height,
capturedAt: mid.capturedAt,
});
made += 1;
} catch (err) {
if (err instanceof MergeError) throw err;
throw new MergeError("failed");
} finally {
job.free();
}
}
return made;
}
+63
View File
@@ -0,0 +1,63 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { stacksToMerge } from "./mergeStacks.js";
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function photo(id: string, exposureTime: number, ms: number, name = `${id}.cr3`): PhotoSummary {
return {
id,
eventId: "e1",
originalName: name,
name,
sha256: id.padEnd(64, "a"),
originalStored: true,
status: "READY",
width: 4000,
height: 3000,
capturedAt: at(ms),
cameraModel: "EOS R5",
lens: null,
focalLength: 16,
aperture: 8,
exposureTime,
iso: 100,
rating: 0,
flag: "NONE",
colorLabel: "NONE",
players: [],
uploader: null,
developSeq: 0,
urls: { thumb: "", preview: "", source: "" },
};
}
describe("stacks to merge", () => {
const dark = photo("a", 1 / 500, 0);
const mid = photo("b", 1 / 125, 200);
const bright = photo("c", 1 / 30, 400);
const later = photo("d", 1 / 125, 30_000);
it("finds one angle in the folder when nothing is selected", () => {
expect(stacksToMerge([dark, mid, bright, later], [])).toEqual([["a", "b", "c"]]);
});
it("merges the selection even when it is not a detected bracket", () => {
expect(stacksToMerge([dark, later], ["a", "d"])).toEqual([["a", "d"]]);
});
it("detects the folder when only the open photo is selected", () => {
expect(stacksToMerge([dark, mid, bright], ["a"])).toEqual([["a", "b", "c"]]);
});
it("does nothing when there is no bracket and fewer than two are selected", () => {
expect(stacksToMerge([dark, later], ["a"])).toEqual([]);
});
it("does not treat a merged file as another exposure", () => {
const merged = photo("m", 1 / 125, 300, "b-fundido.dng");
const renamed = photo("n", 1 / 125, 500, "n.dng");
renamed.name = "n";
expect(stacksToMerge([dark, mid, bright, merged, renamed], [])).toEqual([["a", "b", "c"]]);
});
});
+51
View File
@@ -0,0 +1,51 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
/** The engine's long-side cap for a merge. The DNG is this photo, not the full sensor. */
export const MERGE_EDGE = 4096;
function isMergedFile(photo: PhotoSummary): boolean {
const names = [photo.originalName, photo.name];
return names.some((name) => {
const lower = name.toLowerCase();
return lower.endsWith(".dng") || lower.includes("-fundido");
});
}
export function frameOf(photo: PhotoSummary): BracketFrame {
return {
id: photo.id,
fileName: photo.originalName || photo.name,
capturedAt: photo.capturedAt,
cameraModel: photo.cameraModel,
focalLength: photo.focalLength,
aperture: photo.aperture,
iso: photo.iso,
width: photo.width,
height: photo.height,
exposureTime: photo.exposureTime,
};
}
function byCapture(a: PhotoSummary, b: PhotoSummary): number {
const time = (a.capturedAt ?? "").localeCompare(b.capturedAt ?? "");
if (time !== 0) return time;
return (a.originalName || a.name).localeCompare(b.originalName || b.name, undefined, { numeric: true, sensitivity: "base" });
}
/**
* Stacks to merge. A selection of two or more is that set (detected into angles when they are brackets,
* otherwise one stack in capture order). With nothing selected, every bracket in the folder is a stack.
* A DNG already produced here is not an exposure.
*/
export function stacksToMerge(photos: readonly PhotoSummary[], selectedIds: readonly string[]): string[][] {
const ready = photos.filter((photo) => photo.status === "READY" && !isMergedFile(photo));
const selected = new Set(selectedIds);
const chosen = selected.size >= 2;
const pool = chosen ? ready.filter((photo) => selected.has(photo.id)) : ready;
if (pool.length < 2) return [];
const grouped = groupBrackets(pool.map(frameOf));
if (grouped.stacks.length > 0) return grouped.stacks.map((stack) => stack.frameIds);
if (!chosen) return [];
return [[...pool].sort(byCapture).map((photo) => photo.id)];
}
+15 -2
View File
@@ -15,6 +15,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js"; import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
import { FilterBar } from "../library/FilterBar.js"; import { FilterBar } from "../library/FilterBar.js";
import { cache } from "../offline/cache.js"; import { cache } from "../offline/cache.js";
import { MergeButton } from "../library/MergeButton.js";
import { localPhotos } from "../offline/local.js"; import { localPhotos } from "../offline/local.js";
import { isNetworkError, offlineQueue } from "../offline/queue.js"; import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { patchPhotos, useOfflineSync } from "../offline/sync.js"; import { patchPhotos, useOfflineSync } from "../offline/sync.js";
@@ -219,9 +220,16 @@ export function DevelopPage() {
setPhotos((list) => list.map((p) => (ids.has(p.id) ? applyPatch(p, m.patch) : p))); setPhotos((list) => list.map((p) => (ids.has(p.id) ? applyPatch(p, m.patch) : p)));
} else if (m.type === "photo.rendered") { } else if (m.type === "photo.rendered") {
setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p))); setPhotos((list) => list.map((p) => (p.id === m.photoId ? { ...p, urls: { ...p.urls, ...m.urls } } : p)));
} else if (m.type === "photo.added") {
const inThis = scope === "inbox" || scope === null ? m.photo.eventId === null : m.photo.eventId === scope;
if (!inThis) return;
setAll((list) => {
if (!list || list.some((p) => p.id === m.photo.id)) return list;
return [...list, m.photo].sort((a, b) => (a.capturedAt ?? "").localeCompare(b.capturedAt ?? ""));
});
} }
}, },
[session], [session, scope],
); );
const live = useLibraryLive(api, onMessage); const live = useLibraryLive(api, onMessage);
// Reconnected: anything sent meanwhile is fetched in order. // Reconnected: anything sent meanwhile is fetched in order.
@@ -566,6 +574,9 @@ export function DevelopPage() {
</span> </span>
)} )}
<span className="ml-auto flex items-center gap-2"> <span className="ml-auto flex items-center gap-2">
{canCull && orgId && scope && !scope.startsWith("search:") && !scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={scope === "inbox" ? null : scope} photos={photos} selectedIds={[...selected]} />
)}
<button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}> <button className="h-6 border border-black bg-cell px-2.5 disabled:opacity-40" disabled={!session?.canUndo} onClick={() => session?.undo()}>
{t.dev.undo} {t.dev.undo}
</button> </button>
@@ -602,7 +613,9 @@ export function DevelopPage() {
crop={crop} crop={crop}
onSourceSize={(w, h) => setSourceSize({ w, h })} onSourceSize={(w, h) => setSourceSize({ w, h })}
onError={(m) => setNote(m)} onError={(m) => setNote(m)}
{...(oneToOne ? { localSource: fullSource } : isDesktop() && { localSource: () => localOriginalToView(current.sha256) })} {...(oneToOne || current.originalName.toLowerCase().endsWith(".dng") || current.name.toLowerCase().endsWith(".dng")
? { localSource: fullSource }
: isDesktop() && { localSource: () => localOriginalToView(current.sha256) })}
picking={picking && !cropping && !before} picking={picking && !cropping && !before}
onPick={(u, v) => { onPick={(u, v) => {
setPicking(false); setPicking(false);
@@ -0,0 +1,70 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { FacesQueuePage } from "./FacesQueuePage.js";
const staged = vi.hoisted(() => {
const request = vi.fn();
return { request, api: { request, absolute: (path: string) => path } };
});
vi.mock("../auth.js", () => ({
useAuth: () => ({
organization: { id: "org-1" },
api: staged.api,
}),
}));
const ricardo = {
id: "g1",
eventId: "e1",
size: 4,
suggestion: { id: "p1", name: "Ricardo Candeias", club: "SPORTING CP", number: "C", score: 0.9 },
event: { title: "SPORTING CP x SL BENFICA", startsAt: "2026-10-01T20:00:00.000Z" },
samples: [],
};
describe("faces queue", () => {
beforeEach(() => {
staged.request.mockReset();
});
it("takes the card away as soon as Confirmar is clicked", async () => {
let release: () => void = () => undefined;
const pending = new Promise<void>((resolve) => {
release = resolve;
});
staged.request.mockImplementation((method: string) => {
if (method === "GET") return Promise.resolve({ groups: [ricardo] });
return pending.then(() => ({ person: { id: "p1", name: "Ricardo Candeias" } }));
});
render(
<MemoryRouter>
<FacesQueuePage />
</MemoryRouter>,
);
await userEvent.click(await screen.findByRole("button", { name: "Confirmar" }));
await waitFor(() => expect(screen.queryByText("Ricardo Candeias")).toBeNull());
expect(screen.getByText("A confirmar…")).toBeTruthy();
expect(staged.request).toHaveBeenCalledWith("POST", "/v1/orgs/org-1/face-review/confirm", { personId: "p1", groupIds: ["g1"] });
release();
await waitFor(() => expect(screen.queryByText("A confirmar…")).toBeNull());
});
it("says so when Confirmar fails, and puts the card back", async () => {
staged.request.mockImplementation((method: string) => {
if (method === "GET") return Promise.resolve({ groups: [ricardo] });
return Promise.reject(new Error("conflict"));
});
render(
<MemoryRouter>
<FacesQueuePage />
</MemoryRouter>,
);
await userEvent.click(await screen.findByRole("button", { name: "Confirmar" }));
expect(await screen.findByText("Não confirmei. Tenta outra vez.")).toBeTruthy();
await waitFor(() => expect(screen.getByText("Ricardo Candeias")).toBeTruthy());
expect(screen.getByRole("button", { name: "Confirmar" }).hasAttribute("disabled")).toBe(false);
});
});
+24 -13
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import { Link } from "react-router"; import { Link } from "react-router";
import { useAuth } from "../auth.js"; import { useAuth } from "../auth.js";
import { FaceCrop } from "../library/FacesView.js"; import { FaceCrop } from "../library/FacesView.js";
@@ -31,7 +31,9 @@ export function FacesQueuePage() {
const { api, organization } = useAuth(); const { api, organization } = useAuth();
const orgId = organization?.id ?? ""; const orgId = organization?.id ?? "";
const [rows, setRows] = useState<Row[] | null>(null); const [rows, setRows] = useState<Row[] | null>(null);
const [busy, setBusy] = useState<string | null>(null); const [busy, setBusy] = useState(false);
const [failed, setFailed] = useState(false);
const pending = useRef(false);
const [open, setOpen] = useState<Sample[] | null>(null); const [open, setOpen] = useState<Sample[] | null>(null);
const [at, setAt] = useState(0); const [at, setAt] = useState(0);
@@ -52,31 +54,40 @@ export function FacesQueuePage() {
const confirm = async (pile: Row[]) => { const confirm = async (pile: Row[]) => {
const personId = pile[0]?.suggestion?.id; const personId = pile[0]?.suggestion?.id;
if (!personId) return; if (!personId || pending.current) return;
setBusy(personId); const ids = pile.map((row) => row.id);
pending.current = true;
setBusy(true);
setFailed(false);
setRows((cur) => cur?.filter((row) => !ids.includes(row.id)) ?? null);
try { try {
for (const row of pile) await api.request("POST", `/v1/face-groups/${row.id}/confirm`, { personId }); await api.request("POST", `/v1/orgs/${orgId}/face-review/confirm`, { personId, groupIds: ids });
setRows((cur) => cur?.filter((r) => !pile.some((p) => p.id === r.id)) ?? null); } catch {
setFailed(true);
await load().catch(() => undefined);
} finally { } finally {
setBusy(null); pending.current = false;
setBusy(false);
} }
}; };
return ( return (
<div className="flex h-full flex-col"> <div className="flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden">
<PageHeader title={t.faces.title} /> <PageHeader title={t.faces.title} />
<p className="px-4 pt-3 text-[13px] text-muted"> <p className="px-4 pt-3 text-[13px] text-muted">
As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>. As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>.
</p> </p>
<div className="grid flex-1 content-start gap-3 overflow-auto p-4 sm:grid-cols-2 xl:grid-cols-3"> {busy && <p className="px-4 pt-2 text-[13px] text-muted">{t.faces.confirming}</p>}
{failed && !busy && <p className="px-4 pt-2 text-[13px] text-danger">{t.faces.confirmFailed}</p>}
<div className="grid min-h-0 min-w-0 flex-1 content-start gap-3 overflow-x-hidden overflow-y-auto p-4 pb-6 sm:grid-cols-2 xl:grid-cols-3">
{rows === null && <p className="text-sm text-muted">A carregar…</p>} {rows === null && <p className="text-sm text-muted">A carregar…</p>}
{rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>} {rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>}
{[...piles.values()].map((pile) => { {[...piles.values()].map((pile) => {
const who = pile[0]!.suggestion; const who = pile[0]!.suggestion;
const faces = pile.flatMap((r) => r.samples); const faces = pile.flatMap((r) => r.samples);
return ( return (
<article key={who?.id ?? pile[0]!.id} className="flex flex-col gap-2 border border-[#151516] bg-cell p-2"> <article key={who?.id ?? pile[0]!.id} className="flex min-w-0 flex-col gap-2 border border-[#151516] bg-cell p-2">
<button type="button" className="flex flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}> <button type="button" className="flex min-w-0 flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}>
{faces.slice(0, 6).map((s) => ( {faces.slice(0, 6).map((s) => (
<FaceCrop key={s.faceId} src={api.absolute(s.preview)} box={s} aspect={s.aspect} size={faces.length > 3 ? 52 : 72} /> <FaceCrop key={s.faceId} src={api.absolute(s.preview)} box={s} aspect={s.aspect} size={faces.length > 3 ? 52 : 72} />
))} ))}
@@ -89,8 +100,8 @@ export function FacesQueuePage() {
.join(" · ")} .join(" · ")}
</p> </p>
</div> </div>
<button type="button" className="h-8 border border-black bg-accent text-[12px] text-ink" disabled={busy === who?.id} onClick={() => void confirm(pile)}> <button type="button" className="h-8 w-full shrink-0 border border-black bg-accent text-[12px] text-ink disabled:opacity-70" disabled={busy || !who?.id} onClick={() => void confirm(pile)}>
Confirmar {t.faces.confirm}
</button> </button>
</article> </article>
); );
+6 -1
View File
@@ -18,7 +18,8 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js"; import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js"; import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js"; import { LocalFtpButton } from "../library/LocalFtp.js";
import { CardIngestButton } from "../library/CardIngest.js"; import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { MergeButton } from "../library/MergeButton.js";
import { AutopilotButton } from "../library/Autopilot.js"; import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js"; import { SquadsButton } from "../library/Squads.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js"; import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
@@ -523,6 +524,9 @@ export function LibraryPage() {
))} ))}
</select> </select>
)} )}
{canCull && state.scope && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") && (
<MergeButton api={api} orgId={orgId} eventId={state.scope === "inbox" ? null : state.scope} photos={state.photos} selectedIds={[...state.selected]} />
)}
{canCull && ( {canCull && (
<SendButton <SendButton
api={api} api={api}
@@ -672,6 +676,7 @@ export function LibraryPage() {
)} )}
</div> </div>
)} )}
{desktop && <CardOverallStatus />}
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div> <div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
</div> </div>
+2 -36
View File
@@ -1,9 +1,8 @@
import { DEFAULT_MODULES, MODULES, type Module } from "@photoreport/contracts"; import { DEFAULT_MODULES, MODULES, type Module } from "@photoreport/contracts";
import { ApiError } from "@photoreport/sdk";
import { useState } from "react"; import { useState } from "react";
import { useAuth } from "../auth.js"; import { useAuth } from "../auth.js";
import { LocalCatalog } from "../desktop/LocalCatalog.js";
import { Alert } from "../components/ui.js"; import { Alert } from "../components/ui.js";
import { LocalCatalog } from "../desktop/LocalCatalog.js";
import { t } from "../i18n.js"; import { t } from "../i18n.js";
import { isDesktop } from "../platform.js"; import { isDesktop } from "../platform.js";
import { PageHeader } from "./Shell.js"; import { PageHeader } from "./Shell.js";
@@ -12,12 +11,9 @@ import { PageHeader } from "./Shell.js";
const CHOOSABLE = MODULES.filter((m) => m !== "advanced"); const CHOOSABLE = MODULES.filter((m) => m !== "advanced");
export function PreferencesPage() { export function PreferencesPage() {
const { api, me, reload, organization, role } = useAuth(); const { api, me, reload } = useAuth();
const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]); const [selected, setSelected] = useState<Module[]>(me?.preferences.editorModules ?? [...DEFAULT_MODULES]);
const [status, setStatus] = useState<"idle" | "saved" | "error">("idle"); const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");
const [realEstateError, setRealEstateError] = useState<string | null>(null);
const [realEstateBusy, setRealEstateBusy] = useState(false);
const realEstateOn = organization?.realEstateEnabled === true;
const toggle = async (module: Module) => { const toggle = async (module: Module) => {
const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module]; const next = selected.includes(module) ? selected.filter((m) => m !== module) : [...selected, module];
@@ -54,37 +50,7 @@ export function PreferencesPage() {
</label> </label>
</li> </li>
))} ))}
{role === "OWNER" && organization && (
<li>
<label className="flex h-11 cursor-pointer items-center gap-3 rounded-md border border-line bg-panel px-3 text-sm hover:border-faint">
<input
type="checkbox"
className="h-4 w-4 accent-[var(--color-accent)]"
checked={realEstateOn}
disabled={realEstateBusy}
onChange={() => {
setRealEstateBusy(true);
setRealEstateError(null);
void (async () => {
try {
await api.setRealEstate(organization.id, !realEstateOn);
await reload();
} catch (err) {
const code = err instanceof ApiError ? err.code : "";
setRealEstateError(t.realEstate.errors[code] ?? t.unexpectedError);
} finally {
setRealEstateBusy(false);
}
})();
}}
/>
{t.realEstate.setting}
</label>
</li>
)}
</ul> </ul>
{role === "OWNER" && organization && <p className="mt-3 text-sm text-muted">{t.realEstate.settingHelp}</p>}
{realEstateError && <Alert>{realEstateError}</Alert>}
</section> </section>
{isDesktop() && <LocalCatalog />} {isDesktop() && <LocalCatalog />}
</> </>
-109
View File
@@ -1,109 +0,0 @@
import type { BracketFrame } from "@photoreport/metadata";
import { groupBrackets } from "@photoreport/metadata";
import type { ApiClient, Me, Organization } from "@photoreport/sdk";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { App } from "../App.js";
vi.mock("../library/realtime.js", () => ({
useLibraryLive: () => "live",
onSocketLive: () => () => undefined,
}));
vi.mock("../realestate/fuse.js", () => ({
fuseBracket: () => Promise.resolve(new Blob([Uint8Array.from([0xff, 0xd8])], { type: "image/jpeg" })),
}));
const staged = vi.hoisted(() => ({ frames: new Map<string, BracketFrame>() }));
vi.mock("../realestate/readFrame.js", async () => {
const actual = await vi.importActual<typeof import("../realestate/readFrame.js")>("../realestate/readFrame.js");
return {
...actual,
readBracketFile: (file: File) => Promise.resolve(staged.frames.get(file.name) ?? { id: file.name, fileName: file.name }),
};
});
const org = (realEstateEnabled: boolean): Organization => ({ id: "o1", slug: "fpa", name: "FPA", mode: "AGENCY", realEstateEnabled });
function me(role: Me["memberships"][number]["role"], realEstateEnabled: boolean): Me {
return {
user: { id: "u1", email: "[email protected]", name: "Ana", locale: "pt-PT" },
memberships: [{ role, organization: org(realEstateEnabled) }],
preferences: { editorModules: ["crop", "basic"] },
};
}
function fakeApi(who: Me, overrides: Partial<Record<keyof ApiClient, unknown>> = {}): ApiClient {
return {
client: "web",
resume: vi.fn().mockResolvedValue(true),
me: vi.fn().mockResolvedValue(who),
listEvents: vi.fn().mockResolvedValue({ events: [], inboxCount: 0 }),
listPhotos: vi.fn().mockResolvedValue({ photos: [], total: 0 }),
absolute: (path: string) => path,
groupRealEstate: vi.fn(async (_orgId: string, frames: BracketFrame[]) => groupBrackets(frames)),
setRealEstate: vi.fn().mockResolvedValue({ enabled: true }),
...overrides,
} as unknown as ApiClient;
}
const at = (ms: number) => new Date(Date.parse("2026-10-21T10:00:00.000Z") + ms).toISOString();
function shot(name: string, bias: number, ms: number): BracketFrame {
return {
id: name,
fileName: name,
capturedAt: at(ms),
cameraSerial: "body",
focalLength: 16,
aperture: 8,
iso: 100,
exposureBias: bias,
exposureTime: 0.01,
};
}
describe("real estate area", () => {
beforeEach(() => {
URL.createObjectURL = () => "blob:fused";
URL.revokeObjectURL = () => undefined;
});
afterEach(() => {
staged.frames.clear();
window.history.pushState({}, "", "/");
});
it("stays out of the menu until the organization turns it on", async () => {
render(<App api={fakeApi(me("PHOTOGRAPHER", false))} />);
expect(await screen.findByText(/Ainda não chegaram fotografias/)).toBeTruthy();
expect(screen.queryByRole("link", { name: "Imobiliário" })).toBeNull();
});
it("groups a dropped bracket and leaves the loose frame out", async () => {
staged.frames.set("a.cr3", shot("a.cr3", -2, 0));
staged.frames.set("b.cr3", shot("b.cr3", 0, 200));
staged.frames.set("c.cr3", shot("c.cr3", 2, 400));
staged.frames.set("solo.cr3", shot("solo.cr3", 0, 30_000));
const api = fakeApi(me("PHOTOGRAPHER", true));
render(<App api={api} />);
await userEvent.click(await screen.findByRole("link", { name: "Imobiliário" }));
const input = screen.getByLabelText("Escolher ficheiros");
await userEvent.upload(input, [new File(["a"], "a.cr3"), new File(["b"], "b.cr3"), new File(["c"], "c.cr3"), new File(["s"], "solo.cr3")]);
expect(await screen.findByText("1 ângulo")).toBeTruthy();
expect(screen.getByText("Ângulo 1 · 3 exposições")).toBeTruthy();
expect(await screen.findByRole("img", { name: "Ângulo 1 fundido" })).toBeTruthy();
expect(screen.getByText("1 fotografia fica de fora")).toBeTruthy();
expect(screen.getByText("solo.cr3 · 0 EV")).toBeTruthy();
expect(api.groupRealEstate).toHaveBeenCalledOnce();
});
it("lets the owner show the area from preferences", async () => {
window.history.pushState({}, "", "/preferences");
const api = fakeApi(me("OWNER", false));
render(<App api={api} />);
await userEvent.click(await screen.findByRole("checkbox", { name: "Imobiliário" }));
expect(api.setRealEstate).toHaveBeenCalledWith("o1", true);
});
});
-274
View File
@@ -1,274 +0,0 @@
import type { BracketFrame } from "@photoreport/metadata";
import { ApiError, hasRole, type RealEstateGrouping } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
import { fuseBracket } from "../realestate/fuse.js";
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
import { PageHeader } from "./Shell.js";
const READ_AT_ONCE = 4;
/**
* Interior brackets, separate from the sports library. The files stay on this computer. The server
* only receives exposure metadata and says which frames belong to the same angle; the develop
* engine merges each angle in the browser.
*/
export function RealEstatePage() {
const { api, organization, role } = useAuth();
const enabled = organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER");
const [busy, setBusy] = useState(false);
const busyRef = useRef(false);
const [error, setError] = useState<string | null>(null);
const [frames, setFrames] = useState<BracketFrame[]>([]);
const [files, setFiles] = useState<Map<string, File>>(new Map());
const [result, setResult] = useState<RealEstateGrouping | null>(null);
const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);
const [support, setSupport] = useState(0);
const take = async (list: File[]) => {
const split = partitionBracketFiles(list);
if ((split.images.length === 0 && split.sidecars.length === 0 && split.other === 0) || busyRef.current || !organization) return;
busyRef.current = true;
setBusy(true);
setError(null);
setResult(null);
setFrames([]);
setFiles(new Map());
setSupport(split.sidecars.length + split.other);
setProgress({ done: 0, total: split.images.length + split.sidecars.length });
try {
if (split.images.length === 0) {
setError(t.realEstate.noPhotos);
return;
}
let done = 0;
const total = split.images.length + split.sidecars.length;
const readOne = async (file: File) => {
try {
return await readBracketFile(file);
} finally {
done += 1;
setProgress({ done, total });
}
};
const read = await mapPool(split.images, READ_AT_ONCE, readOne);
const sidecars = await mapPool(split.sidecars, READ_AT_ONCE, readOne);
const byKey = new Map(split.sidecars.map((file, index) => [pairKey(file.webkitRelativePath || file.name), sidecars[index]!]));
const merged = read.map((frame, index) => {
const image = split.images[index];
const extra = image ? byKey.get(pairKey(image.webkitRelativePath || image.name)) : undefined;
return extra ? fillFromSidecar(frame, extra) : frame;
});
setFrames(merged);
const paired = new Map<string, File>();
merged.forEach((frame, index) => {
const file = split.images[index];
if (file) paired.set(frame.id, file);
});
setFiles(paired);
setResult(await api.groupRealEstate(organization.id, merged));
} catch (err) {
const code = err instanceof ApiError ? err.code : "";
setError(t.realEstate.errors[code] ?? t.unexpectedError);
} finally {
busyRef.current = false;
setBusy(false);
setProgress(null);
}
};
return (
<>
<PageHeader title={t.realEstate.title} />
<section className="max-w-3xl p-6">
{!enabled ? (
<p className="text-sm text-muted">{t.realEstate.disabled}</p>
) : (
<>
<p className="text-sm text-muted">{t.realEstate.intro}</p>
<p className="mt-2 text-sm text-muted">{t.realEstate.step}</p>
<div
className="mt-5 border border-dashed border-line bg-panel px-4 py-8 text-center"
onDragOver={(event) => event.preventDefault()}
onDrop={(event) => {
event.preventDefault();
void filesFromDrop(event.dataTransfer).then((files) => take(files));
}}
>
<div className="flex flex-wrap items-center justify-center gap-3">
<label className="inline-flex h-9 cursor-pointer items-center bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong">
{t.realEstate.choose}
<input
aria-label={t.realEstate.choose}
className="sr-only"
type="file"
multiple
disabled={busy}
onChange={(event) => {
const list = event.target.files ? [...event.target.files] : [];
event.target.value = "";
void take(list);
}}
/>
</label>
<label className="inline-flex h-9 cursor-pointer items-center border border-line bg-panel px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-ink hover:border-faint">
{t.realEstate.chooseFolder}
<input
aria-label={t.realEstate.chooseFolder}
className="sr-only"
type="file"
multiple
disabled={busy}
{...{ webkitdirectory: "", directory: "" }}
onChange={(event) => {
const list = event.target.files ? [...event.target.files] : [];
event.target.value = "";
void take(list);
}}
/>
</label>
</div>
<p className="mt-3 text-[13px] text-faint">{t.realEstate.dropHint}</p>
</div>
{busy && progress && <p className="mt-4 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>}
{error && <p className="mt-4 text-sm text-danger">{error}</p>}
{support > 0 && <p className="mt-4 text-sm text-muted">{t.realEstate.support(support)}</p>}
{result && <Grouping frames={frames} files={files} result={result} />}
</>
)}
</section>
</>
);
}
function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Map<string, File>; result: RealEstateGrouping }) {
const byId = new Map(frames.map((frame) => [frame.id, frame]));
return (
<div className="mt-6 space-y-4">
<p className="text-sm text-ink">{t.realEstate.stacks(result.stacks.length)}</p>
{result.stacks.length === 0 && <p className="text-sm text-muted">{t.realEstate.none}</p>}
<ul className="space-y-3">
{result.stacks.map((stack, index) => (
<li key={`${index}-${stack.frameIds[0] ?? ""}`} className="border border-line bg-panel">
<p className="border-b border-line px-3 py-2 text-[13px] font-semibold">{t.realEstate.angle(index + 1, stack.frameIds.length)}</p>
<AnglePreview index={index} ids={stack.frameIds} files={files} />
<ul className="px-3 py-2 text-[13px] text-muted">
{stack.frameIds.map((id) => (
<li key={id}>{line(byId.get(id), id)}</li>
))}
</ul>
</li>
))}
</ul>
{result.aside.length > 0 && (
<div>
<p className="text-sm text-ink">{t.realEstate.aside(result.aside.length)}</p>
<p className="mt-1 text-[13px] text-faint">{t.realEstate.asideHelp}</p>
<ul className="mt-2 text-[13px] text-muted">
{result.aside.slice(0, 12).map((id) => (
<li key={id}>{line(byId.get(id), id)}</li>
))}
{result.aside.length > 12 && <li>{t.realEstate.asideMore(result.aside.length - 12)}</li>}
</ul>
</div>
)}
</div>
);
}
function AnglePreview({ index, ids, files }: { index: number; ids: string[]; files: Map<string, File> }) {
const [url, setUrl] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
const key = ids.join("\n");
useEffect(() => {
const stack = ids.map((id) => files.get(id)).filter((file): file is File => file instanceof File);
if (stack.length < 2) {
setFailed(true);
return;
}
let cancelled = false;
let objectUrl = "";
setUrl(null);
setFailed(false);
fuseBracket(stack)
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
setUrl(objectUrl);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
// `key` is the stack. `files` is replaced as a whole when a new folder is read.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, files]);
if (failed) return <p className="px-3 py-2 text-[13px] text-danger">{t.realEstate.fuseFailed}</p>;
if (!url) return <p className="px-3 py-2 text-[13px] text-muted">{t.realEstate.fusing}</p>;
return <img alt={t.realEstate.previewAlt(index + 1)} className="block w-full" src={url} />;
}
function line(frame: BracketFrame | undefined, id: string): string {
const name = frame?.fileName || id;
return `${name} · ${exposureLabel(frame)}`;
}
function exposureLabel(frame: BracketFrame | undefined): string {
if (!frame || (frame.exposureBias == null && (frame.exposureTime == null || frame.exposureTime <= 0))) return t.realEstate.noExposure;
if (frame.exposureBias == null) return t.realEstate.noBias;
return formatBias(frame.exposureBias);
}
function formatBias(value: number): string {
const rounded = Math.round(value * 10) / 10;
const text = Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1);
if (rounded > 0) return t.realEstate.bias(`+${text}`);
return t.realEstate.bias(text);
}
async function mapPool<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
const out: R[] = new Array(items.length);
let next = 0;
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
while (next < items.length) {
const index = next;
next += 1;
out[index] = await fn(items[index]!);
}
});
await Promise.all(workers);
return out;
}
async function filesFromDrop(data: DataTransfer): Promise<File[]> {
const entries: FileSystemEntry[] = [];
for (const item of data.items) {
const entry = item.webkitGetAsEntry?.();
if (entry) entries.push(entry);
}
if (entries.length === 0) return [...data.files];
const nested = await Promise.all(entries.map((entry) => filesInEntry(entry)));
return nested.flat();
}
async function filesInEntry(entry: FileSystemEntry): Promise<File[]> {
if (entry.name.startsWith(".")) return [];
if (entry.isFile) {
const file = await new Promise<File>((resolve, reject) => (entry as FileSystemFileEntry).file(resolve, reject));
return file.name.startsWith(".") ? [] : [file];
}
if (!entry.isDirectory) return [];
const reader = (entry as FileSystemDirectoryEntry).createReader();
const children: FileSystemEntry[] = [];
for (;;) {
const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => reader.readEntries(resolve, reject));
if (batch.length === 0) break;
children.push(...batch);
}
const nested = await Promise.all(children.map((child) => filesInEntry(child)));
return nested.flat();
}
-10
View File
@@ -111,16 +111,6 @@ export function Shell() {
</NavLink> </NavLink>
</> </>
)} )}
{organization?.realEstateEnabled === true && role !== null && hasRole(role, "PHOTOGRAPHER") && (
<>
<span aria-hidden="true" className="text-[#3a3a3a]">
|
</span>
<NavLink to="/real-estate" className={moduleClass}>
{t.realEstate.nav}
</NavLink>
</>
)}
</nav> </nav>
<Bell /> <Bell />
+31
View File
@@ -0,0 +1,31 @@
import { loadEngine } from "../develop/engine.js";
import { finishValues, needsFinish, type LookId } from "./looks.js";
/** The fused JPEG, then one develop pass when a finish or a slider asks for it. */
export async function applyFinish(jpeg: Blob, look: LookId, tweaks: Record<string, number>): Promise<Blob> {
const values = finishValues(look, tweaks);
if (!needsFinish(values)) return jpeg;
const engine = await loadEngine();
const photo = new engine.Photo(new Uint8Array(await jpeg.arrayBuffer()), 2048);
try {
const settings = engine.apply(engine.defaultSettings(), JSON.stringify({ command: "develop.set", params: { values } }));
photo.render(settings, photo.sourceWidth, photo.sourceHeight, false, false);
return rgbaToJpeg(photo.pixels(), photo.width, photo.height);
} finally {
photo.free();
}
}
function rgbaToJpeg(rgba: Uint8Array, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context || width <= 0 || height <= 0) return Promise.reject(new Error("canvas"));
const pixels = new Uint8ClampedArray(rgba.byteLength);
pixels.set(rgba);
context.putImageData(new ImageData(pixels, width, height), 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("jpeg"))), "image/jpeg", 0.92);
});
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { inOrder } from "./fuse.js";
describe("bracket queue", () => {
it("reads the next angle only after the current one finishes", async () => {
const run = inOrder();
const order: string[] = [];
let release: () => void = () => undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const first = run(async () => {
order.push("start-1");
await gate;
order.push("end-1");
});
const second = run(async () => {
order.push("start-2");
});
await Promise.resolve();
expect(order).toEqual(["start-1"]);
release();
await first;
await second;
expect(order).toEqual(["start-1", "end-1", "start-2"]);
});
});
+34 -1
View File
@@ -3,17 +3,49 @@ import { loadEngine } from "../develop/engine.js";
/** Long side of each frame. The engine bins a raw mosaic down to this instead of demosaicing it whole. */ /** Long side of each frame. The engine bins a raw mosaic down to this instead of demosaicing it whole. */
const PREVIEW_EDGE = 1024; const PREVIEW_EDGE = 1024;
export type FusePhase = "queued" | "reading" | "merging";
/** Runs jobs one after another. A rejected job does not stop the next. */
export function inOrder(): <T>(job: () => Promise<T>) => Promise<T> {
let chain: Promise<unknown> = Promise.resolve();
return (job) => {
const run = chain.then(job, job);
chain = run.then(
() => undefined,
() => undefined,
);
return run;
};
}
const enqueue = inOrder();
function paint(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/** /**
* Merge one angle with the develop engine (LightCraft's HDR merge) and return a JPEG preview. * Merge one angle with the develop engine (LightCraft's HDR merge) and return a JPEG preview.
* Angles run one at a time: reading every raw of a property at once filled memory and the first one never finished.
* The files stay in this browser; nothing is uploaded. * The files stay in this browser; nothing is uploaded.
*/ */
export async function fuseBracket(files: File[]): Promise<Blob> { export function fuseBracket(files: File[], onPhase?: (phase: FusePhase) => void, isCancelled?: () => boolean): Promise<Blob> {
onPhase?.("queued");
return enqueue(async () => {
if (isCancelled?.()) throw new Error("cancelled");
onPhase?.("reading");
await paint();
if (isCancelled?.()) throw new Error("cancelled");
const engine = await loadEngine(); const engine = await loadEngine();
const job = new engine.BracketJob(); const job = new engine.BracketJob();
try { try {
for (const file of files) { for (const file of files) {
if (isCancelled?.()) throw new Error("cancelled");
job.push(new Uint8Array(await file.arrayBuffer())); job.push(new Uint8Array(await file.arrayBuffer()));
} }
onPhase?.("merging");
await paint();
if (isCancelled?.()) throw new Error("cancelled");
const merged = job.merge(PREVIEW_EDGE); const merged = job.merge(PREVIEW_EDGE);
try { try {
const jpeg = new Uint8Array(merged.jpeg()); const jpeg = new Uint8Array(merged.jpeg());
@@ -24,4 +56,5 @@ export async function fuseBracket(files: File[]): Promise<Blob> {
} finally { } finally {
job.free(); job.free();
} }
});
} }
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { finishValues, needsFinish } from "./looks.js";
describe("real estate finishes", () => {
it("keeps the merge when nothing was chosen", () => {
expect(needsFinish(finishValues("natural", {}))).toBe(false);
});
it("lets a slider replace one control of a preset", () => {
const values = finishValues("interior", { "light.shadows": 10 });
expect(values["light.shadows"]).toBe(10);
expect(values["light.highlights"]).toBe(-40);
expect(needsFinish(values)).toBe(true);
});
});
+20
View File
@@ -0,0 +1,20 @@
/** Finishes on top of the fused JPEG. Empty values keep the merge as the engine made it. */
export const LOOKS = [
{ id: "natural", values: {} },
{ id: "interior", values: { "light.exposure": 0.35, "light.highlights": -40, "light.shadows": 45, "light.whites": -15 } },
{ id: "brighter", values: { "light.exposure": 0.65, "light.highlights": -25, "light.shadows": 30 } },
] as const;
export type LookId = (typeof LOOKS)[number]["id"];
/** Preset first. A slider that moved replaces that one control. */
export function finishValues(look: LookId, tweaks: Record<string, number>): Record<string, number> {
const preset = LOOKS.find((item) => item.id === look)?.values ?? {};
const values: Record<string, number> = { ...preset };
for (const [id, value] of Object.entries(tweaks)) values[id] = value;
return values;
}
export function needsFinish(values: Record<string, number>): boolean {
return Object.values(values).some((value) => value !== 0);
}
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { jpegName } from "./save.js";
describe("fused file names", () => {
it("names the jpeg from the raw", () => {
expect(jpegName("PSR10099.CR3")).toBe("PSR10099-fundido.jpg");
expect(jpegName("sala 1.cr3")).toBe("sala-1-fundido.jpg");
expect(jpegName("")).toBe("angulo-fundido.jpg");
});
});
+54
View File
@@ -0,0 +1,54 @@
/** A download name for one fused angle. */
export function jpegName(fileName: string): string {
const stem = fileName.replace(/\.[^.]+$/, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "");
return `${stem || "angulo"}-fundido.jpg`;
}
export function downloadBlob(name: string, blob: Blob): void {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
URL.revokeObjectURL(url);
}
interface Writable {
write(data: Blob): Promise<void>;
close(): Promise<void>;
}
interface DirectoryPicker {
showDirectoryPicker?: () => Promise<{
getFileHandle(name: string, opts: { create: boolean }): Promise<{ createWritable(): Promise<Writable> }>;
}>;
}
/** All the angles into one folder when the browser allows it, otherwise one download each. */
export async function saveBlobs(
files: readonly { name: string; blob: Blob }[],
onStep?: (done: number, total: number) => void,
): Promise<"folder" | "download" | "cancel"> {
const picker = (window as DirectoryPicker).showDirectoryPicker;
if (!picker) {
for (const file of files) downloadBlob(file.name, file.blob);
onStep?.(files.length, files.length);
return "download";
}
try {
const dir = await picker();
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
if (!file) continue;
const handle = await dir.getFileHandle(file.name, { create: true });
const writable = await handle.createWritable();
await writable.write(file.blob);
await writable.close();
onStep?.(index + 1, files.length);
}
return "folder";
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") return "cancel";
throw err;
}
}
+252 -43
View File
@@ -274,6 +274,9 @@ fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
} }
} }
/// Leave this much free on the destination. A copy that would end closer than this does not start the next day.
const DISK_HEADROOM: u64 = 1024 * 1024 * 1024;
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct CardScan { pub struct CardScan {
@@ -281,11 +284,17 @@ pub struct CardScan {
pub jpeg: usize, pub jpeg: usize,
pub other: usize, pub other: usize,
pub bytes: u64, pub bytes: u64,
/// Free space on the destination volume. Absent when it could not be read, or no destination was given.
#[serde(skip_serializing_if = "Option::is_none")]
pub free_bytes: Option<u64>,
/// Whether the photos (and sidecars) fit in that free space, with a gigabyte left over.
#[serde(skip_serializing_if = "Option::is_none")]
pub fits: Option<bool>,
} }
/// Looks at a card/folder: how many RAW, JPEG and other photos, and the total size. No files are touched. /// Looks at a card/folder: how many RAW, JPEG and other photos, and the total size. No files are touched.
#[tauri::command] #[tauri::command]
pub async fn card_scan(source: String) -> Result<CardScan, String> { pub async fn card_scan(source: String, settings: Option<CardSettings>) -> Result<CardScan, String> {
tauri::async_runtime::spawn_blocking(move || { tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source); let root = expand(&source);
if !root.is_dir() { if !root.is_dir() {
@@ -293,13 +302,18 @@ pub async fn card_scan(source: String) -> Result<CardScan, String> {
} }
let mut files = Vec::new(); let mut files = Vec::new();
collect(&root, &mut files); collect(&root, &mut files);
let (mut raw, mut jpeg, mut other, mut bytes) = (0usize, 0usize, 0usize, 0u64); let mode = settings.as_ref().map(|s| s.raw_jpeg).unwrap_or(RawJpeg::Both);
let with_sidecars = settings.as_ref().map(|s| s.sidecars).unwrap_or(false);
let (mut raw, mut jpeg, mut other, mut bytes, mut sidecar_bytes) = (0usize, 0usize, 0usize, 0u64, 0u64);
for f in &files { for f in &files {
let ext = ext_of(f); let ext = ext_of(f);
if !is_image(&ext) { if !wanted(&ext, mode) {
continue; continue;
} }
bytes += std::fs::metadata(f).map(|m| m.len()).unwrap_or(0); bytes += std::fs::metadata(f).map(|m| m.len()).unwrap_or(0);
if with_sidecars {
sidecar_bytes += sidecar_bytes_of(f);
}
if is_raw(&ext) { if is_raw(&ext) {
raw += 1; raw += 1;
} else if is_jpeg(&ext) { } else if is_jpeg(&ext) {
@@ -308,7 +322,16 @@ pub async fn card_scan(source: String) -> Result<CardScan, String> {
other += 1; other += 1;
} }
} }
Ok(CardScan { raw, jpeg, other, bytes }) let (free_bytes, fits) = match settings.as_ref() {
Some(settings) => {
let free = volume_free(&expand(&settings.destination));
let needed = bytes.saturating_add(sidecar_bytes);
let fits = free.map(|free| needed.saturating_add(DISK_HEADROOM) <= free);
(free, fits)
}
None => (None, None),
};
Ok(CardScan { raw, jpeg, other, bytes, free_bytes, fits })
}) })
.await .await
.map_err(|e| e.to_string())? .map_err(|e| e.to_string())?
@@ -326,6 +349,9 @@ pub struct CardResult {
pub destination: String, pub destination: String,
/// The photographer asked to stop. Files already verified stay; the rest were not touched. /// The photographer asked to stop. Files already verified stay; the rest were not touched.
pub stopped: bool, pub stopped: bool,
/// Capture days that were not started, because the next one would not fit.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub held: Vec<String>,
} }
#[derive(Serialize, Clone)] #[derive(Serialize, Clone)]
@@ -399,9 +425,144 @@ fn report(app: Option<&AppHandle>, progress: &Progress) {
} }
} }
/// Bytes still free for a normal user on the volume that holds `path` (the nearest existing parent).
#[cfg(unix)]
fn volume_free(path: &Path) -> Option<u64> {
let mut cursor = if path.as_os_str().is_empty() { PathBuf::from(".") } else { path.to_path_buf() };
loop {
if cursor.exists() {
break;
}
if !cursor.pop() {
return None;
}
}
let Ok(c) = std::ffi::CString::new(cursor.to_string_lossy().as_bytes()) else {
return None;
};
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c.as_ptr(), &mut stat) } != 0 {
return None;
}
Some((stat.f_bavail as u64).saturating_mul(stat.f_frsize as u64))
}
#[cfg(not(unix))]
fn volume_free(_path: &Path) -> Option<u64> {
None
}
fn day_key(when: &chrono::DateTime<Local>) -> String {
format!("{:04}-{:02}-{:02}", when.year(), when.month(), when.day())
}
fn sidecar_bytes_of(src: &Path) -> u64 {
let Some(stem) = src.file_stem().and_then(|s| s.to_str()) else {
return 0;
};
let Some(parent) = src.parent() else {
return 0;
};
let mut n = 0u64;
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if side.is_file() {
n += std::fs::metadata(&side).map(|m| m.len()).unwrap_or(0);
}
}
n
}
struct Planned {
src: PathBuf,
dir: PathBuf,
name: String,
/// Size on the card. The progress bar counts this, including a file that is skipped.
photo_len: u64,
/// Bytes this photo and its sidecars will write. Zero when the destination already has them.
write_len: u64,
}
struct DayPlan {
key: String,
items: Vec<Planned>,
write_len: u64,
}
fn plan_days(photos: &[PathBuf], settings: &CardSettings) -> Vec<DayPlan> {
let base = expand(&settings.destination);
let mut rows: Vec<(String, Planned)> = Vec::with_capacity(photos.len());
for src in photos {
let ext = ext_of(src);
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let when = capture_day(src, &ext);
let key = day_key(&when);
let folder = render_folder(&settings.folder_template, &when, &ext);
let dir = base.join(folder.trim_start_matches('/'));
let photo_len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
let target = dir.join(&name);
let photo_write = if target.exists() && !settings.overwrite { 0 } else { photo_len };
let mut write_len = photo_write;
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{ext}"));
if !side.is_file() {
continue;
}
let side_target = dir.join(format!("{stem}.{ext}"));
if side_target.exists() && !settings.overwrite {
continue;
}
write_len += std::fs::metadata(&side).map(|m| m.len()).unwrap_or(0);
}
}
}
rows.push((key, Planned { src: src.clone(), dir, name, photo_len, write_len }));
}
rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.src.cmp(&b.1.src)));
let mut days: Vec<DayPlan> = Vec::new();
for (key, item) in rows {
if days.last().map(|day| day.key.as_str()) != Some(key.as_str()) {
days.push(DayPlan { key, items: Vec::new(), write_len: 0 });
}
let day = days.last_mut().unwrap();
day.write_len += item.write_len;
day.items.push(item);
}
days
}
/// `room` is space left for this copy, already after the headroom. None: the volume could not be read, so
/// every day is copied. The first day that does not fit, and every day after it, stays on the card.
fn days_that_fit(days: Vec<DayPlan>, room: Option<u64>) -> (Vec<DayPlan>, Vec<String>) {
let Some(mut room) = room else {
return (days, Vec::new());
};
let mut take = Vec::new();
let mut held = Vec::new();
let mut stop = false;
for day in days {
if stop || day.write_len > room {
stop = true;
held.push(day.key);
continue;
}
room -= day.write_len;
take.push(day);
}
(take, held)
}
fn room_for(settings: &CardSettings) -> Option<u64> {
volume_free(&expand(&settings.destination)).map(|free| free.saturating_sub(DISK_HEADROOM))
}
/// One card, one stream. A memory card has a single reader: several threads on it seek back and forth and /// One card, one stream. A memory card has a single reader: several threads on it seek back and forth and
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once. /// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool) -> Result<CardResult, String> { /// `room` limits how much may be written. Days are copied whole, oldest first; a day that does not fit is
/// not started, and neither is any day after it. A move deletes a day's sources only once that day is complete.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool, room: Option<u64>) -> Result<CardResult, String> {
if !root.is_dir() { if !root.is_dir() {
return Err("not_a_folder".to_string()); return Err("not_a_folder".to_string());
} }
@@ -409,8 +570,9 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
let mut files = Vec::new(); let mut files = Vec::new();
collect(root, &mut files); collect(root, &mut files);
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect(); let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
let total = photos.len(); let (days, held) = days_that_fit(plan_days(&photos, settings), room);
let bytes_total: u64 = photos.iter().map(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)).sum(); let total: usize = days.iter().map(|day| day.items.len()).sum();
let bytes_total: u64 = days.iter().map(|day| day.items.iter().map(|item| item.photo_len).sum::<u64>()).sum();
let mut bytes_done = 0u64; let mut bytes_done = 0u64;
let mut r = CardResult { let mut r = CardResult {
copied: 0, copied: 0,
@@ -420,72 +582,86 @@ fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job
notes: Vec::new(), notes: Vec::new(),
destination: base.to_string_lossy().to_string(), destination: base.to_string_lossy().to_string(),
stopped: false, stopped: false,
held: held.clone(),
}; };
for (i, src) in photos.iter().enumerate() { if let Some(day) = held.first() {
note(&mut r.notes, &format!("O dia {day} não cabe. Fica no cartão, tal como os dias a seguir."));
}
let mut index = 0usize;
for day in &days {
if cancel.load(Ordering::Relaxed) { if cancel.load(Ordering::Relaxed) {
r.stopped = true; r.stopped = true;
break; break;
} }
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let mut remove_after: Vec<PathBuf> = Vec::new();
let len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0); let mut day_complete = true;
report(app, &Progress { done: i + 1, total, name: name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total }); let mut wrote = 0usize;
for item in &day.items {
let ext = ext_of(src); if cancel.load(Ordering::Relaxed) {
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext); r.stopped = true;
let dir = base.join(folder.trim_start_matches('/')); day_complete = false;
if let Err(e) = std::fs::create_dir_all(&dir) { break;
}
index += 1;
report(app, &Progress { done: index, total, name: item.name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
if let Err(e) = std::fs::create_dir_all(&item.dir) {
r.failed += 1; r.failed += 1;
bytes_done += len; bytes_done += item.photo_len;
note(&mut r.notes, &format!("{name}: pasta — {e}")); day_complete = false;
note(&mut r.notes, &format!("{}: pasta — {e}", item.name));
continue; continue;
} }
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then. // The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
let target = dir.join(&name); let target = item.dir.join(&item.name);
if target.exists() && !settings.overwrite { if target.exists() && !settings.overwrite {
r.skipped += 1; r.skipped += 1;
bytes_done += len; bytes_done += item.photo_len;
continue; continue;
} }
if let Err(e) = copy_verified(src, &target) { if let Err(e) = copy_verified(&item.src, &target) {
r.failed += 1; r.failed += 1;
bytes_done += len; bytes_done += item.photo_len;
note(&mut r.notes, &format!("{name}: {e}")); day_complete = false;
note(&mut r.notes, &format!("{}: {e}", item.name));
continue; continue;
} }
// Sidecars (same stem): best effort. A sidecar that fails is noted but does not fail the photo.
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new(); let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars { if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) { if let (Some(stem), Some(parent)) = (item.src.file_stem().and_then(|s| s.to_str()), item.src.parent()) {
for s in SIDECAR_EXTS { for ext in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{s}")); let side = parent.join(format!("{stem}.{ext}"));
if !side.exists() { if !side.exists() {
continue; continue;
} }
let side_target = dir.join(format!("{stem}.{s}")); let side_target = item.dir.join(format!("{stem}.{ext}"));
if side_target.exists() && !settings.overwrite { if side_target.exists() && !settings.overwrite {
continue; continue;
} }
match copy_verified(&side, &side_target) { match copy_verified(&side, &side_target) {
Ok(()) => sidecars_done.push(side), Ok(()) => sidecars_done.push(side),
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")), Err(e) => note(&mut r.notes, &format!("{stem}.{ext}: {e}")),
} }
} }
} }
} }
remove_after.push(item.src.clone());
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted. remove_after.extend(sidecars_done);
if settings.mv { wrote += 1;
let _ = std::fs::remove_file(src); bytes_done += item.photo_len;
for side in &sidecars_done {
let _ = std::fs::remove_file(side);
} }
r.moved += 1; // Move deletes the day's sources only when the whole day arrived. A partial day stays on the card.
if settings.mv && day_complete && !r.stopped {
for path in &remove_after {
let _ = std::fs::remove_file(path);
}
r.moved += wrote;
} else { } else {
r.copied += 1; r.copied += wrote;
}
if r.stopped {
break;
} }
bytes_done += len;
} }
let finished = r.copied + r.moved + r.skipped + r.failed; let finished = r.copied + r.moved + r.skipped + r.failed;
report( report(
@@ -505,7 +681,8 @@ pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings,
let end_id = job_id.clone(); let end_id = job_id.clone();
let result = tauri::async_runtime::spawn_blocking(move || { let result = tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source); let root = expand(&source);
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel) let room = room_for(&settings);
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel, room)
}) })
.await .await
.map_err(|e| e.to_string()); .map_err(|e| e.to_string());
@@ -550,15 +727,47 @@ mod tests {
..CardSettings::default() ..CardSettings::default()
}; };
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true)).unwrap(); let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true), None).unwrap();
assert!(stopped.stopped); assert!(stopped.stopped);
assert_eq!(stopped.copied, 0); assert_eq!(stopped.copied, 0);
assert!(!dst.join("a.jpg").exists()); assert!(!dst.join("a.jpg").exists());
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false)).unwrap(); let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), None).unwrap();
assert!(!done.stopped); assert!(!done.stopped);
assert_eq!(done.copied, 2); assert_eq!(done.copied, 2);
assert_eq!(std::fs::read(dst.join("a.jpg")).unwrap(), b"hello card"); assert_eq!(std::fs::read(dst.join("a.jpg")).unwrap(), b"hello card");
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
#[test]
fn a_day_that_does_not_fit_stays_on_the_card_and_the_one_before_is_moved() {
let dir = std::env::temp_dir().join(format!("pr-card-days-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
let dst = dir.join("dst");
std::fs::create_dir_all(&src).unwrap();
let old = src.join("old.jpg");
let new = src.join("new.jpg");
std::fs::write(&old, b"day-one").unwrap();
std::fs::write(&new, b"day-two-is-bigger").unwrap();
let past = std::time::SystemTime::now() - std::time::Duration::from_secs(5 * 24 * 3600);
std::fs::OpenOptions::new().write(true).open(&old).unwrap().set_modified(past).unwrap();
let settings = CardSettings {
destination: dst.to_string_lossy().to_string(),
folder_template: String::new(),
mv: true,
sidecars: false,
..CardSettings::default()
};
let room = std::fs::metadata(&old).unwrap().len();
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false), Some(room)).unwrap();
assert_eq!(done.moved, 1);
assert_eq!(done.held.len(), 1);
assert!(dst.join("old.jpg").exists());
assert!(!dst.join("new.jpg").exists());
assert!(!old.exists());
assert!(new.exists());
assert!(!done.notes.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
} }
+31 -32
View File
@@ -1,7 +1,8 @@
"use client"; "use client";
import { useCallback, useEffect, useMemo, useState } from "react"; import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api"; import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { eventLayout } from "./events";
import { Icon, Loading, PersonFace } from "./parts"; import { Icon, Loading, PersonFace } from "./parts";
export type Tab = "galleries" | "people" | "teams" | "review"; export type Tab = "galleries" | "people" | "teams" | "review";
@@ -60,6 +61,11 @@ export function Browse({
const [filtersOpen, setFiltersOpen] = useState(false); const [filtersOpen, setFiltersOpen] = useState(false);
/** A tournament's day or group opened from its tile. */ /** A tournament's day or group opened from its tile. */
const [openGroup, setOpenGroup] = useState<string | null>(null); const [openGroup, setOpenGroup] = useState<string | null>(null);
const openPanel = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!openGroup) return;
openPanel.current?.scrollIntoView({ block: "nearest" });
}, [openGroup]);
/** "Juntar nomes": the clubs ticked to count as one (null: not joining). */ /** "Juntar nomes": the clubs ticked to count as one (null: not joining). */
const [joining, setJoining] = useState<string[] | null>(null); const [joining, setJoining] = useState<string[] | null>(null);
const [joinInto, setJoinInto] = useState(""); const [joinInto, setJoinInto] = useState("");
@@ -281,57 +287,50 @@ export function Browse({
</button> </button>
); );
/** A tournament's galleries by day or group (the folder above them): one tile each, opened in place. */ /** A tournament's galleries by day or group (the folder above them): one tile each, opened under that tile. */
const events = (items: GalleryCard[]) => { const events = (items: GalleryCard[]) => {
const groups = new Map<string, GalleryCard[]>(); const { groups, loose } = eventLayout(items);
const loose: GalleryCard[] = [];
for (const g of items) {
if (!g.group) loose.push(g);
else groups.set(g.group, [...(groups.get(g.group) ?? []), g]);
}
for (const [name, gs] of groups)
if (gs.length < 2) {
loose.push(...gs);
groups.delete(name);
}
const open = openGroup ? groups.get(openGroup) : undefined;
return ( return (
<> <>
{(groups.size > 0 || loose.length > 0) && ( {(groups.length > 0 || loose.length > 0) && (
<div className="arq-cards"> <div className="arq-cards">
{[...groups].map(([name, gs]) => { {groups.map((group) => {
const cover = gs.find((g) => g.cover)?.cover; const cover = group.galleries.find((g) => g.cover)?.cover;
const dates = gs.map((g) => g.startsAt).filter((d): d is string => !!d).sort(); const dates = group.galleries.map((g) => g.startsAt).filter((d): d is string => !!d).sort();
const expanded = openGroup === group.name;
const photos = group.galleries.reduce((n, g) => n + g.photoCount, 0);
return ( return (
<button key={name} type="button" className="arq-card arq-groupcard" aria-expanded={openGroup === name} onClick={() => setOpenGroup(openGroup === name ? null : name)}> <Fragment key={group.name}>
<button type="button" className="arq-card arq-groupcard" aria-expanded={expanded} onClick={() => setOpenGroup(expanded ? null : group.name)}>
<span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span> <span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span>
<span className="arq-thumb"> <span className="arq-thumb">
{cover && <img src={cover} alt="" loading="lazy" decoding="async" />} {cover && <img src={cover} alt="" loading="lazy" decoding="async" />}
<span className="arq-badge dark">{gs.length} galerias</span> <span className="arq-badge dark">{group.galleries.length} galerias</span>
</span> </span>
<span className="arq-event"> <span className="arq-event">
<strong>{name}</strong> <strong>{group.name}</strong>
<span> <span>
{gs.length} galerias · {gs.reduce((n, g) => n + g.photoCount, 0)} fotos {group.galleries.length} galerias · {photos} fotos
</span> </span>
</span> </span>
</button> </button>
); {expanded && (
})} <div className="arq-group-open" ref={openPanel}>
{loose.map(card)}
</div>
)}
{open && (
<div className="arq-group-open">
<div className="arq-kind-head"> <div className="arq-kind-head">
<h3>{openGroup}</h3> <h3>{group.name}</h3>
<span className="arq-muted">{open.length} galerias</span> <span className="arq-muted">{group.galleries.length} galerias</span>
<span className="arq-grow" /> <span className="arq-grow" />
<button type="button" className="arq-link" onClick={() => setOpenGroup(null)}> <button type="button" className="arq-link" onClick={() => setOpenGroup(null)}>
Fechar Fechar
</button> </button>
</div> </div>
<div className="arq-cards">{open.map(card)}</div> <div className="arq-cards">{group.galleries.map(card)}</div>
</div>
)}
</Fragment>
);
})}
{loose.map(card)}
</div> </div>
)} )}
</> </>
@@ -2292,6 +2292,7 @@
box-shadow: 0 0 0 2px var(--ink), 5px 5px 0 0 var(--card), 5px 5px 0 2px var(--ink); box-shadow: 0 0 0 2px var(--ink), 5px 5px 0 0 var(--card), 5px 5px 0 2px var(--ink);
} }
.arq-group-open { .arq-group-open {
grid-column: 1 / -1;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { GalleryCard } from "./api";
import { eventLayout } from "./events";
function card(id: string, group: string | null): GalleryCard {
return { id, title: id, group, home: null, away: null, competition: null, startsAt: null, photoCount: 10, cover: null };
}
describe("tournament tiles", () => {
it("keeps a tournament's galleries on that tile", () => {
const { groups, loose } = eventLayout([
card("a", "JORNADA 8"),
card("b", "JORNADA 8"),
card("c", "PG COMUNICAÇÃO"),
card("d", "PG COMUNICAÇÃO"),
card("e", "PG COMUNICAÇÃO"),
card("solo", null),
card("one", "Só um dia"),
]);
expect(groups.map((group) => [group.name, group.galleries.map((gallery) => gallery.id)])).toEqual([
["JORNADA 8", ["a", "b"]],
["PG COMUNICAÇÃO", ["c", "d", "e"]],
]);
expect(loose.map((gallery) => gallery.id)).toEqual(["solo", "one"]);
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { GalleryCard } from "./api";
export interface EventGroup {
name: string;
galleries: GalleryCard[];
}
/**
* Tournaments are one tile per folder. A folder with a single gallery is just that gallery: clicking it opens
* the gallery. A folder with several galleries opens under its own tile, not after the whole list.
*/
export function eventLayout(items: readonly GalleryCard[]): { groups: EventGroup[]; loose: GalleryCard[] } {
const byName = new Map<string, GalleryCard[]>();
const loose: GalleryCard[] = [];
for (const item of items) {
const name = item.group?.trim() ?? "";
if (!name) {
loose.push(item);
continue;
}
byName.set(name, [...(byName.get(name) ?? []), item]);
}
const groups: EventGroup[] = [];
for (const [name, galleries] of byName) {
if (galleries.length < 2) loose.push(...galleries);
else groups.push({ name, galleries });
}
return { groups, loose };
}
+22 -11
View File
@@ -187,7 +187,8 @@ Only for organizations whose owner switched it on with a recorded legal basis (b
Each photo that arrives is queued (`photos.faces_status`); the worker reads the last 30 days first (when the photo Each photo that arrives is queued (`photos.faces_status`); the worker reads the last 30 days first (when the photo
was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive. was taken, or the game's date when the camera wrote none), newest game first, and only then the older archive.
A folder of an old season that has just been indexed waits until that month is clear, then comes ahead of the A folder of an old season that has just been indexed waits until that month is clear, then comes ahead of the
archive that has been waiting. Asking to analyse one event still puts it first. A photo whose analysis failed is archive that has been waiting. The worker starts a few face processes and adds more while the CPU stays under
about 99%, stopping sooner when memory (the model) runs short. Asking to analyse one event still puts it first. A photo whose analysis failed is
queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face queued again a few at a time, after it has been quiet for six hours, recent games first. Confirming a face
improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the improves who that person is (their face is the mean of the faces confirmed, plus the official headshot): the
detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original: detector that finds a face in the photo is not retrained. The worker runs `workers/faces` on the original:
@@ -234,17 +235,25 @@ number for that event's context:
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an - **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
old game gets the number worn then, even for players who have since left. old game gets the number worn then, even for players who have since left.
- **Official match (linked to its teams):** the match sheet first — that season's players and coaches, and the - **A game whose two clubs are known** (teams already stored, or the home and away names matching one team of
referees of the fixture, when they already have a face. A face none of them explains is then compared with that sport each): only that season's squad — players and coaches — and the referees of the fixture, when they
everyone of that sport. A session (no away side) has no sheet: the face alone, against everyone of the sport. already have a face. A player who has since moved is included when that season's list has them (the same
The shirt, when it is read, stays with those two clubs. Then what the shirts clearly read (three federation id, or the same birth date and full name), with the shirt number of that season. A face none of
or more clear readings) in the person's confirmed photos of the same season and competition. them explains stays unnamed. It is never someone who was not at either club that season.
A session, a training day or a studio day of a national team (FPA: SNAF, SNAM, M18, and the same team under
its long name) uses that team only: people already confirmed there this season, and the athletes the session
folders name. There is no match number. A gala or a press day names no team: the face alone, against everyone
of that sport, and only a clearly stronger match. The shirt, when it is read, stays with those two clubs.
Then what the shirts clearly read (three or more clear readings) in the person's confirmed photos of the same
season and competition.
- An editor of the folder can give a face another name. The list shows the official face, the club and the shirt - An editor of the folder can give a face another name. The list shows the official face, the club and the shirt
number. number.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's - **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
squad. squad.
- **National team** (a country on either side, or a "Seleção" folder): club squads and club numbers never apply, - **National team** (a country on either side, or a seleção folder): club squads and club numbers never apply.
only what was read in national games of that season. The women's senior team, the men's, and an age group are different lists. A photo is named from people already
confirmed on that same team this season. The shirt number is the one read on that team's games, and an older
Portugal game with no team in the folder still shares what was read for Portugal that season.
- **The number typed on the person** has no season: used only in the current season and never for a national - **The number typed on the person** has no season: used only in the current season and never for a national
team. Training samples never take the model's own readings as labels. team. Training samples never take the model's own readings as labels.
@@ -257,7 +266,8 @@ hand-drawn boxes.
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation: 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. Gives teams, squads (numbers, - **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup. Gives teams, squads (numbers,
positions, official headshots) and the season's fixtures. positions, official headshots) and the season's fixtures. On start the worker walks every season the federation
still publishes, club by club, so a past season keeps the squad and the shirt numbers of that year.
- **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and - **FPA** (`ws.fpa.pt` agenda): every national handball competition (PO01, PO09, PO20...), with teams and
fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the fixtures. Squads of the senior national leagues and cups (PO01, PO01A, PO09, PO09A, PO20, PO23) come from the
match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence match reports (`si.fpa.pt` "Boletim do Jogo", windows-1252 HTML): each player with shirt number and licence
@@ -295,8 +305,9 @@ What organisations do with it:
from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s) from public https hosts (private, loopback and link-local addresses refused, redirects checked again, 5 MB, 10 s)
and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city and cached 5 minutes. For a generic event the form lists the day's entries; picking one fills name, venue, city
and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only. and time and suggests a caption ("Title, Venue, City.") to edit. Repeating entries show their first date only.
- **People from squads:** squads become people (club, number, `sportsPlayerId`). With biometrics on, the Liga - **People from squads:** one person per human. A later season at another club updates the club and the shirt
headshot becomes the reference photo, and number suggestions for faces use the event's squads. number; an older season does not. The number shown on a photo is still that season's. With biometrics on, the
Liga headshot becomes the reference photo, and number suggestions for faces use the event's squads.
## Working without a network (desktop app) ## Working without a network (desktop app)
+60 -4
View File
@@ -2,15 +2,18 @@
//! //!
//! This is not the `hdr.*` develop panel. That panel is display headroom for one photo. Here several //! This is not the `hdr.*` develop panel. That panel is display headroom for one photo. Here several
//! exposures of the same angle become one scene-linear image: the engine aligns them, measures the //! exposures of the same angle become one scene-linear image: the engine aligns them, measures the
//! exposure steps, and weights each pixel so a clipped channel contributes nothing. The result is //! exposure steps, and weights each pixel so a clipped channel contributes nothing. The JPEG preview
//! developed with the engine's Auto settings (the same finish LightCraft applies to a merge). //! is developed with the engine's Auto settings. The linear DNG is not: the editor does that finish.
use std::sync::Arc; use std::sync::Arc;
use lightcraft_color::Xy; use lightcraft_color::Xy;
use lightcraft_develop::DevelopSettings; use lightcraft_develop::DevelopSettings;
use lightcraft_merge::frame::Frame; use lightcraft_merge::frame::Frame;
use lightcraft_merge::{Deghost, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress}; use lightcraft_merge::{
Deghost, DngSamples, FrameColor, HdrOptions, HdrResult, merge_hdr, no_progress,
write_linear_dng,
};
use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto}; use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, auto};
use lightcraft_raster::Rgb32f; use lightcraft_raster::Rgb32f;
use lightcraft_raster::resample::{Filter, fit}; use lightcraft_raster::resample::{Filter, fit};
@@ -188,7 +191,7 @@ fn to_working(merged: &HdrResult) -> (Rgb32f, SourceInfo) {
} }
} }
fn camera_working(image: Rgb32f, color: &ColorData, gain: f32) -> (Rgb32f, SourceInfo) { pub(crate) fn camera_working(image: Rgb32f, color: &ColorData, gain: f32) -> (Rgb32f, SourceInfo) {
let white = as_shot_xy(color); let white = as_shot_xy(color);
let transform = lightcraft_raw::color::camera_transform_of(color, white); let transform = lightcraft_raw::color::camera_transform_of(color, white);
let m = transform.matrix.to_f32(); let m = transform.matrix.to_f32();
@@ -221,6 +224,41 @@ fn as_shot_xy(color: &ColorData) -> Xy {
lightcraft_color::D65 lightcraft_color::D65
} }
/// Scene-linear DNG of one bracket (16-bit float). `max_edge` is the long side of each frame before
/// the merge, clamped to 64..=4096. The develop finish is not baked in: the file stays linear so the
/// editor's controls do it.
pub fn merge_linear_dng(files: &[&[u8]], max_edge: u32) -> Result<Vec<u8>, EngineError> {
if files.len() < 2 {
return Err(EngineError::Decode(
"a bracket needs at least two exposures".into(),
));
}
let edge = clamped_edge(max_edge);
let mut frames = Vec::with_capacity(files.len());
for file in files {
frames.push(load_bracket_frame(file, edge)?);
}
let merged = merge_hdr(
frames,
&HdrOptions {
align: true,
deghost: Deghost::None,
},
&no_progress,
)
.map_err(|e| EngineError::Decode(e.to_string()))?;
write_linear_dng(
&merged.radiance,
&merged.color,
merged.orientation,
&merged.metadata,
merged.baseline_exposure,
DngSamples::Half,
&merged.lens,
)
.map_err(|e| EngineError::Decode(e.to_string()))
}
fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] { fn apply_mat(m: &[[f32; 3]; 3], p: [f32; 3]) -> [f32; 3] {
[ [
m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2], m[0][0] * p[0] + m[0][1] * p[1] + m[0][2] * p[2],
@@ -314,6 +352,24 @@ mod tests {
); );
} }
#[test]
fn a_merge_writes_a_dng_the_editor_can_open() {
let dark = exposure_dng(-2.0);
let mid = exposure_dng(0.0);
let bright = exposure_dng(2.0);
let files = [dark.as_slice(), mid.as_slice(), bright.as_slice()];
let dng = merge_linear_dng(&files, 256).expect("dng");
assert!(dng.len() > 64);
let source = crate::render::Source::decode(&dng, 256).expect("decode");
let (w, h) = source.size();
assert!(w >= 64 && h >= 64, "{w}x{h}");
let pixels = source.render(&DevelopSettings::default(), 128, 128, false, false);
assert_eq!(
pixels.rgba.len(),
pixels.width as usize * pixels.height as usize * 4
);
}
#[test] #[test]
fn one_photo_is_not_a_bracket() { fn one_photo_is_not_a_bracket() {
let mid = exposure_dng(0.0); let mid = exposure_dng(0.0);
+37
View File
@@ -23,6 +23,39 @@ pub struct Source {
pub source_height: u32, pub source_height: u32,
} }
/// A linear DNG (three samples, no mosaic) into the working space. Mosaic raws are refused: those stay
/// on the merge path, which bins them on purpose.
fn decode_linear_dng(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> {
let raw = lightcraft_raw::decode(bytes).map_err(|e| EngineError::Decode(e.to_string()))?;
if raw.cfa.is_some() || raw.cpp != 3 {
return Err(EngineError::Decode("not a linear photo".into()));
}
let developed = raw
.develop(lightcraft_raw::Method::Bilinear)
.map_err(|e| EngineError::Decode(e.to_string()))?;
let gain = 2f32.powf(raw.color.baseline_exposure as f32);
let (image, info) = crate::merge::camera_working(developed, &raw.color, gain);
let image = image.into_oriented(raw.orientation);
let (source_width, source_height) = (image.width as u32, image.height as u32);
let edge = if max_edge == 0 {
usize::MAX
} else {
max_edge as usize
};
let image = if image.width.max(image.height) > edge {
fit(&image, edge, edge, Filter::Mitchell)
} else {
image
};
Ok(Source {
image: Arc::new(image),
info,
cache: StageCache::default(),
source_width,
source_height,
})
}
/// An 8-bit sRGB render with alpha (RGBA, row-major). /// An 8-bit sRGB render with alpha (RGBA, row-major).
pub struct Pixels { pub struct Pixels {
pub width: u32, pub width: u32,
@@ -32,7 +65,11 @@ pub struct Pixels {
impl Source { impl Source {
/// Decodes `bytes`, keeping at most `max_edge` pixels on the long side (0 = full resolution). /// Decodes `bytes`, keeping at most `max_edge` pixels on the long side (0 = full resolution).
/// A linear DNG (a merged bracket) is developed from its camera RGB. Mosaic raws are not.
pub fn decode(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> { pub fn decode(bytes: &[u8], max_edge: u32) -> Result<Source, EngineError> {
if lightcraft_raw::probe(bytes) == Some(lightcraft_raw::RawFormat::Dng) {
return decode_linear_dng(bytes, max_edge);
}
let edge = if max_edge == 0 { u32::MAX } else { max_edge }; let edge = if max_edge == 0 { u32::MAX } else { max_edge };
let d = lightcraft_codecs::decode(bytes, DecodeOptions::fit(edge, edge)) let d = lightcraft_codecs::decode(bytes, DecodeOptions::fit(edge, edge))
.map_err(|e| EngineError::Decode(e.to_string()))?; .map_err(|e| EngineError::Decode(e.to_string()))?;
+7
View File
@@ -189,6 +189,13 @@ impl BracketJob {
self.files.push(bytes.to_vec()); self.files.push(bytes.to_vec());
} }
/// Scene-linear DNG (16-bit float). `max_edge` is the long side of each frame before the merge.
#[wasm_bindgen(js_name = mergeDng)]
pub fn merge_dng(&self, max_edge: u32) -> Result<Vec<u8>, JsError> {
let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect();
photoreport_engine::merge::merge_linear_dng(&refs, max_edge).map_err(js_err)
}
/// Developed JPEG preview of the merged bracket. `max_edge` is the long side of each frame. /// Developed JPEG preview of the merged bracket. `max_edge` is the long side of each frame.
pub fn merge(&self, max_edge: u32) -> Result<BracketMerge, JsError> { pub fn merge(&self, max_edge: u32) -> Result<BracketMerge, JsError> {
let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect(); let refs: Vec<&[u8]> = self.files.iter().map(Vec::as_slice).collect();
+26
View File
@@ -114,6 +114,32 @@ export class ApiClient {
return this.request<{ stored: boolean }>("POST", `/v1/photos/${photoId}/original`, form); return this.request<{ stored: boolean }>("POST", `/v1/photos/${photoId}/original`, form);
} }
/**
* A JPEG preview of a merge. `silent` holds it until {@link attachLinearDng} replaces the file,
* so the library hears about the photo once. `inbox` keeps it out of every event.
*/
uploadPhoto(orgId: string, file: Blob, name: string, opts: { eventId?: string | null; silent?: boolean; inbox?: boolean } = {}) {
const form = new FormData();
form.append("file", file, name);
const params = new URLSearchParams();
if (opts.eventId) params.set("eventId", opts.eventId);
if (opts.inbox) params.set("inbox", "1");
if (opts.silent) params.set("silent", "1");
const query = params.size ? `?${params}` : "";
return this.request<{ status: string; photo: PhotoSummary }>("POST", `/v1/orgs/${orgId}/uploads${query}`, form);
}
/** The linear DNG that replaces a held preview. The photo then shows up in the collection. */
attachLinearDng(photoId: string, file: Blob, meta: { width: number; height: number; capturedAt: string | null }) {
const form = new FormData();
form.append("file", file, "merged.dng");
const params = new URLSearchParams();
params.set("width", String(meta.width));
params.set("height", String(meta.height));
if (meta.capturedAt) params.set("capturedAt", meta.capturedAt);
return this.request<{ status: string; photo: PhotoSummary }>("POST", `/v1/photos/${photoId}/linear-dng?${params}`, form);
}
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */ /** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
claimLocalDeliveries(orgId: string, machine: string) { claimLocalDeliveries(orgId: string, machine: string) {
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine }); return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });