Compare commits

...
Author SHA1 Message Date
spark 4cd83dc8b9 Store each folder's gallery when the archive is scanned.
ci / rust (pull_request) Successful in 7m37s
ci / typescript (pull_request) Successful in 10m5s
The site reads that column instead of grouping folders on each visit. A game or a dated session keeps the folders inside it, and a folder removed from the cloud takes the tree under it.
2026-10-19 10:35:11 +01:00
spark 4eac0e6f95 fix(infra): serialize pm2 startOrReload between boot.sh and deploy.sh
ci / rust (push) Successful in 3m51s
ci / typescript (push) Successful in 7m22s
Live incident 2026-10-19: node09 rebooted and photoreport-boot.service ran
twice concurrently against a freshly-spawned, still-empty PM2 daemon. Both
invocations saw "not running" and launched photoreport-api, creating a
duplicate that crash-looped forever on EADDRINUSE (1700+ restarts by the
time it was caught, silently -- the original instance kept serving so
/health never flagged it). Deleted the ghost process and re-saved live.

Wrap the pm2 startOrReload calls in both scripts with the same flock so a
boot racing a webhook-triggered deploy (or a double-invoked boot unit)
serializes instead of racing the "is it running" check.

Paperclip-Issue: BIT-31073
Paperclip-Run: 9c6946f6-df0c-4544-97ac-6b00a2de8bd1
2026-10-19 10:05:23 +01:00
spark a1cf133193 Merge pull request 'A slash is two clubs only when both sides are clubs' (#45) from task/archive-slash-sponsor into main
ci / rust (push) Successful in 6m5s
ci / typescript (push) Successful in 10m1s
2026-10-19 09:11:25 +01:00
spark 156474bb7a A slash is two clubs only when both sides are clubs.
ci / rust (pull_request) Successful in 9m15s
ci / typescript (pull_request) Successful in 12m50s
"Avanca / Bioria" is Avanca with that season's sponsor. "ALMADA AC / EXT. GIL EANES" stays two teams, and so do two known clubs such as Benfica / Porto.
2026-10-19 09:11:07 +01:00
spark 9bab5a8c25 Merge pull request 'Autopilot edits the agencies' way: tight handball framing, a finishing look, neutral whites' (#44) from task/autopilot-agency-style into main
ci / rust (push) Successful in 9m35s
ci / typescript (push) Successful in 13m29s
2026-10-19 08:55:12 +01:00
spark 67b86879fd Merge pull request 'Archive teams: a slash between two clubs is two teams, and the directory prepares instead of timing out' (#43) from task/archive-teams-fast into main
ci / rust (push) Successful in 12m35s
ci / typescript (push) Successful in 16m4s
2026-10-19 08:54:59 +01:00
spark 68588e0296 Merge main and read a slash between two club names as two teams.
ci / rust (pull_request) Successful in 12m19s
ci / typescript (pull_request) Successful in 15m22s
A folder such as "ALMADA AC / EXT. GIL EANES" was stored as one team in every archive. A slash with spaces is the two sides; a season written 2025/2026 stays a directory.
2026-10-19 08:54:26 +01:00
jos-alves c61d371819 Stop a not-yet-published Liga round from reaching the error hub as a warning
ci / rust (push) Successful in 4m1s
ci / typescript (push) Successful in 7m33s
Liga 400s competition/round/{n}/nominations until it publishes a round's referee
nominations, days before the match (providers.ts doc comment). syncEventSquadsNow
caught that but logged it at warn, and the pino->error-hub hook forwards any warn
carrying an `err` — so routine early reads of a round show up in the error hub as
warnings (ERRCLUSTER 9d79efd242be).

Give `get()` a typed ProviderHttpError carrying the HTTP status, and have the Liga
referees catch distinguish a 400 (not published yet, read again on the next refresh)
from a real failure: info instead of warn for the former, keeping it out of the hub.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31543
Paperclip-Run: 5f8f2566-36ea-4f72-9d15-cf0a107111c2
2026-10-19 06:01:31 +01:00
jos-alves 707420a579 Fix a race where matching a gallery onto an event could hit photos_event_id_fkey
ci / rust (push) Successful in 3m56s
ci / typescript (push) Successful in 7m28s
ArchiveService.dropIfEmpty() read an event's photo/folder/gallery/delivery
counts, then deleted it in a second, separate statement if they were all
zero. Between those two statements, another setFolderEvent() racing on the
same event (the normal concurrent paths: a scheduled rematch sweep and a
manual re-match, or two folders moving in the same sweep) could land a fresh
cloudFolder on it; dropIfEmpty's stale read never saw that and deleted the
event anyway, cascading SetNull back onto the folder that had just landed.
The other call then tried to move that folder's photos onto the
now-deleted event and hit `photos_event_id_fkey` (BIT-31531, same cluster
as the ERRSIG in the issue).

dropIfEmpty() now does the emptiness check and the delete as one
`deleteMany` with the relation-count conditions in its own WHERE, so
Postgres re-evaluates "is it still empty" against whatever just committed
instead of against a stale read. Added a regression test that holds the
delete open with a query extension while a second match lands on the
event, proving it survives instead of being dropped (confirmed the test
fails against the old read-then-delete code before restoring the fix).

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31531
Paperclip-Run: c48a8976-d063-4134-b393-fff6a124f0ce
2026-10-19 05:36:57 +01:00
jos-alves 92ceeee2fe Budget one extra API instance during a deploy's rolling reload
ci / rust (push) Successful in 3m52s
ci / typescript (push) Successful in 7m15s
dbConnectionBudget() sized the API cluster's connections at exactly
apiInstances (2), but pm2 startOrReload on the clustered photoreport-api
app brings a new instance online and confirms it healthy before stopping
an old one, so for a few seconds during every deploy there are
apiInstances + 1 processes alive, each with its own Prisma pool and
realtime connections. That transient extra instance (13 connections with
default pool/realtime sizes) was enough to push the cluster over the
budget BIT-31533 set and into Postgres' superuser_reserved_connections,
surfacing as the same "too many database connections ... reserved for
roles with the SUPERUSER attribute" error from the worker's ArchiveService
(BIT-31550, same cluster as BIT-31519/BIT-31533).

dbConnectionBudget() now takes apiReloadOverlap (default 1) and folds it
into the API cluster term so the worker's own pool is sized to leave room
for the overlap. Default worker budget on a 100-max_connections host drops
from 60 to 47.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31550
Paperclip-Run: 71ac411e-1cce-46e6-b745-7f380228cf79
2026-10-19 05:16:40 +01:00
jos-alves 81bd777e87 Stop a transient Nextcloud blip reading an archive original from reaching the error hub
ci / rust (push) Successful in 3m48s
ci / typescript (push) Successful in 7m9s
BIT-31513 already downgraded this exact self-healing retry to log.info inside
ArchiveService.index(), but DeliveryService.process() hits the same
CloudClient.download() through downloadOriginal() and unconditionally logged the
catch at warn with the raw err, so a 503/423 blip still fingerprinted into
errors.bitreport.pt and reopened the Error Loop (BIT-31522, same cluster pattern
as BIT-31491/BIT-31498/BIT-31505/BIT-31513). The retry behaviour was already
correct (the item is requeued with a backoff); only the log level was wrong.

Use the isTransient() check already imported in this file (and used at the two
other catch sites) to log at info instead of warn when the download blip is
transient, keeping warn for a real failure. Added a regression test mirroring
BIT-31513's.

Paperclip-Issue: BIT-31522
Paperclip-Run: fa16b650-eeb3-4067-81ff-879c78e4c0c1
2026-10-19 04:47:35 +01:00
sparkandClaude Opus 5.5 67765899a6 Autopilot edits the agencies' way: tight handball framing, a finishing look, neutral whites.
ci / rust (pull_request) Successful in 12m32s
ci / typescript (pull_request) Successful in 15m46s
Measured on kolektiff images (600 EHF/IHF handball photos, 2025-26) and Getty/AFP (1093 action photos, Paris 2024):
- Framing "tight" (default): the subject about as tall as the crop, legs cut mid-shin or mid-thigh (never at a
  joint, never below the ball), the photo's own shape. The second pick of a burst gets the whole-body frame.
  A crop over 92% of the width is not made: the photo stays as shot.
- Look "agency" (default, kolektiff) or "natural" (Getty): vibrance, clarity, texture, slightly cool shadows,
  capture sharpening, noise reduction by ISO. Never a vignette or anything local (ethics rules).
- Defaults: white balance on, 75% of the automatic tone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-19 03:30:17 +00:00
jos-alves 0d6a9e27e0 Show a retry screen instead of a hard crash when a page render fails
ci / rust (push) Successful in 7m16s
ci / typescript (push) Successful in 10m59s
The site had no error.tsx or global-error.tsx anywhere, so any transient
failure in a Server Component (an API hiccup, a DB blip like the one fixed
in d6a7edd) took down the whole page with Next's generic "omitted in
production" message and no way to recover short of reloading. The real
error and stack still reach errors.bitreport.pt via instrumentation.ts's
onRequestError, which fires independently of these boundaries.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31537
Paperclip-Run: a91a9196-6082-4408-a3b1-9b3711e28f7b
2026-10-19 04:24:09 +01:00
spark 1652b6ba3c Merge pull request 'A slow Liga month no longer drops the rest of the season' (#42) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m31s
ci / typescript (push) Successful in 14m24s
2026-10-19 04:22:13 +01:00
tiago-neves d6a7edda38 Budget realtime connections per API instance and Postgres superuser reserve
ci / rust (push) Successful in 11m46s
ci / typescript (push) Successful in 15m42s
dbConnectionBudget() only subtracted the API's Prisma pool and the worker's
own 1-connection remote broadcaster, so it never counted the 3 connections
each API process opens for realtime (attachRealtime: a 2-connection publish
pool plus a dedicated LISTEN client), nor the connections Postgres reserves
for superuser roles below max_connections -- exactly what "remaining
connection slots are reserved for roles with the SUPERUSER attribute" means.
With 2 API instances that gap was 9 connections, enough for the worker and
API together to run the cluster right up against the ceiling.

dbConnectionBudget() now takes realtimePerInstance and superuserReserved
(new DB_SUPERUSER_RESERVED_CONNECTIONS env var, default 3) and subtracts
both explicitly instead of leaving them to be absorbed by headroom.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31533
Paperclip-Run: fc6639aa-bf73-43f0-b3f6-85835a1f809b
2026-10-19 04:13:14 +01:00
spark 8020574415 Merge pull request 'Keep every Liga season, because the fixture code is reused each year' (#41) from task/liga-sheet-faces into main
ci / rust (push) Successful in 11m56s
ci / typescript (push) Successful in 15m34s
2026-10-19 04:09:39 +01:00
tiago-neves c4c524c58b Stop reporting a self-healing Nextcloud download blip as a warning (BIT-31513)
ci / rust (push) Successful in 11m30s
ci / typescript (push) Successful in 14m59s
CloudClient.download already retries a transient 503/423 (BIT-31491), and ArchiveService.index
already requeues the file with its attempt given back when those retries run out (BIT-31505) —
a free retry, not a real failure. But the catch block still logged it with log.warn({ err, ... }),
and the reporter's pino hook (lib/reporter.ts logHooks) forwards any warn carrying an err to
errors.bitreport.pt. Each blip names a different file, so it fingerprints as a new ERRSIG under the
same ERRCLUSTER (ef937010320d) every time Nextcloud hiccups, reopening the Error Loop for a condition
that already self-heals — this is the third ticket on that cluster (BIT-31491, BIT-31498, BIT-31505).

Downgrade the transient case to log.info, which the reporter never forwards, and keep log.warn for a
real failure (permanent, or burning the attempt budget). Added a test asserting the transient path logs
at info with no warn call, alongside the existing BIT-31505 regression test for the requeue behaviour.

Paperclip-Issue: BIT-31513
Paperclip-Run: 4f183cb4-7ab1-4be3-ad64-f2af9e8d9742
2026-10-19 04:00:42 +01:00
spark 1aaa3857b0 Merge pull request 'Re-read a past Liga season whose calendar is only partly stored' (#40) from task/liga-sheet-faces into main
ci / typescript (push) Successful in 14m38s
ci / rust (push) Successful in 11m25s
2026-10-19 04:00:23 +01:00
spark 5ed0f94e04 Merge pull request 'Keep each Liga game in the season Liga named' (#39) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m32s
ci / typescript (push) Successful in 14m24s
2026-10-19 03:44:29 +01:00
tiago-neves 5df809eedf Add a regression test for the download-retry path reported by BIT-31505.
ci / rust (push) Successful in 11m46s
ci / typescript (push) Successful in 15m51s
CloudClient.download already retries a transient 503/423 (BIT-31491) and ArchiveService.index
already requeues a file as PENDING with its claimed attempt given back when the retries are
exhausted, instead of failing it outright or burning toward the permanent-failure limit. This
ERRSIG's stack trace runs through exactly that path; the fix is already in main, so this adds
a service-level test (claim -> blip past the retry budget -> requeued -> retried -> DONE) to
keep it covered on its own, the same way cfe9ecc covered the PROPFIND sibling.

Paperclip-Issue: BIT-31505
Paperclip-Run: 0c4396e8-3ed4-4145-821c-0f84468cf755
2026-10-19 03:43:59 +01:00
spark 999ab6d78d Merge pull request 'Liga names from every season, and one face review across games' (#38) from task/liga-sheet-faces into main
ci / rust (push) Successful in 11m10s
ci / typescript (push) Successful in 14m33s
2026-10-19 03:40:56 +01:00
tiago-neves 7b08b78b40 Budget worker DB connections against the APIs cluster, not just one pool
ci / rust (push) Successful in 7m0s
ci / typescript (push) Successful in 10m8s
The worker sized its pool to leave room for only the APIs 10 default pg
connections, but infra/pm2/api.config.cjs runs it as 2 cluster instances
(20 total) and the realtime broadcaster holds one more. On a busy host
the worker and API pools together could reach Postgres default
max_connections, which is why session.findFirst() -- run on every
authenticated request -- was the query that hit "too many clients
already".

dbConnectionBudget() now derives the worker pool cap from the APIs
actual cluster size and pool size, plus headroom for admin/migration
connections, instead of a hardcoded 80. Both are configurable
(API_DB_POOL_SIZE, API_INSTANCES, DB_MAX_CONNECTIONS) for installs that
tune Postgres or PM2 differently.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-31519
Paperclip-Run: f5442a27-6b3b-4c5a-a1ab-8b2b4177be7c
2026-10-19 03:27:08 +01:00
spark a25d65c2c3 Merge pull request 'Keep Liga fixtures in the season Liga named' (#37) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m42s
ci / typescript (push) Successful in 15m22s
2026-10-19 03:18:23 +01:00
tiago-neves cfe9ecc59f Add a PROPFIND-specific regression test for the Nextcloud retry (BIT-31498).
ci / rust (push) Successful in 8m27s
ci / typescript (push) Successful in 14m37s
CloudClient.list() already retries transient statuses via the shared
call() method (fixed for downloads in BIT-31491), so the 503 reported here
is already covered by that retry logic. This test exercises the PROPFIND
path directly so the fix for this ERRSIG stays covered on its own.

Paperclip-Issue: BIT-31498
Paperclip-Run: 0564ac90-43c8-430b-9f93-b580f6775efa
2026-10-19 03:12:20 +01:00
spark 9d1bf4849b Merge pull request 'Index Liga bwin galleries and name faces from the match sheet' (#36) from task/liga-sheet-faces into main
ci / rust (push) Successful in 10m3s
ci / typescript (push) Successful in 14m32s
Index Liga bwin galleries and name faces from the match sheet
2026-10-19 03:04:51 +01:00
sparkandClaude Opus 5.5 5d286299f8 Archive teams: match folder names with prepared teams (6x faster), and say "preparing" instead of timing out.
Each known team's folded names, words and code are worked out once (teamMatcher, same answers as
canonicalTeam). The directory waits 10 s at most; meanwhile it answers { preparing: true } and the page asks
again, so the proxy never gives a 500.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017sovZz1NXBwx4VySojoyA1
2026-10-19 00:45:00 +00:00
41 changed files with 1495 additions and 144 deletions

No files matched your search

+7
View File
@@ -3,6 +3,13 @@ PORT=3000
LOG_LEVEL=info
APP_VERSION=dev
DATABASE_URL=postgresql://photoreport:CHANGE_ME@pr-db:5432/photoreport
# The worker sizes its own pool from these three so the total stays under Postgres' max_connections. Leave unset
# unless this install's PM2 api instances, API pool size, or Postgres max_connections differ from the defaults
# (2, 10, 100).
# API_DB_POOL_SIZE=
# API_INSTANCES=
# DB_MAX_CONNECTIONS=
# DB_SUPERUSER_RESERVED_CONNECTIONS=
# At least 32 random characters, e.g. `openssl rand -base64 48`
JWT_SECRET=
ACCESS_TOKEN_TTL_SEC=900
@@ -0,0 +1,7 @@
-- A folder can be kept off the public archive site. Existing folders stay published.
ALTER TABLE "cloud_folders" ADD COLUMN "published" BOOLEAN NOT NULL DEFAULT true;
-- Which gallery a folder belongs to. Filled by the scanner, not by the site.
ALTER TABLE "cloud_folders" ADD COLUMN "gallery_folder_id" UUID;
CREATE INDEX "cloud_folders_source_id_gallery_folder_id_idx" ON "cloud_folders"("source_id", "gallery_folder_id");
ALTER TABLE "cloud_folders" ADD CONSTRAINT "cloud_folders_gallery_folder_id_fkey" FOREIGN KEY ("gallery_folder_id") REFERENCES "cloud_folders"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+12 -4
View File
@@ -1662,17 +1662,25 @@ model CloudFolder {
matchedBy String? @map("matched_by")
/// Its photos were taken on another day than the official game it was matched to: never matched to one again.
fixtureRejected Boolean @default(false) @map("fixture_rejected")
/// On the public archive site. The app's admin turns this off; the site has no control of its own. Default on.
published Boolean @default(true)
/// The gallery this folder belongs to. A game or a dated session takes the folders inside it; anything else
/// points at itself. Written when the folder is scanned or moved, and again on the periodic check. The site reads it.
galleryFolderId String? @map("gallery_folder_id") @db.Uuid
seenAt DateTime @default(now()) @map("seen_at")
createdAt DateTime @default(now()) @map("created_at")
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
files CloudFile[]
grants ArchiveGrantFolder[]
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
galleryFolder CloudFolder? @relation("GalleryMembers", fields: [galleryFolderId], references: [id], onDelete: SetNull)
galleryMembers CloudFolder[] @relation("GalleryMembers")
files CloudFile[]
grants ArchiveGrantFolder[]
@@unique([sourceId, fileId])
@@index([sourceId, path])
@@index([parentId])
@@index([sourceId, galleryFolderId])
@@map("cloud_folders")
}
+18 -7
View File
@@ -11,6 +11,7 @@ import type { Db } from "../db.js";
import { AppError, badRequest, notFound } from "../lib/errors.js";
import { zipStream, ZipTooLarge, type ZipEntry } from "../lib/zip.js";
import type { LocalStorage } from "../storage/storage.js";
import { galleryMemberIds } from "./gallery.js";
import type { Viewer } from "./viewer.js";
/**
@@ -82,13 +83,18 @@ export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps:
let ids: string[] = [];
if ("folderId" in ask) {
if (visible !== "all" && !visible.includes(ask.folderId)) throw notFound("gallery_not_found");
const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId }, include: { event: true } });
const folder = await db.cloudFolder.findFirst({ where: { id: ask.folderId, sourceId, published: true }, include: { event: true } });
if (!folder) throw notFound("gallery_not_found");
name = folder.event ? eventName(folder.event) : (folder.path.split("/").pop() ?? null);
const n = await db.cloudFile.count({ where: { folderId: folder.id, status: "DONE", photoId: { not: null } } });
const memberIds = await galleryMemberIds(db, sourceId, folder);
const idsInGallery = visible === "all" ? memberIds : memberIds.filter((id) => visible.includes(id));
const galleryId = folder.galleryFolderId ?? folder.id;
const head = galleryId === folder.id ? folder : await db.cloudFolder.findFirst({ where: { id: galleryId, sourceId, published: true }, include: { event: true } });
const shown = head ?? folder;
name = shown.event ? eventName(shown.event) : (shown.path.split("/").pop() ?? null);
const n = await db.cloudFile.count({ where: { folderId: { in: idsInGallery }, status: "DONE", photoId: { not: null } } });
if (n > MAX_PHOTOS) throw new AppError(413, "too_many_photos");
if (!n) throw notFound("photo_not_found");
return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: folder.id, n: name })}`, photos: n };
return { url: `/v1/archive/dl?t=${sign({ s: sourceId, f: shown.id, n: name })}`, photos: n };
} else {
const files = await db.cloudFile.findMany({ where: { sourceId, status: "DONE", photoId: { in: ask.photoIds }, ...scope }, select: { photoId: true }, distinct: ["photoId"] });
ids = ask.photoIds.filter((id) => files.some((f) => f.photoId === id));
@@ -102,9 +108,14 @@ export async function registerArchiveDownloadRoutes(app: FastifyInstance, deps:
const { t: ticket } = TicketQuery.parse(req.query);
const t = open(ticket);
if (!t) throw notFound("download_expired");
const ids = t.f
? (await db.cloudFile.findMany({ where: { folderId: t.f, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((f) => f.photoId!)
: (t.ids ?? []);
let ids: string[] = t.ids ?? [];
if (t.f) {
const stored = await db.cloudFolder.findFirst({ where: { id: t.f, sourceId: t.s, published: true }, select: { id: true, galleryFolderId: true } });
const folderIds = stored ? await galleryMemberIds(db, t.s, stored) : [];
ids = folderIds.length
? (await db.cloudFile.findMany({ where: { folderId: { in: folderIds }, sourceId: t.s, status: "DONE", photoId: { not: null } }, orderBy: { path: "asc" }, select: { photoId: true }, take: MAX_PHOTOS })).map((file) => file.photoId!)
: [];
}
const photos = await db.photo.findMany({
where: { id: { in: ids }, cloudFiles: { some: { sourceId: t.s } } },
select: { id: true, storageKey: true, originalName: true, originalStored: true, width: true, height: true, capturedAt: true },
+121
View File
@@ -0,0 +1,121 @@
import { Prisma } from "../generated/prisma/client.js";
import type { Db } from "../db.js";
import { galleryRoot } from "./match.js";
/** A photo whose folder is still published on the public site. */
export const publishedPhotos = Prisma.sql`EXISTS (SELECT 1 FROM cloud_folders pub WHERE pub.id = cf.folder_id AND pub.published)`;
/** The gallery id of each folder, from the paths already stored. A missing root points the folder at itself. */
export function galleryAssignments(folders: { id: string; path: string }[]): Map<string, string> {
const byPath = new Map(folders.map((folder) => [folder.path, folder.id]));
const out = new Map<string, string>();
for (const folder of folders) {
const root = galleryRoot(folder.path);
out.set(folder.id, byPath.get(root) ?? folder.id);
}
return out;
}
/**
* The folders of one gallery: the row the site opened, and every folder stored as part of it.
* A folder not yet assigned is its own gallery.
*/
export async function galleryMemberIds(db: Db, sourceId: string, folder: { id: string; galleryFolderId: string | null }): Promise<string[]> {
const galleryId = folder.galleryFolderId ?? folder.id;
const rows = await db.cloudFolder.findMany({
where: { sourceId, published: true, OR: [{ id: galleryId }, { galleryFolderId: galleryId }] },
select: { id: true },
});
return rows.map((row) => row.id);
}
export interface StoredGallery {
id: string;
path: string;
photoCount: number;
startsAt: Date | null;
home: string | null;
away: string | null;
competition: string | null;
}
/**
* One page of galleries, read from the column the scanner wrote. A folder with no gallery yet is its own card.
*/
export async function listStoredGalleries(
db: Db,
args: { sourceId: string; visible: string[] | "all"; words: string[]; teamNames: string[]; player?: string | undefined; offset: number; limit: number },
): Promise<{ total: number; galleries: StoredGallery[] }> {
const filters: Prisma.Sql[] = [
Prisma.sql`f.source_id = ${args.sourceId}::uuid`,
Prisma.sql`f.published`,
Prisma.sql`f.photo_count > 0`,
Prisma.sql`f.event_id IS NOT NULL`,
];
if (args.visible !== "all") filters.push(Prisma.sql`f.id = ANY(${args.visible}::uuid[])`);
for (const word of args.words) {
const contains = `%${word.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
const exact = word.replace(/[\\%_]/g, (ch) => `\\${ch}`);
filters.push(
Prisma.sql`(e.home ILIKE ${contains} ESCAPE '\\' OR e.away ILIKE ${contains} ESCAPE '\\' OR e.competition ILIKE ${contains} ESCAPE '\\' OR e.home_short ILIKE ${exact} ESCAPE '\\' OR e.away_short ILIKE ${exact} ESCAPE '\\')`,
);
}
if (args.teamNames.length) filters.push(Prisma.sql`(e.home = ANY(${args.teamNames}::text[]) OR e.away = ANY(${args.teamNames}::text[]))`);
if (args.player) filters.push(Prisma.sql`EXISTS (SELECT 1 FROM photos ph WHERE ph.event_id = f.event_id AND ${args.player} = ANY(ph.players))`);
const where = Prisma.join(filters, " AND ");
const rows = await db.$queryRaw<{ id: string; path: string; photo_count: number; starts_at: Date | null; home: string | null; away: string | null; competition: string | null; total: number }[]>`
WITH members AS (
SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id, f.photo_count, f.event_id, e.starts_at
FROM cloud_folders f
JOIN events e ON e.id = f.event_id
WHERE ${where}
),
agg AS (
SELECT gallery_id,
sum(photo_count)::int AS photo_count,
count(DISTINCT event_id)::int AS n_events,
(array_agg(DISTINCT event_id))[1] AS one_event,
max(starts_at) AS latest
FROM members
GROUP BY gallery_id
),
cards AS (
SELECT root.id, root.path, agg.photo_count,
COALESCE(ev.starts_at, agg.latest) AS starts_at,
ev.home, ev.away, ev.competition
FROM agg
JOIN cloud_folders root ON root.id = agg.gallery_id AND root.published
LEFT JOIN events ev ON ev.id = COALESCE(root.event_id, CASE WHEN agg.n_events = 1 THEN agg.one_event END)
)
SELECT id, path, photo_count, starts_at, home, away, competition, count(*) OVER()::int AS total
FROM cards
ORDER BY starts_at DESC NULLS LAST, path DESC
LIMIT ${args.limit} OFFSET ${args.offset}`;
const total = Number(rows[0]?.total ?? (args.offset === 0 ? 0 : await countStoredGalleries(db, where)));
return {
total,
galleries: rows.map((row) => ({
id: row.id,
path: row.path,
photoCount: Number(row.photo_count),
startsAt: row.starts_at,
home: row.home,
away: row.away || null,
competition: row.competition,
})),
};
}
async function countStoredGalleries(db: Db, where: Prisma.Sql): Promise<number> {
const rows = await db.$queryRaw<{ n: number }[]>`
WITH members AS (
SELECT COALESCE(f.gallery_folder_id, f.id) AS gallery_id
FROM cloud_folders f
JOIN events e ON e.id = f.event_id
WHERE ${where}
)
SELECT count(DISTINCT members.gallery_id)::int AS n
FROM members
JOIN cloud_folders root ON root.id = members.gallery_id AND root.published`;
return rows[0]?.n ?? 0;
}
+200 -10
View File
@@ -1,4 +1,4 @@
import { sameTeam } from "../delivery/zerozero.js";
import { sameTeam, sameWords, words } from "../delivery/zerozero.js";
import { officialSigla } from "../sports/fpa-siglas.js";
/**
@@ -55,15 +55,33 @@ function seasonIn(name: string): string | null {
return m ? toSeason(m[1]!, m[2]!) : null;
}
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date). */
/**
* The two pieces of "A / B". A slash with no letters on a side ("2025/2026", "26/27") is a season. This does not
* decide whether they are two clubs or a club and its sponsor ("Avanca / Bioria" is still one club).
*/
export function slashSides(name: string): { home: string; away: string } | null {
const m = /^(.+?[A-Za-zÀ-ÿ].*?)\s+[//∕⁄]\s+(.+?[A-Za-zÀ-ÿ].+)$/.exec(name.trim());
if (!m) return null;
const side = (s: string) => s.replace(/\s+/g, " ").trim();
const home = side(m[1]!);
const away = side(m[2]!);
if (!/[A-Za-zÀ-ÿ]{2}/.test(home) || !/[A-Za-zÀ-ÿ]{2}/.test(away)) return null;
return { home, away };
}
/** "SCP x ABC", "Sporting CP vs SC Braga", "A - B" (only after a date), "ALMADA AC / EXT. GIL EANES". */
function teamsIn(name: string, dashOk = false): { home: string; away: string } | null {
// "A x B", "A vs B", "A va B" (a slip for vs); "A - B" only after a date or a game's number, or two codes
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game.
// ("MAD - SIR"): "Festa do Andebol 2025 - Externo" is not a game. "A / B" is two clubs only when both sides
// are written as clubs ("ALMADA AC / EXT. GIL EANES"). "Avanca / Bioria" is Avanca and its sponsor.
const dash = /^(.+?)\s+[-–]\s+(.+)$/.exec(name.trim());
const codes = dash && /^[A-Z]{2,6}$/.test(dash[1]!.trim()) && /^[A-Z]{2,6}$/.test(dash[2]!.trim());
const slash = slashSides(name);
const versus = slash && looksLikeClub(slash.home) && looksLikeClub(slash.away) ? slash : null;
const m =
/^(.+?)\s+(?:x|vs\.?|va|v)\s+(.+)$/i.exec(name.trim()) ??
(dashOk || codes ? dash : null) ??
(versus ? { 1: versus.home, 2: versus.away } : null) ??
// "POR_FRA", "PTxES": two codes. "CPACxRAFC", "1.GVFCxPSC": the Liga's old folders glue the siglas.
/^([A-Z]{2,3})(?:_|\s*x\s*)([A-Z]{2,3})$/.exec(name.trim()) ??
/^([A-Za-z]{2,6})x([A-Za-z]{2,6})$/.exec(name.trim());
@@ -74,11 +92,24 @@ function teamsIn(name: string, dashOk = false): { home: string; away: string } |
const home = clean(m[1]!).split(/\s+[-–]\s+/).pop()!.trim();
const away = clean(clean(m[2]!).split(/\s+[-–]\s+/)[0]!);
// "Final - Video", "PO03 - Fase Final": parts and codes, not teams.
const notTeam = (s: string) => SECTION.test(foldName(s)) || GENERIC.test(foldName(s)) || /^PO\d|\bfase\b|\bvideo\b/i.test(s);
if (notTeam(home) || notTeam(away)) return null;
if (sideIsNotTeam(home) || sideIsNotTeam(away)) return null;
return home && away ? { home, away } : null;
}
/**
* A stored side for the teams directory. Two clubs when both are written as clubs, or (when `knownName` is given)
* each side is a different known team. "Avanca / Bioria" stays one name: the sponsor is not a second club.
*/
export function directorySides(name: string, knownName?: (side: string) => string | null): string[] {
const sides = slashSides(name);
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return [name];
const home = knownName?.(sides.home) ?? null;
const away = knownName?.(sides.away) ?? null;
const clubs = looksLikeClub(sides.home) && looksLikeClub(sides.away);
const different = !!home && !!away && fold(home) !== fold(away);
return clubs || different ? [sides.home, sides.away] : [name];
}
const foldName = (s: string) =>
s
.normalize("NFD")
@@ -166,8 +197,20 @@ export interface FolderPlace {
* Where a gallery folder sits: the occasion it belongs to (a game's halves and warm-up are the game; an athlete's
* folder in a photo session is the session, with that athlete named), and a name for it.
*/
/**
* Path segments. A slash with spaces on both sides is inside one folder name ("ALMADA AC / EXT. GIL EANES",
* "Avanca / Bioria"), not another directory. A slash without spaces stays a directory ("2025/2026", "/FPA/Fotos").
*/
export function pathParts(path: string): string[] {
const glued = path.replace(/([^\s/])\s+\/\s+([^\s/])/g, "$1\u0001$2");
return glued
.split("/")
.filter(Boolean)
.map((part) => part.replaceAll("\u0001", " / "));
}
export function describeFolder(path: string): FolderPlace {
const parts = path.split("/").filter(Boolean);
const parts = pathParts(path);
let section: string | null = null;
let people: FolderPerson[] = [];
// At most three levels up ("Torneio/_TEAM PORTUGAL_/PHOTOS MATCH/POR_FRA/M4 - ICONSPORT" stops at the game).
@@ -202,7 +245,7 @@ export function describeFolder(path: string): FolderPlace {
export function parseFolder(path: string): FolderGame | null {
// A game's photos may sit one or two levels down (a folder per photographer, "Selecionadas", the halves): the
// game is the nearest folder above whose name is one.
const parts = describeFolder(path).occasion.split("/").filter(Boolean);
const parts = pathParts(describeFolder(path).occasion);
for (let up = 0; up <= 2 && parts.length - up > 0; up++) {
const game = parseGameFolder(parts.slice(0, parts.length - up));
if (game) return game;
@@ -210,6 +253,55 @@ export function parseFolder(path: string): FolderGame | null {
return null;
}
/** A date written at the start of a folder: "20231217 - …", "04.11.23 …", "15.02.2026 …". */
const LEADING_DATE = /^(?:\d{8}|\d{6})\b|^\d{1,2}[.\-/]\d{1,2}[.\-/](?:\d{4}|\d{2})\b/;
/**
* One game, not a label. "SLB x SCP", "4. SLB x GVFC", "POR_FRA" and "ALMADA AC / EXT. GIL EANES" are games.
* "PBHT - EXT" is two codes with a dash and no date: a shelf, not a game, so the days under it stay separate.
*/
function isGameLeaf(leaf: string): boolean {
const game = parseFolder(`/${leaf}`);
if (!game?.away || game.single) return false;
const name = leaf.trim();
if (LEADING_DATE.test(name)) return true;
if (/\s(?:x|vs\.?|va)\s/i.test(name)) return true;
if (/[A-Za-z]{2,6}x[A-Za-z]{2,6}/.test(name)) return true;
if (/^[A-Z]{2,3}_[A-Z]{2,3}$/.test(name.trim())) return true;
// A slash is two clubs only when the parser already accepted both sides ("Avanca / Bioria" is one club).
if (slashSides(name)) return true;
return false;
}
/** A studio session on a day ("20231008 - Sessao SNAF"). The big archive shelf that only mentions "sessão" is not one. */
function isSessionLeaf(leaf: string): boolean {
const name = leaf.trim();
return LEADING_DATE.test(name) && SESSION.test(foldName(name));
}
/**
* The gallery this folder belongs to. A game (a date and two clubs, or "clube x clube") and a session on a day
* take the folders inside them: halves, warm-up, prizes, an athlete's name. A folder that is itself a game or a
* dated event stays its own gallery, so a game filed under another game is not merged into it.
*
* A name shorter than date, club and club is only a hint. Counting those slots on every folder would swallow
* "Dia 1" and "FanZone". A folder joins the gallery above only when that gallery is a game or a session, and
* this folder is not itself a game or a dated event.
*/
export function galleryRoot(path: string): string {
const parts = pathParts(path);
if (!parts.length) return path.startsWith("/") ? path : `/${path}`;
const leaf = parts[parts.length - 1]!;
if (isGameLeaf(leaf) || isSessionLeaf(leaf) || LEADING_DATE.test(leaf.trim())) return `/${parts.join("/")}`;
for (let i = parts.length - 2; i >= 0; i--) {
const name = parts[i]!;
if (isGameLeaf(name) || isSessionLeaf(name)) return `/${parts.slice(0, i + 1).join("/")}`;
// "20180727 - Fase Final" is a day, not a game: the days under it stay their own galleries.
if (LEADING_DATE.test(name.trim())) break;
}
return `/${parts.join("/")}`;
}
const fullYear = (y: string) => (y.length === 2 ? `20${y}` : y);
/** A real calendar day ("2023-02-30" is not). */
const validDay = (day: string) => {
@@ -424,6 +516,58 @@ export function exhibitionName(game: Pick<FolderGame, "parents">): string | null
return game.parents.find(isExhibitionName)?.trim() ?? null;
}
/** "Final", "Externo", "PO03": a part of a day, not a club. */
function sideIsNotTeam(s: string): boolean {
return SECTION.test(foldName(s)) || GENERIC.test(foldName(s)) || /^PO\d|\bfase\b|\bvideo\b/i.test(s);
}
/**
* A club or a school written as such ("AC", "FC", "SL", "EXT.", "Colégio"). A sponsor ("Bioria", "Betclic") is not.
*/
function looksLikeClub(side: string): boolean {
return /\b(?:fc|sc|cf|cd|ud|gd|ad|cr|ac|sad|gc|ca|oc|cs|sl|cp|ext|externato|colegio|escola|academia|associacao|clube|atletico|recreativo|desportivo|juventude)\b/.test(foldName(side));
}
type TeamRef = { name: string; abbreviation: string | null; slug: string };
function oneTeam(name: string, teams: readonly TeamRef[]): string | null {
const fits = [...new Map(teams.filter((t) => isTeam(name, t)).map((t) => [fold(t.name), t])).values()];
return fits.length === 1 ? fits[0]!.name : null;
}
/**
* What "A / B" means against known teams. Two different clubs: the name stays whole, so each side is read on its
* own. A club and a sponsor ("Avanca / Bioria", "Sporting CP / Betclic"): that club. Undefined when it is not a
* slash name.
*/
function slashClub(label: string, knownName: (side: string) => string | null): string | undefined {
const sides = slashSides(label);
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return undefined;
const home = knownName(sides.home);
const away = knownName(sides.away);
const clubs = looksLikeClub(sides.home) && looksLikeClub(sides.away);
const different = !!home && !!away && fold(home) !== fold(away);
if (clubs || different) return label;
if (home && !away) return home;
if (away && !home) return away;
if (home && away) return home;
return undefined;
}
/**
* "Benfica / Porto" when both are known clubs and neither is written as a club form (the folder parser leaves
* that as one name). "Avanca / Bioria" is not: Bioria is not a club. Null when the parser already split it.
*/
export function knownVersus(name: string, teams: readonly TeamRef[]): { home: string; away: string } | null {
const sides = slashSides(name);
if (!sides || sideIsNotTeam(sides.home) || sideIsNotTeam(sides.away)) return null;
if (looksLikeClub(sides.home) && looksLikeClub(sides.away)) return null;
const home = oneTeam(sides.home, teams);
const away = oneTeam(sides.away, teams);
if (!home || !away || fold(home) === fold(away)) return null;
return { home, away };
}
/** A team's name as written in a folder without the date or number before it ("01.23 Leixões SC", "02_Estoril Praia"). */
export function teamLabel(name: string): string {
return name
@@ -438,11 +582,57 @@ export function teamLabel(name: string): string {
* The known team a folder's name means, when exactly one fits (abbreviation, initials, name or close name): its
* official name, so "SCP", "Sporting" and "Sporting CP" are one team. The cleaned name otherwise.
*/
export function canonicalTeam(name: string, teams: readonly { name: string; abbreviation: string | null; slug: string }[]): string {
export function canonicalTeam(name: string, teams: readonly TeamRef[]): string {
const label = teamLabel(name);
if (!label) return name.trim();
const fits = [...new Map(teams.filter((t) => isTeam(label, t)).map((t) => [fold(t.name), t])).values()];
return fits.length === 1 ? fits[0]!.name : label;
const slash = slashClub(label, (side) => oneTeam(side, teams));
if (slash !== undefined) return slash;
return oneTeam(label, teams) ?? label;
}
/**
* `canonicalTeam` for many names against the same teams: each team's folded names, words and code are worked out
* once, not once per name (thousands of folder names times every Liga team took minutes).
*/
export type TeamMatch = ((name: string) => string) & { knownName(name: string): string | null };
export function teamMatcher(teams: readonly TeamRef[]): TeamMatch {
const prepared = teams.map((t) => {
const sigla = officialSigla(t.name);
return { t, variant: isVariantSide(t.name), abbr: fold(t.abbreviation ?? ""), slug: fold(t.slug), name: fold(t.name), words: words(t.name), sigla: sigla ? fold(sigla) : "" };
});
const knownName = (raw: string): string | null => {
const label = teamLabel(raw);
if (!label) return null;
const n = fold(label);
if (!n) return null;
const variant = isVariantSide(label);
const nameWords = words(label);
const short = label.trim().length <= 6 && !/\s/.test(label.trim());
const fits = new Map<string, (typeof prepared)[number]["t"]>();
for (const p of prepared) {
// The same tests as isTeam, in the same order.
if (variant !== p.variant && p.abbr !== n) continue;
const fit =
(!!p.t.abbreviation && p.abbr === n) ||
p.slug === n ||
p.name === n ||
sameWords(nameWords, p.words) ||
(!!p.sigla && p.sigla === n) ||
(short && isInitials(label, p.t.name));
if (fit) fits.set(p.name, p.t);
}
return fits.size === 1 ? [...fits.values()][0]!.name : null;
};
const match = (raw: string) => {
const label = teamLabel(raw);
if (!label) return raw.trim();
const slash = slashClub(label, knownName);
if (slash !== undefined) return slash;
return knownName(label) ?? label;
};
match.knownName = knownName;
return match;
}
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[], now = new Date()): FixtureCandidate | null {
+7 -6
View File
@@ -7,6 +7,7 @@ import { boxInCrop, cropOfSettings } from "../faces/frame.js";
import { cosine, inFocus, THRESHOLDS } from "../faces/math.js";
import { notFound } from "../lib/errors.js";
import type { UrlSigner } from "../storage/storage.js";
import { publishedPhotos } from "./gallery.js";
import type { Viewer } from "./viewer.js";
/**
@@ -49,8 +50,8 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
const scopeOf = async (v: Viewer): Promise<Prisma.Sql | null> => {
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.length) return null;
if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`;
return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
};
const galleryInfo = async (folderIds: string[]) => {
@@ -123,11 +124,11 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.length) return { people: [], clubs: [] };
const scope = visible === "all"
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
const folderLimit = visible === "all"
? Prisma.sql`cf.source_id = ${v.s}::uuid`
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.id = ANY(${visible}::uuid[])`;
? Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published`
: Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.published AND cf.id = ANY(${visible}::uuid[])`;
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; confirmed: bigint; probable: bigint }[]>`
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference,
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
+40
View File
@@ -244,6 +244,46 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
};
});
/**
* Every indexed folder, for the app's publish tree. The public site does not use this: it only receives the
* folders that stay published. Paths are from the source root, the way the tree shows them.
*/
app.get("/v1/cloud-sources/:sourceId/tree", { preHandler: authenticate }, async (req) => {
const { sourceId } = SourceParams.parse(req.params);
const source = await loadSource(req, sourceId, "EDITOR");
const root = source.rootPath.replace(/\/+$/, "");
const folders = await db.cloudFolder.findMany({
where: { sourceId },
select: { id: true, path: true, published: true, photoCount: true },
orderBy: { path: "asc" },
});
return {
folders: folders.flatMap((folder) => {
const path = folder.path.startsWith(root) ? folder.path.slice(root.length).replace(/^\//, "") : folder.path.replace(/^\//, "");
if (!path) return [];
return [{ id: folder.id, path, published: folder.published, photoCount: folder.photoCount }];
}),
};
});
/** Shows or hides a folder, and everything inside it, on the public site. */
app.put("/v1/cloud-folders/:folderId/published", { preHandler: authenticate }, async (req) => {
const { folderId } = FolderParams.parse(req.params);
const body = z.object({ published: z.boolean() }).parse(req.body);
const folder = await db.cloudFolder.findUnique({ where: { id: folderId } });
if (!folder) throw notFound("folder_not_found");
const source = await db.cloudSource.findUnique({ where: { id: folder.sourceId }, select: { organizationId: true } });
if (!source) throw notFound("folder_not_found");
await requireMembership(db, req, source.organizationId, "EDITOR");
const updated = await db.$executeRaw`
UPDATE cloud_folders
SET published = ${body.published}
WHERE source_id = ${folder.sourceId}::uuid
AND (id = ${folder.id}::uuid OR starts_with(path, ${`${folder.path}/`}))
`;
return { published: body.published, updated: Number(updated) };
});
/** Puts a gallery in an event, or in the event of a game (made when there is none). */
app.put("/v1/cloud-folders/:folderId/event", { preHandler: authenticate }, async (req) => {
const { folderId } = FolderParams.parse(req.params);
+93 -13
View File
@@ -14,7 +14,8 @@ import type { IngestLogger, IngestService } from "../ingest/service.js";
import { ingestWindow } from "../library/events.js";
import { waitUntil } from "../lib/idle.js";
import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js";
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js";
import { galleryAssignments } from "./gallery.js";
import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, knownVersus, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf, slashSides } from "./match.js";
export const IMAGE = /\.(jpe?g)$/i;
/** How long the person has to authorise in their cloud (Nextcloud keeps the flow 20 minutes). */
@@ -278,6 +279,9 @@ export class ArchiveService {
const stats = { folders: 0, queued: 0 };
try {
await this.walk(source, client, source.rootPath, null, stats, !!opts.full);
// The gallery of each folder, from the paths just read. A rule change is also applied by the periodic check,
// because a walk skips a folder whose etag did not change.
await this.assignGalleries(sourceId);
// Galleries named from the folder get their official game once it is known (fixtures arrive later, the
// matching improves): no cloud calls, only the database.
await this.rematch(sourceId);
@@ -335,8 +339,17 @@ export class ArchiveService {
}
await db.cloudFile.deleteMany({ where: { folderId: folder.id, fileId: { notIn: images.map((i) => i.fileId) } } });
// Sub-folders gone from the cloud go from here too (and their images).
await db.cloudFolder.deleteMany({ where: { sourceId: source.id, parentId: folder.id, fileId: { notIn: dirs.map((d) => d.fileId) } } });
// Sub-folders gone from the cloud go from here too, with everything filed under them. The parent link is not a
// foreign key, so deleting only the child would leave its tree behind.
const gone = await db.cloudFolder.findMany({
where: { sourceId: source.id, parentId: folder.id, ...(dirs.length ? { fileId: { notIn: dirs.map((d) => d.fileId) } } : {}) },
select: { id: true, path: true },
});
if (gone.length) {
const tree = gone.flatMap((g) => [{ id: g.id }, { path: { startsWith: `${g.path}/` } }]);
await db.cloudFolder.updateMany({ where: { sourceId: source.id, OR: tree }, data: { galleryFolderId: null } });
await db.cloudFolder.deleteMany({ where: { sourceId: source.id, OR: tree } });
}
folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length } });
if (images.length && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self);
@@ -346,6 +359,53 @@ export class ArchiveService {
await db.cloudFolder.update({ where: { id: folder.id }, data: { etag: self.etag } });
}
/**
* Writes each folder's gallery from its path. One cloud, or every cloud. Safe to run while another pass is
* already writing: the second waits, then finds nothing left to change.
*/
async assignGalleries(sourceId?: string): Promise<number> {
const { db, log } = this.deps;
// One connection for the lock and the writes. A second caller waits, then writes nothing.
const changed = await db.$transaction(async (tx) => {
await tx.$executeRaw`SELECT pg_advisory_xact_lock(84120012026)`;
const folders = await tx.cloudFolder.findMany({
where: sourceId ? { sourceId } : {},
select: { id: true, sourceId: true, path: true, galleryFolderId: true },
});
const bySource = new Map<string, typeof folders>();
for (const folder of folders) {
const list = bySource.get(folder.sourceId);
if (list) list.push(folder);
else bySource.set(folder.sourceId, [folder]);
}
let updated = 0;
for (const group of bySource.values()) {
const want = galleryAssignments(group);
const ids: string[] = [];
const galleryIds: string[] = [];
for (const folder of group) {
const next = want.get(folder.id);
if (!next || next === folder.galleryFolderId) continue;
ids.push(folder.id);
galleryIds.push(next);
}
const chunk = 2000;
for (let i = 0; i < ids.length; i += chunk) {
const sliceIds = ids.slice(i, i + chunk);
const sliceGalleryIds = galleryIds.slice(i, i + chunk);
updated += await tx.$executeRaw`
UPDATE cloud_folders AS f
SET gallery_folder_id = v.gallery_id
FROM (SELECT * FROM unnest(${sliceIds}::uuid[], ${sliceGalleryIds}::uuid[]) AS v(id, gallery_id)) AS v
WHERE f.id = v.id AND f.gallery_folder_id IS DISTINCT FROM v.gallery_id`;
}
}
return updated;
}, { timeout: 180_000, maxWait: 180_000 });
if (changed) log.info({ changed, sourceId: sourceId ?? null }, "archive: galleries stored");
return changed;
}
// --- matching folders to games ---------------------------------------------------------------------------------
/**
@@ -370,6 +430,12 @@ export class ArchiveService {
// matchday, a season, a month), and the check that a game found without a day is the right one.
const shot = game.day ? null : await this.captureDay(folder.id);
if (shot) game = { ...game, day: shot, month: null };
// "Benfica / Porto": both known clubs, neither written as a club form. "Avanca / Bioria" stays one club.
if (!game.away && slashSides(game.home)) {
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
const versus = knownVersus(game.home, await this.teamCatalog(source, !!liga));
if (versus) game = { ...game, home: versus.home, away: versus.away, single: false };
}
const fixture = folder.fixtureRejected ? null : await this.findFixture(game, source);
if (fixture) return { eventId: await this.eventForFixture(source, fixture), matchedBy: "FIXTURE" };
const teams = await this.teamNames(game, source);
@@ -422,6 +488,8 @@ export class ArchiveService {
// One check at a time (on start, every six hours, after a season's calendar is read): a second call waits for it.
this.verifying ??= (async () => {
try {
// Paths already stored: a new naming rule has to land even when the cloud etags did not change.
await this.assignGalleries();
// Every cloud, signed in or not: the check needs only what was indexed.
const sources = await this.deps.db.cloudSource.findMany({ select: { id: true } });
// First what must never be seen: galleries on a game still to come (a quick query, every cloud at once).
@@ -537,16 +605,20 @@ export class ArchiveService {
* A game's sides by their clubs' names when the folder names them by initials ("SLB x FCP" → SL Benfica, FC
* Porto): one known club with that abbreviation, or those initials. Countries are already named.
*/
private async teamNames(game: FolderGame, source: Pick<CloudSource, "baseUrl">): Promise<{ home: string; away: string; homeShort: string | null; awayShort: string | null }> {
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
if (!this.teams || this.teams.liga !== !!liga || Date.now() - this.teams.at > 3_600_000) {
private async teamCatalog(source: Pick<CloudSource, "baseUrl">, liga: boolean) {
if (!this.teams || this.teams.liga !== liga || Date.now() - this.teams.at > 3_600_000) {
const list = await this.deps.db.sportsTeam.findMany({
where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } },
select: { name: true, abbreviation: true, slug: true },
});
this.teams = { at: Date.now(), liga: !!liga, list };
this.teams = { at: Date.now(), liga, list };
}
const list = this.teams.list;
return this.teams.list;
}
private async teamNames(game: FolderGame, source: Pick<CloudSource, "baseUrl">): Promise<{ home: string; away: string; homeShort: string | null; awayShort: string | null }> {
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source.baseUrl);
const list = await this.teamCatalog(source, !!liga);
const resolve = (name: string): { name: string; short: string | null } => {
// A full name: the known team's official name when exactly one fits ("Sporting" → "Sporting CP").
if (!name || name.length > 6 || /\s/.test(name)) return { name: name ? canonicalTeam(name, list) : name, short: null };
@@ -812,12 +884,17 @@ export class ArchiveService {
return moved;
}
/**
* One statement, not read-then-delete: a read-then-delete let another gallery just matched to this event (its
* `setFolderEvent` landing in the gap after the count was read) get silently taken back out by the delete, and
* then fail with a foreign key error moving its photos in here — the "empty" check now lives in the delete's own
* `WHERE`, so Postgres re-reads it against whatever just committed (BIT-31531).
*/
private async dropIfEmpty(eventId: string): Promise<void> {
const { db } = this.deps;
const event = await db.event.findUnique({ where: { id: eventId }, select: { archivedAt: true, _count: { select: { photos: true, cloudFolders: true, galleries: true, deliveries: true } } } });
if (!event?.archivedAt) return;
const c = event._count;
if (c.photos + c.cloudFolders + c.galleries + c.deliveries === 0) await db.event.delete({ where: { id: eventId } }).catch(() => undefined);
await db.event.deleteMany({
where: { id: eventId, archivedAt: { not: null }, photos: { none: {} }, cloudFolders: { none: {} }, galleries: { none: {} }, deliveries: { none: {} } },
});
}
// --- indexing --------------------------------------------------------------------------------------------------
@@ -969,7 +1046,10 @@ export class ArchiveService {
await db.cloudFile.update({ where: { id: fileId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } });
// A file moved since the walk: read its folder again next time.
if (gone) await db.cloudFolder.update({ where: { id: file.folderId }, data: { etag: null } });
log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
// A transient blip is given a free retry and costs nothing (BIT-31513): logged at info so it never reaches
// the error hub as a warning, unlike a real decoding/matching failure or one burning the attempt budget.
if (transient) log.info({ err, fileId, path: file.path }, "archive: image download blipped, requeued for a free retry");
else log.warn({ err, fileId, path: file.path }, "archive: image not indexed");
} finally {
await rm(dir, { recursive: true, force: true });
}
+87 -55
View File
@@ -9,7 +9,8 @@ import type { SecretBox } from "../delivery/secrets.js";
import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
import { canonicalTeam, describeFolder } from "./match.js";
import { galleryMemberIds, listStoredGalleries, publishedPhotos } from "./gallery.js";
import { directorySides, teamMatcher, type TeamMatch } from "./match.js";
import type { FaceService } from "../faces/service.js";
import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import { registerArchiveDownloadRoutes } from "./downloads.js";
@@ -270,14 +271,15 @@ export async function registerArchiveViewerRoutes(
/** Indexed files of this source the viewer may see. Joined in later queries; never a list of photo ids. */
const fileScope = (sourceId: string, visible: string[] | "all"): Prisma.Sql => {
if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND ${publishedPhotos}`;
return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
};
const folderWhere = (v: Viewer, visible: string[] | "all") => ({
sourceId: v.s,
photoCount: { gt: 0 },
eventId: { not: null },
published: true,
...(visible !== "all" && { id: { in: visible } }),
});
@@ -386,31 +388,32 @@ export async function registerArchiveViewerRoutes(
* team: thousands of games times every team blocked the API for minutes). One answer per name, kept for a while,
* shared by every viewer of the source.
*/
const canonicalNames = new Map<string, { at: number; known: Promise<{ name: string; abbreviation: string | null; slug: string }[]>; names: Map<string, string> }>();
const canonicalNames = new Map<string, { at: number; known: Promise<TeamMatch>; names: Map<string, string> }>();
const CANONICAL_TTL_MS = 6 * 3600_000;
const DIRECTORY_WAIT_MS = 10_000;
const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise<Map<string, { names: Set<string>; galleries: number }>> => {
let memo = canonicalNames.get(sourceId);
if (!memo || Date.now() - memo.at > CANONICAL_TTL_MS) {
const known = (async () => {
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
return db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
return teamMatcher(await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } }));
})();
known.catch(() => canonicalNames.delete(sourceId));
memo = { at: Date.now(), known, names: new Map() };
canonicalNames.set(sourceId, memo);
}
const known = await memo.known;
const canonical = await memo.known;
const out = new Map<string, { names: Set<string>; galleries: number }>();
const byKey = new Map<string, string>();
const fold = (x: string) => x.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
let fresh = 0;
for (const g of games)
for (const raw of [g.home, g.away]) {
for (const raw of [g.home, g.away].flatMap((side) => (side ? directorySides(side, (n) => canonical.knownName(n)) : []))) {
if (!raw) continue;
let name = memo.names.get(raw);
if (name === undefined) {
name = canonicalTeam(raw, known);
name = canonical(raw);
memo.names.set(raw, name);
// Let other requests in between the new names (the first reading of a big archive).
if (++fresh % 25 === 0) await new Promise((r) => setImmediate(r));
@@ -437,6 +440,12 @@ export async function registerArchiveViewerRoutes(
};
if (!process.env.VITEST) {
app.addHook("onReady", async () => {
// Before the site is served: the cards are a read of this column.
try {
await deps.archive.assignGalleries();
} catch (err) {
app.log.warn({ err }, "archive: galleries not stored");
}
setTimeout(() => void warmTeams().catch((err: Error) => app.log.warn({ err }, "archive teams warm-up failed")), 5_000).unref();
});
}
@@ -455,36 +464,46 @@ export async function registerArchiveViewerRoutes(
const groups = await teamGroups(sourceId, rows.flatMap((r) => (r.event ? [r.event] : [])));
teamNames = [...(groups.get(query.team)?.names ?? new Set([query.team]))];
}
const eventFilters = [
...words.map((w) => ({ OR: [{ home: { contains: w, mode: "insensitive" as const } }, { away: { contains: w, mode: "insensitive" as const } }, { competition: { contains: w, mode: "insensitive" as const } }, { homeShort: { equals: w, mode: "insensitive" as const } }, { awayShort: { equals: w, mode: "insensitive" as const } }] })),
...(query.team ? [{ OR: [{ home: { in: teamNames } }, { away: { in: teamNames } }] }] : []),
...(query.player ? [{ photos: { some: { players: { has: query.player } } } }] : []),
];
const where = { ...folderWhere(v, visible), ...(eventFilters.length && { event: { AND: eventFilters } }) };
const [total, folders] = await Promise.all([
db.cloudFolder.count({ where }),
db.cloudFolder.findMany({ where, include: { event: true }, orderBy: [{ event: { startsAt: "desc" } }, { path: "desc" }], skip: query.offset, take: query.limit }),
]);
const covers = folders.length
? await db.cloudFile.findMany({ where: { folderId: { in: folders.map((f) => f.id) }, status: "DONE", photoId: { not: null } }, distinct: ["folderId"], orderBy: { path: "asc" }, select: { folderId: true, photoId: true } })
// One card per game or session, from the gallery written when the folder was scanned. The parts are not more cards.
const page = await listStoredGalleries(db, {
sourceId,
visible,
words,
teamNames,
player: query.player,
offset: query.offset,
limit: query.limit,
});
const galleryIds = page.galleries.map((gallery) => gallery.id);
const covers = galleryIds.length
? await db.$queryRaw<{ gallery_id: string; photo_id: string }[]>`
SELECT DISTINCT ON (COALESCE(f.gallery_folder_id, f.id)) COALESCE(f.gallery_folder_id, f.id) AS gallery_id, cf.photo_id
FROM cloud_folders f
JOIN cloud_files cf ON cf.folder_id = f.id AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL
WHERE f.published AND COALESCE(f.gallery_folder_id, f.id) = ANY(${galleryIds}::uuid[])
ORDER BY COALESCE(f.gallery_folder_id, f.id), cf.path`
: [];
const cover = new Map(covers.map((c) => [c.folderId, c.photoId!]));
const cover = new Map(covers.map((file) => [file.gallery_id, file.photo_id]));
return {
viewer: { name: v.n },
total,
galleries: folders.map((f) => ({
id: f.id,
title: f.event ? eventName(f.event) : f.path.split("/").pop(),
/** The part of the game or session ("1P", "Aquecimento", an athlete's name). */
section: describeFolder(f.path).section,
home: f.event?.home ?? null,
away: f.event?.away || null,
competition: f.event?.competition ?? null,
startsAt: f.event?.startsAt ?? null,
photoCount: f.photoCount,
cover: cover.has(f.id) ? signer.url(cover.get(f.id)!, "thumb") : null,
coverLarge: cover.has(f.id) ? signer.url(cover.get(f.id)!, "preview") : null,
})),
total: page.total,
galleries: page.galleries.map((gallery) => {
const photoId = cover.get(gallery.id) ?? null;
const titled = gallery.home ? { home: gallery.home, away: gallery.away } : null;
return {
id: gallery.id,
title: titled ? eventName(titled) : (gallery.path.split("/").pop() ?? gallery.path),
/** Parts share the game's card, so the card itself is not "1P" or an athlete. */
section: null,
home: gallery.home,
away: gallery.away,
competition: gallery.competition,
startsAt: gallery.startsAt,
photoCount: gallery.photoCount,
cover: photoId ? signer.url(photoId, "thumb") : null,
coverLarge: photoId ? signer.url(photoId, "preview") : null,
};
}),
};
});
@@ -497,7 +516,7 @@ export async function registerArchiveViewerRoutes(
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const visible = await visibleFolders(v);
const teams = await remembered(sourceId, "teams", visible, async () => {
const reading = remembered(sourceId, "teams", visible, async () => {
const folders = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { id: true, home: true, away: true } } } });
// Teams of games only (a session or a day of an event is named in "home" too), each game counted once.
const games = new Map<string, { home: string; away: string }>();
@@ -506,6 +525,10 @@ export async function registerArchiveViewerRoutes(
.map(([name, g]) => ({ name, galleries: g.galleries }))
.sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name));
});
// The first reading of a big archive can take a while: say so (the page asks again) rather than let the proxy
// time out. The reading goes on and is kept for the next ask.
const teams = await Promise.race([reading, new Promise<null>((r) => setTimeout(() => r(null), DIRECTORY_WAIT_MS).unref())]);
if (!teams) return { teams: [], preparing: true };
return { teams };
});
@@ -535,13 +558,20 @@ export async function registerArchiveViewerRoutes(
const v = viewerOf(req);
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found");
const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } });
const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s, published: true }, include: { event: true, source: { select: { baseUrl: true } } } });
if (!folder) throw notFound("gallery_not_found");
// The halves, the warm-up and a session's athletes are this gallery, not a folder of their own.
const memberIds = await galleryMemberIds(db, folder.sourceId, folder);
const ids = visible === "all" ? memberIds : memberIds.filter((id) => visible.includes(id));
if (!ids.includes(folderId)) throw notFound("gallery_not_found");
const galleryId = folder.galleryFolderId ?? folder.id;
const head = galleryId === folder.id ? folder : await db.cloudFolder.findFirst({ where: { id: galleryId, sourceId: folder.sourceId, published: true }, include: { event: true } });
const shown = head ?? folder;
// Links to the cloud only for those who edit there; the others need not know where the photos live.
const editable = await editableFolders(v);
const onCloud = editable === "all" || editable.includes(folderId);
const onCloud = editable === "all" || editable.includes(folderId) || (head ? editable.includes(head.id) : false);
const where = {
folderId,
folderId: { in: ids },
status: "DONE" as const,
photoId: { not: null },
...(query.player && { photo: { players: { has: query.player } } }),
@@ -550,8 +580,8 @@ export async function registerArchiveViewerRoutes(
// People named anywhere in this game (every part the viewer may see), not only in this folder.
const rosterScope =
visible === "all"
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE'`
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[])`;
? Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND ${publishedPhotos}`
: Prisma.sql`cf.source_id = ${folder.sourceId}::uuid AND cf.status = 'DONE' AND cf.folder_id = ANY(${visible}::uuid[]) AND ${publishedPhotos}`;
const [total, files, named, sharpest, roster] = await Promise.all([
db.cloudFile.count({ where }),
db.cloudFile.findMany({
@@ -566,25 +596,25 @@ export async function registerArchiveViewerRoutes(
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN people p ON p.id = g.person_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ANY(${ids}::uuid[]) AND cf.status = 'DONE'
GROUP BY p.id
ORDER BY count(DISTINCT f.photo_id) DESC, p.name`,
db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>`
SELECT DISTINCT ON (g.person_id) g.person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ANY(${ids}::uuid[]) AND cf.status = 'DONE'
ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`,
folder.eventId
shown.eventId
? db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; here: number; in_game: number }[]>`
SELECT p.id, p.name, p.club, p.number,
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ${folderId}::uuid)::int AS here,
count(DISTINCT cf.photo_id) FILTER (WHERE cf.folder_id = ANY(${ids}::uuid[]))::int AS here,
count(DISTINCT cf.photo_id)::int AS in_game
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN people p ON p.id = g.person_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND ${rosterScope}
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${folder.eventId}::uuid
JOIN photos ph ON ph.id = cf.photo_id AND ph.event_id = ${shown.eventId}::uuid
GROUP BY p.id, p.name, p.club, p.number
ORDER BY p.name`
: Promise.resolve([]),
@@ -603,16 +633,16 @@ export async function registerArchiveViewerRoutes(
);
const base = folder.source.baseUrl.replace(/\/+$/, "");
return {
id: folder.id,
title: folder.event ? eventName(folder.event) : folder.path.split("/").pop(),
section: describeFolder(folder.path).section,
id: shown.id,
title: shown.event ? eventName(shown.event) : shown.path.split("/").pop(),
section: null,
/** A game's two sides (an event has no away side). */
home: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.home : null,
away: folder.event && folder.matchedBy !== "FOLDER" ? folder.event.away || null : null,
homeShort: folder.event?.homeShort ?? null,
awayShort: folder.event?.awayShort ?? null,
competition: folder.event?.competition ?? null,
startsAt: folder.event?.startsAt ?? null,
home: shown.event && shown.matchedBy !== "FOLDER" ? shown.event.home : null,
away: shown.event && shown.matchedBy !== "FOLDER" ? shown.event.away || null : null,
homeShort: shown.event?.homeShort ?? null,
awayShort: shown.event?.awayShort ?? null,
competition: shown.event?.competition ?? null,
startsAt: shown.event?.startsAt ?? null,
/** The folder on the cloud (opens for those it is shared with). */
cloudUrl: onCloud ? `${base}/f/${folder.fileId}` : null,
total,
@@ -644,6 +674,8 @@ export async function registerArchiveViewerRoutes(
if (!file?.photo) throw notFound("photo_not_found");
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.includes(file.folderId)) throw notFound("photo_not_found");
const listed = await db.cloudFolder.findFirst({ where: { id: file.folderId, published: true }, select: { id: true } });
if (!listed) throw notFound("photo_not_found");
const faces = await facesOfPhotos(db, [file.photo]);
return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] };
});
+51
View File
@@ -0,0 +1,51 @@
/**
* The autopilot's finishing "look": colour, local contrast, sharpening and noise reduction, on top of the measured
* white balance and tone (docs/photo-editing-rules.md §4). Fixed values, not measured per photo, so a match looks
* like one set. Measured on the agencies (October 2026):
*
* - kolektiff images (EHF/IHF handball, 600 photos of 2025-26): saturated, punchy kits (HSV saturation 0.47),
* pure blacks, neutral whites, shadows a touch cool (blue-magenta) in every photographer's work.
* - Getty Images and AFP (Paris 2024, 1093 action photos): the same cool shadows and neutral whites, more natural
* colour (0.40-0.43).
*
* "agency" follows kolektiff, "natural" Getty. Both stay inside the ethics rules: toning for clear reproduction,
* no vignette or background darkening, nothing local.
*/
export type Look = "agency" | "natural" | "none";
const BASE: Record<Exclude<Look, "none">, Record<string, number>> = {
agency: {
"color.vibrance": 18,
"color.saturation": 4,
"effects.clarity": 8,
"effects.texture": 6,
"grading.shadows.hue": 245,
"grading.shadows.sat": 8,
"grading.balance": -10,
},
natural: {
"color.vibrance": 8,
"effects.clarity": 4,
"effects.texture": 4,
"grading.shadows.hue": 245,
"grading.shadows.sat": 4,
},
};
/** Capture sharpening for both looks (Lightroom-like amount, radius, detail; masking keeps flat skin and floor smooth). */
const SHARPEN = { "detail.sharpenAmount": 40, "detail.sharpenRadius": 1, "detail.sharpenDetail": 25, "detail.sharpenMasking": 35 };
/** Noise reduction by ISO: none in good light, more in dim arenas (sports halls run ISO 3200-12800). */
export function noiseReduction(iso: number | null | undefined): Record<string, number> {
const out: Record<string, number> = { "detail.nrColor": 25 };
if (!iso || iso < 1600) return out;
out["detail.nrLuminance"] = iso < 3200 ? 8 : iso < 6400 ? 15 : iso < 12800 ? 22 : 30;
return out;
}
/** The look's values for one photo (empty for "none"). */
export function lookValues(look: Look, iso?: number | null): Record<string, number> {
if (look === "none") return {};
return { ...BASE[look], ...SHARPEN, ...noiseReduction(iso) };
}
+21 -6
View File
@@ -18,6 +18,7 @@ import { sequenceWeights } from "./sequence.js";
import { bestOf, groupBursts } from "./bursts.js";
import { curate, matchMinutes } from "./curate.js";
import { type LearntStyle, learntStyle, TONE_KEYS, WB_KEYS } from "./learning.js";
import { lookValues } from "./look.js";
const STALE_RUNNING_MS = 10 * 60_000;
/** A burst is decided once no new frame of it has arrived for this long. */
@@ -25,12 +26,16 @@ const BURST_SETTLE_MS = 15_000;
/** Straightening beyond this is more likely a creative tilt than a crooked horizon: left alone. */
const MAX_LEVEL = 5;
const MIN_LEVEL = 0.3;
/** A crop this close to the whole frame (width) is not worth making: the photo stays as shot (agencies send a third uncropped). */
const KEEP_WHOLE = 0.92;
export interface AutopilotRecord {
score: number;
reason: string | null;
subject: Box | null;
crop: Box | null;
/** The whole-body frame, when the crop is tight: the second pick of a burst gets it (variety). */
wide?: Box | null;
angle: number;
/** What it had learnt from corrections and added to its own edit. */
style?: LearntStyle | null;
@@ -111,6 +116,8 @@ export class AutopilotService {
const v = (auto.values[k] ?? 0) * settings.toneStrength + (style?.offsets[k] ?? 0);
if (v) values[k] = Math.round(v * 100) / 100;
}
// The finishing look (colour, local contrast, sharpening, noise by ISO): never over what was measured.
for (const [k, v] of Object.entries(lookValues(settings.look, photo.iso))) if (values[k] === undefined) values[k] = v;
if (Object.keys(values).length) ops.push({ command: "develop.set", params: { values } } as EditCommand);
if (settings.level && auto.angle !== null && Math.abs(auto.angle) >= MIN_LEVEL && Math.abs(auto.angle) <= MAX_LEVEL) angle = auto.angle;
}
@@ -121,14 +128,18 @@ export class AutopilotService {
const aspect = settings.aspect ? settings.aspect[0] / settings.aspect[1] : null;
const focusFile = photo.originalStored ? storage.resolve(photo.storageKey) : preview;
const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null);
const composition = detections ? compose(detections, aspect, { minWidth: minCropWidth(W, H, settings.minLongEdge), focus }) : null;
const minWidth = minCropWidth(W, H, settings.minLongEdge);
const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing }) : null;
const wideComposition = detections && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full" }) : null;
let crop: Box | null = null;
if (settings.crop && composition) {
// Photographers who always tighten the autopilot's crop get it tighter (never cutting into the subject).
const rect = style?.cropFactor ? tighter(composition.rect, composition.subject, style.cropFactor) : composition.rect;
crop = constrainRotated(rect, angle, W, H);
// Almost the whole frame: leave the photo as shot.
if (rect.x1 - rect.x0 < KEEP_WHOLE) crop = constrainRotated(rect, angle, W, H);
}
else if (angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
const wide = settings.crop && wideComposition && wideComposition.rect.x1 - wideComposition.rect.x0 < KEEP_WHOLE ? constrainRotated(wideComposition.rect, angle, W, H) : null;
if (!crop && angle) crop = constrainRotated({ x0: 0, y0: 0, x1: 1, y1: 1 }, angle, W, H);
if (crop) ops.push({ command: "crop.set", params: { rect: crop, angle, aspect: settings.aspect ?? [W, H] } } as EditCommand);
// Someone already edited it (on the desktop app without a network, before it was uploaded): their edit
@@ -147,6 +158,7 @@ export class AutopilotService {
reason: composition?.reason ?? null,
subject: composition?.subject ?? null,
crop,
wide,
angle,
style: style && (Object.keys(style.offsets).length || style.cropFactor) ? style : null,
};
@@ -200,11 +212,14 @@ export class AutopilotService {
broadcaster.library(event.organizationId, { type: "photo.updated", ids: toFlag, patch: { flag: "PICK" } });
picked += toFlag.length;
}
// Variety: the second pick gets a slightly tighter frame than the first.
// Variety: the second pick gets the other framing. A tight first pick: the wider, whole-body frame (the
// context the agencies mix in); otherwise a slightly tighter one.
const second = best[1];
const secondEdited = second ? await db.photoEdit.count({ where: { photoId: second.id, NOT: { clientId: "autopilot" } } }) : 0;
if (second?.rec?.crop && second.rec.subject && settings.crop && !secondEdited) {
const rect = constrainRotated(tighter(second.rec.crop, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
const crop2 = second?.rec?.crop;
const wider = crop2 && second.rec?.wide && (second.rec.wide.x1 - second.rec.wide.x0) / (crop2.x1 - crop2.x0) > 1.12 ? second.rec.wide : null;
if (crop2 && second.rec?.subject && settings.crop && !secondEdited) {
const rect = wider ?? constrainRotated(tighter(crop2, second.rec.subject, 0.88), second.rec.angle, second.width ?? 3, second.height ?? 2);
await develop
.append(second.id, second.uploaderId ?? event.createdById ?? null, {
clientId: "autopilot",
+39 -15
View File
@@ -9,6 +9,9 @@
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
* crowd and the stands). Legs may be cut; heads and the ball may not.
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
* - "tight" framing (the agencies' handball look: kolektiff images, measured on 600 photos of 2025-26): the
* subject fills the height, cut mid-shin or mid-thigh, the face big (about a seventh of the frame) near the top.
* "full" keeps whole bodies when they fit (Peter's usual two thirds of the frame).
*
* Boxes are fractions of the upright photo (0..1, y down).
* When the camera wrote a focus point, the person under it is the subject; sharpness still frames everyone else.
@@ -79,7 +82,12 @@ export const TUNING = {
const JOINTS = [0.17, 0.53, 0.74, 0.95];
const JOINT_BAND = 0.035;
/** Tight framing: the subject's tallest body about this many crop heights (a little cut at the bottom). */
export const TIGHT = { fillAt: 1.05, wFill: 2.2, chestAt: 0.34, headMax: 0.2 };
export interface ComposeOptions {
/** "full": whole bodies when they fit (default); "tight": the agencies' close framing, legs cut mid-limb. */
framing?: "full" | "tight";
/** Narrowest crop allowed, as a fraction of the photo's width (from the delivery's minimum resolution). */
minWidth?: number;
/** Where the camera focused. The person there is the subject; the rest of the crop still follows the model. */
@@ -100,7 +108,7 @@ const atEdge = (b: Box) => b.x0 < 0.01 || b.x1 > 0.99;
const sharp = (p: Detection) => p.sharpness ?? 1;
/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */
export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box; reason: Composition["reason"]; people: Detection[] } | null {
export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT);
if (!people.length) return null;
// The main subject: the person the camera focused on, when that point lands on someone. Otherwise in focus
@@ -119,7 +127,7 @@ export function findSubject(d: Detections, focus?: FocusHint | null): { box: Box
const contest = people.filter((p) => p === main || (h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)));
if (!contest.includes(main)) contest.push(main);
const box = contest.reduce<Box>((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 });
return { box, reason: "ball", people: contest };
return { box, reason: "ball", people: contest, ball };
}
// No ball: the subject and the sharp people standing with them (a duel, a celebration, a line-up).
@@ -162,13 +170,24 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
const found = findSubject(d, opts.focus);
if (!found) return null;
const { box: s, reason, people: inSubject } = found;
const { box: s, reason, people: inSubject, ball } = found;
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
const tallest = Math.max(...inSubject.map(h));
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
const headroom = 0.04 * tallest;
// Whole bodies, feet included; only when that can't fit, down to the waist.
const minWidth = opts.minWidth ?? 0;
if (opts.framing === "tight") {
// The ball (and the hands on it) is never cut: the bottom edge stays below it.
const keep = (y: number) => Math.min(s.y1, Math.max(y, ball ? ball.y1 + 0.01 : 0));
// Mid-shin, mid-thigh, or whole: the cost (fill, head, joints) chooses; the waist only when nothing else fits.
const tries = [keep(s.y0 + 0.86 * tallest), keep(s.y0 + 0.64 * tallest), s.y1]
.map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, true))
.filter((c): c is Composition & { cost: number } => !!c);
const best = tries.reduce<(Composition & { cost: number }) | null>((a, b) => (!a || b.cost < a.cost ? b : a), null);
if (best) return { rect: best.rect, subject: best.subject, reason: best.reason, people: best.people };
return frame(s, ratio, keep(s.y0 + 0.55 * tallest), headroom, tallest, others, inSubject, reason, minWidth, true);
}
// Whole bodies, feet included; only when that can't fit, down to the waist.
return frame(s, ratio, s.y1, headroom, tallest, others, inSubject, reason, minWidth) ?? frame(s, ratio, s.y0 + 0.55 * tallest, headroom, tallest, others, inSubject, reason, minWidth);
}
@@ -178,7 +197,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400):
return Math.min(1, Math.max(0.35, minLongEdge / long) * (width >= height ? 1 : height / width));
}
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number): Composition | null {
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false): (Composition & { cost: number }) | null {
const mainSharp = Math.max(...inSubject.map(sharp));
let best: { rect: Box; cost: number } | null = null;
for (let k = 0.35; k <= 1.0001; k += 0.025) {
@@ -200,16 +219,16 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall
const y0 = Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
if (r.x0 > s.x0 + 1e-6 || r.x1 < s.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject) + jointCost(r, inSubject, others, mainSharp);
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight) + jointCost(r, inSubject, others, mainSharp);
if (!best || c < best.cost) best = { rect: r, cost: c };
}
}
}
if (!best) return null;
return { rect: best.rect, subject: s, reason, people: inSubject.length };
return { rect: best.rect, subject: s, reason, people: inSubject.length, cost: best.cost };
}
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[]): number {
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false): number {
let c = 0;
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
for (const p of others) {
@@ -220,21 +239,26 @@ function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number,
const size = Math.min(1, h(p) / tallest);
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
}
// Peter's usual crop is two thirds of the frame; bigger only when the subject needs it.
const k = Math.max(ch, w(r) / ratio);
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
// The subject fills a good part of the height (people tall in the frame).
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
if (tight) {
// The agencies' framing: the subject as tall as the crop (or a little taller, legs cut mid-limb).
c += TIGHT.wFill * Math.abs(tallest / ch - TIGHT.fillAt);
} else {
// Peter's usual crop is two thirds of the frame; bigger only when the subject needs it.
const k = Math.max(ch, w(r) / ratio);
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
// The subject fills a good part of the height (people tall in the frame).
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
}
// Centred across.
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
// Heads a little below the top: not touching it, not floating in empty space.
const head = (s.y0 - r.y0) / ch;
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - TUNING.headMax));
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - (tight ? TIGHT.headMax : TUNING.headMax)));
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
// the middle with a strip of grass below.
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
c += TUNING.wChest * Math.abs(chest - TUNING.chestAt);
c += TUNING.wChest * Math.abs(chest - (tight ? TIGHT.chestAt : TUNING.chestAt));
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
+8
View File
@@ -13,6 +13,14 @@ const Env = z.object({
.default("0")
.transform((v) => v === "1" || v === "true"),
DATABASE_URL: z.string().url(),
/** Prisma/pg pool size of one API process (infra/pm2/api.config.cjs runs API_INSTANCES of these). */
API_DB_POOL_SIZE: z.coerce.number().int().positive().default(10),
/** PM2 cluster instances for the API; mirror a pm2-api.override.json `instances` change here too. */
API_INSTANCES: z.coerce.number().int().positive().default(2),
/** Postgres' max_connections, so the worker leaves it enough room for the API and admin/migration connections. */
DB_MAX_CONNECTIONS: z.coerce.number().int().positive().default(100),
/** Postgres' superuser_reserved_connections: never available to the app, whatever max_connections says. */
DB_SUPERUSER_RESERVED_CONNECTIONS: z.coerce.number().int().nonnegative().default(3),
JWT_SECRET: z.string().min(32, "JWT_SECRET must have at least 32 characters"),
ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900),
REFRESH_TOKEN_TTL_DAYS: z.coerce.number().int().positive().default(30),
+4 -1
View File
@@ -442,7 +442,10 @@ export class DeliveryService {
let cloud: { file: string; done: () => Promise<void> } | null = null;
if (!item.photo.originalStored && this.deps.originals) {
cloud = await this.deps.originals.downloadOriginal(item.photoId).catch((err) => {
log.warn({ err, itemId }, "delivery: original not read from the cloud");
// A transient cloud blip (BIT-31513) is retried below (QUEUED with a backoff), so it is logged at info,
// not warn, to keep it out of the error hub like the archive indexer's own download already is.
if (isTransient(err)) log.info({ err, itemId }, "delivery: original download blipped from the cloud, retrying");
else log.warn({ err, itemId }, "delivery: original not read from the cloud");
return null;
});
}
+6 -3
View File
@@ -301,7 +301,7 @@ export function zerozeroGameId(input: string): string | null {
}
const STOP = new Set(["fc", "sc", "cf", "cd", "ud", "sad", "ac", "ad", "gd", "cs", "sl", "sport", "clube", "club", "futebol", "football", "afc", "the", "de", "da", "do", "e", "fk", "sk"]);
const words = (name: string) =>
export const words = (name: string) =>
name
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
@@ -312,8 +312,11 @@ const words = (name: string) =>
/** Whether two names are the same team ("Torreense" / "SC Torreense", "Sporting CP" / "Sporting"). */
export function sameTeam(a: string, b: string): boolean {
const wa = words(a);
const wb = words(b);
return sameWords(words(a), words(b));
}
/** `sameTeam` on names already split into `words` (to compare one name with many teams). */
export function sameWords(wa: string[], wb: string[]): boolean {
if (!wa.length || !wb.length) return false;
const [short, long] = wa.length <= wb.length ? [wa, wb] : [wb, wa];
return short.every((w) => long.some((x) => x === w || (w.length >= 4 && (x.startsWith(w) || w.startsWith(x)))));
+37
View File
@@ -131,3 +131,40 @@ export class Pressure {
return Math.max(1, Math.floor(full * this.share(burst)));
}
}
/**
* How many Postgres connections the worker's pool may open for `wanted`, leaving room under `max` (Postgres'
* `max_connections`) for: the API's own Prisma pool, one per PM2 cluster instance; each of those instances'
* realtime connections (`attachRealtime` in `realtime.ts`: a 2-connection publish pool plus one dedicated
* `LISTEN` client, so 3 per instance — not just the worker's own 1-connection remote broadcaster); one extra
* instance's worth of API connections during a deploy (`pm2 startOrReload` on the clustered `photoreport-api`
* app brings a new instance online and confirms it before stopping an old one, so for a few seconds there are
* `apiInstances + 1` live, not just `apiInstances` — BIT-31550 was this exact overlap tipping the API's steady
* -state budget into Postgres' `superuser_reserved_connections`); Postgres' `superuser_reserved_connections`
* itself (reserved below `max_connections`, never available to the app no matter how much headroom is left —
* this is what "reserved for roles with the SUPERUSER attribute" means); and extra headroom for ad hoc
* connections (migrations, scripts, psql, admin tools) that aren't sized here.
*/
export function dbConnectionBudget(
wanted: number,
{
max = 100,
apiInstances = 2,
apiPoolSize = 10,
realtimePerInstance = 3,
apiReloadOverlap = 1,
superuserReserved = 3,
headroom = 10,
}: {
max?: number;
apiInstances?: number;
apiPoolSize?: number;
realtimePerInstance?: number;
apiReloadOverlap?: number;
superuserReserved?: number;
headroom?: number;
} = {},
): number {
const available = max - superuserReserved - (apiInstances + apiReloadOverlap) * (apiPoolSize + realtimePerInstance) - 1 - headroom;
return Math.max(1, Math.min(wanted, available));
}
+1 -1
View File
@@ -5,7 +5,7 @@ import { createDb } from "./db.js";
preferIpv4();
const config = loadConfig();
const db = createDb(config.DATABASE_URL);
const db = createDb(config.DATABASE_URL, config.API_DB_POOL_SIZE);
const reporter = reporterFor(config);
reporter.watchProcess("api");
const app = await buildApp({ config, db, realtime: "socket", reporter });
+11 -1
View File
@@ -70,9 +70,19 @@ export interface OfficialData {
const TIMEOUT_MS = 20_000;
/** An HTTP error from a federation's own API, with its status so callers can tell "not available yet" (4xx) from a real outage. */
export class ProviderHttpError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
}
}
async function get(fetcher: Fetch, url: string, headers: Record<string, string>, as: "json" | "text", timeoutMs = TIMEOUT_MS) {
const res = await fetcher(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
if (!res.ok) throw new Error(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`);
if (!res.ok) throw new ProviderHttpError(`${new URL(url).host} ${new URL(url).pathname} ${res.status}`, res.status);
return as === "json" ? res.json() : res.text();
}
+5 -1
View File
@@ -19,6 +19,7 @@ import {
LigaProvider,
type OfficialData,
type PlayerData,
ProviderHttpError,
type TeamData,
UEFA_COMPETITIONS,
UEFA_PITCH_OFFICIALS,
@@ -867,7 +868,10 @@ export class SportsService {
named = await this.liga.referees(fixture.competition.externalId, fixture.competition.season, fixture.round, fixture.externalId.replace(/^\d{8}-/, ""));
if (named.length) await db.sportsFixture.update({ where: { id: fixture.id }, data: { officials: named as unknown as object } });
} catch (err) {
log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
// Liga 400s a round's nominations until it publishes them, days before the match: expected, not an
// outage, so it is logged at info to keep it out of the error hub (it is read again on the next refresh).
if (err instanceof ProviderHttpError && err.status === 400) log.info({ err, fixture: fixture.id }, "sports: liga nominations not published yet for this round");
else log.warn({ err, fixture: fixture.id }, "sports: liga referees failed");
}
}
const officials = named.filter((o) => PEOPLE_OFFICIALS.includes(o.role));
+14 -3
View File
@@ -5,7 +5,7 @@ import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { reporterFor } from "./lib/reporter.js";
import pino from "pino";
import { loadConfig } from "./config.js";
import { planCapacity, Pressure } from "./lib/capacity.js";
import { dbConnectionBudget, planCapacity, Pressure } from "./lib/capacity.js";
import { modelsDir } from "./lib/models.js";
import { createDb } from "./db.js";
import { closeRenderer } from "./delivery/render.js";
@@ -63,8 +63,19 @@ const capacity = planCapacity({
delivery: config.DELIVERY_CONCURRENCY,
});
log.info(capacity, "capacity");
// Enough connections for everything running at once, within Postgres' default 100 (the API keeps its own 10).
const db = createDb(config.DATABASE_URL, Math.min(80, 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2)));
// Enough connections for everything running at once, within what's left of Postgres' max_connections once the
// API's cluster (Prisma pool and realtime connections), the superuser-reserved slots, the realtime broadcaster
// and ad hoc connections (migrations, scripts, psql) have theirs.
const wanted = 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2);
const db = createDb(
config.DATABASE_URL,
dbConnectionBudget(wanted, {
max: config.DB_MAX_CONNECTIONS,
apiInstances: config.API_INSTANCES,
apiPoolSize: config.API_DB_POOL_SIZE,
superuserReserved: config.DB_SUPERUSER_RESERVED_CONNECTIONS,
}),
);
const storage = new LocalStorage(config.STORAGE_ROOT);
const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed"));
+214 -1
View File
@@ -4,7 +4,8 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
import { galleryAssignments } from "../src/archive/gallery.js";
import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryRoot, isExhibition, isInitials, isTeam, knownVersus, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js";
import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js";
import { ArchiveService, localDirs } from "../src/archive/service.js";
import { SecretBox } from "../src/delivery/secrets.js";
@@ -52,6 +53,42 @@ describe("archive folder names", () => {
expect(pickFixture(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")!, [fixture], new Date("2026-10-19T00:00:00Z"))?.id).toBe("cpac");
});
it("reads a slash between two clubs, in any archive, and leaves a season slash alone", () => {
expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09/20250913 - ALMADA AC / EXT. GIL EANES")).toMatchObject({
home: "ALMADA AC",
away: "EXT. GIL EANES",
day: "2025-09-13",
season: "20252026",
competition: "PO09",
});
expect(parseFolder("/Liga/04.11.23 ALMADA AC / EXT. GIL EANES")).toMatchObject({ home: "ALMADA AC", away: "EXT. GIL EANES", day: "2023-11-04" });
expect(directorySides("ALMADA AC / EXT. GIL EANES")).toEqual(["ALMADA AC", "EXT. GIL EANES"]);
expect(parseFolder("/x/20250913 - 2025/2026")).toBeNull();
expect(parseFolder("/x/20250913 - Final / Video")).toBeNull();
expect(directorySides("Sporting CP")).toEqual(["Sporting CP"]);
// A sponsor after the slash is the same club, not the away team. "Avanca / Bioria" was Avanca.
expect(parseFolder("/Liga/04.11.23 Avanca / Bioria")).toMatchObject({ home: "Avanca / Bioria", away: "", single: true, day: "2023-11-04" });
expect(parseFolder("/FPA/Fotos/2024_2025/PO01/20240913 - Avanca / Bioria")).toBeNull();
expect(parseFolder("/Liga/04.11.23 Sporting CP / Betclic")).toMatchObject({ home: "Sporting CP / Betclic", away: "", single: true });
const clubs = [
{ name: "Avanca", abbreviation: null, slug: "avanca" },
{ name: "SL Benfica", abbreviation: "SLB", slug: "benfica" },
{ name: "FC Porto", abbreviation: "FCP", slug: "porto" },
{ name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" },
];
expect(canonicalTeam("Avanca / Bioria", clubs)).toBe("Avanca");
expect(canonicalTeam("Bioria / Avanca", clubs)).toBe("Avanca");
expect(canonicalTeam("Sporting CP / Betclic", clubs)).toBe("Sporting CP");
expect(canonicalTeam("ALMADA AC / EXT. GIL EANES", clubs)).toBe("ALMADA AC / EXT. GIL EANES");
expect(knownVersus("Avanca / Bioria", clubs)).toBeNull();
expect(knownVersus("Benfica / Porto", clubs)).toEqual({ home: "SL Benfica", away: "FC Porto" });
const match = teamMatcher(clubs);
expect(directorySides("Avanca / Bioria", (n) => match.knownName(n))).toEqual(["Avanca / Bioria"]);
expect(directorySides("Benfica / Porto", (n) => match.knownName(n))).toEqual(["Benfica", "Porto"]);
for (const name of ["Avanca / Bioria", "Bioria / Avanca", "Sporting CP / Betclic", "Benfica / Porto", "ALMADA AC / EXT. GIL EANES"])
expect(match(name)).toBe(canonicalTeam(name, clubs));
});
it("reads Liga folders: competition and season from the top, matchday, numbered games", () => {
expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga")).toMatchObject({
home: "Sporting CP",
@@ -166,6 +203,45 @@ describe("archive folder names", () => {
expect(describeFolder(`${session.replace("20241118 - Sessão", "20260306 - Sessao")}/Grupos`).people).toEqual([]);
});
it("puts a game's parts and a session's athletes in one gallery", () => {
const game = "/FPA/Fotos/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP";
for (const part of ["1P", "2P", "Aquecimento", "Cerimónia", "1 - Pre-Match", "2 - 1st Half", "WARM UP", "GAME", "FLASH", "P1"]) {
expect(galleryRoot(`${game}/${part}`)).toBe(game);
expect(galleryRoot(`${game}/${part}/selecionadas`)).toBe(game);
}
const session = "/FPA/Fotos/2023_2024/Seleções Nacionais/Seleção Nacional A Feminina/20231008 - Sessao SNAF";
expect(galleryRoot(`${session}/7 - Bebiana Sabino`)).toBe(session);
expect(galleryRoot(`${session}/Equipa Técnica/Ana Teixeira`)).toBe(session);
expect(galleryRoot("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio/Diogo Rema")).toBe(
"/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio",
);
// A game filed inside another folder stays its own gallery.
const nest = "/FPA/Fotos/2023_2024/Eventos/20240608 - Colégio Gaia x Vermoim";
expect(galleryRoot(`${nest}/20240509 - Portugal x Bosnia`)).toBe(`${nest}/20240509 - Portugal x Bosnia`);
expect(galleryRoot("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC")).toBe("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC");
// A shelf that is not two clubs does not swallow the days under it, nor does a final without two clubs.
expect(galleryRoot("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1")).toBe("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1");
expect(galleryRoot("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1")).toBe("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1");
// The same game copied under another name, when that copy is itself a game, stays separate.
expect(galleryRoot("/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO")).toBe(
"/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO",
);
// The duplicate mirror is not a session just because the shelf says "sessão".
const mirror = "/FPA/Fotos/SESSÃO ESTÚDIO SNAF (2020 a 2022) - Equipamento Select/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP";
expect(galleryRoot(`${mirror}/1P`)).toBe(mirror);
const gameId = "game";
const partId = "part";
const nestedId = "nested";
const assigned = galleryAssignments([
{ id: gameId, path: game },
{ id: partId, path: `${game}/1P` },
{ id: nestedId, path: `${nest}/20240509 - Portugal x Bosnia` },
]);
expect(assigned.get(partId)).toBe(gameId);
expect(assigned.get(gameId)).toBe(gameId);
expect(assigned.get(nestedId)).toBe(nestedId);
});
it("names what is not a game after the folders above when its own name says little", () => {
expect(describeFolder("/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2/Cerimónia")).toMatchObject({
occasion: "/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2",
@@ -247,6 +323,10 @@ describe("archive folder names", () => {
expect(canonicalTeam("06_SPORTING CP", known)).toBe("Sporting CP");
expect(canonicalTeam("02.2024 Benfica B", known)).toBe("SL Benfica B");
expect(canonicalTeam("09.2023 Leiria", known)).toBe("U. Leiria");
// The prepared matcher (many names, same teams) answers the same.
const match = teamMatcher(known);
for (const name of ["01 SCP", "06_SPORTING CP", "02.2024 Benfica B", "09.2023 Leiria", "Benfica", "UDL", "SLB B", "FC Porto", "", "12"])
expect(match(name)).toBe(canonicalTeam(name, known));
});
it("picks the one fixture with those teams on that day", () => {
@@ -329,6 +409,26 @@ describe("CloudClient retries transient failures", () => {
await rm(dir, { recursive: true, force: true });
}
});
it("retries a 503 blip on a PROPFIND (BIT-31498) and succeeds, instead of failing the whole walk", async () => {
const multistatus = `<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
<d:response><d:href>/remote.php/dav/files/peter/FPA/Fotos/</d:href>
<d:propstat><d:prop><d:getetag>"abc"</d:getetag><d:resourcetype><d:collection/></d:resourcetype><oc:fileid>10</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
</d:response>
</d:multistatus>`;
let calls = 0;
const fetchImpl: typeof fetch = async (input) => {
const url = new URL(String(input));
const who = whoami(url);
if (who) return who;
calls++;
return calls <= 2 ? new Response(null, { status: 503 }) : new Response(multistatus, { status: 207 });
};
const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl);
const { self } = await client.list("/FPA/Fotos");
expect(self.fileId).toBe("10");
expect(calls).toBe(3);
});
});
interface Node {
@@ -569,6 +669,70 @@ describe("archive from a Nextcloud", () => {
expect(after.lastScanAt).not.toBeNull();
});
it("requeues a photo instead of failing it when a download blip outlasts the cloud client's own retries (BIT-31505)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
await worker.scan(source.id);
const [id] = await worker.claim(1);
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
expect(claimed).toMatchObject({ status: "WORKING", attempts: 1 });
// Nextcloud stays unavailable for longer than CloudClient.call's own retry budget (BIT-31491): the GET for
// this file keeps answering 503 past the last retry, so download() gives up and throws.
const realFetch = cloud.fetch;
const name = claimed.path.split("/").pop()!;
cloud.fetch = async (input, init) => {
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
return realFetch(input, init);
};
await worker.index(id);
cloud.fetch = realFetch;
// Given back to the walk, not failed outright, and the claim's attempt is given back with it: a cloud blip
// never counts toward the permanent-failure limit the way a real decoding/matching error would.
const requeued = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
expect(requeued).toMatchObject({ status: "PENDING", attempts: 0 });
expect(requeued.error).toContain("503");
const [again] = await worker.claim(1);
expect(again).toBe(id);
await worker.index(again);
expect(await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: "DONE" });
});
it("logs a download blip at info, not warn, so a free retry never reaches the error hub as a new error (BIT-31513)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
const calls: { level: "info" | "warn"; msg: string }[] = [];
const spy = {
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
};
const storage = new LocalStorage(storageRoot);
const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet });
const spied = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: spy, ingest, fetchImpl: fetchProxy });
await spied.scan(source.id);
const [id] = await spied.claim(1);
const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } });
const realFetch = cloud.fetch;
const name = claimed.path.split("/").pop()!;
cloud.fetch = async (input, init) => {
if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 });
return realFetch(input, init);
};
await spied.index(id);
cloud.fetch = realFetch;
// Same recoverable blip as BIT-31505: a free retry, not an error to page on, so logHooks (reporter.ts) must
// never see it as a "warn" carrying an err (it would otherwise reach errors.bitreport.pt and reopen the Loop).
expect(calls).toContainEqual({ level: "info", msg: "archive: image download blipped, requeued for a free retry" });
expect(calls.some((c) => c.level === "warn")).toBe(false);
});
it("puts a game's halves in one event with the clubs' names, and names a session's athletes on their photos", async () => {
const game = "/FPA/Fotos/2024_2025/Supertaça Kempa 2024/20240824 - SCP x ABC";
cloud.add(`${game}/1P/H_0001.jpg`, await jpeg(6));
@@ -628,6 +792,55 @@ describe("archive from a Nextcloud", () => {
expect(await ctx.db.event.findUnique({ where: { id: oldEvent } })).toBeNull();
});
it("never drops an event a match lands on while its own cleanup still thinks it is empty (BIT-31531)", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
await worker.scan(source.id);
for (const id of await worker.claim(10)) await worker.index(id);
const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } });
const galaFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } });
const gameEventId = gameFolder.eventId!;
const galaEventId = galaFolder.eventId!;
// galaFolder is galaEventId's only folder, so moving it onto the game's event makes galaEventId empty and
// triggers dropIfEmpty(galaEventId) at the end of the move. Hold that cleanup open right at its delete — as if
// another match had just made it look empty a moment ago — while a second move lands gameFolder (and its
// photos) on galaEventId. Before BIT-31531 dropIfEmpty read "empty" and deleted on that stale read regardless
// of what arrived after; the fix folds the check into the delete's own WHERE, so it must see the new tenant.
let releaseDelete!: () => void;
const heldOpen = new Promise<void>((resolve) => (releaseDelete = resolve));
let reachedDelete!: () => void;
const deleteReached = new Promise<void>((resolve) => (reachedDelete = resolve));
const gated = ctx.db.$extends({
query: {
event: {
async deleteMany({ args, query }) {
if (args.where?.id === galaEventId) {
reachedDelete();
await heldOpen;
}
return query(args);
},
},
},
});
const slowWorker = new ArchiveService({ db: gated as unknown as TestContext["db"], secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy });
const held = slowWorker.setFolderEvent(galaFolder.id, { eventId: gameEventId });
await deleteReached;
await worker.setFolderEvent(gameFolder.id, { eventId: galaEventId });
releaseDelete();
await held;
const gameAfter = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: gameFolder.id } });
expect(gameAfter.eventId).toBe(galaEventId);
expect(await ctx.db.event.findUnique({ where: { id: galaEventId } })).not.toBeNull();
const gamePhotos = await ctx.db.photo.findMany({ where: { originalName: { in: ["PS_0001.jpg", "PS_0002.jpg"] } } });
expect(gamePhotos.every((p) => p.eventId === galaEventId)).toBe(true);
});
it("asks again when the cloud revokes the app password", async () => {
const source = await connect();
cloud.authorised = true;
+14 -1
View File
@@ -187,7 +187,8 @@ describe("autopilot", () => {
ingestFrom: new Date("2026-10-11T12:00:00Z"),
ingestUntil: new Date("2026-10-11T18:00:00Z"),
iptcTemplate: {},
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2 } }),
// The original settings (half tone, white balance as shot, no look, whole bodies); the agency defaults have a test of their own.
...(autopilotOn && { autopilot: { enabled: true, picksPerBurst: 2, toneStrength: 0.5, whiteBalance: false, look: "none", framing: "full" } }),
},
});
return { orgId: org!.id, userId: user.id, eventId: event.id };
@@ -297,6 +298,18 @@ describe("autopilot", () => {
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photoId } })).autopilotStatus).toBe("DONE");
});
it("edits the agencies' way by default: neutral whites, fuller tone, the finishing look", async () => {
const { orgId, userId, eventId } = await setup();
await ctx.db.event.update({ where: { id: eventId }, data: { autopilot: { enabled: true } } });
const id = await shot(orgId, userId, eventId, 0, 300);
await ctx.db.photo.update({ where: { id }, data: { iso: 6400 } });
await runQueue();
const edits = await ctx.db.photoEdit.findMany({ where: { photoId: id }, orderBy: { seq: "asc" } });
const values = (edits[0]!.command as { params: { values: Record<string, number> } }).params.values;
expect(values).toMatchObject({ "wb.temp": 5200, "wb.tint": 4, "light.exposure": 0.3, "light.contrast": 15, "color.vibrance": 18, "detail.sharpenAmount": 40, "detail.nrLuminance": 22 });
expect(Object.keys(values).some((k) => k.startsWith("vignette."))).toBe(false);
});
it("leaves events without autopilot alone", async () => {
const { orgId, userId, eventId } = await setup(false);
await shot(orgId, userId, eventId, 0, 100);
+22 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
import { dbConnectionBudget, planCapacity, Pressure, type Reading } from "../src/lib/capacity.js";
const GB = 1e9;
@@ -38,3 +38,24 @@ describe("capacity", () => {
expect(at({ free: 6 * GB }).allow(36, true)).toBe(18);
});
});
describe("dbConnectionBudget", () => {
it("stays under what the API's cluster, a deploy's reload overlap, the superuser reserve, the broadcaster and headroom leave of max_connections", () => {
// 100 - 3 superuser reserved - ((2 api instances + 1 reload overlap) * (10 pool + 3 realtime)) - 1 broadcaster - 10 headroom = 47.
expect(dbConnectionBudget(500)).toBe(47);
expect(dbConnectionBudget(10)).toBe(10);
});
it("follows a differently sized API cluster or Postgres limit", () => {
expect(dbConnectionBudget(500, { max: 200, apiInstances: 4, apiPoolSize: 15 })).toBe(96);
expect(dbConnectionBudget(500, { max: 40, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
});
it("can be told a deploy never overlaps instances (e.g. a non-cluster or single-instance API)", () => {
expect(dbConnectionBudget(500, { apiReloadOverlap: 0 })).toBe(60);
});
it("never goes below 1, even if the API and headroom already exceed max_connections", () => {
expect(dbConnectionBudget(50, { max: 20, apiInstances: 2, apiPoolSize: 10 })).toBe(1);
});
});
+26
View File
@@ -84,3 +84,29 @@ describe("automatic crop", () => {
expect(((c.rect.x1 - c.rect.x0) * 3000) / ((c.rect.y1 - c.rect.y0) * 2000)).toBeCloseTo(0.8, 2);
});
});
describe("tight framing (the agencies' handball look)", () => {
it("fills the height with the player, cutting the legs mid-limb, never at a joint or below the ball", () => {
const p = { ...person(0.42, 0.1, 0.56, 0.9), sharpness: 1 };
const ball = { x0: 0.5, y0: 0.35, x1: 0.54, y1: 0.41, score: 0.8 };
const full = compose({ ...frame, people: [p], balls: [ball] })!;
const tight = compose({ ...frame, people: [p], balls: [ball] }, null, { framing: "tight" })!;
const hT = tight.rect.y1 - tight.rect.y0;
expect(hT).toBeLessThan(full.rect.y1 - full.rect.y0);
// The player about as tall as the crop: feet out, head in.
expect(tight.rect.y1).toBeLessThan(p.y1);
expect(tight.rect.y0).toBeLessThanOrEqual(p.y0);
expect(tight.rect.y1).toBeGreaterThan(ball.y1);
const at = (tight.rect.y1 - p.y0) / (p.y1 - p.y0);
for (const j of [0.53, 0.74, 0.95]) expect(Math.abs(at - j)).toBeGreaterThanOrEqual(0.035);
// Same shape as the photo.
expect(((tight.rect.x1 - tight.rect.x0) * 3000) / (hT * 2000)).toBeCloseTo(1.5, 2);
});
it("keeps a ball held low inside the crop", () => {
const p = { ...person(0.42, 0.1, 0.56, 0.9), sharpness: 1 };
const ball = { x0: 0.5, y0: 0.7, x1: 0.54, y1: 0.76, score: 0.8 };
const tight = compose({ ...frame, people: [p], balls: [ball] }, null, { framing: "tight" })!;
expect(tight.rect.y1).toBeGreaterThan(ball.y1);
});
});
+32
View File
@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { NextcloudError } from "../src/delivery/nextcloud.js";
import { closeRenderer } from "../src/delivery/render.js";
import { SecretBox } from "../src/delivery/secrets.js";
import { DeliveryService } from "../src/delivery/service.js";
@@ -705,6 +706,37 @@ describe("delivery", () => {
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
});
it("logs a blip reading an archive original from the cloud at info, not warn, so it never reaches the error hub (BIT-31522)", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
});
const targetId = (created.json() as { id: string }).id;
const a = await photo("archived.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
const calls: { level: "info" | "warn"; msg: string }[] = [];
const spy = {
info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }),
warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }),
};
// A cloud "originals" source whose download always comes back as the Nextcloud 503 seen in BIT-31522 — the
// same self-healing blip BIT-31513 already stopped from reaching the error hub out of the archive indexer.
const originals = { downloadOriginal: async () => { throw new NextcloudError("GET /archived.jpg failed: 503", 503); } };
const spied = new DeliveryService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), secrets: new SecretBox(KEY), broadcaster, log: spy, fetchImpl: nc.fetch, originals });
const [claimed] = await delivery.claim(5);
await spied.process(claimed!);
expect(calls).toContainEqual({ level: "info", msg: "delivery: original download blipped from the cloud, retrying" });
expect(calls.some((c) => c.level === "warn")).toBe(false);
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "QUEUED", lastError: "waiting_for_original" });
});
it("retries transient errors with back-off and stops at auth errors", async () => {
const { orgId, token, target } = await setup();
const id = await photo("a.jpg", "2026:09:23 21:10:00");
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { lookValues, noiseReduction } from "../src/autopilot/look.js";
describe("autopilot look", () => {
it("gives the agency look punchier colour than the natural one, and nothing for none", () => {
const agency = lookValues("agency", 400);
const natural = lookValues("natural", 400);
expect(agency["color.vibrance"]!).toBeGreaterThan(natural["color.vibrance"]!);
expect(agency["detail.sharpenAmount"]).toBe(40);
expect(lookValues("none", 6400)).toEqual({});
// Never a vignette: the ethics rules forbid darkening the background.
expect(Object.keys(agency).some((k) => k.startsWith("vignette."))).toBe(false);
});
it("reduces noise more as the ISO climbs", () => {
expect(noiseReduction(800)["detail.nrLuminance"]).toBeUndefined();
expect(noiseReduction(3200)["detail.nrLuminance"]!).toBeLessThan(noiseReduction(12800)["detail.nrLuminance"]!);
});
});
+15
View File
@@ -303,6 +303,15 @@ export const t = {
tone: "Tom",
whiteBalance: "Equilíbrio de brancos",
toneStrength: (n: number) => `Intensidade do tom: ${n}%`,
framing: "Enquadramento",
framingTight: "Apertado (estilo agência)",
framingFull: "Corpo inteiro",
framingHelp: "Apertado: o jogador ocupa a altura, cortado a meio da perna, a cara grande; a segunda escolhida de cada sequência leva o enquadramento largo, de corpo inteiro. Fotos já bem enquadradas ficam como foram tiradas.",
look: "Acabamento",
lookAgency: "Agência (cores fortes)",
lookNatural: "Natural",
lookNone: "Nenhum",
lookHelp: "Cor, contraste local, nitidez e redução de ruído conforme o ISO, iguais em todas as fotos do jogo. Nunca escurece o fundo nem mexe numa zona só.",
picksPerBurst: "Escolher por sequência",
noPicks: "Não escolher",
minLongEdge: "Resolução mínima do recorte",
@@ -506,6 +515,12 @@ export const t = {
diskNeeded: (n: string) => ` · as fotos por indexar vão ocupar cerca de ${n}`,
diskShort: (min: string) => `Não chega: aumenta o disco do servidor. A indexação pára sozinha quando ficarem menos de ${min} livres.`,
diskPaused: (min: string) => `Indexação em pausa: o disco tem menos de ${min} livres. Aumenta o disco e continua sozinha.`,
siteFolders: "Pastas no site",
siteFoldersHelp: "Por defeito entram todas. Tira o visto a uma pasta para ela deixar de aparecer no site, mesmo que a cloud a partilhe. Vale também para as pastas que estão dentro.",
siteFoldersSearch: "Procurar pasta…",
siteFoldersEmpty: "Ainda não há pastas indexadas.",
siteFoldersLoading: "A carregar…",
siteFoldersPhotos: (n: number) => `${n.toLocaleString("pt-PT")} fotos`,
},
metadataPage: {
iptc: "Legendas",
+15
View File
@@ -58,6 +58,21 @@ export function AutopilotButton(props: { api: ApiClient; event: EventSummary; ta
<span className="text-faint">{L.toneStrength(Math.round(s.toneStrength * 100))}</span>
<input type="range" min={0} max={100} value={Math.round(s.toneStrength * 100)} disabled={!s.enabled || !s.tone || !props.canEdit} className="w-full" onChange={(e) => setS({ ...s, toneStrength: Number(e.target.value) / 100 })} onPointerUp={() => void save(s)} />
</label>
<label className="flex items-center justify-between gap-2" title={L.framingHelp}>
<span>{L.framing}</span>
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !s.crop || !props.canEdit} value={s.framing} onChange={(e) => void save({ ...s, framing: e.target.value as AutopilotSettings["framing"] })}>
<option value="tight">{L.framingTight}</option>
<option value="full">{L.framingFull}</option>
</select>
</label>
<label className="flex items-center justify-between gap-2" title={L.lookHelp}>
<span>{L.look}</span>
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.look} onChange={(e) => void save({ ...s, look: e.target.value as AutopilotSettings["look"] })}>
<option value="agency">{L.lookAgency}</option>
<option value="natural">{L.lookNatural}</option>
<option value="none">{L.lookNone}</option>
</select>
</label>
<label className="flex items-center justify-between gap-2">
<span>{L.picksPerBurst}</span>
<select className="h-6 border border-black bg-cell px-1" disabled={!s.enabled || !props.canEdit} value={s.picksPerBurst} onChange={(e) => void save({ ...s, picksPerBurst: Number(e.target.value) })}>
+3
View File
@@ -6,6 +6,7 @@ import { t } from "../i18n.js";
import { teamDisplayName } from "../library/EventForm.js";
import { openExternal } from "../platform.js";
import { PageHeader } from "./Shell.js";
import { SiteFolders } from "./SiteFolders.js";
const A = t.archive;
const VIEWER_BASE = EVENTS_URL;
@@ -22,6 +23,7 @@ export function ArchivePage() {
const { api, organization, role } = useAuth();
const orgId = organization?.id ?? "";
const isAdmin = role !== null && hasRole(role, "ADMIN");
const canEdit = role !== null && hasRole(role, "EDITOR");
const [sources, setSources] = useState<CloudSource[] | null>(null);
const [selected, setSelected] = useState<string | null>(null);
const [storage, setStorage] = useState<ArchiveStorage | null>(null);
@@ -72,6 +74,7 @@ export function ArchivePage() {
))}
{isAdmin ? <ConnectForm api={api} orgId={orgId} onConnected={(s) => setSources((list) => [...(list ?? []), s])} /> : <p className="text-[12px] text-faint">{A.adminOnly}</p>}
{current && current.status !== "LOGIN" && <Galleries key={current.id} api={api} source={current} />}
{current && current.status !== "LOGIN" && canEdit && <SiteFolders key={`${current.id}-site`} api={api} source={current} />}
</div>
</>
);
+213
View File
@@ -0,0 +1,213 @@
import { ApiError, type ApiClient, type CloudSource, type CloudTreeFolder } from "@photoreport/sdk";
import { useEffect, useMemo, useState } from "react";
import { t } from "../i18n.js";
const A = t.archive;
const errorText = (code: string | null) => (code ? (A.errors[code] ?? code) : null);
const errorOf = (err: unknown) => errorText(err instanceof ApiError ? err.code : null) ?? t.unexpectedError;
interface Node {
id: string;
name: string;
path: string;
published: boolean;
photoCount: number;
children: Node[];
}
/** Folders under a source root, nested by path. */
function treeOf(folders: CloudTreeFolder[]): Node[] {
const byPath = new Map<string, Node>();
const roots: Node[] = [];
const sorted = [...folders].sort((a, b) => a.path.localeCompare(b.path, "pt"));
for (const folder of sorted) {
const path = folder.path.replace(/^\/+|\/+$/g, "");
if (!path) continue;
const name = path.split("/").pop() ?? path;
const node: Node = { id: folder.id, name, path, published: folder.published, photoCount: folder.photoCount, children: [] };
byPath.set(path, node);
const parentPath = path.split("/").slice(0, -1).join("/");
const parent = parentPath ? byPath.get(parentPath) : undefined;
if (parent) parent.children.push(node);
else roots.push(node);
}
return roots;
}
function filterTree(nodes: Node[], query: string): Node[] {
const needle = query.trim().toLocaleLowerCase("pt");
if (!needle) return nodes;
const walk = (node: Node): Node | null => {
const children = node.children.flatMap((child) => {
const kept = walk(child);
return kept ? [kept] : [];
});
if (node.name.toLocaleLowerCase("pt").includes(needle) || children.length) return { ...node, children };
return null;
};
return nodes.flatMap((node) => {
const kept = walk(node);
return kept ? [kept] : [];
});
}
type Box = "on" | "off" | "mixed";
function boxOf(node: Node): Box {
if (!node.published) return "off";
const hidden = (current: Node): boolean => current.children.some((child) => !child.published || hidden(child));
return hidden(node) ? "mixed" : "on";
}
function Branch({
node,
depth,
expanded,
busy,
onToggle,
onCheck,
}: {
node: Node;
depth: number;
expanded: Set<string>;
busy: string | null;
onToggle: (path: string) => void;
onCheck: (node: Node) => void;
}) {
const box = boxOf(node);
const open = expanded.has(node.path);
return (
<li>
<div className="flex items-center gap-1 py-0.5" style={{ paddingLeft: depth * 16 }}>
<button
type="button"
className="h-5 w-5 text-[11px] text-muted"
aria-label={open ? "Fechar" : "Abrir"}
onClick={() => node.children.length && onToggle(node.path)}
>
{node.children.length ? (open ? "−" : "+") : ""}
</button>
<Check box={box} disabled={busy === node.id} label={node.name} onChange={() => onCheck(node)} />
<span className="truncate text-[13px] text-ink">{node.name}</span>
{node.photoCount > 0 && <span className="shrink-0 text-[11px] text-faint">{A.siteFoldersPhotos(node.photoCount)}</span>}
</div>
{open && node.children.length > 0 && (
<ul>
{node.children.map((child) => (
<Branch key={child.id} node={child} depth={depth + 1} expanded={expanded} busy={busy} onToggle={onToggle} onCheck={onCheck} />
))}
</ul>
)}
</li>
);
}
function Check({ box, disabled, label, onChange }: { box: Box; disabled: boolean; label: string; onChange: () => void }) {
const [el, setEl] = useState<HTMLInputElement | null>(null);
useEffect(() => {
if (el) el.indeterminate = box === "mixed";
}, [el, box]);
return (
<input
ref={setEl}
type="checkbox"
className="h-3.5 w-3.5"
checked={box === "on"}
disabled={disabled}
aria-label={label}
onChange={onChange}
/>
);
}
/**
* Which indexed folders appear on the public archive site. This stays in the app: the site itself has no tree.
* Everything starts published. Unchecking a folder hides it and the folders inside it.
*/
export function SiteFolders({ api, source }: { api: ApiClient; source: CloudSource }) {
const [open, setOpen] = useState(false);
const [rows, setRows] = useState<CloudTreeFolder[] | null>(null);
const [query, setQuery] = useState("");
const [expanded, setExpanded] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open || rows) return;
let live = true;
api.cloudFolderTree(source.id).then(
(body) => live && setRows(body.folders),
(err) => live && setError(errorOf(err)),
);
return () => {
live = false;
};
}, [api, source.id, open, rows]);
const tree = useMemo(() => filterTree(treeOf(rows ?? []), query), [rows, query]);
const shown = query.trim() ? new Set(collect(tree)) : expanded;
const toggle = (path: string) => {
setExpanded((cur) => {
const next = new Set(cur);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
};
const check = (node: Node) => {
const published = boxOf(node) !== "on";
setBusy(node.id);
setError(null);
api.setCloudFolderPublished(node.id, published).then(
() => {
setRows((cur) =>
(cur ?? []).map((folder) =>
folder.path === node.path || folder.path.startsWith(`${node.path}/`) ? { ...folder, published } : folder,
),
);
setBusy(null);
},
(err) => {
setError(errorOf(err));
setBusy(null);
},
);
};
return (
<section className="border border-line bg-panel">
<div className="panel-head">
<button type="button" onClick={() => setOpen((value) => !value)} className="text-left">
{open ? "−" : "+"} {A.siteFolders}
</button>
</div>
{open && (
<div className="space-y-2 px-4 py-3">
<p className="max-w-3xl text-[12px] text-muted">{A.siteFoldersHelp}</p>
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={A.siteFoldersSearch}
className="h-8 w-full max-w-sm border border-black bg-cell px-2 text-[13px] text-ink"
/>
{error && <p className="text-[12px] text-danger">{error}</p>}
{!rows && !error && <p className="text-[12px] text-faint">{A.siteFoldersLoading}</p>}
{rows && tree.length === 0 && <p className="text-[12px] text-faint">{A.siteFoldersEmpty}</p>}
{rows && tree.length > 0 && (
<ul className="max-h-[28rem] overflow-auto">
{tree.map((node) => (
<Branch key={node.id} node={node} depth={0} expanded={shown} busy={busy} onToggle={toggle} onCheck={check} />
))}
</ul>
)}
</div>
)}
</section>
);
}
function collect(nodes: Node[]): string[] {
return nodes.flatMap((node) => [node.path, ...collect(node.children)]);
}
+16 -3
View File
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { cached, call, fold, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
import { cached, call, fold, forget, initials, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type PeopleList } from "./api";
import { Icon, Loading, PersonFace } from "./parts";
export type Tab = "galleries" | "people" | "teams" | "review";
@@ -37,6 +37,7 @@ export function Browse({
const [total, setTotal] = useState(0);
const [loadingMore, setLoadingMore] = useState(false);
const [teams, setTeams] = useState<Directory["teams"] | null>(null);
const [teamsTry, setTeamsTry] = useState(0);
const [players, setPlayers] = useState<NonNullable<Directory["players"]> | null>(null);
const [people, setPeople] = useState<PeopleList | null>(null);
const [club, setClub] = useState<string | null>(null);
@@ -86,16 +87,28 @@ export function Browse({
useEffect(() => {
let cancel = false;
let retry: ReturnType<typeof setTimeout> | undefined;
setFailed(false);
if (tab === "teams") {
cached<Directory>(`/v1/archive/${sourceId}/directory`, token, (body) => !cancel && setTeams(body.teams)).catch((err) => !cancel && guard(err));
const url = `/v1/archive/${sourceId}/directory`;
cached<Directory>(url, token, (body) => {
if (cancel) return;
// The server is still reading a big archive's teams: ask again in a moment (the list keeps loading).
if (body.preparing) {
forget(url);
retry = setTimeout(() => setTeamsTry((n) => n + 1), 4000);
return;
}
setTeams(body.teams);
}).catch((err) => !cancel && guard(err));
cached<Directory>(`/v1/archive/${sourceId}/directory/players`, token, (body) => !cancel && setPlayers(body.players ?? [])).catch(() => !cancel && setPlayers([]));
}
if (tab === "people") cached<PeopleList>(`/v1/archive/${sourceId}/people`, token, (body) => !cancel && setPeople(body)).catch((err) => !cancel && guard(err));
return () => {
cancel = true;
clearTimeout(retry);
};
}, [tab, sourceId, token, guard, attempt]);
}, [tab, sourceId, token, guard, attempt, teamsTry]);
const more = () => {
if (!list || loadingMore) return;
+2
View File
@@ -107,6 +107,8 @@ export interface Directory {
teams: { name: string; galleries: number }[];
/** Named on the photos (a session's folder per athlete, the editors' tags). */
players?: { name: string; club: string | null; photos: number }[];
/** The server is still reading the teams of a big archive: ask again shortly. */
preparing?: boolean;
}
export interface PeopleList {
+17
View File
@@ -0,0 +1,17 @@
"use client";
/**
* Catches render errors anywhere under the root layout (pages, nested layouts) so a transient API or DB
* hiccup shows a retry screen instead of a hard crash. The real error already reached errors.bitreport.pt
* via instrumentation.ts's onRequestError, which fires regardless of this boundary.
*/
export default function Error({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<main className="wrap empty">
<p>Não foi possível carregar esta página. Tenta novamente.</p>
<button type="button" onClick={() => reset()}>
Tentar novamente
</button>
</main>
);
}
+23
View File
@@ -0,0 +1,23 @@
"use client";
import "./globals.css";
/**
* Catches errors thrown by the root layout itself (e.g. getSite() failing for a reason other than
* NotFound). Next only reaches this boundary for root-layout errors, so it must render its own
* html/body — the layout that would normally do that is what just failed.
*/
export default function GlobalError({ reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<html lang="pt">
<body>
<main className="wrap empty">
<p>Não foi possível carregar esta página. Tenta novamente.</p>
<button type="button" onClick={() => reset()}>
Tentar novamente
</button>
</main>
</body>
</html>
);
}
+29 -6
View File
@@ -24,12 +24,18 @@ Following the AP and NPPA codes:
or a point on nobody, the subject is the person in focus, not the biggest one. With a ball in play, the ball and
everyone contesting it come along. Without one, the subject and the sharp people with them (a duel, a
celebration, a line-up).
- **Shape:** the photo's own aspect unless the event or the editor chose another. Peter's usual crop is about two
thirds of the frame; larger only when the subject needs it.
- **Shape:** the photo's own aspect unless the event or the editor chose another (never turned vertical).
- **Framing** (per event):
- **"tight"** (default) is the agencies' handball framing, measured on kolektiff images (600 EHF/IHF photos of
2025-26). The subject is about as tall as the crop, the legs are cut mid-shin or mid-thigh, and the face is
big (a median face of 14% of the frame height) near the top. Whole bodies are kept only when that frames
better.
- **"full"** keeps whole bodies when they fit: Peter's usual crop, about two thirds of the frame.
- **Never cut:** heads, faces, hands holding the ball, the ball itself.
- **Limbs:** if a body has to be cut, cut mid-limb (mid-thigh, mid-shin, mid-forearm), never at a joint (ankle,
knee, hip, wrist, elbow, neck). The engine estimates joints from the body box and avoids crop edges there.
- **Feet:** keep whole bodies when they fit; otherwise cut above the knee rather than at the ankle.
- **Feet:** with "full", keep whole bodies when they fit; otherwise cut above the knee rather than at the ankle.
With "tight", cut mid-shin or mid-thigh, never below the ball.
- **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and
background people don't count.
- **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.
@@ -42,6 +48,8 @@ Following the AP and NPPA codes:
edge of the original (configurable per organisation; agencies often ask for more).
- **Not too much:** if the only crop that works is tighter than the resolution allows, keep the wider frame. A good
photo uncropped beats a bad crop.
- **Not for nothing:** a crop of more than 92% of the width is not made: the photo stays as shot. The agencies
send a fifth to a half of their photos uncropped (Getty, AFP, Paris 2024).
## 3. Bursts (sequences)
@@ -56,8 +64,9 @@ A camera at 10–30 frames per second sends several photos of the same moment.
is the only picture of that moment.
- **Keep:** the best 1–2 frames per burst (configurable), flagged as picks. The rest stay unflagged (never
rejected or deleted automatically).
- **Variety:** when two frames of a burst are kept, the second gets a slightly different crop (tighter or wider) so
the client has a choice.
- **Variety:** when two frames of a burst are kept, the second gets the other framing so the client has a choice.
After a tight first pick, the second gets the wider, whole-body frame with context, as Getty mixes in.
Otherwise the second is slightly tighter.
- **Saturation:** an event can cap how many picks one burst, or one minute of play, may produce, so a long attack
doesn't flood the delivery.
@@ -67,12 +76,26 @@ Per event (and an organisation default), off unless switched on. When on, every
the local FTP of the desktop app or auto-ingest is, in order:
1. analysed (people, ball, focus);
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop.
2. edited: white balance, tone, level (only with a clear horizon or verticals, at most a few degrees), crop,
and the finishing look.
The level reads the advertising boards, stands, posts and railings, never the pitch markings (lines on grass),
which perspective tilts; when those lines disagree the photo is left as it is;
3. scored within its burst; when the burst ends, its best frames are flagged as picks;
4. optionally delivered (rendered with the edits, IPTC from the event) to the event's delivery target.
**Look** (per event, `apps/api/src/autopilot/look.ts`): fixed values on top of the measured tone, the same for
every photo of a match. They never go over a measured control.
- **"agency"** (default): kolektiff's punchy kits. Vibrance +18, saturation +4, clarity +8, texture +6, and
shadows a touch blue-magenta. Every agency measured has that last trait: Getty, AFP and kolektiff all do it.
- **"natural"**: Getty's more natural colour.
- **"none"**: no look.
- **Both looks** add capture sharpening (40, radius 1, masking 35), colour noise reduction, and luminance noise
reduction by ISO (from ISO 1600). There is never a vignette or a local change (§1).
Defaults follow the agencies: white balance on (neutral whites) and 75% of the automatic tone (full range,
pure blacks).
Uploads made by hand in the browser are not touched. Anything the autopilot did can be undone, changed or reset
in Revelar.
+7
View File
@@ -20,6 +20,13 @@ log() { printf '[%s] boot %s: %s\n' "$(date -u +%FT%TZ)" "$SERVICE" "$*"; }
[[ -n "${TMPDIR:-}" ]] && mkdir -p "$TMPDIR" && chmod 700 "$TMPDIR"
export PATH="$HOME/.cargo/bin:/usr/local/bin:$PATH"
# Observed 2026-10-19: a concurrent second run of this script raced `pm2 startOrReload` against a PM2 daemon
# that had just been spawned (empty process list) and lost the "is it already running" check, launching a
# duplicate photoreport-api that crash-looped forever on EADDRINUSE. Serialize with deploy.sh via the same lock
# so a boot racing a webhook-triggered deploy can't do the same thing.
exec 9>/run/photoreport-pm2.lock
flock 9
cd "$REPO_DIR"
SHA="$(git rev-parse HEAD)"
+8 -2
View File
@@ -60,7 +60,11 @@ deploy_api() {
log "WARNING: no Rust toolchain: face analysis and edited renders stay off"
fi
bash infra/faces/download-models.sh "${MODELS_DIR:-/srv/photoreport-data/models}" || log "WARNING: face models could not be downloaded"
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
# Same lock as boot.sh: a reboot racing this deploy's pm2 call against a freshly-spawned, still-empty PM2
# daemon duplicated photoreport-api on 2026-10-19 (crash-looped on EADDRINUSE forever). Serialize instead.
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/api.config.cjs --update-env
)
wait_for_version "http://127.0.0.1:${API_PORT}/health" "$sha"
# The process list PM2 restores after a reboot follows every deploy (photoreport-boot.service starts it too).
pm2 save --force >/dev/null
@@ -120,7 +124,9 @@ deploy_site() {
# from apps/site/.env (that's Next's own, separate env loading) — source it here, same gap
# class as the prisma CLI fix above, so a host's API_URL override actually reaches pm2.
if [[ -f apps/site/.env ]]; then set -a; source apps/site/.env; set +a; fi
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
( exec 9>/run/photoreport-pm2.lock; flock 9
APP_VERSION="$sha" pm2 startOrReload infra/pm2/site.config.cjs --update-env
)
local i
for ((i = 1; i <= HEALTH_TRIES; i++)); do
if curl -fsS --max-time 3 -o /dev/null "http://127.0.0.1:${SITE_PORT:-3100}/"; then pm2 save --force >/dev/null; return 0; fi
+11 -3
View File
@@ -30,9 +30,17 @@ export const AutopilotSettings = z.object({
crop: z.boolean().default(true),
level: z.boolean().default(true),
tone: z.boolean().default(true),
/** How much of the automatic tone to apply (news photos want minimal toning). */
toneStrength: z.number().min(0).max(1).default(0.5),
whiteBalance: z.boolean().default(false),
/** How much of the automatic tone to apply (agencies deliver full-range, contrasty photos: pure blacks, bright whites). */
toneStrength: z.number().min(0).max(1).default(0.75),
/** Neutral whites (white kits, the floor's lines), as the agencies deliver. */
whiteBalance: z.boolean().default(true),
/**
* Crop framing: "tight", the agencies' close handball framing (subject fills the height, legs cut mid-limb, the
* second pick of a burst gets the wider, whole-body frame); "full", whole bodies when they fit.
*/
framing: z.enum(["tight", "full"]).default("tight"),
/** Finishing look (apps/api/src/autopilot/look.ts): "agency" punchy kits, "natural" Getty-like, "none". */
look: z.enum(["agency", "natural", "none"]).default("agency"),
/** Crop shape (width, height); null: the photo's own. */
aspect: z.tuple([z.number().positive(), z.number().positive()]).nullable().default(null),
/** The crop keeps at least this many pixels on its long edge of the original. */
+11 -1
View File
@@ -1,5 +1,5 @@
import type { BundleInput, BundleSummary, PressAccountInput, PressAccountSummary, PressStatement, NotificationView, AffiliateInput, AffiliateSummary, EarningsOverview, EarningsSettings, MemberPayoutInput, MyEarnings, PayeeAccount, PayoutInput, PayoutView, CodeGeneratorSettings, CodeLine, ConfirmFaceGroup, DeliveryItemSummary, DevelopState, EditLogEntry, FaceGroupSummary, GalleryInput, GalleryPhotosChange, GallerySummary, Module, OrderView, PhotoPatch, PhotoSummary, PostEdits, PrinterSummary, PrintEventInput, PrintEventSummary, PrintJobSummary, ProductInput, ProofingReport, ProductSummary, SiteInfo, SiteInput, StationSummary } from "@photoreport/contracts";
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
import type { AgendaEntry, ArchiveStorage, CardScan, FaceIdentify, CloudFolderSummary, CloudSource, CloudTreeFolder, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, FtpTargetAccount, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
/**
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
@@ -808,6 +808,16 @@ export class ApiClient {
return this.request<Pick<CloudFolderSummary, "id" | "matchedBy" | "event">>("PUT", `/v1/cloud-folders/${folderId}/event`, target);
}
/** The folders an editor chooses to show on the public site. Not used by the site itself. */
cloudFolderTree(sourceId: string) {
return this.request<{ folders: CloudTreeFolder[] }>("GET", `/v1/cloud-sources/${sourceId}/tree`);
}
/** Publishes or hides a folder and everything inside it. */
setCloudFolderPublished(folderId: string, published: boolean) {
return this.request<{ published: boolean; updated: number }>("PUT", `/v1/cloud-folders/${folderId}/published`, { published });
}
// ---- delivery --------------------------------------------------------------------------------------
listDeliveryTargets(orgId: string) {
+9
View File
@@ -461,6 +461,15 @@ export interface ArchiveStorage {
paused: boolean;
}
/** One folder in the app's publish tree. The public site never sees this list. */
export interface CloudTreeFolder {
id: string;
/** From the source's root, without a leading slash. */
path: string;
published: boolean;
photoCount: number;
}
export interface CloudFolderSummary {
id: string;
/** From the source's root. */