Compare commits

..
Author SHA1 Message Date
spark 5c4b4e5195 Faces: a requested event jumps the analysis queue.
ci / rust (pull_request) Successful in 7m53s
ci / typescript (pull_request) Successful in 9m57s
The backlog is oldest-first, so a game someone asks to analyse now never starts. Boosted photos are claimed first, and the library says when the face worker is not running.
2026-10-17 15:40:08 +01:00
spark 2190cecbd2 Merge pull request 'fix(api): do not crash the process on the known undici socket-end assertion (BIT-31305)' (#7) from task/BIT-31305-undici-socket-end-assertion-guard into main
ci / rust (push) Successful in 4m9s
ci / typescript (push) Successful in 7m18s
2026-10-17 14:30:55 +01:00
tiago-neves 6d37b9b541 fix(api): do not crash the process on the known undici socket-end assertion
ci / rust (pull_request) Successful in 3m55s
ci / typescript (pull_request) Successful in 7m28s
A single-occurrence critical alert (BIT-31305) traced to node09 CT 264: the
worker crashed with AssertionError [ERR_ASSERTION]: false == true at
Parser.finish in Node's bundled undici. That is nodejs/undici#5360 -- the
HTTP/1 parser asserts !this.paused when the remote socket ends while the
parser is paused for backpressure, and throws uncatchably from the socket
end handler. pm2 already restarted the worker within the same second, but
watchProcess() was also killing the whole process (and losing any other
in-flight work) for this one already-closed connection.

Recognize the narrow ERR_ASSERTION + undici + Parser.finish signature in
watchProcess() and report it as a warning without exiting; every other
uncaught exception still fails fast as before.

Paperclip-Issue: BIT-31305
Paperclip-Run: 02f17eaf-2939-43e0-93b2-f6d047452558
2026-10-17 14:23:59 +01:00
spark 29d437fb62 Merge pull request 'Ingest: tolerate truncated JPEGs when making previews and reads' (#4) from task/ingest-truncated-jpeg into main
ci / rust (push) Successful in 6m10s
ci / typescript (push) Successful in 8m56s
2026-10-17 10:30:57 +01:00
spark 649521f7b4 Merge pull request 'Library: send up to three originals at a time from the desktop app' (#5) from task/ingest-original-responder-serial into main
ci / rust (push) Successful in 11m15s
ci / typescript (push) Successful in 13m34s
2026-10-17 10:30:53 +01:00
spark 4f3ed9ace8 Ingest: tolerate truncated JPEGs when making previews and reads
ci / rust (pull_request) Successful in 10m45s
ci / typescript (pull_request) Successful in 13m15s
An interrupted upload still has a usable image. sharp's default warning-as-error
drops the photo before composition and jersey reads can run.
2026-10-17 10:26:47 +01:00
spark 8ba9f61619 Library: send up to three originals at a time from the desktop app
ci / rust (pull_request) Successful in 10m58s
ci / typescript (pull_request) Successful in 14m3s
One at a time is slow when ZeroZero asks for a whole game. Three keeps the
webview responsive and still sends a file Photo Mechanic has rewritten.
2026-10-17 10:26:47 +01:00
1sonhador 1fa97ca3bb Keep ZeroZero uploads alive when the worker is busy.
ci / rust (push) Successful in 4m11s
ci / typescript (push) Successful in 7m20s
Cap face analysis at what one Node thread can commit, prefer IPv4 so a dead IPv6 route cannot fail the fetch, and leave a photo on the desk when ZeroZero says it is already there. Desktop originals go out one at a time so the app does not freeze on "A enviar…".
2026-10-15 20:14:04 +01:00
root 673a06c9dd Fix ZeroZero delivery stalling behind local exports and parallel uploads.
ci / rust (push) Successful in 4m37s
ci / typescript (push) Successful in 7m42s
The shared ZeroZero session was used by many deliveries at once, and a photo the desk already had was retried as a failure. Live targets now go ahead of a computer folder.
2026-10-15 19:13:30 +01:00
sparkandClaude Opus 5.5 0b56ba8c4c Delivery: a delivered photo edited again is sent again (ZeroZero: old one taken back)
ci / rust (push) Successful in 4m20s
ci / typescript (push) Successful in 7m1s
Once the edits of a delivered photo pause for a minute, it goes again to every destination it went to, with the same name: files are replaced; on ZeroZero the new image goes up and the previous one is deleted. Originals' backups are not resent; deliveries made before count as current.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 14:37:36 +01:00
spark 0736d34f4d Merge pull request 'fix(api): swallow EPIPE on dead worker stdin write (BIT-31194)' (#3) from fix/BIT-31194-line-process-epipe into main
ci / rust (push) Successful in 8m53s
ci / typescript (push) Successful in 11m26s
2026-10-15 06:26:47 +01:00
tiago-neves 685e864d62 fix(api): swallow EPIPE on dead worker stdin write (BIT-31194)
ci / rust (pull_request) Successful in 9m6s
ci / typescript (pull_request) Successful in 11m34s
LineProcess.request() writes JSON requests to the worker child process stdin
(line-process.ts:80). When the worker dies mid-request the write can race the
exit handler and hit the pipe after it's already broken, raising EPIPE. With
no "error" listener on child.stdin, that EPIPE was an unhandled stream error
and crashed the whole API process. Attach a no-op error listener on stdin;
the existing "exit" handler already rejects any pending requests for that
worker, so callers still see a clean rejection instead of a process crash.

Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f)
Paperclip-Issue: BIT-31194
Paperclip-Run: de3027ac-866e-4c9d-919b-6f21ff532c3d
2026-10-15 06:25:31 +01:00
sparkandClaude Opus 5.5 01b943169d Archive: check a cloud's games again on demand and see what changed
ci / rust (push) Successful in 6m1s
ci / typescript (push) Successful in 9m48s
"Rever jogos" / "Rever tudo" on a cloud's galleries runs the check now (games still to come first, then the official games, or everything) and lists every gallery that changed and any it could not check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 04:59:07 +01:00
sparkandClaude Opus 5.5 f0ee1e24f3 Archive: galleries on a game still to come moved first, official games checked before the rest
ci / rust (push) Successful in 4m17s
ci / typescript (push) Successful in 7m40s
The check on start now first takes every gallery off a game still to come (one query, every cloud), then rechecks every cloud's official games, then the rest: a restart midway no longer leaves one cloud unchecked behind another cloud's thousands of folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 04:18:48 +01:00
sparkandClaude Opus 5.5 303aedef80 Archive: both teams or no game, legends are events, every match redone; faces keep to the sport
ci / rust (push) Successful in 4m19s
ci / typescript (push) Successful in 7m38s
A folder is matched to an official game only when both teams are recognised (never a first team for its B side); legends', veterans', charity and exhibition games never get a championship fixture; every match but a manual one is made again on start and every six hours (one failing folder never stops the rest), renaming events to clean team names. The viewer merges teams written with dates before them and known teams under one name. Faces are never suggested as someone of another sport, and old such suggestions are taken away. Visible loading in the archive site. More archive work at once (previews, images in flight, face processes).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 03:49:08 +01:00
sparkandClaude Opus 5.5 ea63b30452 Delivery: the central FTP as a relay to a computer (chosen logins, untouched originals)
ci / rust (push) Successful in 4m19s
ci / typescript (push) Successful in 7m12s
An every-arrival destination can take only some FTP logins' photos, and with "untouched" the original goes byte for byte as the camera sent it, with its own name, into the folder a local Photo Mechanic Live Ingest watches. The photo still enters PhotoReport as any FTP arrival.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 03:13:53 +01:00
sparkandClaude Opus 5.5 52d340ef43 Archive: past FPA seasons read club by club; games apart from events
ci / rust (push) Successful in 4m10s
ci / typescript (push) Successful in 7m9s
The archive reads the FPA national games of any season it meets (club by club from today's agenda, following every club met, regional games left out), in the background in the worker, then matches every gallery again. Galleries split into official games, games known by their folder only, and events; events read no shirt numbers (faces only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 03:06:32 +01:00
sparkandClaude Opus 5.5 04137476ff Photo Mechanic compatibility: all its variables and modifiers, its full IPTC pad, camera details
ci / rust (push) Successful in 4m27s
ci / typescript (push) Successful in 7m27s
Templates (IPTC pad, folders, file names, rename on arrival) take every variable of Photo Mechanic's list under its names and short names, in any case, with its modifiers (substrings, lc/UC/PC, tr:find/repl). IPTC variables are the photo's pad, as in Photo Mechanic. The pad gains every Photo Mechanic field with the same IIM/XMP tags, read back from incoming files. Camera details (exposure compensation, flash, metering, program, white balance, 35mm, lens range, firmware, owner, artist, GPS) are kept in photos.exif at ingest and read from the file at delivery for older photos.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 02:43:43 +01:00
sparkandClaude Opus 5.5 7675edb6c6 Archive: never a game still to come; date galleries by their photos; re-check every gallery
ci / rust (push) Successful in 4m9s
ci / typescript (push) Successful in 7m5s
Galleries were matched to Liga games of January/February 2027 and a name event was dated 2028. Fixtures not yet played are never candidates; a folder date in the future is read the other way (23.09.28 -> 2023-09-28) or ignored, and name events are never dated ahead. A folder whose name has no day is dated by its photos' camera time (captureDay: 3+ photos, 60%+ on one Lisbon day); a date in the name always wins. Every walk, and on start for all clouds (verifyAll), FIXTURE galleries dated ahead, or (no day in the name) on another day than their photos, are taken off that game for good.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 02:16:50 +01:00
sparkandClaude Opus 5.5 f578bdd15c Delivery: originals backup (untouched originals, IPTC written) and every arrival sent on its own
ci / rust (push) Successful in 4m14s
ci / typescript (push) Successful in 7m8s
A destination can take the originals as they arrived (no resizing or recompression; IPTC written by exiftool; renamed by the templates), like Photo Mechanic's Live Ingest destination, and every arrival (FTP, desktop, uploads, once in an event) can be queued to it on its own. On a LOCAL destination: one's own backup in a folder on the computer, e.g. /Users/cyclop/Desktop/2026/{iptcdate} - {event}/PS_{event}_{timesort}.jpg. Adds {iptcdate} (CCYYMMDD).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 02:08:37 +01:00
sparkandClaude Opus 5.5 11460968e4 Events: edit times and photographers, archive, delete (photos kept), Receber FTP aqui
ci / rust (push) Successful in 4m29s
ci / typescript (push) Successful in 7m15s
An "Evento" panel on the open event: FTP logins can send everything to it whatever the camera clock says, until the event ends or switched off (ftp_accounts.target_event_id/target_until; editors any login, photographers their own); start, ingest window and photographers; archive / unarchive; delete, with its photos back in Sem evento (archive games cannot be deleted). The list shows the last 4 days, upcoming and FTP-receiving events, the rest under Anteriores, and put-away events under Arquivados.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 01:57:32 +01:00
spark 087aabc72b Merge pull request 'fix(api): drain worker before Prisma pool end (BIT-31189)' (#2) from fix/BIT-31189-prisma-pool-after-end into main
ci / rust (push) Successful in 10m12s
ci / typescript (push) Successful in 11m54s
2026-10-15 01:31:39 +01:00
sparkandClaude Opus 5.5 19ccaf76f5 Archive: never add to live events; stricter game matching; take wrong folders back out
ci / rust (push) Successful in 10m25s
ci / typescript (push) Successful in 12m11s
Archive photos ended up in a live event (SC Braga x Sporting CP) from other games. The archive now keeps to its own events (never a library event, even for the same fixture); name events only join archive events of the same day, never by the cloud folder's date; a fixture needs a dated folder or competition+season+matchday, and reserve/youth/women's sides never match the first team. A FIXTURE folder whose photos were taken more than 36 h from the game is taken off it for good (cloud_folders.fixture_rejected). On start the worker moves folders out of live events (leaveLiveEvents), their CLOUD photos with them (faces found again), keeping photos that were already there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 01:31:16 +01:00
CI Runner c28aae2740 fix(api): drain worker jobs before Prisma pool disconnect (BIT-31189)
ci / typescript (pull_request) Failing after 7s
ci / rust (pull_request) Successful in 9m16s
PM2 max_memory SIGINT was ending the Prisma/pg pool while archive and
delivery jobs still queried it, flooding "Cannot use a pool after calling
end". Await idle on all loop workers before $disconnect, and raise the
worker memory/kill_timeout so burst indexing does not restart every few
minutes.

Paperclip-Agent: David Santos (urlKey founding-engineer; id 0b1fcf92-5fe3-4ac0-9f29-df4ab72f5376)
Paperclip-Issue: BIT-31189
Paperclip-Run: 61448079-9293-4b3b-989d-b5857bf058c1
2026-10-15 01:30:06 +01:00
sparkandClaude Opus 5.5 4741aa3c53 Faces: shirt numbers by season and competition, never club numbers for the national team
ci / rust (push) Successful in 4m31s
ci / typescript (push) Successful in 7m34s
A person's number is read for the event's context (faces/numbers.ts): that season's squad, then what the shirts clearly read in their confirmed photos of the same season and competition (first when the game is not an official match), and the number typed on the person only in the current season and never for a national team. Used for face/number agreement, squad suggestions and the shirt-sample labels (which never take the model's own readings).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 01:02:44 +01:00
sparkandClaude Opus 5.5 4b7cca0556 Archive looks: owner's name on top, themed photo view, phones
ci / rust (push) Successful in 4m56s
ci / typescript (push) Successful in 7m31s
The band names the owner (Liga Portugal, Federação de Andebol de Portugal) with the session, the page is the photo archive (not the source's technical name). Large photo, people, teams and the gallery page in the look's colours; cards as top-aligned panels; phone layout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 00:48:36 +01:00
sparkandClaude Opus 5.5 1e4d910cfd Archive sites in their owner's look: Liga Portugal and FPA
ci / rust (push) Successful in 4m22s
ci / typescript (push) Successful in 7m11s
cloud_sources.look (liga, fpa or none), set from the source's name or folder and changeable in the app. The archive site wears Liga Portugal's (night blue, orange, condensed capitals) or the FPA's (light grey, red bar, Open Sans capitals) colours and type; no marks or logos of theirs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 00:28:02 +01:00
sparkandClaude Opus 5.5 26d317e017 Archive: read clouds from a local mount, more downloads in flight
ci / rust (push) Successful in 6m35s
ci / typescript (push) Successful in 8m53s
WebDAV through Nextcloud's PHP is what holds a big import back (CPUs idle). ARCHIVE_LOCAL_DIRS maps a cloud folder to its data on a read-only mount; files there are read from disk, the rest downloaded as before. Downloads in flight: up to 4 per CPU (192).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 00:16:00 +01:00
sparkandClaude Opus 5.5 82add5ed93 Archive: share the index worker fairly between clouds
ci / rust (push) Successful in 4m19s
ci / typescript (push) Successful in 7m29s
Each cloud with pending photos gets its share of every claim, so a big newer-season backlog (Liga) no longer starves another cloud (FPA).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-15 00:03:38 +01:00
sparkandClaude Opus 5.5 a24ac0bae6 Archive: many downloads in flight, previews by the CPUs; pace and time left on screen
ci / rust (push) Successful in 4m13s
ci / typescript (push) Successful in 7m25s
Indexing waits mostly on the cloud's download: a big backlog keeps 16-96 images in flight,
while only the CPU share makes previews at once. A fixed ARCHIVE_CONCURRENCY no longer
holds the backlog pace down. The Arquivo page shows photos per hour and the time left.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-14 23:49:18 +01:00
spark 6bd78762dc Merge pull request 'fix(api): ignore realtime publish after pg pool end (BIT-31177)' (#1) from fix/BIT-31177-pg-pool-after-end into main
ci / rust (push) Successful in 7m3s
ci / typescript (push) Successful in 8m52s
Merge PR #1: fix(api): ignore realtime publish after pg pool end (BIT-31177)
2026-10-14 23:30:14 +01:00
94 changed files with 5271 additions and 535 deletions

No files matched your search

@@ -0,0 +1,5 @@
-- How each archive's site looks (its owner's colours and type).
ALTER TABLE "cloud_sources" ADD COLUMN "look" TEXT;
UPDATE "cloud_sources" SET "look" = 'liga' WHERE "name" ~* 'liga' OR "root_path" ~* 'liga';
UPDATE "cloud_sources" SET "look" = 'fpa' WHERE "look" IS NULL AND ("name" ~* 'fpa|andebol' OR "root_path" ~* 'fpa|andebol');
@@ -0,0 +1,2 @@
-- A folder whose photos were taken on another day than the official game it was matched to.
ALTER TABLE "cloud_folders" ADD COLUMN "fixture_rejected" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,5 @@
-- "Receber FTP aqui": an FTP login sends everything to one event until a time.
ALTER TABLE "ftp_accounts" ADD COLUMN "target_event_id" UUID;
ALTER TABLE "ftp_accounts" ADD COLUMN "target_until" TIMESTAMP(3);
ALTER TABLE "ftp_accounts" ADD CONSTRAINT "ftp_accounts_target_event_id_fkey" FOREIGN KEY ("target_event_id") REFERENCES "events"("id") ON DELETE SET NULL ON UPDATE CASCADE;
CREATE INDEX "ftp_accounts_target_event_id_idx" ON "ftp_accounts"("target_event_id");
@@ -0,0 +1,3 @@
-- A destination for the originals as they arrived (one's own backup), and sending every arrival on its own.
ALTER TABLE "delivery_targets" ADD COLUMN "originals" BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE "delivery_targets" ADD COLUMN "on_arrival" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,2 @@
-- The rest of the camera's EXIF, for Photo Mechanic's variables.
ALTER TABLE "photos" ADD COLUMN "exif" JSONB;
@@ -0,0 +1,3 @@
-- Arrivals of chosen FTP logins only, and originals exactly as they arrived (the central FTP as a relay).
ALTER TABLE "delivery_targets" ADD COLUMN "arrival_logins" UUID[] NOT NULL DEFAULT '{}';
ALTER TABLE "delivery_targets" ADD COLUMN "untouched" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,5 @@
-- A delivered photo edited again is sent again: which edit each delivery shows, and what a new send replaces.
ALTER TABLE "delivery_items" ADD COLUMN "delivered_seq" INTEGER;
ALTER TABLE "delivery_items" ADD COLUMN "replaces_path" TEXT;
-- What is already delivered counts as showing the photo as it is now (no wave of sends on deploy).
UPDATE "delivery_items" di SET "delivered_seq" = p."develop_seq" FROM "photos" p WHERE p."id" = di."photo_id" AND di."status" IN ('DONE', 'WAITING');
@@ -0,0 +1,6 @@
-- Someone asking to analyse one event jumps its photos ahead of the oldest-first backlog.
ALTER TABLE "events" ADD COLUMN "face_boosted_at" TIMESTAMP(3);
ALTER TABLE "photos" ADD COLUMN "faces_boosted_at" TIMESTAMP(3);
DROP INDEX "photos_faces_pending_idx";
CREATE INDEX "photos_faces_pending_idx" ON "photos" ("faces_boosted_at" DESC NULLS LAST, "created_at") WHERE "faces_status" = 'PENDING';
+32
View File
@@ -254,6 +254,8 @@ model Event {
iptcTemplate Json @map("iptc_template")
/// Autopilot settings (contracts AutopilotSettings); null: off.
autopilot Json?
/// Set when someone asks to analyse this event now: its photos jump the face queue (the backlog is oldest-first).
faceBoostedAt DateTime? @map("face_boosted_at")
/// The official match this event covers, and its teams (squads, names for codes, faces and numbers).
fixtureId String? @map("fixture_id") @db.Uuid
homeTeamId String? @map("home_team_id") @db.Uuid
@@ -275,6 +277,8 @@ model Event {
faceGroups FaceGroup[]
galleries Gallery[]
cloudFolders CloudFolder[]
/// FTP logins sending everything to this event, whatever the camera's clock says ("Receber FTP aqui").
ftpTargets FtpAccount[]
@@index([organizationId, startsAt])
@@map("events")
@@ -310,12 +314,17 @@ model FtpAccount {
planId String? @map("plan_id") @db.Uuid
/// The login stops working after this (from the plan's days, or set by hand); null: never.
expiresAt DateTime? @map("expires_at")
/// Everything this login sends goes to this event (chosen in the library), until `targetUntil`; else by the time.
targetEventId String? @map("target_event_id") @db.Uuid
targetUntil DateTime? @map("target_until")
createdAt DateTime @default(now()) @map("created_at")
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
plan FtpPlan? @relation(fields: [planId], references: [id], onDelete: SetNull)
targetEvent Event? @relation(fields: [targetEventId], references: [id], onDelete: SetNull)
@@index([targetEventId])
@@map("ftp_accounts")
}
@@ -372,6 +381,9 @@ model Photo {
aperture Float?
exposureTime Float? @map("exposure_time")
iso Int?
/// The rest of the camera's EXIF Photo Mechanic shows (exposure compensation, flash, metering, program, white
/// balance, 35 mm focal length, lens range, owner, artist, GPS...): src/ingest/exif.ts CameraExtra.
exif Json?
rating Int @default(0)
flag PhotoFlag @default(NONE)
colorLabel ColorLabel @default(NONE) @map("color_label")
@@ -383,6 +395,8 @@ model Photo {
embeddedIptc Json? @map("embedded_iptc")
/// Face analysis: NONE (organization without biometrics), PENDING, DONE or FAILED.
facesStatus FacesStatus @default(NONE) @map("faces_status")
/// When the event was asked to the front of the face queue. Null waits behind every boosted photo.
facesBoostedAt DateTime? @map("faces_boosted_at")
/// Autopilot queue (docs/photo-editing-rules.md): NONE unless the event's autopilot took this photo.
autopilotStatus FacesStatus @default(NONE) @map("autopilot_status")
/// What the autopilot saw and did: subject, crop, angle, frame score, burst decision.
@@ -532,6 +546,16 @@ model DeliveryTarget {
dpi Int @default(300)
keepExif Boolean @default(true) @map("keep_exif")
srgb Boolean @default(false)
/// The original as it arrived (no resizing, no recompression), with the metadata written into it and renamed:
/// a copy for one's own backup, like Photo Mechanic's Live Ingest destination.
originals Boolean @default(false)
/// Every photo that arrives (FTP, the desktop app, uploads) is sent here on its own, as soon as it is in an event.
onArrival Boolean @default(false) @map("on_arrival")
/// With `onArrival`: only the photos of these FTP logins (ids; empty: everyone's). The central FTP then works as
/// a relay to a photographer's computer, as if the camera had sent to the FTP there.
arrivalLogins String[] @default([]) @map("arrival_logins") @db.Uuid
/// With `originals`: the file exactly as it arrived (no metadata written), for a local Live Ingest to take.
untouched Boolean @default(false)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
disabledAt DateTime? @map("disabled_at")
@@ -556,6 +580,10 @@ model DeliveryItem {
attempts Int @default(0)
lastError String? @map("last_error")
remotePath String? @map("remote_path")
/// The photo's edit (op-log sequence) the delivered file shows: edited again after it, it is sent again.
deliveredSeq Int? @map("delivered_seq")
/// Being sent again after an edit: where the previous version is (taken back on ZeroZero once the new one is up).
replacesPath String? @map("replaces_path")
byteSize Int? @map("byte_size")
requestedById String? @map("requested_by_id") @db.Uuid
nextAttemptAt DateTime @default(now()) @map("next_attempt_at")
@@ -1562,6 +1590,8 @@ model CloudSource {
ownerId String? @map("owner_id") @db.Uuid
/// LOGIN (waiting for the person to authorise), READY, SCANNING, ERROR, PAUSED.
status String @default("LOGIN")
/// How the archive's site looks: "liga" (Liga Portugal), "fpa" (Federação de Andebol), or null (PhotoReport).
look String?
/// Nextcloud login flow v2: where to poll for the app password while status is LOGIN (sealed token).
loginPoll String? @map("login_poll")
loginExpires DateTime? @map("login_expires")
@@ -1594,6 +1624,8 @@ model CloudFolder {
eventId String? @map("event_id") @db.Uuid
/// How the event was found: FIXTURE (the official game), NAME (from the folder name), MANUAL, or null.
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")
seenAt DateTime @default(now()) @map("seen_at")
createdAt DateTime @default(now()) @map("created_at")
+8 -2
View File
@@ -32,6 +32,7 @@ import { registerFaceRoutes } from "./faces/routes.js";
import { FaceLookup, IdleEngine } from "./faces/lookup.js";
import { registerLookupRoutes } from "./faces/lookupRoutes.js";
import { type FaceEngine, FaceProcess } from "./faces/process.js";
import { faceWorkerLive } from "./faces/heartbeat.js";
import { faceEnginePaths } from "./lib/engines.js";
import { registerJerseyRoutes } from "./jersey/routes.js";
import { JerseyService } from "./jersey/service.js";
@@ -73,13 +74,15 @@ export interface AppDeps {
reporter?: ErrorReporter;
/** The face engine for search by photo (tests pass a fake; otherwise the built engine, started on demand). */
faceEngine?: FaceEngine;
/** Whether the worker is running face analysis. Tests set this; otherwise a heartbeat file next to storage. */
engineOnline?: () => boolean;
}
/**
* Builds the API. Modules (ingest, library, oplog, galleries, sales, events, print, delivery) register here as
* they are built.
*/
export async function buildApp({ config, db, realtime, fetchImpl, reporter: given, faceEngine }: AppDeps): Promise<FastifyInstance> {
export async function buildApp({ config, db, realtime, fetchImpl, reporter: given, faceEngine, engineOnline }: AppDeps): Promise<FastifyInstance> {
const reporter = given ?? reporterFor(config);
const app = Fastify({
// Error lines (and warnings carrying an error) also go to errors.bitreport.pt.
@@ -139,10 +142,13 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give
await registerSearchRoutes(app, { db, sessions, signer });
await registerFtpRoutes(app, { db, sessions, ingestRoot: config.INGEST_ROOT, hookSecret: config.SFTPGO_HOOK_KEY });
const ingest = new IngestService({ db, storage, signer, broadcaster, ingestRoot: config.INGEST_ROOT, log: app.log });
ingest.arrivals = (photo) => delivery.queueArrival(photo);
await registerUploadRoutes(app, { db, sessions, ingest, storage, signer });
// The API never runs the face engine: it confirms and merges groups; the worker detects and groups.
const faces = new FaceService({ db, storage, broadcaster, log: app.log });
await registerFaceRoutes(app, { db, sessions, faces, signer, storage });
// The worker writes the heartbeat. Tests have no worker, so they say the engine is on unless a case says otherwise.
const facesOnline = engineOnline ?? (() => (config.NODE_ENV === "test" ? true : faceEnginePaths(config) !== null && faceWorkerLive(config.STORAGE_ROOT)));
await registerFaceRoutes(app, { db, sessions, faces, signer, storage, engineOnline: facesOnline });
// Search by photo (library and "Encontra-te" on the sites): the API's own face engine, started on demand.
const facePaths = faceEnginePaths(config);
const lookupEngine = new IdleEngine(
+88 -15
View File
@@ -198,6 +198,13 @@ export function parseFolder(path: string): FolderGame | null {
}
const fullYear = (y: string) => (y.length === 2 ? `20${y}` : y);
/** A real calendar day ("2023-02-30" is not). */
const validDay = (day: string) => {
const d = new Date(`${day}T12:00:00Z`);
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === day;
};
/** Today or before (Lisbon), with a day's margin: photos are never of a day still to come. */
export const pastOrToday = (day: string, now = new Date()) => new Date(`${day}T00:00:00Z`).getTime() <= now.getTime() + 86_400_000;
const pad = (n: string) => n.padStart(2, "0");
function parseGameFolder(parts: string[]): FolderGame | null {
@@ -213,8 +220,13 @@ function parseGameFolder(parts: string[]): FolderGame | null {
day = `${m[1]}-${m[2]}-${m[3]}`;
rest = m[4]!;
} else if ((m = /^(\d{1,2})[.\-/](\d{1,2})[.\-/](\d{4}|\d{2})\s*[-–_]?\s*(.+)$/.exec(rest)) && Number(m[2]) >= 1 && Number(m[2]) <= 12 && Number(m[1]) <= 31) {
// "04.11.2023 Mafra vs Leixões"
// "04.11.2023 Mafra vs Leixões"; "23.09.28" is the 28th of September 2023 written year first when read the
// other way would be a day still to come (photos are never of a game that has not happened).
day = `${fullYear(m[3]!)}-${pad(m[2]!)}-${pad(m[1]!)}`;
if (m[3]!.length === 2 && !pastOrToday(day) && Number(m[3]) <= 31) {
const yearFirst = `${fullYear(m[1]!.padStart(2, "0"))}-${pad(m[2]!)}-${pad(m[3]!)}`;
if (validDay(yearFirst) && pastOrToday(yearFirst)) day = yearFirst;
}
rest = m[4]!;
} else if ((m = /^(\d{1,2})[.\-/](\d{4}|\d{2})\s+(.+)$/.exec(rest)) && Number(m[1]) >= 1 && Number(m[1]) <= 12) {
// "01.2024 Nacional", "02.23 SC Covilhã": the month, and the opponent
@@ -225,6 +237,9 @@ function parseGameFolder(parts: string[]): FolderGame | null {
rest = m[2]!;
numbered = true;
}
// A date still to come is not the day of these photos: read as if it had none.
if (day && (!validDay(day) || !pastOrToday(day))) day = null;
if (month && !pastOrToday(`${month}-01`)) month = null;
let teams = teamsIn(rest, !!(day || month || numbered));
let single = false;
// One club after a date is how the Liga's photographers write ("04.11.2023 Mafra", "01.2024 Nacional"); after
@@ -282,6 +297,16 @@ function countryName(name: string): string {
return COUNTRIES[fold(name)] ?? name;
}
let countryNames: Set<string> | null = null;
/** A national team's side ("Portugal", "POR", "Seleção Nacional A") rather than a club. */
export function isNationalSide(name: string | null | undefined): boolean {
if (!name) return false;
const n = fold(name.trim());
countryNames ??= new Set(Object.values(COUNTRIES).map(fold));
return !!COUNTRIES[n] || countryNames.has(n) || /sele[cç][aãoõ]/i.test(name);
}
/** A national teams' game: under a national team's folder, or Portugal on one side. */
function isNational(teams: { home: string; away: string }, parts: string[]): boolean {
const portugal = (s: string) => countryName(s) === "Portugal";
@@ -290,7 +315,7 @@ function isNational(teams: { home: string; away: string }, parts: string[]): boo
}
/** The season a day falls in (July to June): "2024-01-20" → "20232024". */
function seasonOf(day: string): string {
export function seasonOf(day: string): string {
const [y, mo] = day.split("-").map(Number) as [number, number];
const start = mo >= 7 ? y : y - 1;
return `${start}${start + 1}`;
@@ -338,9 +363,17 @@ export function isInitials(short: string, name: string): boolean {
}
/** A folder's team name against a team: its name ("Sporting CP"), abbreviation ("SCP"), initials or slug. */
/** A reserve, youth or women's side named ("Benfica B", "Sporting Sub-23", "ABC Feminino"). */
export const isVariantSide = (s: string) =>
/\b(b|sub[\s-]?\d{2}|u[\s-]?\d{2}|feminin[oa]s?|fem\.?|juniores|juvenis|iniciados|infantis|benjamins|revela[cç][aã]o)\b/i.test(
s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
);
export function isTeam(name: string, team: { name: string; abbreviation: string | null; slug: string }): boolean {
const n = fold(name);
if (!n) return false;
// "SL Benfica" is never "SL Benfica B", nor the other way round.
if (isVariantSide(name) !== isVariantSide(team.name) && fold(team.abbreviation ?? "") !== n) return false;
if (team.abbreviation && fold(team.abbreviation) === n) return true;
if (fold(team.slug) === n || fold(team.name) === n) return true;
if (sameTeam(name, team.name)) return true;
@@ -360,7 +393,44 @@ export const lisbonDay = (d: Date) => new Intl.DateTimeFormat("en-CA", { timeZon
* The official game of a folder among candidate fixtures: same teams (home and away, or swapped as a last resort),
* then the same day, or the same competition, season and matchday. Null when not exactly one fits.
*/
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[]): FixtureCandidate | null {
/**
* Games outside any official competition: legends' and veterans' tournaments, charity, exhibition and tribute games,
* galas. They are events with games in them, never matched to a championship's fixture.
*/
const EXHIBITION = /\b(legends?|lendas|veteranos|old ?boys|solidari[oa]|beneficen[ct]i?a|exibi[cç][aã]o|homenagem|despedida|gala|festa|showcase|all[ -]?stars?)\b/i;
const isExhibitionName = (x: string) => EXHIBITION.test(x.normalize("NFD").replace(/[\u0300-\u036f]/g, ""));
export function isExhibition(game: Pick<FolderGame, "home" | "away" | "parents">): boolean {
return [game.home, game.away, ...game.parents].some((x) => !!x && isExhibitionName(x));
}
/** The tournament or occasion an exhibition game belongs to ("Liga Portugal Legends 2025-26"), from the folders above. */
export function exhibitionName(game: Pick<FolderGame, "parents">): string | null {
return game.parents.find(isExhibitionName)?.trim() ?? null;
}
/** 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
.replace(/\(c[oó]pia(r)?\)/gi, " ")
.replace(/\s+/g, " ")
// The numbers, dates and separators before the name ("10 .22 ", "02_", "01.2023 "), never a name's own "1º".
.replace(/^[\d\s._-]*\d[\d._-]*[\s._-]+(?=\S)/, "")
.trim();
}
/**
* 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 {
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;
}
export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[], now = new Date()): FixtureCandidate | null {
// A game still to be played has no photos yet.
fixtures = fixtures.filter((f) => f.startsAt.getTime() <= now.getTime() + 6 * 3600_000);
const fits = (f: FixtureCandidate) => {
if (game.competition && f.competition.externalId.toUpperCase() !== game.competition.toUpperCase()) return false;
if (game.season && f.season.replace(/\D/g, "") !== game.season) return false;
@@ -372,6 +442,20 @@ export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[]): Fix
} else if (game.round && f.round && String(Number(/\d+/.exec(f.round)?.[0] ?? "")) !== game.round) return false;
return true;
};
// Only a dated folder, or one placed in its competition, season and matchday ("LPBetclic 26-27/Jornada 5"), is an
// official game: a season, a month or a matchday alone says too little (the same pairing is played again, by the
// B team, the youth, the women), and a wrong game is worse than none.
if (isExhibition(game)) return null;
const placed = !!(game.competition && game.season && game.round);
if (!game.day && !placed && !(game.single && game.month)) return null;
// A reserve, youth or women's side ("Sporting B", "Sub-23", "Feminino") is never the first team's game.
const variant = (s: string) =>
/\b(b|sub[\s-]?\d{2}|u[\s-]?\d{2}|feminin[oa]s?|fem\.?|juniores|juvenis|iniciados|infantis|benjamins|revela[cç][aã]o|liga 3|camp\.? de portugal)\b/i.test(
s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
);
if ([game.home, game.away, ...game.parents].some((x) => x && variant(x))) {
fixtures = fixtures.filter((f) => [f.homeTeam.name, f.awayTeam.name, f.competition.externalId].some((x) => variant(x)));
}
const pool = fixtures.filter(fits);
if (game.single) {
// One club named ("01.2024 Nacional"): its game that day/month, against the club a folder above names if any.
@@ -389,17 +473,6 @@ export function pickFixture(game: FolderGame, fixtures: FixtureCandidate[]): Fix
const same = found.filter((f) => lisbonDay(f.startsAt) === game.day);
if (same.length === 1) return same[0]!;
}
// One side not recognised (a nickname, a sponsor's name): the only game that day of that competition with the other.
if (!found.length && game.day && game.competition) {
const onDay = pool.filter((f) => lisbonDay(f.startsAt) === game.day);
const half = onDay.filter((f) => isTeam(game.home, f.homeTeam) || isTeam(game.away, f.awayTeam));
const only = half[0];
if (half.length === 1 && only) {
// ... unless the other name is a team of another game that day: then the folder is not this game.
const other = isTeam(game.home, only.homeTeam) ? game.away : game.home;
const elsewhere = onDay.some((f) => f !== only && (isTeam(other, f.homeTeam) || isTeam(other, f.awayTeam)));
if (!elsewhere) return only;
}
}
// Both teams must be recognised: a game with one side guessed is not matched (a wrong game is worse than none).
return null;
}
+34 -5
View File
@@ -7,7 +7,7 @@ import type { Db } from "../db.js";
import { NextcloudError } from "../delivery/nextcloud.js";
import type { CloudSource } from "../generated/prisma/client.js";
import { AppError, badRequest, notFound } from "../lib/errors.js";
import { ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService } from "./service.js";
import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService, type RematchReport } from "./service.js";
const OrgParams = z.object({ orgId: z.uuid() });
const SourceParams = z.object({ sourceId: z.uuid() });
@@ -22,9 +22,11 @@ const Update = z.object({
name: z.string().trim().min(1).max(80).optional(),
rootPath: z.string().trim().min(1).max(500).optional(),
paused: z.boolean().optional(),
look: z.enum(ARCHIVE_LOOKS).nullable().optional(),
});
const FolderQuery = z.object({
state: z.enum(["all", "games", "unmatched", "folders"]).default("all"),
/** games: official games; named: games known only by their folder; events (or folders): not games. */
state: z.enum(["all", "games", "named", "events", "unmatched", "folders"]).default("all"),
q: z.string().trim().max(120).optional(),
limit: z.coerce.number().int().min(1).max(500).default(200),
});
@@ -49,8 +51,11 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
if (!sourceIds.length) return new Map<string, Record<string, number>>();
const files = await db.cloudFile.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } });
const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, photoCount: { gt: 0 } }, _count: { _all: true } });
// The pace: images indexed in the last 15 minutes, per hour.
const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } });
const out = new Map<string, Record<string, number>>();
const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0 }).get(id)!;
const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0 }).get(id)!;
for (const r of recent) get(r.sourceId).perHour = r._count._all * 4;
for (const f of files) {
const c = get(f.sourceId);
if (f.status === "DONE") c.done! += f._count._all;
@@ -72,13 +77,14 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
name: s.name,
baseUrl: s.baseUrl,
rootPath: s.rootPath,
look: s.look,
account: s.username || null,
status: s.status,
lastScanAt: s.lastScanAt,
nextScanAt: s.nextScanAt,
lastError: s.lastError,
loginUrl: loginUrl ?? archive.pendingLoginUrl(s),
counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, ...c },
counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, ...c },
});
const loadSource = async (req: Parameters<typeof requireMembership>[1], sourceId: string, role: "EDITOR" | "ADMIN") => {
@@ -138,6 +144,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
...(body.rootPath && { rootPath: normalisePath(body.rootPath), nextScanAt: new Date() }),
...(status && { status }),
...(status === "READY" && { nextScanAt: new Date() }),
...(body.look !== undefined && { look: body.look }),
},
});
return serialize(source, (await counts([source.id])).get(source.id));
@@ -152,6 +159,27 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
return serialize(source, (await counts([source.id])).get(source.id));
});
/**
* Checks a cloud's galleries again now, with today's rules, and says what changed: the official games (and any
* gallery on a game still to come) by default, every gallery with `all`.
*/
app.post("/v1/cloud-sources/:sourceId/rematch", { preHandler: authenticate }, async (req) => {
const { sourceId } = SourceParams.parse(req.params);
await loadSource(req, sourceId, "EDITOR");
const all = (req.query as { all?: string }).all === "1";
const report: RematchReport = { checked: 0, changes: [], errors: [] };
const future = await archive.takeOffFutureGames();
const moved = await archive.rematch(sourceId, all ? undefined : "fixtures", report);
const root = (await db.cloudSource.findUniqueOrThrow({ where: { id: sourceId }, select: { rootPath: true } })).rootPath.replace(/\/+$/, "");
const rel = (p: string) => (p.startsWith(root) ? p.slice(root.length) || "/" : p);
return {
checked: report.checked,
moved: moved + future,
changes: report.changes.slice(0, 300).map((c) => ({ ...c, path: rel(c.path) })),
errors: report.errors.slice(0, 100).map((e) => ({ ...e, path: rel(e.path) })),
};
});
app.delete("/v1/cloud-sources/:sourceId", { preHandler: authenticate }, async (req, reply) => {
const { sourceId } = SourceParams.parse(req.params);
await loadSource(req, sourceId, "ADMIN");
@@ -170,7 +198,8 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db
photoCount: { gt: 0 },
...(query.state === "games" && { matchedBy: { in: ["FIXTURE", "MANUAL"] } }),
...(query.state === "unmatched" && { OR: [{ matchedBy: { in: ["NAME", "FOLDER"] } }, { matchedBy: null }] }),
...(query.state === "folders" && { matchedBy: "FOLDER" }),
...(query.state === "named" && { matchedBy: "NAME" }),
...((query.state === "folders" || query.state === "events") && { matchedBy: "FOLDER" }),
...(query.q && { path: { contains: query.q, mode: "insensitive" as const } }),
},
include: { event: true },
+446 -65
View File
@@ -1,3 +1,4 @@
import { readCameraInfo } from "../ingest/exif.js";
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { mkdtemp, rm, stat, statfs } from "node:fs/promises";
@@ -11,8 +12,10 @@ import type { SecretBox } from "../delivery/secrets.js";
import type { CloudFolder, CloudSource } from "../generated/prisma/client.js";
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 { describeFolder, type FolderGame, isInitials, isTeamName, lisbonDay, parseFolder, pickFixture } from "./match.js";
import { describeFolder, type FolderGame, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture } from "./match.js";
import { canonicalTeam, exhibitionName, isExhibition } 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). */
@@ -21,9 +24,23 @@ const LOGIN_TTL_MS = 20 * 60_000;
export const RESCAN_EVERY_MS = 6 * 3600_000;
const MAX_ATTEMPTS = 3;
const DAY_MS = 86_400_000;
/** Played FPA games of a season above which it counts as read (a national season has well over a thousand). */
const FPA_SEASON_KNOWN = 300;
/** The season ("20252026", July to June) a game's day falls in. */
const seasonOfDay = (day: Date) => {
const start = day.getUTCMonth() >= 6 ? day.getUTCFullYear() : day.getUTCFullYear() - 1;
return `${start}${start + 1}`;
};
export class ArchiveRejected extends Error {}
/** What a check did: galleries looked at, the ones that changed (from/to how they were matched), the ones it could not check. */
export interface RematchReport {
checked: number;
changes: { path: string; from: string | null; to: string | null }[];
errors: { path: string; error: string }[];
}
export interface ArchiveDeps {
db: Db;
secrets: SecretBox | undefined;
@@ -32,12 +49,73 @@ export interface ArchiveDeps {
ingest?: IngestService;
/** Liga Portugal's calendar of a past season, read once when its folders are matched (fixtures saved). */
ligaSeason?: (season: string) => Promise<number>;
/** The FPA's national games of a season (slow: run in the background, the galleries matched again after). */
fpaSeason?: (season: string) => Promise<number>;
/** Brings the squads of a game's teams into the event (names for faces and codes). */
syncSquads?: (eventId: string) => Promise<unknown>;
fetchImpl?: typeof fetch;
/** Where previews are kept: indexing waits while it has less than `minFreeBytes` free. */
storageRoot?: string;
minFreeBytes?: number;
/** How many images make their preview at once (CPU); downloads in flight can be many more. */
cpuSlots?: number;
/** Clouds' folders mounted on this machine (read from disk, not downloaded): see `localDirs`. */
localDirs?: LocalDir[];
}
/** The looks an archive's site can have (its owner's colours and type); none is PhotoReport's own. */
export const ARCHIVE_LOOKS = ["liga", "fpa"] as const;
export type ArchiveLook = (typeof ARCHIVE_LOOKS)[number];
/** The look a new archive starts with, from its name or folder (it can be changed). */
export function lookFor(name: string, rootPath: string): ArchiveLook | null {
const s = `${name} ${rootPath}`;
if (/liga/i.test(s)) return "liga";
if (/fpa|andebol/i.test(s)) return "fpa";
return null;
}
export interface LocalDir {
baseUrl: string;
prefix: string;
dir: string;
}
/** "https://cloud.x/FPA=/mnt/nc/peter/files/FPA,…" → where each cloud folder is on disk. */
export function localDirs(spec: string): LocalDir[] {
return spec
.split(",")
.map((part) => part.trim())
.filter(Boolean)
.flatMap((part) => {
const eq = part.lastIndexOf("=");
if (eq < 0) return [];
let url: URL;
try {
url = new URL(part.slice(0, eq));
} catch {
return [];
}
const prefix = "/" + decodeURIComponent(url.pathname).replace(/^\/+|\/+$/g, "");
return [{ baseUrl: url.origin, prefix: prefix === "/" ? "" : prefix, dir: part.slice(eq + 1).replace(/\/+$/, "") }];
});
}
/** At most `n` at a time; the rest wait their turn. */
class Slots {
private busy = 0;
private readonly waiting: (() => void)[] = [];
constructor(private readonly n: number) {}
async run<T>(fn: () => Promise<T>): Promise<T> {
if (this.busy >= this.n) await new Promise<void>((r) => this.waiting.push(r));
this.busy++;
try {
return await fn();
} finally {
this.busy--;
this.waiting.shift()?.();
}
}
}
/** What the archive keeps per photo (the 2048 px preview with its metadata, the shown preview and the thumbnail). */
@@ -64,7 +142,11 @@ interface LoginState {
* originals, each gallery folder matched to its game. The cloud stays the place they live and who may see them.
*/
export class ArchiveService {
constructor(private readonly deps: ArchiveDeps) {}
private readonly cpu: Slots;
constructor(private readonly deps: ArchiveDeps) {
this.cpu = new Slots(Math.max(1, deps.cpuSlots ?? Number.MAX_SAFE_INTEGER));
}
private get fetchImpl(): typeof fetch {
return this.deps.fetchImpl ?? fetch;
@@ -95,6 +177,7 @@ export class ArchiveService {
name: input.name.trim() || new URL(baseUrl).hostname,
baseUrl,
rootPath: normalisePath(input.rootPath),
look: lookFor(input.name, input.rootPath),
status: "LOGIN",
loginPoll: box.seal(JSON.stringify({ endpoint: flow.endpoint, token: flow.token, loginUrl: flow.loginUrl } satisfies LoginState)),
loginExpires: new Date(Date.now() + LOGIN_TTL_MS),
@@ -170,6 +253,11 @@ export class ArchiveService {
/** Sources whose time to be walked again has come (the worker runs this). */
async scanDue(now = new Date()): Promise<number> {
// Every gallery is checked again every six hours (on start too): new calendars, stricter rules.
if (now.getTime() - this.verifiedAt > 6 * 3600_000) {
this.verifiedAt = now.getTime();
void this.verifyAll().catch((err) => this.deps.log.warn({ err }, "archive: galleries not checked"));
}
const due = await this.deps.db.cloudSource.findMany({ where: { status: { in: ["READY", "ERROR"] }, secretEnc: { not: null }, nextScanAt: { lte: now } }, select: { id: true } });
for (const s of due) await this.scan(s.id);
return due.length;
@@ -275,13 +363,17 @@ export class ArchiveService {
* a session's athletes go with the game or session above them, so they share its event.
*/
private async eventOf(source: CloudSource, folder: CloudFolder, modified: Date | null): Promise<{ eventId: string; matchedBy: "FIXTURE" | "NAME" | "FOLDER" }> {
const game = parseFolder(folder.path);
let game = parseFolder(folder.path);
if (game) {
const fixture = await this.findFixture(game, source);
// The day the photos were taken, when most of them agree: the game's day when the folder does not say it (a
// 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 };
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);
const day = game.day ?? (game.month ? `${game.month}-15` : null);
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, round: game.round }, day, modified, folder.eventId), matchedBy: "NAME" };
return { eventId: await this.eventForName(source, { ...teams, competition: game.competition, competitionName: exhibitionName(game), round: game.round }, day, modified, folder.eventId), matchedBy: "NAME" };
}
return { eventId: await this.eventForOccasion(source, folder, modified), matchedBy: "FOLDER" };
}
@@ -291,20 +383,137 @@ export class ArchiveService {
* (a game's half, an athlete in a session) joins the event of what it is part of. The athletes a session's
* folders name are added to their photos.
*/
async rematch(sourceId: string): Promise<number> {
/**
* The Lisbon day most of a folder's indexed photos were taken (their camera time), when it is clear: at least 3
* photos and 60% of those with a time on that day, and not a day still to come (a camera set wrong). Null
* otherwise. Cameras can be set wrong, so a date in the folder's name always wins over it.
*/
async captureDay(folderId: string): Promise<string | null> {
const rows = await this.deps.db.$queryRaw<{ day: string; n: bigint }[]>`
SELECT to_char(p.captured_at AT TIME ZONE 'Europe/Lisbon', 'YYYY-MM-DD') AS day, count(*) AS n
FROM cloud_files f JOIN photos p ON p.id = f.photo_id
WHERE f.folder_id = ${folderId}::uuid AND p.captured_at IS NOT NULL
GROUP BY 1 ORDER BY n DESC`;
const total = rows.reduce((t, r) => t + Number(r.n), 0);
const top = rows[0];
if (!top || Number(top.n) < 3 || Number(top.n) < total * 0.6) return null;
return pastOrToday(top.day) ? top.day : null;
}
/**
* Whether a folder's game is dated right: never a day still to come, and (the folder's name not saying the day)
* the day the photos were taken. Folders matched by hand are left alone.
*/
private async misdated(folder: CloudFolder): Promise<boolean> {
if (!folder.eventId || folder.matchedBy === "MANUAL") return false;
const event = await this.deps.db.event.findUnique({ where: { id: folder.eventId }, select: { startsAt: true } });
if (!event) return true;
if (!pastOrToday(lisbonDay(event.startsAt))) return true;
if (parseFolder(folder.path)?.day) return false;
const shot = await this.captureDay(folder.id);
if (!shot) return false;
const gap = Math.abs(new Date(`${shot}T12:00:00Z`).getTime() - new Date(`${lisbonDay(event.startsAt)}T12:00:00Z`).getTime());
return gap > 1.5 * DAY_MS;
}
/** Every cloud's galleries checked again (on start): games of another day, or still to come, put right. */
async verifyAll(): Promise<number> {
// 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 {
// 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).
// Then every cloud's official games, then the rest: a restart midway (a deploy) never leaves a cloud's
// official games unchecked behind another cloud's thousands of folders.
let moved = await this.takeOffFutureGames();
for (const part of ["fixtures", "rest"] as const)
for (const s of sources) {
try {
moved += await this.rematch(s.id, part);
} catch (err) {
this.deps.log.warn({ err, sourceId: s.id }, "archive: cloud not checked");
}
}
return moved;
} finally {
this.verifying = null;
}
})();
return this.verifying;
}
private verifying: Promise<number> | null = null;
private verifiedAt = Date.now();
/**
* Galleries whose event is a day still to come (an official game not played yet, matched by an older rule):
* matched again at once, in every cloud. Returns how many moved.
*/
async takeOffFutureGames(now = new Date()): Promise<number> {
const { db, log } = this.deps;
const source = await db.cloudSource.findUniqueOrThrow({ where: { id: sourceId } });
const folders = await db.cloudFolder.findMany({ where: { sourceId, photoCount: { gt: 0 } } });
const folders = await db.cloudFolder.findMany({
where: { photoCount: { gt: 0 }, OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }], event: { startsAt: { gt: new Date(now.getTime() + 6 * 3600_000) } } },
include: { source: true },
});
let moved = 0;
for (const folder of folders) {
if (folder.matchedBy === "NAME" || folder.matchedBy === "FOLDER" || !folder.eventId) {
const target = await this.eventOf(source, folder, null);
if (target.eventId !== folder.eventId || target.matchedBy !== folder.matchedBy) {
try {
if (folder.matchedBy === "FIXTURE") await this.rejectFixture(folder.id);
else {
const target = await this.eventOf(folder.source, folder, null);
await this.setFolderEvent(folder.id, { eventId: target.eventId }, target.matchedBy);
moved++;
}
moved++;
log.warn({ folderId: folder.id, path: folder.path }, "archive: gallery taken off a game still to come");
} catch (err) {
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery on a game still to come not moved");
}
}
return moved;
}
/** Every gallery of a cloud matched again (`part`: only its official games, or only the rest). */
async rematch(sourceId: string, part?: "fixtures" | "rest", report?: RematchReport): Promise<number> {
const { db, log } = this.deps;
const source = await db.cloudSource.findUniqueOrThrow({ where: { id: sourceId } });
const folders = await db.cloudFolder.findMany({
where: {
sourceId,
photoCount: { gt: 0 },
...(part === "fixtures" && { matchedBy: "FIXTURE" }),
...(part === "rest" && { OR: [{ matchedBy: null }, { matchedBy: { not: "FIXTURE" } }] }),
},
});
let moved = 0;
for (const folder of folders) {
// One folder that cannot be read again never stops the others from being checked.
try {
// An official game that is not the photos' (a day still to come, another day than they were taken): never
// that game again; the folder gets the event of its own day.
if (report) report.checked++;
if (folder.matchedBy === "FIXTURE" && !folder.fixtureRejected && (await this.misdated(folder))) {
await this.rejectFixture(folder.id);
log.warn({ folderId: folder.id, path: folder.path }, "archive: gallery taken off a game of another day");
report?.changes.push({ path: folder.path, from: folder.matchedBy, to: (await db.cloudFolder.findUnique({ where: { id: folder.id }, select: { matchedBy: true } }))?.matchedBy ?? null });
moved++;
continue;
}
// Every match but one made by hand is made again with today's rules (stricter ones put old mistakes right:
// another game, or no official game at all).
if (folder.matchedBy !== "MANUAL") {
const target = await this.eventOf(source, folder, null);
if (target.eventId !== folder.eventId || target.matchedBy !== folder.matchedBy) {
if (folder.matchedBy === "FIXTURE") log.warn({ folderId: folder.id, path: folder.path, to: target.matchedBy }, "archive: gallery taken off a game that is not its own");
await this.setFolderEvent(folder.id, { eventId: target.eventId }, target.matchedBy);
report?.changes.push({ path: folder.path, from: folder.matchedBy, to: target.matchedBy });
moved++;
}
}
await this.namePeople(folder);
} catch (err) {
log.warn({ err, folderId: folder.id, path: folder.path }, "archive: gallery not checked");
report?.errors.push({ path: folder.path, error: err instanceof Error ? err.message : String(err) });
}
await this.namePeople(folder);
}
if (moved) log.info({ sourceId, moved }, "archive: galleries matched to their games");
return moved;
@@ -338,7 +547,8 @@ export class ArchiveService {
}
const list = this.teams.list;
const resolve = (name: string): { name: string; short: string | null } => {
if (!name || name.length > 6 || /\s/.test(name)) return { name, short: 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 };
const byAbbr = [...new Map(list.filter((t) => t.abbreviation && t.abbreviation.toUpperCase() === name.toUpperCase()).map((t) => [t.name, t])).values()];
if (byAbbr.length === 1) return { name: byAbbr[0]!.name, short: name.toUpperCase() };
const byInitials = [...new Map(list.filter((t) => isInitials(name, t.name)).map((t) => [t.name, t])).values()];
@@ -359,8 +569,8 @@ export class ArchiveService {
const place = describeFolder(folder.path);
const fits = (e: { home: string; away: string } | null | undefined) => !!e && e.home === place.title && !e.away;
if (folder.eventId) {
const current = await db.event.findUnique({ where: { id: folder.eventId }, select: { home: true, away: true } });
if (fits(current)) return folder.eventId;
const current = await db.event.findUnique({ where: { id: folder.eventId }, select: { home: true, away: true, archivedAt: true } });
if (current?.archivedAt && fits(current)) return folder.eventId;
}
// Another part of the same occasion already has its event.
const near = await db.cloudFolder.findMany({
@@ -376,20 +586,46 @@ export class ArchiveService {
}
private readonly seasonsAsked = new Set<string>();
private fpaQueue: Promise<unknown> = Promise.resolve();
/**
* A FPA season whose played games are not here yet is read from the federation, one season at a time, and then
* every gallery is matched again: the games named only by their folder find their official game.
*/
private fpaSeasonInBackground(season: string): void {
const { db, log } = this.deps;
this.fpaQueue = this.fpaQueue.then(async () => {
const played = await db.sportsFixture.count({ where: { season, homeScore: { not: null }, competition: { provider: "FPA" } } });
if (played >= FPA_SEASON_KNOWN) return;
log.info({ season, played }, "archive: reading a FPA season");
const saved = await this.deps.fpaSeason!(season);
if (saved > played) await this.verifyAll();
}).catch((err) => log.warn({ err, season }, "archive: fpa season not read"));
}
private async findFixture(game: NonNullable<ReturnType<typeof parseFolder>>, source?: Pick<CloudSource, "baseUrl">) {
if (!game.day && !game.month && !game.competition && !game.season) return null;
// A legends' tournament, a charity game, a gala: games, but in no championship.
if (isExhibition(game)) return null;
const day = game.day ? new Date(`${game.day}T12:00:00Z`) : null;
// A Liga season not read yet (an older one): its calendar comes from Liga Portugal first.
// The Liga's own cloud, or a Liga competition folder.
const liga = (game.competition && /^liga|^allianz/i.test(game.competition)) || /liga/i.test(source?.baseUrl ?? "");
if (game.season && liga && this.deps.ligaSeason && !this.seasonsAsked.has(game.season)) {
this.seasonsAsked.add(game.season);
const known = await this.deps.db.sportsFixture.count({ where: { season: game.season, competition: { provider: "LIGA" } } });
if (!known) await this.deps.ligaSeason(game.season).catch((err) => this.deps.log.warn({ err, season: game.season }, "archive: liga season not read"));
// The season: the folder's, else the one its day falls in.
const season = game.season ?? (day ? seasonOfDay(day) : null);
if (season && liga && this.deps.ligaSeason && !this.seasonsAsked.has(`LIGA|${season}`)) {
this.seasonsAsked.add(`LIGA|${season}`);
const known = await this.deps.db.sportsFixture.count({ where: { season, competition: { provider: "LIGA" } } });
if (!known) await this.deps.ligaSeason(season).catch((err) => this.deps.log.warn({ err, season }, "archive: liga season not read"));
}
if (season && !liga && this.deps.fpaSeason && !this.seasonsAsked.has(`FPA|${season}`)) {
this.seasonsAsked.add(`FPA|${season}`);
this.fpaSeasonInBackground(season);
}
const fixtures = await this.deps.db.sportsFixture.findMany({
where: {
// Never a game still to be played.
startsAt: { lte: new Date(Date.now() + 6 * 3600_000) },
...(day && { startsAt: { gte: new Date(day.getTime() - 1.5 * DAY_MS), lte: new Date(day.getTime() + 1.5 * DAY_MS) } }),
...(!day && game.month && { startsAt: { gte: new Date(`${game.month}-01T00:00:00Z`), lt: new Date(new Date(`${game.month}-01T00:00:00Z`).getTime() + 32 * DAY_MS) } }),
...(!day && !game.month && game.season && !game.competition && { season: game.season }),
@@ -408,8 +644,9 @@ export class ArchiveService {
private async eventForFixture(source: CloudSource, fixture: { id: string }): Promise<string> {
const { db } = this.deps;
// The game may already be an event (photographed live with PhotoReport): the archive adds to it.
const existing = await db.event.findFirst({ where: { organizationId: source.organizationId, fixtureId: fixture.id }, orderBy: { createdAt: "asc" }, select: { id: true } });
// The archive keeps to its own events: an event worked on in the library (photographed live) is never added to,
// even for the same official game. A wrong match must never put photos in someone's working event.
const existing = await db.event.findFirst({ where: { organizationId: source.organizationId, fixtureId: fixture.id, archivedAt: { not: null } }, orderBy: { createdAt: "asc" }, select: { id: true } });
if (existing) return existing.id;
const f = await db.sportsFixture.findUniqueOrThrow({ where: { id: fixture.id }, include: { competition: true, homeTeam: true, awayTeam: true } });
const event = await db.event.create({
@@ -441,7 +678,7 @@ export class ArchiveService {
private async eventForName(
source: CloudSource,
g: { home: string; away: string; homeShort?: string | null; awayShort?: string | null; competition: string | null; round: string | null },
g: { home: string; away: string; homeShort?: string | null; awayShort?: string | null; competition: string | null; competitionName?: string | null; round: string | null },
day: string | null,
modified: Date | null,
current: string | null = null,
@@ -450,14 +687,22 @@ export class ArchiveService {
const { db } = this.deps;
// The folder's own event still fits (read again, nothing new): kept.
if (current && !occasion) {
const e = await db.event.findUnique({ where: { id: current }, select: { home: true, away: true, homeShort: true, awayShort: true, startsAt: true, fixtureId: true } });
if (e && !e.fixtureId && (!day || lisbonDay(e.startsAt) === day) && isTeamName(g.home, e.home, e.homeShort) && (g.away ? isTeamName(g.away, e.away, e.awayShort) : !e.away)) return current;
const e = await db.event.findUnique({ where: { id: current }, select: { home: true, away: true, homeShort: true, awayShort: true, startsAt: true, fixtureId: true, archivedAt: true, competition: true } });
if (e && !e.fixtureId && e.archivedAt && (!day || lisbonDay(e.startsAt) === day) && isTeamName(g.home, e.home, e.homeShort) && (g.away ? isTeamName(g.away, e.away, e.awayShort) : !e.away)) {
// The same teams, now named better ("01.23 Leixões SC" → "Leixões SC"): the event takes the names.
if (e.home !== g.home || e.away !== g.away || (g.competitionName && e.competition !== g.competitionName))
await db.event.update({ where: { id: current }, data: { home: g.home, away: g.away, homeShort: g.homeShort ?? e.homeShort, awayShort: g.awayShort ?? e.awayShort, ...(g.competitionName && { competition: g.competitionName }) } });
return current;
}
}
if (day && !pastOrToday(day)) day = null;
const startsAt = day ? new Date(`${day}T12:00:00Z`) : (modified ?? new Date());
if (g.away) {
// An event of that day with those teams (made before, by hand or by another folder of the same game).
if (g.away && day) {
// An archive event of that day with those teams (made by another folder of the same game). Never by the
// folder's date in the cloud (when it was copied there), never a live event, never an official game's (a
// folder that would fit it is matched to it, or was taken off it).
const near = await db.event.findMany({
where: { organizationId: source.organizationId, startsAt: { gte: new Date(startsAt.getTime() - DAY_MS), lte: new Date(startsAt.getTime() + DAY_MS) } },
where: { organizationId: source.organizationId, archivedAt: { not: null }, fixtureId: null, startsAt: { gte: new Date(startsAt.getTime() - DAY_MS), lte: new Date(startsAt.getTime() + DAY_MS) } },
select: { id: true, home: true, away: true, homeShort: true, awayShort: true, startsAt: true },
});
const same = near.find((e) => (!day || lisbonDay(e.startsAt) === day) && isTeamName(g.home, e.home, e.homeShort) && isTeamName(g.away, e.away, e.awayShort));
@@ -471,6 +716,7 @@ export class ArchiveService {
homeShort: g.homeShort ?? null,
awayShort: g.awayShort ?? null,
competitionCode: g.competition && /^PO\d/i.test(g.competition) ? g.competition : null,
competition: g.competitionName ?? null,
round: g.round,
startsAt,
...ingestWindow(startsAt),
@@ -503,12 +749,55 @@ export class ArchiveService {
const updated = await db.cloudFolder.update({ where: { id: folderId }, data: { eventId, matchedBy } });
const files = await db.cloudFile.findMany({ where: { folderId, photoId: { not: null } }, select: { photoId: true } });
const ids = files.map((f) => f.photoId!);
if (ids.length) await db.photo.updateMany({ where: { id: { in: ids }, source: "CLOUD", ...(previous ? { OR: [{ eventId: previous }, { eventId: null }] } : {}) }, data: { eventId } });
if (ids.length) {
const moving = (
await db.photo.findMany({ where: { id: { in: ids }, source: "CLOUD", NOT: { eventId }, ...(previous ? { OR: [{ eventId: previous }, { eventId: null }] } : {}) }, select: { id: true } })
).map((p) => p.id);
if (moving.length) {
const faceBoostedAt = (await db.event.findUnique({ where: { id: eventId }, select: { faceBoostedAt: true } }))?.faceBoostedAt ?? null;
await db.photo.updateMany({ where: { id: { in: moving } }, data: { eventId, facesBoostedAt: faceBoostedAt } });
// Their faces belonged to the other event's groups: taken out of them, and found again in the new event.
await db.face.deleteMany({ where: { photoId: { in: moving } } });
await db.photo.updateMany({ where: { id: { in: moving }, facesStatus: { in: ["DONE", "FAILED", "RUNNING"] } }, data: { facesStatus: "PENDING" } });
if (previous) await db.faceGroup.deleteMany({ where: { eventId: previous, faces: { none: {} } } });
}
}
// An event the archive made and that nothing uses any more goes.
if (previous && previous !== eventId) await this.dropIfEmpty(previous);
return updated;
}
/** A folder that is not the official game it was matched to: its own event from now on, never that game again. */
async rejectFixture(folderId: string): Promise<void> {
const { db } = this.deps;
const folder = await db.cloudFolder.update({ where: { id: folderId }, data: { fixtureRejected: true }, include: { source: true } });
const target = await this.eventOf(folder.source, folder, null);
await this.setFolderEvent(folder.id, { eventId: target.eventId }, target.matchedBy);
}
/**
* Folders that ended up in a live event (an event of the library, not one the archive made): taken back out, their
* photos with them, into events of their own. Photos that were already in that event (the same picture sent
* live) stay. Folders put there by hand stay. Returns how many folders moved.
*/
async leaveLiveEvents(): Promise<number> {
const { db, log } = this.deps;
const folders = await db.cloudFolder.findMany({
where: { eventId: { not: null }, OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }], event: { archivedAt: null } },
include: { source: true, event: { select: { home: true, away: true, startsAt: true } } },
});
let moved = 0;
for (const folder of folders) {
const target = await this.eventOf(folder.source, folder, null);
if (target.eventId === folder.eventId) continue;
await this.setFolderEvent(folder.id, { eventId: target.eventId }, target.matchedBy);
moved++;
log.warn({ folderId: folder.id, path: folder.path, from: folder.event, to: target }, "archive: gallery taken out of a live event");
}
if (moved) log.warn({ moved }, "archive: galleries taken out of live events");
return moved;
}
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 } } } });
@@ -556,14 +845,39 @@ export class ArchiveService {
async claim(limit: number): Promise<string[]> {
if (limit <= 0) return [];
if (await this.diskLow()) return [];
// Every cloud gets its share (the FPA's older seasons do not wait for all of the Liga's newer ones); a share
// a cloud cannot use goes to the others.
const sources = await this.deps.db.$queryRaw<{ source_id: string }[]>`
SELECT DISTINCT f.source_id FROM cloud_files f JOIN cloud_sources s ON s.id = f.source_id
WHERE f.status = 'PENDING' AND s.status IN ('READY', 'SCANNING')`;
const ids: string[] = [];
let left = sources.map((r) => r.source_id);
while (left.length && ids.length < limit) {
const share = Math.max(1, Math.ceil((limit - ids.length) / left.length));
const next: string[] = [];
for (const sourceId of left) {
const want = Math.min(share, limit - ids.length);
if (want <= 0) break;
const got = await this.claimFrom(sourceId, want);
ids.push(...got);
if (got.length === want) next.push(sourceId);
}
// Only clouds that filled their share can take more.
if (next.length === left.length && ids.length < limit && share * left.length >= limit) break;
left = next;
}
return ids;
}
/** Images of one cloud, newest season first, then the latest game, its photos in order. */
private async claimFrom(sourceId: string, limit: number): Promise<string[]> {
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
UPDATE cloud_files SET status = 'WORKING', attempts = attempts + 1, updated_at = now()
WHERE id IN (
SELECT f.id FROM cloud_files f
JOIN cloud_folders d ON d.id = f.folder_id
JOIN cloud_sources s ON s.id = f.source_id
JOIN events e ON e.id = d.event_id
WHERE f.status = 'PENDING' AND d.event_id IS NOT NULL AND s.status IN ('READY', 'SCANNING')
WHERE f.source_id = ${sourceId}::uuid AND f.status = 'PENDING' AND d.event_id IS NOT NULL
ORDER BY coalesce(substring(f.path from '(20[0-9]{2})[_-]20[0-9]{2}'), '20' || substring(f.path from '([0-9]{2})[_-][0-9]{2}(/|$| )')) DESC NULLS LAST,
e.starts_at DESC, f.path
LIMIT ${limit}
@@ -586,25 +900,47 @@ export class ArchiveService {
const dir = await mkdtemp(path.join(tmpdir(), "pr-archive-"));
try {
if (!file.folder.eventId || !file.source.ownerId) throw new ArchiveRejected("no_event");
const original = path.join(dir, "original.jpg");
await this.client(file.source).download(file.path, original);
const size = (await stat(original)).size;
const sha256 = await hashFile(original);
const meta = await sharp(original).metadata();
const eventId = file.folder.eventId;
const ownerId = file.source.ownerId;
// Read from disk when the cloud's files are mounted here; downloaded otherwise.
let original = await this.localFile(file.source.baseUrl, file.path, file.size);
if (!original) {
original = path.join(dir, "original.jpg");
await this.client(file.source).download(file.path, original);
}
const from = original;
// The official game's day against the day the photos were taken: a folder matched to the wrong game is
// taken off it (and its photos go to an event of their own) before anything is added.
if (file.folder.matchedBy === "FIXTURE") {
const taken = (await readCameraInfo(from).catch(() => null))?.capturedAt;
const event = await db.event.findUnique({ where: { id: eventId }, select: { startsAt: true } });
if (taken && event && Math.abs(taken.getTime() - event.startsAt.getTime()) > 36 * 3600_000) {
await this.rejectFixture(file.folder.id);
await db.cloudFile.update({ where: { id: fileId }, data: { status: "PENDING" } });
log.warn({ folderId: file.folder.id, path: file.folder.path, taken, game: event.startsAt }, "archive: photos taken on another day than the game, unmatched");
return;
}
}
// Downloads run many at a time; the preview and the ingest (CPU) only as many as the machine's share.
const outcome = await this.cpu.run(async () => {
const size = (await stat(from)).size;
const sha256 = await hashFile(from);
const meta = await sharp(from).metadata();
const turned = (meta.orientation ?? 1) >= 5;
const width = turned ? meta.height : meta.width;
const height = turned ? meta.width : meta.height;
const preview = path.join(dir, "preview.jpg");
// Pixels as stored and the orientation tag kept, like the desktop app's previews.
await sharp(original).resize(2048, 2048, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(preview);
const outcome = await ingest.ingest(preview, {
await sharp(from).resize(2048, 2048, { fit: "inside", withoutEnlargement: true }).keepMetadata().jpeg({ quality: 90 }).toFile(preview);
return ingest.ingest(preview, {
organizationId: file.source.organizationId,
userId: file.source.ownerId,
userId: ownerId,
source: "CLOUD",
originalName: path.posix.basename(file.path),
eventId: file.folder.eventId,
eventId,
original: { sha256, size, width, height },
});
});
if (outcome.status === "failed") {
await db.cloudFile.update({ where: { id: fileId }, data: { status: "FAILED", error: outcome.error, photoId: outcome.photoId } });
return;
@@ -636,10 +972,37 @@ export class ArchiveService {
return !!(await this.cloudFileOf(photoId));
}
/** The file on this machine's mount of the cloud, when there is one and it is the size the walk saw. */
private async localFile(baseUrl: string, filePath: string, size: bigint | null): Promise<string | null> {
const origin = (() => {
try {
return new URL(baseUrl).origin;
} catch {
return baseUrl;
}
})();
for (const m of this.deps.localDirs ?? []) {
if (m.baseUrl !== origin) continue;
if (m.prefix && filePath !== m.prefix && !filePath.startsWith(m.prefix + "/")) continue;
const rest = filePath.slice(m.prefix.length);
if (rest.split("/").includes("..")) continue;
const local = m.dir + rest;
try {
const st = await stat(local);
if (st.isFile() && (size === null || BigInt(st.size) === size)) return local;
} catch {
// Not there: downloaded instead.
}
}
return null;
}
/** The original downloaded to a temporary file (the caller removes it with `done`), or null when no cloud has it. */
async downloadOriginal(photoId: string): Promise<{ file: string; done: () => Promise<void> } | null> {
const cf = await this.cloudFileOf(photoId);
if (!cf) return null;
const local = await this.localFile(cf.source.baseUrl, cf.path, cf.size);
if (local) return { file: local, done: async () => {} };
const dir = await mkdtemp(path.join(tmpdir(), "pr-original-"));
const file = path.join(dir, "original.jpg");
try {
@@ -681,6 +1044,7 @@ export class ArchiveWorker {
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private scanning = false;
private ticking = false;
constructor(
private readonly service: ArchiveService,
@@ -697,37 +1061,51 @@ export class ArchiveWorker {
start(): void {
// Before the first round, so an interrupted walk is picked up by it.
const ready = this.service
.requeueStale()
.leaveLiveEvents()
.catch((err) => void this.opts.log.warn({ err }, "archive: live events not checked"))
.then(() => {
// In the background: the indexing does not wait for it.
void this.service.verifyAll().then(
(n) => void (n && this.opts.log.warn({ moved: n }, "archive: galleries re-dated on start")),
(err) => this.opts.log.warn({ err }, "archive: galleries not checked"),
);
})
.then(() => this.service.requeueStale())
.then((n) => void (n && this.opts.log.info({ count: n }, "archive: re-queued images")))
.catch((err) => this.opts.log.warn({ err }, "archive: re-queue failed"));
const tick = async () => {
await ready;
this.ticking = true;
try {
if (!this.scanning) {
this.scanning = true;
// Walking runs beside the indexing (a big first walk should not hold the queue back).
void this.service
.scanDue()
.catch((err) => this.opts.log.warn({ err }, "archive: scan failed"))
.finally(() => {
this.scanning = false;
await ready;
try {
if (!this.scanning) {
this.scanning = true;
// Walking runs beside the indexing (a big first walk should not hold the queue back).
void this.service
.scanDue()
.catch((err) => this.opts.log.warn({ err }, "archive: scan failed"))
.finally(() => {
this.scanning = false;
});
}
// Bulk work: less of it while the machine is busy with live games, all of it when quiet.
const burst = !!this.opts.burst && (await this.backlog()) > BURST_BACKLOG;
const full = burst ? this.opts.burst! : this.opts.concurrency;
const allowed = this.opts.pressure ? this.opts.pressure.allow(full, burst) : full;
const ids = await this.service.claim(allowed - this.inFlight);
for (const id of ids) {
this.inFlight++;
void this.service.index(id).finally(() => {
this.inFlight--;
});
}
} catch (err) {
this.opts.log.warn({ err }, "archive: poll failed");
}
// Bulk work: less of it while the machine is busy with live games, all of it when quiet.
const burst = !!this.opts.burst && (await this.backlog()) > BURST_BACKLOG;
const full = burst ? this.opts.burst! : this.opts.concurrency;
const allowed = this.opts.pressure ? this.opts.pressure.allow(full, burst) : full;
const ids = await this.service.claim(allowed - this.inFlight);
for (const id of ids) {
this.inFlight++;
void this.service.index(id).finally(() => {
this.inFlight--;
});
}
} catch (err) {
this.opts.log.warn({ err }, "archive: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
@@ -744,8 +1122,11 @@ export class ArchiveWorker {
return this.backlogCount;
}
stop(): void {
/** Stop claiming work and wait for in-flight index/scan jobs before the DB pool is closed. */
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && !this.scanning && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight, scanning: this.scanning }, "archive: stop timed out with work still running");
}
}
+38 -5
View File
@@ -8,7 +8,7 @@ import type { SecretBox } from "../delivery/secrets.js";
import { AppError, badRequest, notFound, unauthorized } from "../lib/errors.js";
import type { UrlSigner } from "../storage/storage.js";
import { CloudClient, pollLogin, startLogin } from "./nextcloud.js";
import { describeFolder } from "./match.js";
import { canonicalTeam, describeFolder } from "./match.js";
import { facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import type { ArchiveService } from "./service.js";
@@ -112,7 +112,7 @@ export async function registerArchiveViewerRoutes(
const { sourceId } = SourceParams.parse(req.params);
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, include: { organization: { select: { name: true } } } });
if (!source || !source.secretEnc) throw notFound("archive_not_found");
return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name };
return { id: source.id, name: source.name, cloud: new URL(source.baseUrl).host, organization: source.organization.name, look: source.look };
});
/** Starts the viewer's sign-in on the cloud: they open `loginUrl`, the page polls with `state`. */
@@ -169,6 +169,33 @@ export async function registerArchiveViewerRoutes(
}
});
/**
* The teams of the viewer's games under one name each: without the date or number a folder put before it ("01.23
* Leixões SC"), and the known team's official name when exactly one fits ("SCP", "Sporting" → "Sporting CP").
* Each with the names its galleries use, so filtering by it finds them all.
*/
const teamGroups = async (sourceId: string, games: Iterable<{ home: string; away: string }>): Promise<Map<string, { names: Set<string>; galleries: number }>> => {
const source = await db.cloudSource.findUnique({ where: { id: sourceId }, select: { look: true, baseUrl: true } });
const liga = source?.look === "liga" || /liga/i.test(source?.baseUrl ?? "");
const known = await db.sportsTeam.findMany({ where: liga ? { provider: "LIGA" } : { provider: { not: "LIGA" }, sport: { not: "futebol" } }, select: { name: true, abbreviation: true, slug: true } });
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();
for (const g of games)
for (const raw of [g.home, g.away]) {
if (!raw) continue;
const name = canonicalTeam(raw, known);
const key = fold(name);
const label = byKey.get(key) ?? name;
byKey.set(key, label);
const cur = out.get(label) ?? { names: new Set<string>(), galleries: 0 };
cur.names.add(raw);
cur.galleries++;
out.set(label, cur);
}
return out;
};
/** Galleries the viewer may see, newest first; by words in the name, a team or a player. */
app.get("/v1/archive/:sourceId/galleries", async (req) => {
const { sourceId } = SourceParams.parse(req.params);
@@ -176,9 +203,16 @@ export async function registerArchiveViewerRoutes(
const query = ListQuery.parse(req.query);
const visible = await visibleFolders(v);
const words = (query.q ?? "").split(/\s+/).filter(Boolean);
// A team of the directory: every name its galleries use.
let teamNames: string[] = [];
if (query.team) {
const rows = await db.cloudFolder.findMany({ where: { ...folderWhere(v, visible), matchedBy: { not: "FOLDER" } }, select: { event: { select: { home: true, away: true } } } });
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: { equals: query.team, mode: "insensitive" as const } }, { away: { equals: query.team, 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 } }) };
@@ -215,10 +249,9 @@ export async function registerArchiveViewerRoutes(
const visible = await visibleFolders(v);
const folders = await db.cloudFolder.findMany({ where: folderWhere(v, visible), select: { eventId: true, matchedBy: true, 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 teams = new Map<string, number>();
const games = new Map<string, { home: string; away: string }>();
for (const f of folders) if (f.event && f.matchedBy !== "FOLDER") games.set(f.event.id, f.event);
for (const g of games.values()) for (const t of [g.home, g.away]) if (t) teams.set(t, (teams.get(t) ?? 0) + 1);
const teams = new Map([...(await teamGroups(sourceId, games.values()))].map(([name, g]) => [name, g.galleries]));
const eventIds = [...new Set(folders.map((f) => f.eventId!))];
const players = eventIds.length
? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>`
+9 -2
View File
@@ -7,6 +7,7 @@ import { type Box, compose, frameScore, minCropWidth, peopleIn } from "../compos
import type { SubjectDetector } from "../composition/detect.js";
import { constrainRotated, tighter } from "../composition/geometry.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import { CANDIDATE_SELECT, candidatesOf } from "./best.js";
@@ -274,6 +275,7 @@ export class AutopilotWorker {
private timer: ReturnType<typeof setTimeout> | undefined;
private inFlight = 0;
private stopped = false;
private ticking = false;
private lastDecide = 0;
constructor(
@@ -284,6 +286,7 @@ export class AutopilotWorker {
start(): void {
void this.service.requeueStale();
const tick = async () => {
this.ticking = true;
try {
const ids = await this.service.claim(this.opts.concurrency - this.inFlight);
for (const id of ids) {
@@ -298,14 +301,18 @@ export class AutopilotWorker {
}
} catch (err) {
this.opts.log.warn({ err }, "autopilot: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "autopilot: stop timed out with work still running");
}
}
+3 -3
View File
@@ -37,14 +37,14 @@ export class SubjectDetector {
/** Detections in `file` (any JPEG/PNG), upright, as fractions of the photo. */
async detect(file: string | Buffer): Promise<Detections> {
const img = sharp(file).rotate();
const img = sharp(file, { failOn: "none" }).rotate();
const meta = await img.metadata();
const width = meta.autoOrient?.width ?? meta.width ?? 1;
const height = meta.autoOrient?.height ?? meta.height ?? 1;
const scale = Math.min(SIZE / width, SIZE / height);
const rw = Math.round(width * scale);
const rh = Math.round(height * scale);
const { data } = await sharp(file)
const { data } = await sharp(file, { failOn: "none" })
.rotate()
.resize(rw, rh, { fit: "fill" })
.removeAlpha()
@@ -131,7 +131,7 @@ function nms(list: Raw[], threshold = 0.45): Detection[] {
async function addSharpness(file: string | Buffer, people: Detection[]): Promise<void> {
if (!people.length) return;
const W = 1024;
const { data, info } = await sharp(file).rotate().resize({ width: W }).greyscale().raw().toBuffer({ resolveWithObject: true });
const { data, info } = await sharp(file, { failOn: "none" }).rotate().resize({ width: W }).greyscale().raw().toBuffer({ resolveWithObject: true });
const H = info.height;
const values = people.map((p) => {
const x0 = Math.max(1, Math.floor(p.x0 * W));
+6
View File
@@ -42,6 +42,12 @@ const Env = z.object({
ARCHIVE_CONCURRENCY: z.coerce.number().int().positive().optional(),
/** Indexing stops while the storage has less free space than this (GB), so the archive never fills the disk. */
ARCHIVE_MIN_FREE_GB: z.coerce.number().nonnegative().default(25),
/**
* The clouds' files mounted read-only on this machine, read from disk instead of downloaded (much faster than
* WebDAV for a big archive). Comma-separated "<cloud address><folder as the account sees it>=<local folder>",
* e.g. "https://cloud.photoreport.pt/FPA=/mnt/nextcloud/peter/files/FPA". A file missing there is downloaded.
*/
ARCHIVE_LOCAL_DIRS: z.string().default(""),
/** Read competitions, squads and fixtures from Liga Portugal, FPF and FPA (worker). "off" to disable. */
SPORTS_SYNC: z.enum(["on", "off"]).default("on"),
/** How long signed photo URLs stay valid (seconds). */
+16
View File
@@ -61,6 +61,22 @@ export async function renderDelivery(original: string, iptc: IptcValues, opts: R
}
}
/**
* The original as it arrived, untouched (no resizing, no recompression, the camera's EXIF and profile as they
* are), with the IPTC written into it as Photo Mechanic does on ingest: a copy for one's own backup.
*/
export async function originalWithMetadata(original: string, iptc: IptcValues, created?: CreatedStamp): Promise<Buffer> {
const dir = await mkdtemp(path.join(tmpdir(), "pr-original-"));
const file = path.join(dir, `copy${path.extname(original).toLowerCase() || ".jpg"}`);
try {
await writeFile(file, await readFile(original));
await exiftool.write(file, {}, { writeArgs: ["-overwrite_original", ...toExiftoolArgs(iptc, created)] });
return await readFile(file);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
export async function closeRenderer(): Promise<void> {
await exiftool.end();
}
+20
View File
@@ -46,6 +46,14 @@ const TargetBase = z.object({
dpi: z.number().int().min(72).max(1200),
keepExif: z.boolean(),
srgb: z.boolean(),
/** The original as it arrived, metadata written in, renamed (no resizing or recompression). */
originals: z.boolean(),
/** Everything that arrives is sent here on its own. */
onArrival: z.boolean(),
/** With onArrival: only these FTP logins' photos (empty: everyone's). */
arrivalLogins: z.array(z.uuid()).max(100),
/** With originals: the file exactly as it arrived, no metadata written. */
untouched: z.boolean(),
});
const checkAddress = (kind: z.infer<typeof KIND>, baseUrl: string, username: string) => {
if (!ADDRESS[kind].test(baseUrl)) throw badRequest("invalid_address", `address for ${kind} must look like ${ADDRESS[kind].source}`);
@@ -60,6 +68,10 @@ const TargetFields = TargetBase.extend({
dpi: TargetBase.shape.dpi.default(300),
keepExif: TargetBase.shape.keepExif.default(true),
srgb: TargetBase.shape.srgb.default(false),
originals: TargetBase.shape.originals.default(false),
onArrival: TargetBase.shape.onArrival.default(false),
arrivalLogins: TargetBase.shape.arrivalLogins.default([]),
untouched: TargetBase.shape.untouched.default(false),
});
const UpdateTarget = TargetBase.partial().extend({ disabled: z.boolean().optional(), resetHostKey: z.boolean().optional() });
const ListQuery = z.object({
@@ -99,6 +111,12 @@ export async function registerDeliveryRoutes(
) {
const { db, secrets, delivery } = deps;
const authenticate = requireAuth(deps.sessions);
/** The FTP logins a target takes arrivals from must be the organisation's. */
const checkLogins = async (orgId: string, ids: string[]) => {
if (!ids.length) return;
const found = await db.ftpAccount.count({ where: { organizationId: orgId, id: { in: ids } } });
if (found !== new Set(ids).size) throw badRequest("unknown_ftp_login");
};
const seal = (password: string) => {
if (!secrets) throw new AppError(503, "delivery_not_configured", "DELIVERY_SECRET_KEY is not set");
return secrets.seal(password);
@@ -127,6 +145,7 @@ export async function registerDeliveryRoutes(
if (await db.deliveryTarget.findUnique({ where: { organizationId_name: { organizationId: orgId, name: body.name } } })) throw conflict("name_taken");
const { password, ...fields } = body;
if (!password && body.kind !== "LOCAL") throw badRequest("password_required");
await checkLogins(orgId, body.arrivalLogins);
const target = await db.deliveryTarget.create({ data: { ...fields, organizationId: orgId, secretEnc: seal(password ?? "") } });
return reply.code(201).send({ ...publicTarget(target), example });
});
@@ -144,6 +163,7 @@ export async function registerDeliveryRoutes(
// Another server, another key: a changed address forgets the remembered one.
const forgetKey = body.resetHostKey === true || kind !== current.kind || baseUrl !== current.baseUrl;
const { password, disabled, resetHostKey: _reset, ...fields } = body;
if (fields.arrivalLogins) await checkLogins(orgId, fields.arrivalLogins);
const target = await db.deliveryTarget.update({
where: { id: targetId },
data: {
+94 -18
View File
@@ -3,13 +3,17 @@ import { buildVars, createdStamp, eventName, PathTemplateError, renderFileName,
import type { Db } from "../db.js";
import type { DeliveryItem } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { eventInfoOf } from "../library/event-info.js";
import { iptcForPhoto } from "../library/iptc.js";
import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import type { RenderEngine, Settings } from "../develop/engine.js";
import { type DeliveryEdit, renderDelivery } from "./render.js";
import { type DeliveryEdit, originalWithMetadata, renderDelivery } from "./render.js";
import type { SecretBox } from "./secrets.js";
import { readCameraInfo } from "../ingest/exif.js";
import { photoInfoOf } from "../library/photo-info.js";
import { readFile } from "node:fs/promises";
import { lisbonTime } from "../sports/providers.js";
import { type Transport, type TransportKind, ZerozeroTransport, createTransport, isTransient } from "./transports.js";
import { type ZerozeroGame, matchGame, zerozeroGameId } from "./zerozero.js";
@@ -21,6 +25,8 @@ export const ORIGINAL_WAIT_MS = 72 * 3600_000;
export const ORIGINAL_ASK_MS = 60_000;
/** Running items older than this belonged to a worker that died; they go back in the queue. */
const STALE_RUNNING_MS = 10 * 60_000;
/** A delivered photo edited again is sent again once its edits have paused this long. */
const EDIT_PAUSE_MS = 60_000;
export function backoffMs(attempt: number): number {
return Math.min(10_000 * 2 ** (attempt - 1), 10 * 60_000);
@@ -92,7 +98,26 @@ export class DeliveryService {
return settings ? { engine: develop.engine, settings } : undefined;
}
async enqueue(input: { organizationId: string; targetId: string; photoIds: string[]; again: boolean; requestedById: string }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> {
/**
* A photo that just arrived (or just joined an event): queued for every destination that takes all arrivals.
* Errors are logged, never thrown: arriving must not fail because of a destination.
*/
async queueArrival(photo: { id: string; organizationId: string; uploaderId: string | null }): Promise<void> {
const { db } = this.deps;
const all = await db.deliveryTarget.findMany({ where: { organizationId: photo.organizationId, onArrival: true, disabledAt: null }, select: { id: true, arrivalLogins: true } });
// A target taking only some FTP logins' photos: the photographer's logins.
const logins = all.some((t) => t.arrivalLogins.length) && photo.uploaderId
? new Set((await db.ftpAccount.findMany({ where: { organizationId: photo.organizationId, userId: photo.uploaderId }, select: { id: true } })).map((a) => a.id))
: new Set<string>();
const targets = all.filter((t) => !t.arrivalLogins.length || t.arrivalLogins.some((id) => logins.has(id)));
for (const target of targets) {
await this.enqueue({ organizationId: photo.organizationId, targetId: target.id, photoIds: [photo.id], again: false, requestedById: photo.uploaderId }).catch((err) =>
this.deps.log.warn({ err, photoId: photo.id, targetId: target.id }, "delivery: arrival not queued"),
);
}
}
async enqueue(input: { organizationId: string; targetId: string; photoIds: string[]; again: boolean; requestedById: string | null }): Promise<{ queued: DeliveryItem[]; skipped: { photoId: string; reason: string }[] }> {
const { db } = this.deps;
const target = await db.deliveryTarget.findFirst({ where: { id: input.targetId, organizationId: input.organizationId, disabledAt: null } });
if (!target) throw new DeliveryRejected("target_not_found");
@@ -146,17 +171,49 @@ export class DeliveryService {
return { queued, skipped };
}
private editsCheckedAt = 0;
/**
* Delivered photos edited again since (a crop put right, a colour fixed), once the edits have paused for a
* minute: sent again to where they went, with the same name (a file is replaced; on ZeroZero the new one goes up
* and the old one is taken back). Not the originals' backups (they carry no edits). Returns how many.
*/
async queueEdited(now = new Date()): Promise<number> {
const rows = await this.deps.db.$queryRaw<{ id: string; organization_id: string }[]>`
UPDATE delivery_items di SET status = 'QUEUED', attempts = 0, next_attempt_at = now(), last_error = NULL, finished_at = NULL,
replaces_path = di.remote_path, updated_at = now()
FROM photos p, delivery_targets t
WHERE p.id = di.photo_id AND t.id = di.target_id
AND di.status = 'DONE' AND t.originals = false AND t.disabled_at IS NULL
AND p.develop_seq > COALESCE(di.delivered_seq, p.develop_seq)
AND p.edited_at IS NOT NULL AND p.edited_at < ${new Date(now.getTime() - EDIT_PAUSE_MS)}
RETURNING di.id, di.organization_id`;
for (const r of rows) {
const item = await this.deps.db.deliveryItem.findUnique({ where: { id: r.id } });
if (item) this.deps.broadcaster.library(item.organizationId, { type: "delivery.updated", item: toItemSummary(item) });
}
if (rows.length) this.deps.log.info({ count: rows.length }, "delivery: edited photos sent again");
return rows.length;
}
/** Atomically takes up to `limit` due items (safe with several workers). */
async claim(limit: number): Promise<string[]> {
// Every half minute: delivered photos edited again join the queue.
if (Date.now() - this.editsCheckedAt > 30_000) {
this.editsCheckedAt = Date.now();
await this.queueEdited().catch((err) => this.deps.log.warn({ err }, "delivery: edited photos not checked"));
}
if (limit <= 0) return [];
const rows = await this.deps.db.$queryRaw<{ id: string }[]>`
UPDATE delivery_items SET status = 'RUNNING', started_at = now(), attempts = attempts + 1, updated_at = now()
WHERE id IN (
SELECT id FROM delivery_items
WHERE status = 'QUEUED' AND next_attempt_at <= now()
ORDER BY next_attempt_at, sequence
SELECT di.id FROM delivery_items di
JOIN delivery_targets t ON t.id = di.target_id
WHERE di.status = 'QUEUED' AND di.next_attempt_at <= now()
-- A computer folder can wait. A live desk (ZeroZero and the rest) goes first.
ORDER BY CASE WHEN t.kind = 'LOCAL' THEN 1 ELSE 0 END, di.next_attempt_at, di.sequence
LIMIT ${limit}
FOR UPDATE SKIP LOCKED
FOR UPDATE OF di SKIP LOCKED
)
RETURNING id`;
return rows.map((r) => r.id);
@@ -244,24 +301,30 @@ export class DeliveryService {
return saved;
}
try {
const vars = buildVars(
eventInfoOf(item.event),
{ capturedAt: item.photo.capturedAt ?? undefined, players: item.photo.players, sequence: item.sequence, cameraModel: item.photo.cameraModel ?? undefined, cameraSerial: item.photo.cameraSerial ?? undefined },
item.photo.uploader?.name,
);
// The IPTC first: Photo Mechanic's {headline}, {caption}... in folder and file names are the photo's pad.
const iptc = await iptcForPhoto(db, item.photoId);
const source = cloud?.file ?? storage.resolve(item.photo.storageKey);
// Photos from before the camera details were kept: read them from the file being sent.
const exif = item.photo.exif ?? (await readCameraInfo(source).then((c) => c.extra ?? null, () => null));
const vars = buildVars(eventInfoOf(item.event), photoInfoOf({ ...item.photo, exif }, { sequence: item.sequence }), item.photo.uploader?.name, { iptc: iptc?.values });
let folder = renderFolder(item.target.folderTemplate, vars);
if (item.target.kind === "ZEROZERO") folder = `${await this.zerozeroGameId(item.target, item.event)}/`;
// {originalName} is the name given on arrival when the photo was renamed (as Photo Mechanic renames the file).
const fileName = renderFileName(item.target.fileNameTemplate, vars, deliveredName(item.photo));
const iptc = await iptcForPhoto(db, item.photoId);
// Untouched: the camera's own name, as a local FTP would have received it.
const fileName = renderFileName(item.target.fileNameTemplate, vars, item.target.originals && item.target.untouched ? item.photo.originalName : deliveredName(item.photo));
const edit = await this.editFor(item.photoId, item.photo.developSeq);
const rendered = await renderDelivery(cloud?.file ?? storage.resolve(item.photo.storageKey), iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined, edit);
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
const rendered = item.target.originals
? item.target.untouched
? await readFile(source)
: await originalWithMetadata(source, iptc?.values ?? {}, created)
: await renderDelivery(source, iptc?.values ?? {}, { longEdge: item.target.longEdge, quality: item.target.jpegQuality, sharpen: item.target.sharpen, dpi: item.target.dpi, exif: item.target.keepExif, srgb: item.target.srgb }, created, edit);
const data = rendered;
if (item.target.kind === "LOCAL") {
// Kept here until the computer's desktop app takes it (localClaim → localFile → localResult).
await storage.write(localKey(item.organizationId, item.id), data);
const relative = (folder + fileName).replace(/^[/\\]+/, "");
update = { status: "WAITING", remotePath: relative, byteSize: data.length, lastError: null };
update = { status: "WAITING", remotePath: relative, byteSize: data.length, lastError: null, deliveredSeq: item.photo.developSeq, replacesPath: null };
log.info({ itemId, remotePath: relative }, "delivery: rendered for a computer's folder");
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: update });
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
@@ -273,7 +336,14 @@ export class DeliveryService {
const creator = typeof iptc?.values.creator === "string" ? iptc.values.creator.split(" / ")[0]!.trim() : "";
const remote = await client.upload(folder + fileName, data, { author: creator || item.photo.uploader?.name || undefined });
const remotePath = typeof remote === "string" ? remote : folder + fileName;
update = { status: "DONE", remotePath, byteSize: data.length, lastError: null, finishedAt: new Date() };
// "synced-…" means the desk already had this file, so this attempt did not put a new image up.
// Taking the previous one back here would remove the only copy (the new upload never landed).
const alreadyThere = remotePath.includes("/synced-");
if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath && client instanceof ZerozeroTransport) {
await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous version not taken back"));
}
const storedPath = alreadyThere && item.replacesPath ? item.replacesPath : remotePath;
update = { status: "DONE", remotePath: storedPath, byteSize: data.length, lastError: null, finishedAt: new Date(), deliveredSeq: item.photo.developSeq, replacesPath: null };
log.info({ itemId, remotePath }, "delivery: uploaded");
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -407,6 +477,7 @@ export class DeliveryWorker {
private inFlight = 0;
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private ticking = false;
constructor(
private readonly service: DeliveryService,
@@ -416,12 +487,15 @@ export class DeliveryWorker {
start(): void {
void this.service.requeueStale().then((n) => n && this.opts.log.info({ count: n }, "delivery: re-queued stale items"));
const tick = async () => {
this.ticking = true;
try {
await this.fill();
} catch (err) {
this.opts.log.warn({ err }, "delivery: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
@@ -436,8 +510,10 @@ export class DeliveryWorker {
}
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "delivery: stop timed out with work still running");
}
}
+33 -15
View File
@@ -80,24 +80,42 @@ export function createTransport(config: TransportConfig, fetchImpl: typeof fetch
/** fotos.zerozero.pt: the folder is the game's id ("12627747/"), checked once; the file keeps its name. */
export class ZerozeroTransport implements Transport {
// One session cookie and one tus upload at a time. Parallel deliveries share this client and otherwise
// corrupt the cookie jar (fetch failed) or the upload (400/422 at byte 0).
private readonly serial = new Serial();
constructor(readonly client: ZerozeroClient) {}
async ensureFolder(folder: string) {
const id = folder.replace(/\/+$/, "");
if (!/^\d+$/.test(id)) throw new TransportError("zerozero: no game chosen for this event", false);
await this.client.game(id);
ensureFolder(folder: string) {
return this.serial.run(async () => {
const id = folder.replace(/\/+$/, "");
if (!/^\d+$/.test(id)) throw new TransportError("zerozero: no game chosen for this event", false);
await this.client.game(id);
});
}
async upload(remoteFile: string, data: Buffer, meta?: UploadMeta) {
const slash = remoteFile.indexOf("/");
const gameId = remoteFile.slice(0, slash);
const fileName = remoteFile.slice(slash + 1);
const account = await this.client.login();
const author = meta?.author?.trim() || account.name || "PhotoReport";
const imageId = await this.client.upload(gameId, fileName, data, author);
return `${gameId}/${imageId}`;
upload(remoteFile: string, data: Buffer, meta?: UploadMeta) {
return this.serial.run(async () => {
const slash = remoteFile.indexOf("/");
const gameId = remoteFile.slice(0, slash);
const fileName = remoteFile.slice(slash + 1);
const account = await this.client.login();
const author = meta?.author?.trim() || account.name || "PhotoReport";
const imageId = await this.client.upload(gameId, fileName, data, author);
return `${gameId}/${imageId}`;
});
}
async test() {
const account = await this.client.login();
return { account: account.name ?? account.role };
/** Takes back an image sent before ("<game>/<image id>", as `upload` returned it). */
remove(remotePath: string) {
return this.serial.run(async () => {
const imageId = remotePath.slice(remotePath.indexOf("/") + 1);
if (!imageId) return;
await this.client.login();
await this.client.remove(imageId);
});
}
test() {
return this.serial.run(async () => {
const account = await this.client.login();
return { account: account.name ?? account.role };
});
}
async close() {}
}
+20 -2
View File
@@ -77,6 +77,19 @@ function splitSetCookie(v: string | null): string[] {
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
/** `fetch` hides the socket error on `cause`. Keep the code (ETIMEDOUT, ECONNRESET, …) in the delivery error. */
export function fetchFailure(err: unknown): string {
const error = err as { message?: string; cause?: { code?: string; message?: string; errors?: { code?: string }[] } };
const message = error?.message || "fetch failed";
const cause = error?.cause;
const codes = new Set<string>();
if (cause?.code) codes.add(cause.code);
for (const item of cause?.errors ?? []) if (item.code) codes.add(item.code);
const extra = [...codes];
if (!extra.length && cause?.message && cause.message !== message) extra.push(cause.message);
return extra.length ? `${message} (${extra.join(", ")})` : message;
}
export class ZerozeroClient {
private readonly jar = new CookieJar();
private account: { role: string; name: string | null } | null = null;
@@ -103,7 +116,7 @@ export class ZerozeroClient {
try {
res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) });
} catch (err) {
throw new TransportError(`zerozero: ${(err as Error).message}`, true);
throw new TransportError(`zerozero: ${fetchFailure(err)}`, true);
}
this.jar.store(current, res.headers);
const location = res.headers.get("location");
@@ -238,7 +251,12 @@ export class ZerozeroClient {
headers: { "tus-resumable": "1.0.0", "upload-offset": String(offset), "content-type": "application/offset+octet-stream" },
body: new Uint8Array(chunk),
});
if (res.status !== 204) throw new TransportError(`zerozero upload: ${res.status} at ${offset} bytes`, res.status >= 500 || res.status === 409 || res.status === 429);
if (res.status !== 204) {
const detail = (await res.text().catch(() => "")).replace(/\s+/g, " ").slice(0, 180);
// The desk already has this file (a previous attempt landed). Not a failure.
if (res.status === 422 && /j[aá] foi enviada/i.test(detail)) return `synced-${fileName}`;
throw new TransportError(`zerozero upload: ${res.status} at ${offset} bytes${detail ? `: ${detail}` : ""}`, res.status >= 500 || res.status === 409 || res.status === 429);
}
const next = Number(res.headers.get("upload-offset"));
offset = Number.isFinite(next) && next > offset ? next : offset + chunk.length;
}
+9 -2
View File
@@ -2,6 +2,7 @@ import { type DevelopState, type EditCommand, type EditLogEntry, type PostEdits,
import type { Db } from "../db.js";
import { Prisma, type PhotoEdit } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { photoUrls } from "../library/serialize.js";
import type { Broadcaster } from "../realtime.js";
import { type LocalStorage, type UrlSigner, VARIANT_SIZE } from "../storage/storage.js";
@@ -198,6 +199,7 @@ export class RenderWorker {
private inFlight = 0;
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private ticking = false;
constructor(
private readonly service: DevelopService,
@@ -207,6 +209,7 @@ export class RenderWorker {
start(): void {
void this.service.requeueStale();
const tick = async () => {
this.ticking = true;
try {
for (const id of await this.service.claimRenders(this.opts.concurrency - this.inFlight)) {
this.inFlight++;
@@ -216,14 +219,18 @@ export class RenderWorker {
}
} catch (err) {
this.opts.log.warn({ err }, "develop: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "develop: stop timed out with work still running");
}
}
+27
View File
@@ -0,0 +1,27 @@
import { mkdirSync, renameSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
/** No beat for this long means the worker is not running face analysis. */
export const FACE_HEARTBEAT_STALE_MS = 90_000;
/** Written by the face worker, read by the API. Both share the storage directory. */
export function faceHeartbeatPath(storageRoot: string): string {
return join(storageRoot, ".photoreport", "faces-heartbeat");
}
export function touchFaceHeartbeat(storageRoot: string, now = new Date()): void {
const path = faceHeartbeatPath(storageRoot);
mkdirSync(join(storageRoot, ".photoreport"), { recursive: true });
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, now.toISOString());
renameSync(tmp, path);
}
/** True when the worker has written a beat recently. A missing file means face analysis never started. */
export function faceWorkerLive(storageRoot: string, now = Date.now(), staleMs = FACE_HEARTBEAT_STALE_MS): boolean {
try {
return now - statSync(faceHeartbeatPath(storageRoot)).mtimeMs < staleMs;
} catch {
return false;
}
}
+146
View File
@@ -0,0 +1,146 @@
import { isNationalSide, seasonOf } from "../archive/match.js";
import type { Db } from "../db.js";
import { normLabel } from "../jersey/service.js";
import { JERSEY_MIN_SCORE, majorityNumber } from "./votes.js";
/**
* Where a shirt number holds: a player keeps a number within a season and competition, but may wear another one
* five seasons later, in a cup with its own numbering, or for the national team. So a person's number is always
* read for an event's context, never as one number for life.
*/
export interface NumberContext {
organizationId: string;
eventId: string;
/** "20252026": from the official match, or the day (July to June). */
season: string;
/** The competition's code or name, folded ("" when unknown). */
competition: string;
/** A national team's game or session: club numbers never apply. */
national: boolean;
/** The season now: only then does the number typed on the person (with no season of its own) apply. */
current: boolean;
teamIds: string[];
}
const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
const day = (d: Date) => d.toISOString().slice(0, 10);
export function competitionKey(e: { competitionCode: string | null; competition: string | null }): string {
return e.competitionCode ? e.competitionCode.toUpperCase() : e.competition ? fold(e.competition) : "";
}
export function isNationalEvent(e: { home: string; away: string | null; competition: string | null }): boolean {
return isNationalSide(e.home) || isNationalSide(e.away) || /sele[cç][aãoõ]/i.test(e.competition ?? "");
}
/** Season bounds (July to June) of "20252026". */
function seasonRange(season: string): { from: Date; to: Date } {
const start = Number(season.slice(0, 4));
return { from: new Date(Date.UTC(start, 6, 1)), to: new Date(Date.UTC(start + 1, 6, 1)) };
}
/** The context numbers are read in; null for an event that is not a game (no numbers there). */
export async function numberContext(db: Db, eventId: string, now = new Date()): Promise<NumberContext | null> {
const e = await db.event.findUnique({
where: { id: eventId },
select: { organizationId: true, home: true, away: true, competition: true, competitionCode: true, startsAt: true, homeTeamId: true, awayTeamId: true, fixture: { select: { season: true } } },
});
// An event that is not a game (a gala, a session, a presentation): nobody is known by a shirt there, only by face.
if (!e || !e.away?.trim()) return null;
const season = e.fixture?.season ?? seasonOf(day(e.startsAt));
return {
organizationId: e.organizationId,
eventId,
season,
competition: competitionKey(e),
national: isNationalEvent(e),
current: season === seasonOf(day(now)),
teamIds: [e.homeTeamId, e.awayTeamId].filter((t): t is string => !!t),
};
}
/**
* The number each person wears in this context, when it is known: the squad of that season (the official list)
* and what the shirts clearly read in their confirmed photos of the same season and competition (`learned`; first
* when the game is not an official match of a squad's competition), else the number typed on the person, only in
* the current season and never for a national team.
*/
export async function numbersIn(db: Db, ctx: NumberContext, personIds: string[], opts: { learned?: boolean } = {}): Promise<Map<string, string>> {
const out = new Map<string, string>();
if (!personIds.length) return out;
const people = await db.person.findMany({ where: { id: { in: personIds } }, select: { id: true, number: true, sportsPlayerId: true } });
const squadOf = new Map<string, string>();
const learnedOf = new Map<string, string>();
// 1. The squad of that season: the same player (by the federation's id, or name in the same club).
const linked = people.filter((p) => p.sportsPlayerId);
if (linked.length) {
const entries = await db.sportsPlayer.findMany({ where: { id: { in: linked.map((p) => p.sportsPlayerId!) } }, select: { id: true, teamId: true, name: true, externalId: true } });
const byId = new Map(entries.map((e) => [e.id, e]));
const squad = await db.sportsPlayer.findMany({
where: {
season: ctx.season,
number: { not: null },
...(ctx.teamIds.length && { teamId: { in: ctx.teamIds } }),
OR: [
{ externalId: { in: entries.map((e) => e.externalId).filter((x): x is string => !!x) } },
...entries.map((e) => ({ teamId: e.teamId, name: e.name })),
],
},
select: { teamId: true, name: true, externalId: true, number: true },
});
// A national game without its own squads: the clubs' lists say nothing about it.
const usable = ctx.national && !ctx.teamIds.length ? [] : squad;
for (const p of linked) {
const e = byId.get(p.sportsPlayerId!);
if (!e) continue;
const hit = usable.find((s) => (e.externalId && s.externalId === e.externalId) || (s.teamId === e.teamId && s.name === e.name));
const n = hit?.number ? normLabel(hit.number) : null;
if (n) squadOf.set(p.id, n);
}
}
// 2. What their shirts read in other confirmed photos of the same season and competition (and kind of team).
const rest = people.map((p) => p.id);
if (opts.learned !== false) {
const { from, to } = seasonRange(ctx.season);
const events = await db.event.findMany({
where: { organizationId: ctx.organizationId, startsAt: { gte: from, lt: to } },
select: { id: true, home: true, away: true, competition: true, competitionCode: true },
});
const same = events.filter((e) => competitionKey(e) === ctx.competition && isNationalEvent(e) === ctx.national).map((e) => e.id);
if (same.length) {
const faces = await db.face.findMany({
where: { photo: { eventId: { in: same } }, group: { personId: { in: rest } }, jerseyNumber: { not: null }, jerseyScore: { gte: JERSEY_MIN_SCORE } },
select: { jerseyNumber: true, jerseyScore: true, group: { select: { personId: true } } },
});
const byPerson = new Map<string, { jerseyNumber: string | null; jerseyScore: number | null }[]>();
for (const f of faces) {
const id = f.group?.personId;
if (id) byPerson.set(id, [...(byPerson.get(id) ?? []), f]);
}
for (const [id, list] of byPerson) {
const vote = majorityNumber(list);
if (vote && vote.votes >= 3) learnedOf.set(id, vote.number);
}
}
}
// An official match: its season's squad first. A game not linked to one (a cup, a friendly, a tournament with
// its own numbering): what the shirts read in that competition first, then the season's squad.
const order = ctx.teamIds.length ? [squadOf, learnedOf] : [learnedOf, squadOf];
for (const p of people) {
const n = order[0]!.get(p.id) ?? order[1]!.get(p.id);
if (n) out.set(p.id, n);
}
// 3. The number typed on the person: it has no season, so only now, and only for their club.
if (ctx.current && !ctx.national) {
for (const p of people) {
if (out.has(p.id) || !p.number) continue;
const n = normLabel(p.number);
if (n) out.set(p.id, n);
}
}
return out;
}
+18 -6
View File
@@ -35,7 +35,10 @@ const FileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(1
const personOut = (p: { id: string; name: string; club: string | null; number: string | null } | null) =>
p ? { id: p.id, name: p.name, club: p.club, number: p.number } : null;
export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; faces: FaceService; signer: UrlSigner; storage: LocalStorage }) {
export async function registerFaceRoutes(
app: FastifyInstance,
deps: { db: Db; sessions: SessionService; faces: FaceService; signer: UrlSigner; storage: LocalStorage; engineOnline?: () => boolean },
) {
const { db, faces, signer, storage } = deps;
const authenticate = requireAuth(deps.sessions);
const fail = (err: unknown): never => {
@@ -103,7 +106,7 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
preview: signer.url(f.photoId, "preview"),
})),
}));
return { groups: out, pending, unclear };
return { groups: out, pending, unclear, available: deps.engineOnline ? deps.engineOnline() : true };
});
app.post("/v1/face-groups/:groupId/confirm", { preHandler: authenticate }, async (req) => {
@@ -258,18 +261,27 @@ export async function registerFaceRoutes(app: FastifyInstance, deps: { db: Db; s
data: { biometricsEnabled: body.enabled, ...(body.legalBasis !== undefined && { biometricsLegalBasis: body.legalBasis }) },
});
// Switched on: the photos already here are analysed too, not only the ones that arrive from now on.
if (org.biometricsEnabled) await db.photo.updateMany({ where: { organizationId: orgId, status: "READY", facesStatus: "NONE" }, data: { facesStatus: "PENDING" } });
if (org.biometricsEnabled) {
await db.$executeRaw`
UPDATE photos AS p
SET faces_status = 'PENDING',
faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id),
updated_at = now()
WHERE p.organization_id = ${orgId}::uuid AND p.status = 'READY' AND p.faces_status = 'NONE'`;
}
return { enabled: org.biometricsEnabled, legalBasis: org.biometricsLegalBasis };
});
/** Analyse (again) the photos of an event, e.g. after switching face analysis on. */
/**
* Analyse this event ahead of the backlog. Photos already waiting jump the queue; a RUNNING photo is queued
* again only when the worker has left it (it is not the one being analysed right now).
*/
app.post("/v1/events/:eventId/faces/analyse", { preHandler: authenticate }, async (req) => {
const { eventId } = EventParams.parse(req.params);
const event = await db.event.findUnique({ where: { id: eventId }, include: { organization: { select: { biometricsEnabled: true } } } });
if (!event) throw notFound("event_not_found");
await requireMembership(db, req, event.organizationId, "EDITOR");
if (!event.organization.biometricsEnabled) throw conflict("biometrics_disabled");
const r = await db.photo.updateMany({ where: { eventId, status: "READY", facesStatus: { in: ["NONE", "FAILED"] } }, data: { facesStatus: "PENDING" } });
return { queued: r.count };
return { queued: await faces.boostEvent(eventId) };
});
}
+174 -51
View File
@@ -3,6 +3,7 @@ import type { Db } from "../db.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import type { FaceGroup, Person } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import type { Broadcaster } from "../realtime.js";
import type { LocalStorage } from "../storage/storage.js";
import { type Box, colourDistance, kitColour, numberBoxes, smallImage, torsoBox } from "../jersey/crop.js";
@@ -11,36 +12,18 @@ import { normLabel } from "../jersey/service.js";
/** A suggestion this sure (face and shirt agreeing) counts like a confirmation when learning the teams' kit colours. */
const STRONG_SUGGESTION = 0.85;
/** Below this the shirt-number reading is not used for suggestions. */
export const JERSEY_MIN_SCORE = 0.7;
export interface NumberVote {
number: string;
score: number;
votes: number;
}
/** The number more than half of these readings agree on (clear readings only), with its mean score. */
export function majorityNumber(faces: { jerseyNumber: string | null; jerseyScore: number | null }[]): NumberVote | null {
const clear = faces.filter((f) => f.jerseyNumber !== null && (f.jerseyScore ?? 0) >= JERSEY_MIN_SCORE);
const tally = new Map<string, { votes: number; sum: number }>();
for (const f of clear) {
const t = tally.get(f.jerseyNumber!) ?? { votes: 0, sum: 0 };
t.votes++;
t.sum += f.jerseyScore!;
tally.set(f.jerseyNumber!, t);
}
const [best] = [...tally.entries()].sort((a, b) => b[1].votes - a[1].votes);
if (!best || best[1].votes * 2 <= clear.length) return null;
return { number: best[0], score: Math.round((best[1].sum / best[1].votes) * 1000) / 1000, votes: best[1].votes };
}
export { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
const norm = (s: string) => s.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s+/g, " ").trim();
import { JERSEY_MIN_SCORE, majorityNumber, type NumberVote } from "./votes.js";
import { numberContext, numbersIn, type NumberContext } from "./numbers.js";
import { addToMean, cosine, inFocus, mergeMeans, MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import type { FaceEngine } from "./process.js";
/** Faces this small (fraction of the photo's longer side) are crowd, not subjects. */
const MIN_FACE_SIDE = 0.012;
const STALE_RUNNING_MS = 10 * 60_000;
/** A photo left RUNNING this long is no longer being analysed (the worker stopped mid-photo). */
export const STALE_RUNNING_MS = 10 * 60_000;
export class FaceRejected extends Error {
constructor(readonly code: string) {
@@ -76,13 +59,18 @@ export class FaceService {
UPDATE photos SET faces_status = 'RUNNING', updated_at = now()
WHERE id IN (
SELECT id FROM photos WHERE faces_status = 'PENDING' AND status = 'READY'
ORDER BY created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED
ORDER BY faces_boosted_at DESC NULLS LAST, created_at LIMIT ${limit} FOR UPDATE SKIP LOCKED
)
RETURNING id`;
return rows.map((r) => r.id);
}
async requeueStale(now = new Date()): Promise<number> {
// On start, too: suggestions of someone of another sport (made before suggestions knew sports) taken away.
await this.dropCrossSport().then(
(n) => void (n && this.deps.log.warn({ groups: n }, "faces: suggestions of another sport taken away")),
(err) => this.deps.log.warn({ err }, "faces: cross-sport suggestions not checked"),
);
const r = await this.deps.db.photo.updateMany({
where: { facesStatus: "RUNNING", updatedAt: { lt: new Date(now.getTime() - STALE_RUNNING_MS) } },
data: { facesStatus: "PENDING" },
@@ -95,9 +83,33 @@ export class FaceService {
* while a toggle raced their ingest): queue them. Cheap; the worker runs it at start and every minute.
*/
async queueMissed(): Promise<number> {
// A boosted event keeps that place in the queue for photos that were missed, not only the ones already pending.
return Number(
await this.deps.db.$executeRaw`
UPDATE photos AS p
SET faces_status = 'PENDING',
faces_boosted_at = (SELECT e.face_boosted_at FROM events e WHERE e.id = p.event_id),
updated_at = now()
FROM organizations o
WHERE p.organization_id = o.id AND o.biometrics_enabled AND p.faces_status = 'NONE' AND p.status = 'READY'`,
);
}
/**
* The "Analisar caras" button: this event's photos go ahead of the oldest-first backlog, including ones already
* pending. A photo the worker is analysing right now (RUNNING, recently touched) is left alone; one it abandoned
* is queued again.
*/
async boostEvent(eventId: string, now = new Date()): Promise<number> {
const staleBefore = new Date(now.getTime() - STALE_RUNNING_MS);
await this.deps.db.event.update({ where: { id: eventId }, data: { faceBoostedAt: now } });
const r = await this.deps.db.photo.updateMany({
where: { facesStatus: "NONE", status: "READY", organization: { biometricsEnabled: true } },
data: { facesStatus: "PENDING" },
where: {
eventId,
status: "READY",
OR: [{ facesStatus: { in: ["NONE", "FAILED", "PENDING"] } }, { facesStatus: "RUNNING", updatedAt: { lt: staleBefore } }],
},
data: { facesStatus: "PENDING", facesBoostedAt: now },
});
return r.count;
}
@@ -237,12 +249,32 @@ export class FaceService {
}
}
/** See `dropCrossSportSuggestions`. */
dropCrossSport(): Promise<number> {
return dropCrossSportSuggestions(this.deps.db);
}
async refreshSuggestions(eventId: string): Promise<void> {
const { db } = this.deps;
await this.joinSamePerson(eventId);
const groups = await db.faceGroup.findMany({ where: { eventId, personId: null, ignoredAt: null } });
if (!groups.length) return;
const people = await db.person.findMany({ where: { organizationId: groups[0]!.organizationId, NOT: { centroid: { isEmpty: true } } } });
const everyone = await db.person.findMany({ where: { organizationId: groups[0]!.organizationId, NOT: { centroid: { isEmpty: true } } } });
// Never someone of another sport (a footballer at a handball game): known by their squad's team.
const sport = await eventSport(db, eventId);
const sports = sport ? await peopleSports(db, everyone) : new Map<string, string>();
const people = everyone.filter((p) => !sport || !sports.has(p.id) || sports.get(p.id) === sport);
// Numbers as worn in this event's season and competition (another season, a cup, the national team: another).
const ctx = await numberContext(db, eventId);
const worn = new Map<string, string | null>();
const numberOf = async (ids: string[]): Promise<Map<string, string | null>> => {
const missing = ids.filter((id) => !worn.has(id));
if (missing.length && ctx) {
const found = await numbersIn(db, ctx, missing);
for (const id of missing) worn.set(id, found.get(id) ?? null);
}
return worn;
};
for (const g of groups) {
const { match, margin } = this.thresholds(g.model);
const ranked = people
@@ -254,16 +286,19 @@ export class FaceService {
let suggestedPersonId = ok ? first.p.id : null;
let suggestionScore = ok ? first.s : null;
const read = await this.groupNumber(g.id);
if (ok && read && first.p.number && normLabel(first.p.number) !== read.number && read.votes >= 2) {
const firstNumber = ok && read ? (await numberOf([first.p.id])).get(first.p.id) : null;
if (ok && read && firstNumber && firstNumber !== read.number && read.votes >= 2) {
// The face says one person, the shirt clearly says another number: still suggested, but as less sure.
suggestionScore = Math.round(first.s * 0.8 * 1000) / 1000;
} else if (ok && read && normLabel(first.p.number) === read.number) {
} else if (ok && read && firstNumber === read.number) {
// Face and shirt agree on the same player: surer than either alone.
suggestionScore = Math.round(Math.min(0.99, first.s + 0.15 * read.score) * 1000) / 1000;
} else if (!ok && read) {
// The face alone is not sure (too weak, or two people too close): the number decides among the near ones,
// and when two of them wear it (one per team), the kit colour.
let near = ranked.filter((r) => r.s >= match * 0.8 && normLabel(r.p.number) === read.number);
const close = ranked.filter((r) => r.s >= match * 0.8);
const nums = await numberOf(close.map((r) => r.p.id));
let near = close.filter((r) => nums.get(r.p.id) === read.number);
if (near.length > 1) {
const team = await this.teamByKit(g.id, eventId);
const onTeam = team ? await this.playersOfTeam(near.map((r) => r.p), team.teamId) : null;
@@ -274,7 +309,7 @@ export class FaceService {
suggestionScore = Math.round(Math.max(near[0]!.s, read.score * 0.9) * 1000) / 1000;
} else {
// No face to go by: the number (and, when both teams have it, the colour of the kit).
const byNumber = await this.suggestByNumber(g.id, eventId, read);
const byNumber = ctx ? await this.suggestByNumber(g.id, ctx, read) : null;
if (byNumber) ({ personId: suggestedPersonId, score: suggestionScore } = byNumber);
}
}
@@ -294,40 +329,53 @@ export class FaceService {
* A suggestion from the shirt number: when one squad player of the event's teams has it, or when both teams have
* one and the kit colour clearly says which team. Never names on its own.
*/
private async suggestByNumber(groupId: string, eventId: string, read: NumberVote): Promise<{ personId: string; score: number } | null> {
private async suggestByNumber(groupId: string, ctx: NumberContext, read: NumberVote): Promise<{ personId: string; score: number } | null> {
const { db } = this.deps;
const eventId = ctx.eventId;
const event = await db.event.findUnique({
where: { id: eventId },
select: { organizationId: true, home: true, away: true, homeShort: true, awayShort: true, homeTeamId: true, awayTeamId: true },
});
if (!event) return null;
// Linked to the official match: the squads say who wears the number.
const teamIds = [event.homeTeamId, event.awayTeamId].filter((t): t is string => !!t);
// Linked to the official match: that season's squads say who wears the number (not today's squad).
const teamIds = ctx.teamIds;
if (teamIds.length) {
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, goneAt: null, number: read.number }, select: { id: true, teamId: true } });
const people = players.length
? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: players.map((p) => p.id) } }, select: { id: true } })
const players = await db.sportsPlayer.findMany({ where: { teamId: { in: teamIds }, season: ctx.season, number: read.number }, select: { id: true, teamId: true, name: true, externalId: true } });
// The person may have been made from another season's entry of the same player.
const same = players.length
? await db.sportsPlayer.findMany({
where: { OR: [{ externalId: { in: players.map((p) => p.externalId).filter((x): x is string => !!x) } }, ...players.map((p) => ({ teamId: p.teamId, name: p.name }))] },
select: { id: true, teamId: true, name: true, externalId: true },
})
: [];
const teamOf = new Map<string, string>();
for (const sp of same) {
const season = players.find((p) => (p.externalId && p.externalId === sp.externalId) || (p.teamId === sp.teamId && p.name === sp.name));
if (season) teamOf.set(sp.id, season.teamId);
}
const people = teamOf.size
? await db.person.findMany({ where: { organizationId: event.organizationId, sportsPlayerId: { in: [...teamOf.keys()] } }, select: { id: true, sportsPlayerId: true } })
: [];
if (people.length === 1) return { personId: people[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
if (people.length === 2) {
// One in each team: the kit colour of this group against each team's (from players already confirmed here).
const byPlayer = new Map(players.map((p) => [p.id, p.teamId]));
const withTeam = await db.person.findMany({ where: { id: { in: people.map((p) => p.id) } }, select: { id: true, sportsPlayerId: true } });
const team = await this.teamByKit(groupId, eventId);
const pick = team ? withTeam.find((p) => p.sportsPlayerId && byPlayer.get(p.sportsPlayerId) === team.teamId) : undefined;
const pick = team ? people.find((p) => p.sportsPlayerId && teamOf.get(p.sportsPlayerId) === team.teamId) : undefined;
if (pick && team) return { personId: pick.id, score: Math.round(read.score * 0.85 * team.sure * 1000) / 1000 };
}
if (players.length) return null; // two players with that number and no clear kit, or not people yet: no guess
}
// Not linked: people of these clubs (or this national team) who wear that number in this season and competition.
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(norm);
const candidates = (await db.person.findMany({ where: { organizationId: event.organizationId, number: { not: null }, club: { not: null } } }))
.filter((p) => normLabel(p.number) === read.number)
.filter((p) => {
const club = norm(p.club!);
return teams.some((t) => t && (t.includes(club) || club.includes(t)));
});
if (candidates.length !== 1) return null;
return { personId: candidates[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
const candidates = (await db.person.findMany({ where: { organizationId: event.organizationId, club: { not: null } }, select: { id: true, club: true } })).filter((p) => {
const club = norm(p.club!);
return teams.some((t) => t && (t.includes(club) || club.includes(t)));
});
if (!candidates.length || candidates.length > 400) return null;
const nums = await numbersIn(db, ctx, candidates.map((p) => p.id));
const wearing = candidates.filter((p) => nums.get(p.id) === read.number);
if (wearing.length !== 1) return null;
return { personId: wearing[0]!.id, score: Math.round(read.score * 0.9 * 1000) / 1000 };
}
/** Which of these people play for the team (by their squad entry). */
@@ -520,21 +568,92 @@ export class FaceService {
}
/** Keeps `processes` face engines busy. */
/** "Futebol", "football" → "futebol"; "Andebol", "handball" → "andebol". */
export function normSport(s: string | null | undefined): string | null {
const v = (s ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().trim();
if (!v) return null;
if (/futebol|football|soccer/.test(v)) return "futebol";
if (/andebol|handball/.test(v)) return "andebol";
return v;
}
/** The sport of an event: its own, its official game's, or its archive cloud's (Liga: football, FPA: handball). */
export async function eventSport(db: Db, eventId: string): Promise<string | null> {
const rows = await db.$queryRaw<{ sport: string | null }[]>`
SELECT COALESCE(e.sport, c.sport, CASE s.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END) AS sport
FROM events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
LEFT JOIN LATERAL (SELECT cs.look FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1) s ON true
WHERE e.id = ${eventId}::uuid`;
return normSport(rows[0]?.sport);
}
/** Each person's sport, from the team of the squad they came from (people typed by hand have none). */
export async function peopleSports(db: Db, people: { id: string; sportsPlayerId: string | null }[]): Promise<Map<string, string>> {
const ids = [...new Set(people.map((p) => p.sportsPlayerId).filter((x): x is string => !!x))];
if (!ids.length) return new Map();
const players = await db.sportsPlayer.findMany({ where: { id: { in: ids } }, select: { id: true, team: { select: { sport: true } } } });
const bySquad = new Map(players.map((p) => [p.id, normSport(p.team.sport)]));
const out = new Map<string, string>();
for (const p of people) {
const sport = p.sportsPlayerId ? bySquad.get(p.sportsPlayerId) : null;
if (sport) out.set(p.id, sport);
}
return out;
}
/**
* Suggestions of someone of another sport than the event's (made before suggestions knew sports) taken away;
* names confirmed by a person stay. Returns how many.
*/
export async function dropCrossSportSuggestions(db: Db): Promise<number> {
const n = await db.$executeRaw`
UPDATE face_groups g SET suggested_person_id = NULL, suggestion_score = NULL
FROM people p, sports_players sp, sports_teams t, events e
LEFT JOIN sports_fixtures f ON f.id = e.fixture_id
LEFT JOIN sports_competitions c ON c.id = f.competition_id
WHERE g.suggested_person_id = p.id AND sp.id = p.sports_player_id AND t.id = sp.team_id AND e.id = g.event_id
AND g.person_id IS NULL
AND lower(t.sport) <> lower(COALESCE(e.sport, c.sport, (
SELECT CASE cs.look WHEN 'liga' THEN 'futebol' WHEN 'fpa' THEN 'andebol' END
FROM cloud_folders cf JOIN cloud_sources cs ON cs.id = cf.source_id WHERE cf.event_id = e.id LIMIT 1), lower(t.sport)))`;
return n;
}
export class FaceWorker {
private inFlight = 0;
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private ticking = false;
private lastBeat = 0;
constructor(
private readonly service: FaceService,
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger },
private readonly opts: { concurrency: number; intervalMs: number; log: IngestLogger; heartbeat?: () => void },
) {}
/** Lets the API tell a dead worker from a long queue. Throttled: the tick itself is every second. */
private beat(): void {
if (!this.opts.heartbeat) return;
const now = Date.now();
if (now - this.lastBeat < 15_000) return;
this.lastBeat = now;
try {
this.opts.heartbeat();
} catch (err) {
this.opts.log.warn({ err }, "faces: heartbeat not written");
}
}
start(): void {
void this.service.requeueStale();
let missedAt = 0;
const tick = async () => {
this.ticking = true;
try {
this.beat();
if (Date.now() - missedAt > 60_000) {
missedAt = Date.now();
const n = await this.service.queueMissed();
@@ -550,14 +669,18 @@ export class FaceWorker {
}
} catch (err) {
this.opts.log.warn({ err }, "faces: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "faces: stop timed out with work still running");
}
}
+22
View File
@@ -0,0 +1,22 @@
/** Below this the shirt-number reading is not used for suggestions. */
export const JERSEY_MIN_SCORE = 0.7;
export interface NumberVote {
number: string;
score: number;
votes: number;
}
/** The number more than half of these readings agree on (clear readings only), with its mean score. */
export function majorityNumber(faces: { jerseyNumber: string | null; jerseyScore: number | null }[]): NumberVote | null {
const clear = faces.filter((f) => f.jerseyNumber !== null && (f.jerseyScore ?? 0) >= JERSEY_MIN_SCORE);
const tally = new Map<string, { votes: number; sum: number }>();
for (const f of clear) {
const t = tally.get(f.jerseyNumber!) ?? { votes: 0, sum: 0 };
t.votes++;
t.sum += f.jerseyScore!;
tally.set(f.jerseyNumber!, t);
}
const [best] = [...tally.entries()].sort((a, b) => b[1].votes - a[1].votes);
if (!best || best[1].votes * 2 <= clear.length) return null;
return { number: best[0], score: Math.round((best[1].sum / best[1].votes) * 1000) / 1000, votes: best[1].votes };
}
+34
View File
@@ -38,6 +38,22 @@ const iim = (v: unknown) => {
};
const iimList = (v: unknown) => list(v)?.map(repairMacRoman);
/** IPTC Core's creator contact block (XMP struct `Iptc4xmpCore:CreatorContactInfo`). */
function contact(value: unknown): Record<string, string | undefined> {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const c = value as Raw;
return {
creatorAddress: text(c.CiAdrExtadr),
creatorCity: text(c.CiAdrCity),
creatorRegion: text(c.CiAdrRegion),
creatorPostalCode: text(c.CiAdrPcode),
creatorCountry: text(c.CiAdrCtry),
creatorPhone: text(c.CiTelWork),
creatorEmail: text(c.CiEmailWork),
creatorUrl: text(c.CiUrlWork),
};
}
export async function readEmbeddedIptc(file: string | Buffer): Promise<IptcValues> {
let tags: Raw | undefined;
try {
@@ -60,6 +76,24 @@ export async function readEmbeddedIptc(file: string | Buffer): Promise<IptcValue
supplementalCategories: list(tags.SupplementalCategories)?.map(repairMacRoman),
creator: text(tags.creator) ?? iim(tags.Byline),
personsShown: list(tags.PersonInImage),
// The rest of Photo Mechanic's pad.
jobTitle: text(tags.AuthorsPosition) ?? iim(tags.BylineTitle),
captionWriter: text(tags.CaptionWriter) ?? iim(tags.Writer),
// Same names in IIM and XMP (exifr merges them): repairing is harmless on XMP's UTF-8.
state: iim(tags.State),
country: iim(tags.Country),
countryCode: iim(tags.CountryCode),
transmissionReference: text(tags.TransmissionReference) ?? iim(tags.OriginalTransmissionReference),
instructions: text(tags.Instructions) ?? iim(tags.SpecialInstructions),
category: iim(tags.Category),
urgency: iim(tags.Urgency),
editStatus: iim(tags.EditStatus),
genre: text(tags.IntellectualGenre) ?? iim(tags.ObjectAttributeReference),
scene: list(tags.Scene)?.join(", "),
subjectCode: list(tags.SubjectCode)?.join(", ") ?? iim(tags.SubjectReference),
usageTerms: text(tags.UsageTerms),
copyrightUrl: text(tags.WebStatement),
...contact(tags.CreatorContactInfo),
};
return Object.fromEntries(Object.entries(found).filter(([, v]) => v !== undefined)) as IptcValues;
}
+81 -1
View File
@@ -1,5 +1,34 @@
import type { PmPhoto } from "@photoreport/metadata";
import exifr from "exifr";
/**
* The camera details Photo Mechanic shows beyond the ones with their own column (stored in `photos.exif`), for
* its variables: {comp}, {flash}, {meteringmode}, {program}, {white}, {lens35}, {owner}, {artist}... Readable
* strings, as Photo Mechanic writes them.
*/
export type CameraExtra = Pick<
PmPhoto,
| "exposureCompensation"
| "flashFired"
| "meteringMode"
| "exposureProgram"
| "whiteBalance"
| "focalLength35"
| "lensRange"
| "software"
| "firmware"
| "owner"
| "artist"
| "tiffCopyright"
| "imageDescription"
| "userComment"
| "colorSpace"
| "resolution"
| "latitude"
| "longitude"
| "altitude"
>;
export interface CameraInfo {
capturedAt?: Date | undefined;
cameraMake?: string | undefined;
@@ -10,6 +39,7 @@ export interface CameraInfo {
aperture?: number | undefined;
exposureTime?: number | undefined;
iso?: number | undefined;
extra?: CameraExtra | undefined;
}
const TIME_ZONE = "Europe/Lisbon";
@@ -57,11 +87,60 @@ export function parseExifDate(value: unknown, offset?: unknown, subSec?: unknown
const str = (v: unknown) => (typeof v === "string" && v.trim() !== "" ? v.trim().replace(/\0+$/, "") : undefined);
const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
const METERING = ["Unknown", "Average", "Center-weighted average", "Spot", "Multi-spot", "Multi-segment", "Partial"];
const PROGRAM = ["Not Defined", "Manual", "Program AE", "Aperture-priority AE", "Shutter speed priority AE", "Creative (Slow speed)", "Action (High speed)", "Portrait", "Landscape"];
const COLOR_SPACE: Record<number, string> = { 1: "sRGB", 2: "Adobe RGB", 65535: "Uncalibrated" };
/** UserComment comes as bytes with an 8-byte charset header ("ASCII\0\0\0", "UNICODE\0"). */
function comment(v: unknown): string | undefined {
if (typeof v === "string") return str(v);
if (!(v instanceof Uint8Array) || v.length <= 8) return undefined;
const head = new TextDecoder("latin1").decode(v.subarray(0, 8));
const body = v.subarray(8);
const text = head.startsWith("UNICODE") ? new TextDecoder(body[0] === 0 ? "utf-16be" : "utf-16le").decode(body) : new TextDecoder().decode(body);
return str(text.replace(/\0+/g, " "));
}
function extraOf(tags: Record<string, unknown>): CameraExtra {
const flash = num(tags.Flash);
const metering = num(tags.MeteringMode);
const program = num(tags.ExposureProgram);
const wb = num(tags.WhiteBalance);
const lensInfo = Array.isArray(tags.LensInfo) ? (tags.LensInfo as unknown[]).map(num) : [];
const software = str(tags.Software);
const lat = num(tags.latitude);
const lon = num(tags.longitude);
const alt = num(tags.GPSAltitude);
const extra: CameraExtra = {
exposureCompensation: num(tags.ExposureCompensation) ?? num(tags.ExposureBiasValue),
flashFired: flash === undefined ? undefined : (flash & 1) === 1,
meteringMode: metering === undefined ? undefined : (METERING[metering] ?? (metering === 255 ? "Other" : undefined)),
exposureProgram: program === undefined ? undefined : PROGRAM[program],
whiteBalance: wb === undefined ? undefined : wb === 0 ? "Auto" : "Manual",
focalLength35: num(tags.FocalLengthIn35mmFormat),
lensRange: lensInfo[0] && lensInfo[1] ? [lensInfo[0], lensInfo[1]] : undefined,
software,
// Canon and Nikon write the firmware as the Software ("Firmware Version 1.8.1", "Ver.1.10").
firmware: software && /firmware|^ver\.?\s*\d/i.test(software) ? software.replace(/^firmware\s*version\s*/i, "") : undefined,
owner: str(tags.OwnerName) ?? str(tags.CameraOwnerName),
artist: str(tags.Artist),
tiffCopyright: str(tags.Copyright),
imageDescription: str(tags.ImageDescription),
userComment: comment(tags.UserComment),
colorSpace: COLOR_SPACE[num(tags.ColorSpace) ?? -1],
resolution: num(tags.XResolution),
latitude: lat,
longitude: lon,
altitude: alt === undefined ? undefined : num(tags.GPSAltitudeRef) === 1 ? -alt : alt,
};
return Object.fromEntries(Object.entries(extra).filter(([, v]) => v !== undefined)) as CameraExtra;
}
export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo> {
const tags = (await exifr.parse(file, {
tiff: true,
exif: true,
gps: false,
gps: true,
iptc: false,
xmp: false,
icc: false,
@@ -80,5 +159,6 @@ export async function readCameraInfo(file: string | Buffer): Promise<CameraInfo>
aperture: num(tags.FNumber),
exposureTime: num(tags.ExposureTime),
iso,
extra: extraOf(tags),
};
}
+7 -2
View File
@@ -1,5 +1,6 @@
import { readdir, stat } from "node:fs/promises";
import path from "node:path";
import { waitUntil } from "../lib/idle.js";
import type { IngestLogger, IngestService } from "./service.js";
interface Seen {
@@ -17,6 +18,7 @@ export class IngestScanner {
private readonly busy = new Set<string>();
private timer: NodeJS.Timeout | undefined;
private running = false;
private stopped = false;
constructor(
private readonly service: IngestService,
@@ -36,13 +38,16 @@ export class IngestScanner {
this.running = false;
}
}
this.timer = setTimeout(tick, this.opts.intervalMs);
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.running && this.busy.size === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ busy: this.busy.size }, "ingest: stop timed out with work still running");
}
private async *walk(dir: string): AsyncGenerator<string> {
+27 -4
View File
@@ -38,6 +38,9 @@ export interface PreviewOf {
}
export class IngestService {
/** Called with each photo that is ready in an event (the worker sends it to the destinations taking all arrivals). */
arrivals?: (photo: { id: string; organizationId: string; uploaderId: string | null }) => Promise<void>;
constructor(
private readonly deps: {
db: Db;
@@ -86,12 +89,19 @@ export class IngestService {
return { status: "skipped", reason: "unknown_login" };
}
// "Receber FTP aqui": the login sends everything to the event chosen in the library, whatever the camera's
// clock says, until the time set; then (or with that event put away) by the time again.
const target =
account.targetEventId && (!account.targetUntil || account.targetUntil > new Date())
? await db.event.findFirst({ where: { id: account.targetEventId, organizationId: account.organizationId, archivedAt: null }, select: { id: true } })
: null;
return this.ingest(file, {
organizationId: account.organizationId,
userId: account.userId,
source: "FTP",
originalName: path.basename(file),
clockOffsetSec: account.clockOffsetSec,
eventId: target?.id,
});
}
@@ -164,6 +174,7 @@ export class IngestService {
aperture: camera.aperture ?? null,
exposureTime: camera.exposureTime ?? null,
iso: camera.iso ?? null,
...(camera.extra && Object.keys(camera.extra).length && { exif: camera.extra }),
...(Object.keys(embedded).length && { embeddedIptc: embedded }),
},
});
@@ -182,16 +193,25 @@ export class IngestService {
const { width, height } = origin.original?.width && origin.original.height ? { width: origin.original.width, height: origin.original.height } : made;
const org = await db.organization.findUnique({ where: { id: orgId }, select: { biometricsEnabled: true } });
// The event's autopilot edits what arrives by FTP or the desktop app's ingest; hand uploads stay as sent.
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true } }) : null;
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null;
const autopilot = origin.source !== "UPLOAD" && origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
photo = await db.photo.update({
where: { id: photo.id },
data: { status: "READY", width, height, facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE", ...(autopilot && { autopilotStatus: "PENDING" }) },
data: {
status: "READY",
width,
height,
facesStatus: org?.biometricsEnabled ? "PENDING" : "NONE",
...(org?.biometricsEnabled && event?.faceBoostedAt && { facesBoostedAt: event.faceBoostedAt }),
...(autopilot && { autopilotStatus: "PENDING" }),
},
});
// Photo Mechanic's "Rename as" on Live Ingest: the arrival name (camera name kept in originalName).
if (origin.source !== "UPLOAD" && origin.source !== "CLOUD") await applyRename(db, photo.id).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: rename failed"));
outcome = { status: "ingested", photoId: photo.id, eventId };
log.info({ photoId: photo.id, eventId, source: origin.source }, "ingest: photo ready");
// A copy of every arrival where one asked for it (one's own backup, a client taking everything).
if (eventId && origin.source !== "CLOUD" && this.arrivals) await this.arrivals({ id: photo.id, organizationId: orgId, uploaderId: photo.uploaderId }).catch((err) => log.warn({ err, photoId: photo!.id }, "ingest: arrival not sent on"));
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
photo = await db.photo.update({ where: { id: photo.id }, data: { status: "FAILED", error } });
@@ -247,12 +267,15 @@ export class IngestService {
private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> {
const { storage } = this.deps;
const source = storage.resolve(storageKey);
const meta = await sharp(source).metadata();
// A truncated upload (interrupted FTP) still has a usable image: decode what is there
// instead of failing the whole photo, as Photo Mechanic does. Genuinely unreadable
// files still throw below (no width/height).
const meta = await sharp(source, { failOn: "none" }).metadata();
if (!meta.width || !meta.height) throw new Error("not a readable image");
const rotated = (meta.orientation ?? 1) >= 5;
for (const variant of ["thumb", "preview"] as const) {
const side = VARIANT_SIZE[variant];
const data = await sharp(source)
const data = await sharp(source, { failOn: "none" })
.rotate()
.resize({ width: side, height: side, fit: "inside", withoutEnlargement: true })
.jpeg({ quality: variant === "thumb" ? 80 : 88, mozjpeg: true })
+9 -2
View File
@@ -2,6 +2,7 @@ import type { Db } from "../db.js";
import type { SecretBox } from "../delivery/secrets.js";
import type { Invoice } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { lineNet } from "../shop/earnings.js";
import { periodOf, periodRange } from "../shop/press.js";
import { countryName, type DocumentInput, InvoiceXpress, InvoicingError } from "./invoicexpress.js";
@@ -201,6 +202,7 @@ export class InvoicingService {
export class InvoicingWorker {
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private ticking = false;
private lastMonthly = 0;
constructor(
@@ -210,6 +212,7 @@ export class InvoicingWorker {
start(): void {
const tick = async () => {
this.ticking = true;
try {
// Monthly press invoices: checked every hour, created once per account and month.
if (Date.now() - this.lastMonthly > 3600_000) {
@@ -220,14 +223,18 @@ export class InvoicingWorker {
for (const id of await this.invoicing.claim(5)) await this.invoicing.issue(id);
} catch (err) {
this.opts.log.warn({ err }, "invoicing: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking, { timeoutMs });
if (!drained) this.opts.log.warn({}, "invoicing: stop timed out with work still running");
}
}
+3 -3
View File
@@ -69,7 +69,7 @@ export function numberBoxes(face: Box, width: number, height: number): { region:
* sharp as the photo has it; the model scales it itself).
*/
export async function cropJpeg(original: string, box: Box, size = 512): Promise<Buffer> {
const img = sharp(original).rotate();
const img = sharp(original, { failOn: "none" }).rotate();
const meta = await img.metadata();
const w = meta.autoOrient?.width ?? meta.width ?? 1;
const h = meta.autoOrient?.height ?? meta.height ?? 1;
@@ -77,7 +77,7 @@ export async function cropJpeg(original: string, box: Box, size = 512): Promise<
const top = Math.round(box.y0 * h);
const width = Math.max(1, Math.min(w - left, Math.round((box.x1 - box.x0) * w)));
const height = Math.max(1, Math.min(h - top, Math.round((box.y1 - box.y0) * h)));
return sharp(original).rotate().extract({ left, top, width, height }).resize({ width: size, height: size, fit: "inside", withoutEnlargement: true }).jpeg({ quality: 92 }).toBuffer();
return sharp(original, { failOn: "none" }).rotate().extract({ left, top, width, height }).resize({ width: size, height: size, fit: "inside", withoutEnlargement: true }).jpeg({ quality: 92 }).toBuffer();
}
/** A photo decoded once, small: enough to tell the colour of a kit. */
@@ -89,7 +89,7 @@ export interface SmallImage {
}
export async function smallImage(original: string, side = 512): Promise<SmallImage> {
const { data, info } = await sharp(original).rotate().resize(side, side, { fit: "inside" }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
const { data, info } = await sharp(original, { failOn: "none" }).rotate().resize(side, side, { fit: "inside" }).removeAlpha().raw().toBuffer({ resolveWithObject: true });
return { data, width: info.width, height: info.height, channels: info.channels };
}
+2 -2
View File
@@ -37,7 +37,7 @@ export class JerseyModel {
/** Reads the number in `box` (fractions of the upright photo). `number` is null when it can't be read. */
async read(original: string, box: Box): Promise<JerseyReading> {
const { size, mean, std, letterbox, labels } = this.meta;
const img = sharp(original).rotate();
const img = sharp(original, { failOn: "none" }).rotate();
const m = await img.metadata();
const w = m.autoOrient?.width ?? m.width ?? 1;
const h = m.autoOrient?.height ?? m.height ?? 1;
@@ -45,7 +45,7 @@ export class JerseyModel {
const top = Math.round(box.y0 * h);
const width = Math.max(1, Math.min(w - left, Math.round((box.x1 - box.x0) * w)));
const height = Math.max(1, Math.min(h - top, Math.round((box.y1 - box.y0) * h)));
const { data } = await sharp(original)
const { data } = await sharp(original, { failOn: "none" })
.rotate()
.extract({ left, top, width, height })
.resize({ width: size, height: size, fit: "contain", background: { r: letterbox, g: letterbox, b: letterbox } })
+21 -4
View File
@@ -1,3 +1,4 @@
import { numberContext, numbersIn, type NumberContext } from "../faces/numbers.js";
import { createHmac } from "node:crypto";
import type { Db } from "../db.js";
import type { JerseySample, JerseySampleStatus } from "../generated/prisma/client.js";
@@ -59,20 +60,36 @@ export class JerseyService {
organizationId,
jerseyCrops: { lt: JERSEY_CROPS },
OR: [{ sharpness: null }, { sharpness: { gte: MIN_SHARPNESS } }],
group: { person: { number: { not: null } } },
group: { personId: { not: null } },
},
include: { photo: { select: { width: true, height: true } }, group: { include: { person: true } }, jerseySamples: { select: { region: true } } },
include: { photo: { select: { width: true, height: true, eventId: true } }, group: { include: { person: true } }, jerseySamples: { select: { region: true } } },
take: 5000,
});
// The number the person wore in that photo's season and competition (squad, or the one typed on them this
// season): never another season's, a cup's own or a club number on a national team's shirt. Not what the
// model itself reads, which is what is being taught.
const contexts = new Map<string, NumberContext | null>();
const numbers = new Map<string, string | null>();
const wornIn = async (eventId: string | null, personId: string): Promise<string | null> => {
if (!eventId) return null;
const key = `${eventId}|${personId}`;
if (numbers.has(key)) return numbers.get(key)!;
if (!contexts.has(eventId)) contexts.set(eventId, await numberContext(db, eventId));
const ctx = contexts.get(eventId);
const n = ctx ? ((await numbersIn(db, ctx, [personId], { learned: false })).get(personId) ?? null) : null;
numbers.set(key, n);
return n;
};
let added = 0;
for (const f of faces) {
const person = f.group?.person;
const have = new Set(f.jerseySamples.map((s) => s.region));
const boxes = person?.number && f.photo.width && f.photo.height ? numberBoxes(f, f.photo.width, f.photo.height) : [];
const number = person ? await wornIn(f.photo.eventId, person.id) : null;
const boxes = number && f.photo.width && f.photo.height ? numberBoxes(f, f.photo.width, f.photo.height) : [];
for (const { region, box } of boxes) {
if (have.has(region)) continue;
await db.jerseySample.create({
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: normLabel(person!.number) ?? person!.number!.trim() },
data: { organizationId, faceId: f.id, photoId: f.photoId, personId: person!.id, region, ...box, suggested: number! },
});
added++;
}
+14 -3
View File
@@ -16,6 +16,11 @@ export interface Capacity {
archive: number;
/** The archive with a big backlog (a first import): most of the machine, until the backlog is gone. */
archiveBurst: number;
/**
* Archive images in flight at once with a big backlog: most of each one is waiting for the cloud's download, so
* many more than the CPUs; only `archiveBurst` of them make previews at the same time.
*/
archiveDownloads: number;
faces: number;
render: number;
delivery: number;
@@ -38,11 +43,17 @@ export function planCapacity(
return {
cpus,
memoryGb: Math.round(memoryGb * 10) / 10,
// Face processes wait idle when there is nothing to analyse (memory only): enough for an archive's backlog.
faces: set.faces ?? clamp(Math.min(cpus * 0.45, byMemory("faces", 0.4)), 2, 32),
// Face binaries use the cores and wait idle when there is nothing to analyse. Their results are committed
// by this one Node thread, which also uploads to ZeroZero. Dozens at once stall that thread: deliveries
// fail with "fetch failed" and face transactions expire. FACES_PROCESSES in the environment still overrides.
faces: set.faces ?? clamp(Math.min(cpus * 0.9, byMemory("faces", 0.5)), 2, 6),
ingest: set.ingest ?? clamp(Math.min(cpus * 0.25, byMemory("ingest", 0.15)), 4, 32),
archive: set.archive ?? clamp(Math.min(cpus * 0.3, byMemory("archive", 0.2)), 2, 32),
archiveBurst: set.archive ?? clamp(Math.min(cpus * 0.75, byMemory("archive", 0.35)), 2, 64),
// A fixed ARCHIVE_CONCURRENCY sets the everyday pace; a big backlog still gets the machine's share.
// A backlog to clear gets as much as the machine has: previews several per core (each waits on disk and the
// database too), and many more images in flight, which mostly wait for the cloud.
archiveBurst: Math.max(set.archive ?? 0, clamp(Math.min(cpus * 3, byMemory("archive", 0.6)), 2, 192)),
archiveDownloads: clamp(Math.max(16, cpus * 20), 16, 1000),
render: set.render ?? clamp(Math.min(cpus * 0.15, byMemory("render", 0.15)), 2, 12),
delivery: set.delivery ?? clamp(cpus * 0.25, 4, 16),
};
+17
View File
@@ -0,0 +1,17 @@
/**
* Wait until `ok()` is true, or until `timeoutMs` elapses.
* Used by worker shutdown to drain in-flight jobs before `$disconnect()` (BIT-31189).
*/
export async function waitUntil(
ok: () => boolean,
opts: { timeoutMs?: number; intervalMs?: number } = {},
): Promise<boolean> {
const timeoutMs = opts.timeoutMs ?? 25_000;
const intervalMs = opts.intervalMs ?? 50;
const deadline = Date.now() + timeoutMs;
while (!ok()) {
if (Date.now() >= deadline) return false;
await new Promise<void>((r) => setTimeout(r, intervalMs));
}
return true;
}
+4
View File
@@ -21,6 +21,10 @@ export class LineProcess {
if (this.ready) return this.ready;
const child = spawn(this.opts.bin, this.opts.args ?? [], { stdio: ["pipe", "pipe", "pipe"] });
this.child = child;
// Writing to stdin after the child has died (e.g. mid-request crash) raises EPIPE; without
// this listener the unhandled "error" event on the stream kills the whole Node process.
// The "exit" handler below still rejects any pending requests.
child.stdin.on("error", () => {});
let stderr = "";
child.stderr.on("data", (d: Buffer) => {
stderr = (stderr + d.toString()).slice(-2000);
+12
View File
@@ -0,0 +1,12 @@
import { setDefaultResultOrder } from "node:dns";
import { setDefaultAutoSelectFamily } from "node:net";
/**
* Use IPv4 only. fotos.zerozero.pt (Cloudflare) publishes IPv6 addresses this network cannot reach.
* Happy Eyeballs then fails the whole request ("fetch failed") even though IPv4 is fine.
* Call before any request. An IPv6-only host would need this removed.
*/
export function preferIpv4(): void {
setDefaultResultOrder("ipv4first");
setDefaultAutoSelectFamily(false);
}
+15
View File
@@ -125,6 +125,14 @@ export class ErrorReporter {
watchProcess(component: string): void {
if (!this.enabled) return;
process.on("uncaughtException", (err) => {
if (isUndiciSocketEndAssertion(err)) {
// Known upstream bug (nodejs/undici#5360): undici's HTTP/1 parser asserts !this.paused when the remote
// socket ends while the parser is paused for backpressure. It fires from the socket's own "end" handler,
// so no try/catch around the request can reach it. The one connection involved is already gone; nothing
// else in this process is corrupted, so log it and keep running instead of killing a healthy worker/api.
this.reportError(err, component, { uncaught: true, undici_known_bug: "nodejs/undici#5360" }, "warning");
return;
}
this.reportError(err, component, { uncaught: true }, "critical");
void this.flush().finally(() => process.exit(1));
});
@@ -177,6 +185,13 @@ function frameOf(stack?: string): { file: string; line: number } | null {
return null;
}
/** nodejs/undici#5360: `assert(!this.paused)` / `false == true` thrown from the parser when a socket ends mid-backpressure. */
function isUndiciSocketEndAssertion(err: unknown): boolean {
if (!(err instanceof Error) || (err as { code?: unknown }).code !== "ERR_ASSERTION") return false;
const stack = err.stack ?? "";
return /undici/.test(stack) && /Parser\.finish|onHttpSocketEnd|onParserTimeout/.test(stack);
}
/** The reporter of this deployment (off without ERROR_REPORTING_TOKEN, and in tests). */
export function reporterFor(
config: { ERROR_REPORTING_TOKEN?: string | undefined; ERROR_REPORTING_ENDPOINT: string; ERROR_REPORTING_DISABLED: boolean; NODE_ENV: string; APP_VERSION: string },
+5 -2
View File
@@ -8,10 +8,13 @@ import { applyRename } from "./rename.js";
*/
export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise<void> {
if (!ids.length) return;
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } });
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true, organization: { select: { biometricsEnabled: true } } } });
if (!event) return;
if (event.organization.biometricsEnabled) {
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED"] } }, data: { facesStatus: "PENDING" } });
await db.photo.updateMany({
where: { id: { in: ids }, status: "READY", facesStatus: { in: ["DONE", "FAILED", "PENDING"] } },
data: { facesStatus: "PENDING", facesBoostedAt: event.faceBoostedAt },
});
}
if ((event.autopilot as { enabled?: boolean } | null)?.enabled === true) {
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "UPLOAD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } });
+75 -5
View File
@@ -7,7 +7,7 @@ import type { SessionService } from "../auth/sessions.js";
import type { Db } from "../db.js";
import { type Event, Prisma } from "../generated/prisma/client.js";
import { compact } from "../lib/compact.js";
import { badRequest, notFound } from "../lib/errors.js";
import { badRequest, conflict, forbidden, notFound } from "../lib/errors.js";
import type { Broadcaster } from "../realtime.js";
import type { SportsService } from "../sports/service.js";
import { claimInbox } from "./adopt.js";
@@ -51,24 +51,43 @@ const ListQuery = z.object({
from: z.coerce.date().optional(),
to: z.coerce.date().optional(),
includeArchived: z.coerce.boolean().default(false),
/** Only the events put away by hand (not the archive's own games, which the Arquivo page lists). */
archived: z.coerce.boolean().default(false),
});
const FtpTarget = z.object({
/** The FTP logins that send everything here; the others pointing here stop. */
accountIds: z.array(z.uuid()).max(100),
/** Until when; null: until switched off. Left out: the end of the event's window (or 12 h from now if past). */
until: z.coerce.date().nullable().optional(),
});
type EventWithPeople = Event & { assignments: { user: { id: string; name: string } }[]; _count: { photos: number } };
type EventWithPeople = Event & {
assignments: { user: { id: string; name: string } }[];
_count: { photos: number; cloudFolders: number };
ftpTargets: { id: string; login: string; targetUntil: Date | null; user: { id: string; name: string } }[];
};
/** A login's choice still holds (no end, or not reached). */
const live = (until: Date | null, now = new Date()) => !until || until > now;
function serialize(event: EventWithPeople) {
const { assignments, _count, organizationId, createdById, ...rest } = event;
const { assignments, _count, organizationId, createdById, ftpTargets, ...rest } = event;
return {
...rest,
organizationId,
title: eventName(event),
photographers: assignments.map((a) => a.user),
photoCount: _count.photos,
/** A game the archive made from a cloud folder (not deleted from here). */
fromArchive: _count.cloudFolders > 0,
ftpTargets: ftpTargets.filter((a) => live(a.targetUntil)).map((a) => ({ accountId: a.id, login: a.login, user: a.user, until: a.targetUntil })),
};
}
const include = {
assignments: { include: { user: { select: { id: true, name: true } } } },
_count: { select: { photos: true } },
_count: { select: { photos: true, cloudFolders: true } },
ftpTargets: { select: { id: true, login: true, targetUntil: true, user: { select: { id: true, name: true } } } },
} as const;
/** Default ingest window: two hours before the start (warm-up) to four hours after. */
@@ -137,7 +156,7 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const where: Prisma.EventWhereInput = {
organizationId: orgId,
...(query.includeArchived ? {} : { archivedAt: null }),
...(query.archived ? { archivedAt: { not: null }, cloudFolders: { none: {} } } : query.includeArchived ? {} : { archivedAt: null }),
...(query.from || query.to ? { startsAt: { ...(query.from && { gte: query.from }), ...(query.to && { lte: query.to }) } } : {}),
...(ROLE_RANK[membership.role] < ROLE_RANK.INGESTER ? { assignments: { some: { userId: membership.userId } } } : {}),
};
@@ -218,4 +237,55 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
}
return serialize(event);
});
/** Deleting an event: its photos go back to "Sem evento" (nothing is lost); its galleries stay, without it. */
app.delete("/v1/events/:eventId", { preHandler: authenticate }, async (req, reply) => {
const { eventId } = EventParams.parse(req.params);
const event = await loadEvent(req, eventId, "EDITOR");
if (event._count.cloudFolders > 0) throw conflict("archive_event");
const photos = await db.photo.findMany({ where: { eventId }, select: { id: true }, take: 5000 });
await db.event.delete({ where: { id: eventId } });
if (photos.length) deps.broadcaster?.library(event.organizationId, { type: "photo.updated", ids: photos.map((p) => p.id), patch: { eventId: null } });
return reply.code(200).send({ deleted: eventId, photos: event._count.photos });
});
/** The FTP logins and where each sends its photos now: an event chosen by hand, or by the time. */
app.get("/v1/events/:eventId/ftp-target", { preHandler: authenticate }, async (req) => {
const { eventId } = EventParams.parse(req.params);
const event = await loadEvent(req, eventId, "PHOTOGRAPHER");
const membership = await requireMembership(db, req, event.organizationId, "PHOTOGRAPHER");
const editor = ROLE_RANK[membership.role] >= ROLE_RANK.EDITOR;
const accounts = await db.ftpAccount.findMany({
where: { organizationId: event.organizationId, ...(!editor && { userId: membership.userId }) },
select: { id: true, login: true, targetUntil: true, targetEventId: true, user: { select: { id: true, name: true } }, targetEvent: { select: { id: true, home: true, away: true, competition: true, startsAt: true } } },
orderBy: { login: "asc" },
});
return {
accounts: accounts.map((a) => {
const on = !!a.targetEventId && live(a.targetUntil);
return { id: a.id, login: a.login, user: a.user, here: on && a.targetEventId === eventId, elsewhere: on && a.targetEventId !== eventId && a.targetEvent ? { id: a.targetEvent.id, title: eventName(a.targetEvent) } : null, until: on ? a.targetUntil : null };
}),
};
});
/** "Receber FTP aqui": these logins send everything to this event (until a time); the others stop sending here. */
app.put("/v1/events/:eventId/ftp-target", { preHandler: authenticate }, async (req) => {
const { eventId } = EventParams.parse(req.params);
const body = FtpTarget.parse(req.body);
const event = await loadEvent(req, eventId, "PHOTOGRAPHER");
if (event.archivedAt) throw badRequest("event_archived");
const membership = await requireMembership(db, req, event.organizationId, "PHOTOGRAPHER");
const editor = ROLE_RANK[membership.role] >= ROLE_RANK.EDITOR;
const mine = { organizationId: event.organizationId, ...(!editor && { userId: membership.userId }) };
const chosen = await db.ftpAccount.findMany({ where: { ...mine, id: { in: body.accountIds } }, select: { id: true } });
if (chosen.length !== new Set(body.accountIds).size) throw forbidden("ftp_account_not_yours");
const now = new Date();
const until = body.until === undefined ? (event.ingestUntil > now ? event.ingestUntil : new Date(now.getTime() + 12 * HOUR)) : body.until;
if (until && until <= now) throw badRequest("until_in_the_past");
await db.$transaction([
db.ftpAccount.updateMany({ where: { ...mine, targetEventId: eventId, id: { notIn: body.accountIds } }, data: { targetEventId: null, targetUntil: null } }),
db.ftpAccount.updateMany({ where: { ...mine, id: { in: body.accountIds } }, data: { targetEventId: eventId, targetUntil: until } }),
]);
return serialize(await db.event.findUniqueOrThrow({ where: { id: eventId }, include }));
});
}
+6 -3
View File
@@ -1,4 +1,4 @@
import { buildVars, variablesIn } from "@photoreport/metadata";
import { badModifiers, buildVars, variablesIn } from "@photoreport/metadata";
import { compact } from "../lib/compact.js";
import { nameFromTemplate } from "./rename.js";
import type { FastifyInstance } from "fastify";
@@ -73,9 +73,12 @@ const UpdateBody = z.object({
/** Renders a rename template against a sample photo; unknown variables are refused when saved, not at ingest. */
export function renameExample(template: string): string {
const event = { id: "", organizationId: "", home: "ABC Braga", away: "CDE Gil Eanes", homeShort: "ABC", awayShort: "CDE", venue: "Pavilhão Flávio Sá Leite", city: "Braga", sport: "andebol", competition: "Campeonato Betclic", competitionCode: "PO01", round: "8", matchNumber: "169", startsAt: new Date("2026-10-11T17:00:00Z") };
const known = new Set(Object.keys(buildVars(event, { capturedAt: new Date(), cameraModel: "X", cameraSerial: "1" }, "Peter Spark")).concat("originalName"));
const unknown = variablesIn(template).filter((v) => !known.has(v));
// Every Photo Mechanic variable is known (names in any case), as are PhotoReport's.
const known = new Set(Object.keys(buildVars(event, { capturedAt: new Date(), cameraModel: "X", cameraSerial: "1" }, "Peter Spark")).concat("originalName").map((k) => k.toLowerCase()));
const unknown = variablesIn(template).filter((v) => !known.has(v.toLowerCase()));
if (unknown.length) throw badRequest("invalid_template", `unknown variables: ${unknown.join(", ")}`);
const bad = badModifiers(template);
if (bad.length) throw badRequest("invalid_template", `invalid modifiers: ${bad.join(", ")}`);
const name = nameFromTemplate(
template,
{ originalName: "IMG_1234.JPG", capturedAt: new Date("2026-10-11T18:31:07.456Z"), createdAt: new Date(), cameraModel: "Canon EOS R3", cameraSerial: "123" },
+5 -2
View File
@@ -2,6 +2,7 @@ import { applyTemplate, type ApplyResult, buildVars, type CodeList, IptcTemplate
import type { Db } from "../db.js";
import type { Event } from "../generated/prisma/client.js";
import { eventInfoOf } from "./event-info.js";
import { photoInfoOf, type PhotoRow } from "./photo-info.js";
export const DEFAULT_CODE_LIST = "default";
@@ -25,12 +26,14 @@ export async function codeListOf(db: Db, organizationId: string): Promise<CodeLi
/** The same as `iptcForPhoto` for a photo already loaded with its event (many photos: one code list query). */
export function iptcOf(
photo: { capturedAt: Date | null; players: string[]; iptcOverrides: unknown },
photo: PhotoRow & { players: string[]; iptcOverrides: unknown; embeddedIptc?: unknown },
event: Event,
photographer: string | null | undefined,
codes: CodeList | undefined,
): ApplyResult {
const template = { ...IptcTemplate.parse(event.iptcTemplate), ...IptcTemplate.partial().parse(photo.iptcOverrides ?? {}) };
const vars = buildVars(eventInfoOf(event), { capturedAt: photo.capturedAt ?? undefined, players: photo.players }, photographer ?? undefined);
// Photo Mechanic's IPTC variables ({caption}, {headline}...) in the pad are the photo's own, as it arrived.
const embedded = photo.embeddedIptc && typeof photo.embeddedIptc === "object" ? (photo.embeddedIptc as Record<string, string | string[]>) : {};
const vars = buildVars(eventInfoOf(event), photoInfoOf(photo), photographer ?? undefined, { iptc: embedded });
return applyTemplate(template, vars, codes);
}
+70
View File
@@ -0,0 +1,70 @@
import type { PhotoInfo } from "@photoreport/metadata";
import type { CameraExtra } from "../ingest/exif.js";
/**
* Photo Mechanic's colour classes by our labels (its default set: 1 Winner red, 3 Superior yellow, 4 Superior alt
* green, 5 Typical blue, 7 Extra purple).
*/
const COLOR_CLASS: Record<string, [number, string]> = {
RED: [1, "Winner"],
YELLOW: [3, "Superior"],
GREEN: [4, "Superior alt"],
BLUE: [5, "Typical"],
PURPLE: [7, "Extra"],
};
export interface PhotoRow {
originalName: string;
fileName?: string | null;
byteSize?: number;
createdAt?: Date;
width?: number | null;
height?: number | null;
capturedAt: Date | null;
cameraMake?: string | null;
cameraModel?: string | null;
cameraSerial?: string | null;
lens?: string | null;
focalLength?: number | null;
aperture?: number | null;
exposureTime?: number | null;
iso?: number | null;
rating?: number;
colorLabel?: string;
flag?: string;
players?: string[];
exif?: unknown;
}
const opt = <T,>(v: T | null | undefined) => (v === null ? undefined : v);
/** A photo row → the shape templates read: every camera and file detail Photo Mechanic's variables show. */
export function photoInfoOf(photo: PhotoRow, batch: { sequence?: number | undefined; total?: number | undefined } = {}): PhotoInfo {
const extra = (photo.exif && typeof photo.exif === "object" ? photo.exif : {}) as CameraExtra;
const color = photo.colorLabel ? COLOR_CLASS[photo.colorLabel] : undefined;
return {
...extra,
capturedAt: opt(photo.capturedAt),
// The camera's name, as Photo Mechanic's {filename}: the arrival rename is {originalName} in deliveries.
fileName: photo.originalName,
fileSize: photo.byteSize,
modifiedAt: photo.createdAt,
width: opt(photo.width),
height: opt(photo.height),
make: opt(photo.cameraMake),
model: opt(photo.cameraModel),
serial: opt(photo.cameraSerial),
lensModel: opt(photo.lens),
focalLength: opt(photo.focalLength),
aperture: opt(photo.aperture),
exposureTime: opt(photo.exposureTime),
iso: opt(photo.iso),
rating: photo.rating,
colorClass: color?.[0] ?? (photo.colorLabel ? 0 : undefined),
colorClassName: color?.[1] ?? (photo.colorLabel ? "None" : undefined),
tagged: photo.flag === undefined ? undefined : photo.flag === "PICK",
players: photo.players,
sequence: batch.sequence,
total: batch.total,
};
}
+10 -5
View File
@@ -1,6 +1,8 @@
import { buildVars, PathTemplateError, renderFileName } from "@photoreport/metadata";
import type { Db } from "../db.js";
import { eventInfoOf } from "./event-info.js";
import { iptcForPhoto } from "./iptc.js";
import { photoInfoOf, type PhotoRow } from "./photo-info.js";
/**
* Rename on arrival, like Photo Mechanic's Live Ingest "Rename as" (Peter: `PS_{event}_{timesort}`). The template
@@ -20,14 +22,16 @@ export async function renameTemplateFor(db: Db, organizationId: string, userId:
/** The name a template gives a photo (without extension), or null while variables are missing (no event yet). */
export function nameFromTemplate(
template: string,
photo: { originalName: string; capturedAt: Date | null; createdAt: Date; cameraModel: string | null; cameraSerial: string | null },
photo: PhotoRow & { createdAt: Date },
event: Parameters<typeof eventInfoOf>[0] | null,
photographer: string | undefined,
/** The photo's IPTC (its event's pad applied), as Photo Mechanic renames after applying the pad: {headline}... */
iptc: Record<string, string | string[] | undefined> = {},
): string | null {
const info = event ? eventInfoOf(event) : { home: "", away: "", startsAt: photo.capturedAt ?? photo.createdAt };
const vars = buildVars(info, { capturedAt: photo.capturedAt ?? undefined, cameraModel: photo.cameraModel ?? undefined, cameraSerial: photo.cameraSerial ?? undefined }, photographer);
// Without an event, {event} would be " x ": wait for the event instead.
const usable = event ? vars : Object.fromEntries(Object.entries(vars).filter(([k]) => !["home", "away", "event", "homeShort", "awayShort"].includes(k)));
const vars = buildVars(info, photoInfoOf(photo), photographer, { iptc });
// Without an event its names are empty ({event} would be ""): the rename waits for the event.
const usable = vars;
try {
const name = renderFileName(template, usable, photo.originalName);
return name.replace(/\.[a-z0-9]{2,4}$/i, "");
@@ -43,7 +47,8 @@ export async function applyRename(db: Db, photoId: string): Promise<string | nul
if (!photo || photo.source === "UPLOAD") return null;
const template = await renameTemplateFor(db, photo.organizationId, photo.uploaderId);
if (!template) return null;
const base = nameFromTemplate(template, photo, photo.event, photo.uploader?.name);
const iptc = photo.event ? (await iptcForPhoto(db, photo.id))?.values : undefined;
const base = nameFromTemplate(template, photo, photo.event, photo.uploader?.name, iptc);
if (!base) return null;
if (photo.fileName === base) return base;
const taken = new Set(
+2
View File
@@ -1,7 +1,9 @@
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { buildApp, reporterFor } from "./app.js";
import { loadConfig } from "./config.js";
import { createDb } from "./db.js";
preferIpv4();
const config = loadConfig();
const db = createDb(config.DATABASE_URL);
const reporter = reporterFor(config);
+9 -2
View File
@@ -9,6 +9,7 @@ import type { SecretBox } from "../delivery/secrets.js";
import type { DevelopService } from "../develop/service.js";
import type { Event, Gallery, Order, OrderItem, Photo, Product, Site } from "../generated/prisma/client.js";
import type { IngestLogger } from "../ingest/service.js";
import { waitUntil } from "../lib/idle.js";
import { codeListOf, iptcForPhoto, iptcOf } from "../library/iptc.js";
import type { LocalStorage, UrlSigner } from "../storage/storage.js";
import { EU, formatOrderNumber, priceOrder, splitVat } from "./pricing.js";
@@ -716,6 +717,7 @@ export class FulfilmentWorker {
private timer: NodeJS.Timeout | undefined;
private stopped = false;
private inFlight = 0;
private ticking = false;
constructor(
private readonly shop: ShopService,
@@ -725,6 +727,7 @@ export class FulfilmentWorker {
start(): void {
void this.shop.requeueStale();
const tick = async () => {
this.ticking = true;
try {
for (const id of await this.shop.claimDownloads(this.opts.concurrency - this.inFlight)) {
this.inFlight++;
@@ -734,14 +737,18 @@ export class FulfilmentWorker {
}
} catch (err) {
this.opts.log.warn({ err }, "shop: poll failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.intervalMs);
};
this.timer = setTimeout(tick, 0);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking && this.inFlight === 0, { timeoutMs });
if (!drained) this.opts.log.warn({ inFlight: this.inFlight }, "shop: stop timed out with work still running");
}
}
+36 -7
View File
@@ -317,18 +317,24 @@ export class FpaProvider {
return (rows as Record<string, unknown>[]).map(fpaFixture).filter((f): f is FixtureData => !!f);
}
/** The portal's ids for a club's current season and its levels ("Seniores M" → 4), from the club page. */
async clubTerms(clubId: string): Promise<{ season: string | null; levels: { id: string; name: string }[] }> {
/** The portal's ids for a club's seasons (current first) and its levels ("Seniores M" → 4), from the club page. */
async clubTerms(clubId: string): Promise<FpaClubTerms> {
return parseFpaClubTerms(await this.html(`${FpaProvider.PORTAL}/clube/id/${encodeURIComponent(clubId)}/`));
}
/** A club's games of a season and level (played and to play). */
async clubGames(clubId: string, season: string, level: string): Promise<FixtureData[]> {
/**
* A club's games of a season and level (played and to play). `nationalOnly`: only the federation's own
* competitions (the regional associations' are left out).
*/
async clubGames(clubId: string, season: string, level: string, nationalOnly = false): Promise<FixtureData[]> {
const path = ["getJogosClubeEpocaEscalao", clubId, season, level].map(encodeURIComponent).join("/");
const rows = await get(this.fetcher, `${FpaProvider.WS}/${path}`, { accept: "application/json" }, "json");
await this.pause();
if (!Array.isArray(rows)) return [];
return (rows as Record<string, unknown>[]).map(fpaFixture).filter((f): f is FixtureData => !!f);
return (rows as Record<string, unknown>[])
.filter((r) => !nationalOnly || String(r.ID_ASSOCIACAO ?? "") === FPA_ASSOCIATION_ID)
.map(fpaFixture)
.filter((f): f is FixtureData => !!f);
}
/** The match report: empty until the game is played. */
@@ -477,8 +483,27 @@ export function parseFpaReferees(html: string): OfficialData[] {
return parseFpaMatchPage(html).officials;
}
/** The federation's own id among the associations of the portal's games (the others are regional). */
export const FPA_ASSOCIATION_ID = "8";
export interface FpaClubTerms {
/** The current season's id. */
season: string | null;
/** Every season the portal has for the club, current first: our code ("20242025") and the portal's id. */
seasons: { id: string; season: string }[];
levels: { id: string; name: string }[];
}
/** "Época 2024/25" → "20242025". */
export function fpaSeasonCode(name: string): string | null {
const m = /(\d{4})\s*\/\s*(\d{2,4})/.exec(name);
if (!m) return null;
const start = Number(m[1]);
return `${start}${start + 1}`;
}
/** The club page carries its selectors as JSON: the first season is the current one. */
export function parseFpaClubTerms(html: string): { season: string | null; levels: { id: string; name: string }[] } {
export function parseFpaClubTerms(html: string): FpaClubTerms {
const options = (id: string) => {
const at = html.indexOf(`"id":"${id}"`);
if (at === -1) return [];
@@ -493,7 +518,11 @@ export function parseFpaClubTerms(html: string): { season: string | null; levels
return [];
}
};
return { season: options("season")[0]?.id ?? null, levels: options("level") };
const seasons = options("season").flatMap((o) => {
const season = fpaSeasonCode(o.name);
return season ? [{ id: o.id, season }] : [];
});
return { season: options("season")[0]?.id ?? null, seasons, levels: options("level") };
}
/** "PO01 - Campeonato Betclic Masculino" → PO01 and its name; "PARTICULARES SELECOES NACIONAIS" has no code. */
+64 -2
View File
@@ -6,6 +6,7 @@ import type { SportsCompetition, SportsPlayer, SportsProvider } from "../generat
import type { IngestLogger } from "../ingest/service.js";
import { DEFAULT_CODE_LIST } from "../library/iptc.js";
import { badRequest, notFound } from "../lib/errors.js";
import { waitUntil } from "../lib/idle.js";
import type { LocalStorage } from "../storage/storage.js";
import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js";
import {
@@ -170,6 +171,61 @@ export class SportsService {
return saved;
}
/**
* A whole past FPA season (the archive's folders of other seasons): the federation's national games of every
* level, club by club. It starts from the clubs of today's agenda and follows every club met in those games, so
* clubs that have since gone down or closed are reached too. Slow on purpose (the portal is asked one page at a
* time), so it runs in the background, once per season.
*/
async importFpaSeason(season: string, opts: { maxClubs?: number } = {}): Promise<number> {
const { log } = this.deps;
const maxClubs = opts.maxClubs ?? 800;
const queue: string[] = [];
const seen = new Set<string>();
const add = (club: string | undefined | null) => {
if (club && !seen.has(club) && seen.size < maxClubs) {
seen.add(club);
queue.push(club);
}
};
for (const f of await this.fpa.agenda().catch(() => [] as FixtureData[])) for (const t of [f.home, f.away]) add(t.clubId);
// Games of the season already saved are not saved again.
const known = await this.deps.db.sportsFixture.findMany({ where: { season, competition: { provider: "FPA" } }, select: { externalId: true } });
const saved = new Set(known.map((k) => k.externalId));
let clubs = 0;
while (queue.length) {
const club = queue.shift()!;
let terms: Awaited<ReturnType<FpaProvider["clubTerms"]>>;
try {
terms = await this.fpa.clubTerms(club);
} catch (err) {
log.warn({ err, club }, "sports: fpa club page not read");
continue;
}
const term = terms.seasons.find((s) => s.season === season)?.id;
if (!term) continue;
clubs++;
for (const level of terms.levels) {
let games: FixtureData[];
try {
games = await this.fpa.clubGames(club, term, level.id, true);
} catch {
continue;
}
for (const g of games) {
if (g.season !== season) continue;
add(g.home.clubId);
add(g.away.clubId);
if (saved.has(g.externalId)) continue;
saved.add(g.externalId);
await this.saveFixture(await this.fpaCompetition(g), "FPA", g);
}
}
}
log.info({ season, clubs, fixtures: saved.size }, "sports: fpa season imported");
return saved.size;
}
async refreshLiga(comps: SportsCompetition[], now = new Date()): Promise<RefreshResult> {
const { db, log } = this.deps;
const result: RefreshResult = { competitions: 0, teams: 0, players: 0, fixtures: 0, errors: [] };
@@ -996,6 +1052,7 @@ export class SportsService {
export class SportsWorker {
private timer: ReturnType<typeof setTimeout> | undefined;
private stopped = false;
private ticking = false;
private lastRefresh = 0;
constructor(
@@ -1005,6 +1062,7 @@ export class SportsWorker {
start(): void {
const tick = async () => {
this.ticking = true;
try {
if (Date.now() - this.lastRefresh >= (this.opts.refreshCheckMs ?? 10 * 60_000)) {
this.lastRefresh = Date.now();
@@ -1013,14 +1071,18 @@ export class SportsWorker {
await this.service.pollLineups();
} catch (err) {
this.opts.log.warn({ err }, "sports: tick failed");
} finally {
this.ticking = false;
if (!this.stopped) this.timer = setTimeout(tick, this.opts.lineupEveryMs ?? 5 * 60_000);
}
if (!this.stopped) this.timer = setTimeout(tick, this.opts.lineupEveryMs ?? 5 * 60_000);
};
this.timer = setTimeout(tick, 5_000);
}
stop(): void {
async stop(timeoutMs = 25_000): Promise<void> {
this.stopped = true;
if (this.timer) clearTimeout(this.timer);
const drained = await waitUntil(() => !this.ticking, { timeoutMs });
if (!drained) this.opts.log.warn({}, "sports: stop timed out with work still running");
}
}
+33 -14
View File
@@ -1,6 +1,7 @@
import { existsSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { preferIpv4 } from "./lib/prefer-ipv4.js";
import { reporterFor } from "./lib/reporter.js";
import pino from "pino";
import { loadConfig } from "./config.js";
@@ -15,10 +16,11 @@ import { DevelopService, RenderWorker } from "./develop/service.js";
import { FacePool, FaceProcess } from "./faces/process.js";
import { AutopilotService, AutopilotWorker } from "./autopilot/service.js";
import { SportsService, SportsWorker } from "./sports/service.js";
import { ArchiveService, ArchiveWorker } from "./archive/service.js";
import { ArchiveService, ArchiveWorker, localDirs } from "./archive/service.js";
import { lazyDetector } from "./composition/detect.js";
import { smtpMailer } from "./lib/mailer.js";
import { FulfilmentWorker, ShopService } from "./shop/service.js";
import { touchFaceHeartbeat } from "./faces/heartbeat.js";
import { FaceService, FaceWorker } from "./faces/service.js";
import { JerseyModel } from "./jersey/model.js";
import { IngestScanner } from "./ingest/scanner.js";
@@ -32,6 +34,7 @@ import { InvoicingService, InvoicingWorker } from "./invoicing/service.js";
* Background worker: FTP ingest and the delivery queue. One per installation, next to the SFTPGo drop folder
* and the storage (PM2 app `photoreport-worker`, never clustered: it owns the drop folder).
*/
preferIpv4();
const config = loadConfig();
// Error lines (and warnings carrying an error) also go to errors.bitreport.pt, as do crashes.
const reporter = reporterFor(config);
@@ -61,7 +64,7 @@ const capacity = planCapacity({
});
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(60, 10 + Math.ceil((capacity.archiveBurst + capacity.faces + capacity.ingest) / 2)));
const db = createDb(config.DATABASE_URL, Math.min(80, 10 + Math.ceil((capacity.archiveDownloads + capacity.faces + capacity.ingest) / 2)));
const storage = new LocalStorage(config.STORAGE_ROOT);
const broadcaster = createRemoteBroadcaster(config.DATABASE_URL, (err) => log.error({ err }, "realtime publish failed"));
@@ -87,9 +90,12 @@ const renders = renderEngine ? new RenderWorker(develop, { concurrency: capacity
const sportsService = new SportsService({ db, storage, log, fetch });
// Archive clouds: walked for new galleries, each image indexed as a preview whose original stays in the cloud.
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9 });
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveBurst, intervalMs: 2000, log, pressure: new Pressure() });
// A big backlog: many downloads from the cloud in flight, previews made by as many as the machine's share.
const archiveService = new ArchiveService({ db, secrets, log, ingest, syncSquads: (id) => sportsService.syncEventSquads(id), ligaSeason: (season) => sportsService.importLigaSeason(season), fpaSeason: (season) => sportsService.importFpaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, cpuSlots: capacity.archiveBurst, localDirs: localDirs(config.ARCHIVE_LOCAL_DIRS) });
const archive = new ArchiveWorker(archiveService, { concurrency: capacity.archive, burst: capacity.archiveDownloads, intervalMs: 2000, log, pressure: new Pressure() });
const deliveryService = new DeliveryService({ db, storage, secrets, broadcaster, log, develop, originals: archiveService, notifications: new Notifications(db, (err) => log.warn({ err }, "notifications: not written")) });
// Every arrival goes on to the destinations that take all of them (one's own backup of the originals).
ingest.arrivals = (photo) => deliveryService.queueArrival(photo);
const deliveries = new DeliveryWorker(deliveryService, {
concurrency: capacity.delivery,
intervalMs: 1000,
@@ -112,7 +118,12 @@ const faceEngine =
const jersey = faceEngine && config.JERSEY_MODEL_DIR ? await JerseyModel.load(config.JERSEY_MODEL_DIR) : undefined;
if (jersey) log.info({ dir: config.JERSEY_MODEL_DIR }, "shirt-number model loaded");
const faces = faceEngine
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey }), { concurrency: capacity.faces, intervalMs: 1000, log })
? new FaceWorker(new FaceService({ db, storage, broadcaster, log, engine: faceEngine, jersey }), {
concurrency: capacity.faces,
intervalMs: 1000,
log,
heartbeat: () => touchFaceHeartbeat(config.STORAGE_ROOT),
})
: undefined;
if (!faces) log.warn("FACES_BIN/FACES_MODELS_DIR not set: face analysis is off in this worker");
@@ -135,17 +146,25 @@ fulfilment.start();
invoices.start();
log.info({ ingestRoot: config.INGEST_ROOT, storage: config.STORAGE_ROOT }, "worker started");
/** Drain in-flight jobs before ending the Prisma/pg pool (BIT-31189). Leave headroom under PM2 kill_timeout. */
const DRAIN_MS = 25_000;
let shuttingDown = false;
const shutdown = async (signal: string) => {
if (shuttingDown) return;
shuttingDown = true;
log.info({ signal }, "worker stopping");
scanner.stop();
archive.stop();
autopilot.stop();
sports?.stop();
deliveries.stop();
faces?.stop();
renders?.stop();
fulfilment.stop();
invoices.stop();
// Stop claiming first, then wait for ticks/in-flight work so `$disconnect` does not race Prisma queries.
await Promise.all([
scanner.stop(DRAIN_MS),
archive.stop(DRAIN_MS),
autopilot.stop(DRAIN_MS),
sports?.stop(DRAIN_MS) ?? Promise.resolve(),
deliveries.stop(DRAIN_MS),
faces?.stop(DRAIN_MS) ?? Promise.resolve(),
renders?.stop(DRAIN_MS) ?? Promise.resolve(),
fulfilment.stop(DRAIN_MS),
invoices.stop(DRAIN_MS),
]);
await faceEngine?.close();
await deliveryService.close();
await renderEngine?.close();
+230 -4
View File
@@ -1,12 +1,12 @@
import { createHash } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { describeFolder, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, type FixtureCandidate } from "../src/archive/match.js";
import { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
import { parseMultistatus } from "../src/archive/nextcloud.js";
import { ArchiveService } from "../src/archive/service.js";
import { ArchiveService, localDirs } from "../src/archive/service.js";
import { SecretBox } from "../src/delivery/secrets.js";
import { IngestService } from "../src/ingest/service.js";
import { MemoryBroadcaster } from "../src/realtime.js";
@@ -48,6 +48,28 @@ describe("archive folder names", () => {
expect(pickFixture(parseFolder("/LPBetclic 26-27/Jornada 6/03. Sporting CP x SC Braga")!, [fixture])).toBeNull();
});
it("never takes a game from a season or month alone, nor a reserve or youth side for the first team", () => {
const t = (name: string) => ({ name, abbreviation: null, slug: name });
const senior: FixtureCandidate = { id: "s", startsAt: new Date("2026-10-09T19:15:00Z"), season: "20262027", round: "Jornada 8", competition: { externalId: "ligaportugalbetclic" }, homeTeam: t("SC Braga"), awayTeam: t("Sporting CP") };
expect(pickFixture(parseFolder("/2026_2027/Braga x Sporting")!, [senior])).toBeNull();
expect(pickFixture(parseFolder("/2026_2027/09.10.2026 Braga x Sporting")!, [senior])?.id).toBe("s");
expect(pickFixture(parseFolder("/2026_2027/09.10.2026 Braga B x Sporting B")!, [senior])).toBeNull();
expect(pickFixture(parseFolder("/Sub-23/09.10.2026 Braga x Sporting")!, [senior])).toBeNull();
});
it("never dates photos on a day still to come: future games are not candidates, and years read the right way", () => {
const t = (name: string) => ({ name, abbreviation: null, slug: name });
const now = new Date("2026-10-15T12:00:00Z");
const later: FixtureCandidate = { id: "f", startsAt: new Date("2027-01-10T15:00:00Z"), season: "20262027", round: "Jornada 17", competition: { externalId: "ligaportugalmeusuper" }, homeTeam: t("FC Porto B"), awayTeam: t("SL Benfica B") };
expect(pickFixture(parseFolder("/LP2 26-27/Jornada 17/FC Porto B x SL Benfica B")!, [later], now)).toBeNull();
const played = { ...later, id: "p", startsAt: new Date("2026-01-10T15:00:00Z"), season: "20252026" };
expect(pickFixture(parseFolder("/LP2/10.01.2026 FC Porto B x SL Benfica B")!, [later, played], now)?.id).toBe("p");
// "23.09.28": the 28th of September 2023 (the 23rd of September 2028 has not come yet).
expect(parseFolder("/Liga/23.09.28 Estrela Amadora x Braga")).toMatchObject({ day: "2023-09-28", home: "Estrela Amadora", away: "Braga" });
expect(parseFolder("/Liga/04.11.23 Mafra x Leixoes")).toMatchObject({ day: "2023-11-04" });
expect(parseFolder("/x/20991010 - SCP x ABC")).toMatchObject({ day: null });
});
it("reads the Liga cloud's own namings: dashes, month and year, day.month.year, one club", () => {
expect(parseFolder("/LP2 23-24/02. CD Feirense - U Leiria")).toMatchObject({ home: "CD Feirense", away: "U Leiria", single: false });
expect(parseFolder("/Mafra/04.11.2023 Mafra va Leixoes")).toMatchObject({ home: "Mafra", away: "Leixoes", day: "2023-11-04", season: "20232024" });
@@ -149,12 +171,43 @@ describe("archive folder names", () => {
expect(isTeam("SLB", { name: "Sporting Clube de Portugal", abbreviation: null, slug: "sporting" })).toBe(false);
});
it("takes the only game of that competition and day when one side is named otherwise", () => {
it("takes a game only when both sides are recognised, never with one guessed", () => {
const t = (name: string) => ({ name, abbreviation: null, slug: name });
const f = (id: string, home: string, away: string): FixtureCandidate => ({ id, startsAt: new Date("2026-10-03T17:00:00Z"), season: "20262027", round: null, competition: { externalId: "PO01" }, homeTeam: t(home), awayTeam: t(away) });
const fixtures = [f("a", "Sporting Clube de Portugal", "Marítimo Madeira Andebol SAD"), f("b", "Sport Lisboa e Benfica", "FC Gaia")];
expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x Marítimo")!, fixtures)?.id).toBe("a");
expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x SLB")!, fixtures)).toBeNull();
expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x Desconhecido")!, fixtures)).toBeNull();
});
it("never matches a legends' tournament or a charity game to a championship, nor a first team to its B side", () => {
const t = (name: string) => ({ name, abbreviation: null, slug: name });
const f = (id: string, day: string, home: string, away: string, season = "20252026"): FixtureCandidate => ({ id, startsAt: new Date(`${day}T17:00:00Z`), season, round: "2", competition: { externalId: "ligaportugalmeusuper" }, homeTeam: t(home), awayTeam: t(away) });
const legends = parseFolder("/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense")!;
expect(isExhibition(legends)).toBe(true);
expect(exhibitionName(legends)).toBe("Liga Portugal Legends 2025-26");
expect(pickFixture({ ...legends, day: "2026-03-10" }, [f("a", "2026-03-10", "SL Benfica", "SCU Torreense")])).toBeNull();
expect(isTeam("SL Benfica", t("SL Benfica B"))).toBe(false);
expect(isTeam("Benfica B", t("SL Benfica B"))).toBe(true);
const game = parseFolder("/2025_2026/Liga/20260310 - SL Benfica x SCU Torreense")!;
expect(pickFixture(game, [f("b", "2026-03-10", "SL Benfica B", "SCU Torreense")])).toBeNull();
});
it("names teams without the date before them, and as the known team when one fits", () => {
expect(teamLabel("01.23 Leixoes SC")).toBe("Leixoes SC");
expect(teamLabel("02_ESTORIL PRAIA")).toBe("ESTORIL PRAIA");
expect(teamLabel("10 (copiar).22 CD Tondela")).toBe("CD Tondela");
expect(teamLabel("1 Gil Vicente")).toBe("Gil Vicente");
expect(teamLabel("Sporting CP B")).toBe("Sporting CP B");
const known = [
{ name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" },
{ name: "U. Leiria", abbreviation: "UDL", slug: "u-leiria" },
{ name: "SL Benfica B", abbreviation: "SLB B", slug: "benfica-b" },
];
expect(canonicalTeam("01 SCP", known)).toBe("Sporting CP");
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");
});
it("picks the one fixture with those teams on that day", () => {
@@ -651,4 +704,177 @@ describe("archive from a Nextcloud", () => {
expect(await full.claim(10)).toEqual([]);
expect((await worker.claim(10)).length).toBe(3);
});
it("reads the files from disk when the cloud is mounted here, and downloads the ones that are not", async () => {
expect(localDirs(" https://cloud.test/FPA/Fotos/=/mnt/nc/peter/files/FPA/Fotos/ , nada, https://x.pt=/d")).toEqual([
{ baseUrl: "https://cloud.test", prefix: "/FPA/Fotos", dir: "/mnt/nc/peter/files/FPA/Fotos" },
{ baseUrl: "https://x.pt", prefix: "", dir: "/d" },
]);
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 game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
const mount = path.join(storageRoot, "mount");
await mkdir(path.join(mount, "2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"), { recursive: true });
for (const name of ["PS_0001.jpg", "PS_0002.jpg"]) {
const node = cloud.nodes.get(`${game}/${name}`)!;
await writeFile(path.join(mount, "2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC", name), node.data!);
// What the cloud would send now is broken: only the copy on disk can make the photo.
node.data = Buffer.alloc(node.data!.length, 1);
}
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 mounted = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, ingest, fetchImpl: fetchProxy, localDirs: localDirs(`https://cloud.test/FPA/Fotos=${mount}`) });
for (const id of await mounted.claim(10)) await mounted.index(id);
const files = await ctx.db.cloudFile.findMany({ include: { photo: true } });
// The gala photo is not on the mount: downloaded as usual.
expect(files.map((f) => [f.path.split("/").pop(), f.status, f.photo?.width]).sort()).toEqual([
["G_0001.jpg", "DONE", 3000],
["PS_0001.jpg", "DONE", 3000],
["PS_0002.jpg", "DONE", 3000],
]);
await rm(mount, { recursive: true, force: true });
});
it("never adds to a live event: the same game gets an archive event of its own, and folders put there before leave", async () => {
const source = await connect();
cloud.authorised = true;
await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
// The game photographed live: an event of the library linked to the official game.
const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } });
const live = await ctx.db.event.create({ data: { organizationId: orgId, home: "Sporting CP", away: "ABC de Braga", startsAt: fixture.startsAt, ingestFrom: fixture.startsAt, ingestUntil: fixture.startsAt, iptcTemplate: {}, createdById: ownerId, fixtureId: fixture.id } });
await worker.scan(source.id);
for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id);
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "SCP x ABC" } }, include: { event: true } });
expect(folder.matchedBy).toBe("FIXTURE");
expect(folder.eventId).not.toBe(live.id);
expect(folder.event!.archivedAt).not.toBeNull();
expect(await ctx.db.photo.count({ where: { eventId: live.id } })).toBe(0);
// What an earlier version did: the folder and its photos in the live event. Taken back out.
const photos = (await ctx.db.cloudFile.findMany({ where: { folderId: folder.id } })).map((f) => f.photoId!);
await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { eventId: live.id } });
await ctx.db.photo.updateMany({ where: { id: { in: photos } }, data: { eventId: live.id } });
expect(await worker.leaveLiveEvents()).toBe(1);
expect(await ctx.db.photo.count({ where: { eventId: live.id } })).toBe(0);
expect((await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id } })).eventId).toBe(folder.eventId);
});
it("takes a folder off the official game when its photos were taken on another day", async () => {
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
const taken = await sharp({ create: { width: 3000, height: 2000, channels: 3, background: "#456" } }).jpeg().withExif({ IFD2: { DateTimeOriginal: "2025:11:02 18:00:00" } }).toBuffer();
cloud.add(`${game}/PS_0003.jpg`, taken);
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 (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id);
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game }, include: { event: true } });
expect(folder).toMatchObject({ matchedBy: "NAME", fixtureRejected: true });
expect(folder.event!.fixtureId).toBeNull();
// Every photo of the folder went with it (none left in the official game's event).
const files = await ctx.db.cloudFile.findMany({ where: { folderId: folder.id }, include: { photo: true } });
expect(files.every((f) => f.status === "DONE" && f.photo?.eventId === folder.eventId)).toBe(true);
expect(await ctx.db.event.count({ where: { fixtureId: { not: null } } })).toBe(0);
});
it("takes every gallery off a game still to come at once, whatever rule matched it", async () => {
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC";
cloud.add(`${game}/PS_0004.jpg`, await sharp({ create: { width: 600, height: 400, channels: 3, background: "#456" } }).jpeg().toBuffer());
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 (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id);
// As an older rule left it: on an official game of next year.
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } });
const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } });
await ctx.db.sportsFixture.update({ where: { id: fixture.id }, data: { startsAt: new Date("2027-02-28T15:00:00Z") } });
await ctx.db.event.update({ where: { id: folder.eventId! }, data: { startsAt: new Date("2027-02-28T15:00:00Z"), fixtureId: fixture.id } });
await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { matchedBy: "FIXTURE" } });
expect(await worker.takeOffFutureGames()).toBe(1);
const after = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } });
expect(after.matchedBy).not.toBe("FIXTURE");
expect(after.event!.startsAt.getTime()).toBeLessThan(Date.now() + 6 * 3600_000);
});
it("an editor checks the official games again on demand and sees what changed: a legends' game leaves the championship's", async () => {
const game = "/FPA/Fotos/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense";
cloud.add(`${game}/LEG_0001.jpg`, await sharp({ create: { width: 600, height: 400, channels: 3, background: "#456" } }).jpeg().toBuffer());
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 (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id);
// As an older rule left it: on another game of the championship (its day already past).
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } });
const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } });
await ctx.db.event.update({ where: { id: folder.eventId! }, data: { startsAt: fixture.startsAt, fixtureId: fixture.id } });
await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { matchedBy: "FIXTURE" } });
const res = await ctx.app.inject({ method: "POST", url: `/v1/cloud-sources/${source.id}/rematch`, headers: bearer(token) });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ errors: [] });
expect(res.json().changes).toContainEqual({ path: "/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense", from: "FIXTURE", to: "NAME" });
const after = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } });
expect(after.event).toMatchObject({ fixtureId: null, competition: "Liga Portugal Legends 2025-26" });
});
it("dates a gallery by its photos when its name has no day, and takes it off a game of another day", async () => {
const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/SCP x ABC";
for (const [i, at] of ["2025:07:10 18:00:00", "2025:07:10 18:30:00", "2025:07:10 19:10:00", "2025:07:11 01:00:00"].entries()) {
cloud.add(`${game}/X_${i}.jpg`, await sharp({ create: { width: 900, height: 600, channels: 3, background: { r: 10 * i, g: 80, b: 120 } } }).jpeg().withExif({ IFD2: { DateTimeOriginal: at } }).toBuffer());
}
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 (let ids = await worker.claim(20); ids.length; ids = await worker.claim(20)) for (const id of ids) await worker.index(id);
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } });
expect(await worker.captureDay(folder.id)).toBe("2025-07-10");
// What an earlier version did: the folder put in the official SCP x ABC of September (another day).
const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } });
await worker.setFolderEvent(folder.id, { fixtureId: fixture.id }, "FIXTURE");
expect(await worker.rematch(source.id)).toBeGreaterThan(0);
const fixed = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } });
expect(fixed).toMatchObject({ matchedBy: "NAME", fixtureRejected: true });
expect(fixed.event!.fixtureId).toBeNull();
expect(lisbonDay(fixed.event!.startsAt)).toBe("2025-07-10");
// Its photos went with it.
const photos = await ctx.db.cloudFile.findMany({ where: { folderId: folder.id }, include: { photo: true } });
expect(photos.every((f) => f.photo?.eventId === fixed.eventId)).toBe(true);
});
it("gives the archive's site its owner's look, which can be changed", async () => {
const source = await connect();
cloud.authorised = true;
let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) });
expect(res.json()).toMatchObject({ look: "fpa" });
expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ look: "fpa", name: "Cloud FPA" });
res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "liga" } });
expect(res.json()).toMatchObject({ look: "liga" });
res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: null } });
expect(res.json()).toMatchObject({ look: null });
expect((await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "benfica" } })).statusCode).toBe(400);
});
it("shares the worker between clouds: a big newer archive does not starve another", 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 folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { sourceId: source.id, eventId: { not: null } } });
// Another cloud with a much bigger backlog, all in a later game.
const other = await ctx.db.cloudSource.create({ data: { organizationId: orgId, name: "Liga", baseUrl: "https://liga.test", rootPath: "/", status: "READY" } });
const ev = await ctx.db.event.findUniqueOrThrow({ where: { id: folder.eventId! } });
const later = await ctx.db.event.create({ data: { organizationId: orgId, home: "SLB", away: "FCP", startsAt: new Date(ev.startsAt.getTime() + 365 * 864e5), ingestFrom: new Date(), ingestUntil: new Date(), iptcTemplate: {} } });
const f2 = await ctx.db.cloudFolder.create({ data: { sourceId: other.id, fileId: "f2", path: "/Liga/SLB x FCP", photoCount: 40, eventId: later.id, matchedBy: "FIXTURE" } });
await ctx.db.cloudFile.createMany({ data: Array.from({ length: 40 }, (_, i) => ({ sourceId: other.id, folderId: f2.id, fileId: `x${i}`, path: `/Liga/SLB x FCP/${i}.jpg` })) });
const ids = await worker.claim(10);
expect(ids).toHaveLength(10);
const bySource = await ctx.db.cloudFile.groupBy({ by: ["sourceId"], where: { id: { in: ids } }, _count: true });
expect(Object.fromEntries(bySource.map((r) => [r.sourceId, r._count]))).toEqual({ [source.id]: 3, [other.id]: 7 });
});
});
+5 -3
View File
@@ -7,9 +7,11 @@ describe("capacity", () => {
it("does more at once on a bigger container", () => {
const small = planCapacity({}, { cpus: 4, memoryBytes: 8 * GB });
const big = planCapacity({}, { cpus: 32, memoryBytes: 64 * GB });
expect(small).toMatchObject({ faces: 2, ingest: 4, archive: 2, render: 2, delivery: 4 });
expect(big).toMatchObject({ cpus: 32, faces: 14, ingest: 8, archive: 9, archiveBurst: 24, render: 4, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 21, archiveBurst: 36 });
expect(small).toMatchObject({ faces: 3, ingest: 4, archive: 2, render: 2, delivery: 4 });
expect(big).toMatchObject({ cpus: 32, faces: 6, ingest: 8, archive: 9, archiveBurst: 91, render: 4, delivery: 8 });
expect(planCapacity({}, { cpus: 48, memoryBytes: 64 * GB })).toMatchObject({ faces: 6, archiveBurst: 91, archiveDownloads: 960 });
// A fixed ARCHIVE_CONCURRENCY never holds a backlog back; downloads run many at once even on a small machine.
expect(planCapacity({ archive: 2 }, { cpus: 4, memoryBytes: 8 * GB })).toMatchObject({ archive: 2, archiveBurst: 7, archiveDownloads: 80 });
});
it("is held back by memory when cores are many and memory is short", () => {
+37
View File
@@ -0,0 +1,37 @@
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import { createDb } from "../src/db.js";
import { dropCrossSportSuggestions, eventSport, normSport, peopleSports } from "../src/faces/service.js";
import { resetDb, seedUser } from "./helpers.js";
/** A footballer is never suggested at a handball game, nor a handball player at a football game. */
describe("face suggestions keep to the event's sport", () => {
const db = createDb(process.env.DATABASE_URL_TEST ?? "");
afterAll(() => db.$disconnect());
beforeEach(() => resetDb(db));
it("knows each person's sport by their squad, and takes away suggestions of another sport", async () => {
const { org, user } = await seedUser(db, "[email protected]", { org: "fpa", role: "OWNER" });
const orgId = org!.id;
const football = await db.sportsTeam.create({ data: { provider: "LIGA", externalId: "est", sport: "futebol", name: "Estoril Praia", slug: "estoril" } });
const handball = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "abc", sport: "andebol", name: "ABC de Braga", slug: "abc" } });
const xeka = await db.person.create({
data: { organizationId: orgId, name: "Xeka", sportsPlayerId: (await db.sportsPlayer.create({ data: { teamId: football.id, season: "20262027", externalId: "x", name: "Xeka" } })).id },
});
const ana = await db.person.create({
data: { organizationId: orgId, name: "Ana", sportsPlayerId: (await db.sportsPlayer.create({ data: { teamId: handball.id, season: "20262027", externalId: "a", name: "Ana" } })).id },
});
const typed = await db.person.create({ data: { organizationId: orgId, name: "Sem equipa" } });
const at = new Date("2026-10-04T18:00:00Z");
const game = await db.event.create({ data: { organizationId: orgId, home: "ABC de Braga", away: "CD Feirense", sport: "Andebol", startsAt: at, ingestFrom: at, ingestUntil: at, iptcTemplate: {}, createdById: user.id } });
expect(await eventSport(db, game.id)).toBe("andebol");
expect(normSport("Football")).toBe("futebol");
const sports = await peopleSports(db, [xeka, ana, typed]);
expect([sports.get(xeka.id), sports.get(ana.id), sports.get(typed.id)]).toEqual(["futebol", "andebol", undefined]);
const group = (personId: string) => db.faceGroup.create({ data: { organizationId: orgId, eventId: game.id, centroid: [1, 0], model: "m", size: 2, suggestedPersonId: personId, suggestionScore: 0.7 } });
const [g1, g2, g3] = [await group(xeka.id), await group(ana.id), await group(typed.id)];
expect(await dropCrossSportSuggestions(db)).toBe(1);
const after = await db.faceGroup.findMany({ where: { id: { in: [g1.id, g2.id, g3.id] } }, orderBy: { createdAt: "asc" } });
expect(after.map((g) => g.suggestedPersonId)).toEqual([null, ana.id, typed.id]);
});
});
+97 -1
View File
@@ -1,5 +1,6 @@
import { createHash } from "node:crypto";
import { exiftool } from "exiftool-vendored";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
@@ -72,6 +73,7 @@ class FakeNextcloud {
*/
class FakeZerozero {
logins = 0;
removed: string[] = [];
uploads = new Map<string, { gameId: string; meta: Record<string, string>; data: Buffer; length: number }>();
password = "zz-pass";
@@ -126,6 +128,11 @@ class FakeZerozero {
this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) });
return new Response(null, { status: 201, headers: { location: `/upload/${id}` } });
}
const gone = /^\/api\/images\/(.+)$/.exec(url.pathname);
if (gone && method === "DELETE") {
this.removed.push(gone[1]!);
return new Response(null, { status: 204 });
}
const patch = /^\/upload\/(.+)$/.exec(url.pathname);
if (patch && method === "PATCH") {
const up = this.uploads.get(patch[1]!)!;
@@ -367,6 +374,27 @@ describe("delivery", () => {
// Signed in once for the whole batch.
expect(zz.logins).toBe(1);
// The crop of a delivered photo put right: once the edits pause, the new version goes up and the old one is
// taken back (never while still being edited).
const itemA = items.find((i) => i.photoId === a)!;
await ctx.db.photo.update({ where: { id: a }, data: { developSeq: 3, editedAt: new Date() } });
expect(await delivery.queueEdited()).toBe(0);
await ctx.db.photo.update({ where: { id: a }, data: { editedAt: new Date(Date.now() - 2 * 60_000) } });
expect(await delivery.queueEdited()).toBe(1);
const again = await ctx.db.deliveryItem.findUniqueOrThrow({ where: { id: itemA.id } });
expect([again.status, again.replacesPath, again.sequence]).toEqual(["QUEUED", itemA.remotePath, itemA.sequence]);
// (No render engine here: the edit itself is not rendered, the round trip is what is checked.)
await ctx.db.photo.update({ where: { id: a }, data: { developSeq: 0 } });
await drain();
const resent = await ctx.db.deliveryItem.findUniqueOrThrow({ where: { id: itemA.id } });
expect(resent.status).toBe("DONE");
expect(resent.remotePath).not.toBe(itemA.remotePath);
expect(resent.replacesPath).toBeNull();
expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]);
// Same name ({n} kept), shown once in the game.
expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename);
expect(await delivery.queueEdited()).toBe(0);
// A wrong password stops at once, with the desk's message.
await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}`, headers: bearer(token), payload: { password: "errada" } });
const failed = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/delivery-targets/${targetId}/test`, headers: bearer(token) });
@@ -410,6 +438,74 @@ describe("delivery", () => {
expect((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) })).statusCode).toBe(404);
});
it("a backup of the originals on a computer: every arrival, untouched, with its metadata and Photo Mechanic's names", 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: "Backup 2026", kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/2026", username: "mac-0001-peter", folderTemplate: "/{iptcdate} - {event}/", fileNameTemplate: "PS_{event}_{timesort}", originals: true, onArrival: true },
});
expect(created.json()).toMatchObject({ originals: true, onArrival: true });
const targetId = (created.json() as { id: string }).id;
ingest.arrivals = (p) => delivery.queueArrival(p);
try {
// Bigger than any delivery size: the copy keeps every pixel.
const id = await photo("backup.jpg", "2026:09:23 21:10:05", { width: 6000, height: 4000 });
await drain();
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId, photoId: id } });
expect([item.status, item.remotePath]).toEqual(["WAITING", "20260923 - VSC x AAAS/PS_VSC x AAAS_21100500.jpg"]);
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string }[] };
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
expect(await sharp(file.rawPayload).metadata()).toMatchObject({ width: 6000, height: 4000 });
// The same compressed image as the original (only the metadata around it changed).
const original = await ctx.db.photo.findUniqueOrThrow({ where: { id } });
const pixels = async (b: Buffer | string) => createHash("sha256").update(await sharp(b).raw().toBuffer()).digest("hex");
expect(await pixels(file.rawPayload)).toBe(await pixels(new LocalStorage(ctx.config.STORAGE_ROOT).resolve(original.storageKey)));
expect(file.rawPayload.toString("latin1")).toContain("VSC x AAAS");
} finally {
ingest.arrivals = undefined;
}
});
it("the central FTP as a relay: chosen logins' photos, exactly as they arrived, to a computer's ingest folder", async () => {
const { orgId, token } = await setup();
const { user: other } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const outro = await ctx.db.ftpAccount.create({ data: { organizationId: orgId, userId: other.id, login: "outro" } });
const mine = await ctx.db.ftpAccount.findFirstOrThrow({ where: { organizationId: orgId, login: "foto" } });
const target = async (name: string, logins: string[]) =>
(
await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name, kind: "LOCAL", baseUrl: "/Users/cyclop/Desktop/ingest", username: "mac-0001-peter", folderTemplate: "/", fileNameTemplate: "{originalName}", originals: true, untouched: true, onArrival: true, arrivalLogins: logins },
})
).json() as { id: string; arrivalLogins: string[]; untouched: boolean };
const relay = await target("Relay foto", [mine.id]);
expect(relay).toMatchObject({ arrivalLogins: [mine.id], untouched: true });
const others = await target("Relay outro", [outro.id]);
// Someone else's login is refused.
const bad = await ctx.app.inject({ method: "PATCH", url: `/v1/orgs/${orgId}/delivery-targets/${relay.id}`, headers: bearer(token), payload: { arrivalLogins: ["00000000-0000-4000-8000-000000000000"] } });
expect(bad.json()).toMatchObject({ error: "unknown_ftp_login" });
ingest.arrivals = (p) => delivery.queueArrival(p);
try {
const id = await photo("IMG_0042.JPG", "2026:09:23 21:10:05");
await drain();
expect(await ctx.db.deliveryItem.count({ where: { targetId: others.id } })).toBe(0);
const item = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId: relay.id, photoId: id } });
expect([item.status, item.remotePath]).toEqual(["WAITING", "IMG_0042.jpg"]);
const claim = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries/local/claim`, headers: bearer(token), payload: { machine: "mac-0001-peter" } })).json() as { items: { id: string }[] };
const file = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) });
// Byte for byte the file the camera sent: no metadata written.
const original = await ctx.db.photo.findUniqueOrThrow({ where: { id } });
const sent = await readFile(new LocalStorage(ctx.config.STORAGE_ROOT).resolve(original.storageKey));
expect(Buffer.compare(file.rawPayload, sent)).toBe(0);
} finally {
ingest.arrivals = undefined;
}
});
it("waits for an original still on the photographer's computer instead of delivering its preview", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
+60
View File
@@ -5,6 +5,7 @@ import path from "node:path";
import sharp from "sharp";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { readEmbeddedIptc, repairMacRoman } from "../src/ingest/embedded.js";
import { readCameraInfo } from "../src/ingest/exif.js";
describe("IPTC already in incoming files", () => {
let dir: string;
@@ -34,6 +35,65 @@ describe("IPTC already in incoming files", () => {
expect(await readEmbeddedIptc(p)).toEqual({ title: "Nome do Jogador", event: "ABC Braga x CDE Gil Eanes", location: "Pavilhão", personsShown: ["Rui Silva"] });
});
it("reads the rest of Photo Mechanic's pad, as Photo Mechanic writes it", async () => {
const p = await file("pm.jpg", [
"-IPTC:By-lineTitle=Fotojornalista",
"-IPTC:Writer-Editor=PS",
"-IPTC:Province-State=Braga",
"-IPTC:Country-PrimaryLocationName=Portugal",
"-IPTC:SpecialInstructions=Embargo",
"-XMP-iptcCore:[email protected]",
"-XMP-iptcCore:CreatorCity=Braga",
"-XMP-xmpRights:UsageTerms=Uso editorial",
]);
expect(await readEmbeddedIptc(p)).toMatchObject({
jobTitle: "Fotojornalista",
captionWriter: "PS",
state: "Braga",
country: "Portugal",
instructions: "Embargo",
creatorEmail: "[email protected]",
creatorCity: "Braga",
usageTerms: "Uso editorial",
});
});
it("reads the camera details Photo Mechanic shows", async () => {
const p = await file("cam.jpg", [
"-EXIF:Make=Canon",
"-EXIF:Model=Canon EOS R3",
"-EXIF:ExposureCompensation=-0.33",
"-EXIF:Flash#=16",
"-EXIF:MeteringMode#=3",
"-EXIF:ExposureProgram#=1",
"-EXIF:WhiteBalance#=0",
"-EXIF:FocalLengthIn35mmFormat=400",
"-EXIF:LensInfo=100 500 4.5 7.1",
"-EXIF:Software=Firmware Version 1.8.1",
"-EXIF:OwnerName=Peter Spark",
"-EXIF:Artist=Peter Spark",
"-GPSLatitude=41.5618",
"-GPSLatitudeRef=N",
"-GPSLongitude=8.4291",
"-GPSLongitudeRef=W",
]);
const { extra } = await readCameraInfo(p);
expect(extra).toMatchObject({
exposureCompensation: -0.33,
flashFired: false,
meteringMode: "Spot",
exposureProgram: "Manual",
whiteBalance: "Auto",
focalLength35: 400,
lensRange: [100, 500],
firmware: "1.8.1",
owner: "Peter Spark",
artist: "Peter Spark",
});
expect(extra?.latitude).toBeCloseTo(41.5618, 3);
expect(extra?.longitude).toBeCloseTo(-8.4291, 3);
});
it("returns nothing for a bare camera file", async () => {
const p = path.join(dir, "bare.jpg");
await writeFile(p, await sharp({ create: { width: 8, height: 8, channels: 3, background: "#000" } }).jpeg().toBuffer());
+25
View File
@@ -0,0 +1,25 @@
import { mkdtemp, stat, utimes } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { FACE_HEARTBEAT_STALE_MS, faceHeartbeatPath, faceWorkerLive, touchFaceHeartbeat } from "../src/faces/heartbeat.js";
describe("face worker heartbeat", () => {
const dirs: string[] = [];
afterEach(async () => {
const { rm } = await import("node:fs/promises");
await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
});
it("is live just after a beat and not once the beat is old or missing", async () => {
const root = await mkdtemp(path.join(tmpdir(), "pr-face-beat-"));
dirs.push(root);
expect(faceWorkerLive(root)).toBe(false);
touchFaceHeartbeat(root, new Date("2026-10-17T12:00:00Z"));
const beat = await stat(faceHeartbeatPath(root));
expect(faceWorkerLive(root, beat.mtimeMs + 1_000)).toBe(true);
const old = new Date(beat.mtimeMs - FACE_HEARTBEAT_STALE_MS - 1_000);
await utimes(faceHeartbeatPath(root), old, old);
expect(faceWorkerLive(root, beat.mtimeMs)).toBe(false);
});
});
+64
View File
@@ -466,4 +466,68 @@ describe("faces", () => {
expect(both.score).toBeGreaterThan(byFace.score);
expect(both.score).toBeLessThanOrEqual(0.99);
});
it("claims a boosted photo ahead of an older one", async () => {
const { orgId, day1 } = await setup();
await ctx.db.photo.create({
data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: "old.jpg", sha256: "a".repeat(64), byteSize: 1, storageKey: "old", status: "READY", facesStatus: "PENDING", createdAt: new Date("2026-10-01T00:00:00Z") },
});
const newer = await ctx.db.photo.create({
data: {
organizationId: orgId,
eventId: day1.id,
source: "UPLOAD",
originalName: "new.jpg",
sha256: "b".repeat(64),
byteSize: 1,
storageKey: "new",
status: "READY",
facesStatus: "PENDING",
facesBoostedAt: new Date(),
createdAt: new Date("2026-10-02T00:00:00Z"),
},
});
expect(await faces.claim(1)).toEqual([newer.id]);
});
it("puts the event at the front of the queue and requeues a face the worker abandoned", async () => {
const { orgId, token, day1 } = await setup();
const photoOf = (name: string, facesStatus: "PENDING" | "FAILED" | "RUNNING") =>
ctx.db.photo.create({
data: { organizationId: orgId, eventId: day1.id, source: "UPLOAD", originalName: name, sha256: name.padEnd(64, "0"), byteSize: 1, storageKey: name, status: "READY", facesStatus },
});
const pending = await photoOf("pending.jpg", "PENDING");
const failed = await photoOf("failed.jpg", "FAILED");
const fresh = await photoOf("fresh.jpg", "RUNNING");
const stale = await photoOf("stale.jpg", "RUNNING");
const aged = await ctx.db.$executeRaw`UPDATE photos SET updated_at = ${new Date(Date.now() - 60 * 60_000)} WHERE id = ${stale.id}::uuid`;
expect(aged).toBe(1);
const res = await ctx.app.inject({ method: "POST", url: `/v1/events/${day1.id}/faces/analyse`, headers: bearer(token) });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ queued: 3 });
const statusOf = async (id: string) => ctx.db.photo.findUniqueOrThrow({ where: { id }, select: { facesStatus: true, facesBoostedAt: true } });
expect(await statusOf(pending.id)).toMatchObject({ facesStatus: "PENDING" });
expect((await statusOf(pending.id)).facesBoostedAt).not.toBeNull();
expect((await statusOf(failed.id)).facesStatus).toBe("PENDING");
expect((await statusOf(stale.id)).facesStatus).toBe("PENDING");
expect((await statusOf(fresh.id)).facesStatus).toBe("RUNNING");
expect((await statusOf(fresh.id)).facesBoostedAt).toBeNull();
const event = await ctx.db.event.findUniqueOrThrow({ where: { id: day1.id }, select: { faceBoostedAt: true } });
expect(event.faceBoostedAt).not.toBeNull();
const listed = await ctx.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) });
expect(listed.json()).toMatchObject({ available: true, pending: 4 });
});
it("says face analysis is unavailable when the worker engine is not running", async () => {
const off = await createTestApp({ STORAGE_ROOT: ctx.config.STORAGE_ROOT, INGEST_ROOT: ingestRoot }, broadcaster, undefined, () => false);
try {
const { token, day1 } = await setup();
const res = await off.app.inject({ method: "GET", url: `/v1/events/${day1.id}/face-groups`, headers: bearer(token) });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ available: false, groups: [] });
} finally {
await off.app.close();
await off.db.$disconnect();
}
});
});
+2 -2
View File
@@ -13,7 +13,7 @@ export interface TestContext {
config: Config;
}
export async function createTestApp(overrides: Record<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch): Promise<TestContext> {
export async function createTestApp(overrides: Record<string, string> = {}, realtime?: Broadcaster, fetchImpl?: typeof fetch, engineOnline?: () => boolean): Promise<TestContext> {
const config = loadConfig({
NODE_ENV: "test",
DATABASE_URL: assertTestDatabase(process.env.DATABASE_URL_TEST),
@@ -23,7 +23,7 @@ export async function createTestApp(overrides: Record<string, string> = {}, real
...overrides,
});
const db = createDb(config.DATABASE_URL);
const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }) });
const app = await buildApp({ config, db, ...(realtime && { realtime }), ...(fetchImpl && { fetchImpl }), ...(engineOnline && { engineOnline }) });
return { app, db, config };
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { waitUntil } from "../src/lib/idle.js";
describe("waitUntil", () => {
it("resolves true when the predicate is already true", async () => {
expect(await waitUntil(() => true, { timeoutMs: 100 })).toBe(true);
});
it("waits until the predicate flips", async () => {
let ready = false;
setTimeout(() => {
ready = true;
}, 30);
expect(await waitUntil(() => ready, { timeoutMs: 500, intervalMs: 10 })).toBe(true);
});
it("returns false on timeout", async () => {
expect(await waitUntil(() => false, { timeoutMs: 40, intervalMs: 10 })).toBe(false);
});
});
+47
View File
@@ -160,6 +160,53 @@ describe("library", () => {
expect(forged.statusCode).toBe(404);
});
it("sends a login's photos to the event chosen by hand, whatever the camera's clock, until switched off", async () => {
const { orgId, admin, foto, other, event } = await setup();
const until = new Date(Date.now() + 3600_000).toISOString();
const press = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Conferência de imprensa", startsAt: new Date().toISOString(), photographerIds: [] } })).json() as { id: string };
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/ftp-accounts`, headers: bearer(admin), payload: { userId: other.id, login: "outro.r1" } });
// The photographer sees only their own login; the editor sees all.
let res = await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) });
const mine = (res.json() as { accounts: { id: string; login: string; here: boolean }[] }).accounts;
expect(mine.map((a) => [a.login, a.here])).toEqual([["foto.r1", false]]);
const all = ((await ctx.app.inject({ method: "GET", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin) })).json() as { accounts: { id: string; login: string }[] }).accounts;
expect(all.map((a) => a.login)).toEqual(["foto.r1", "outro.r1"]);
const theirs = all.find((a) => a.login === "outro.r1")!;
expect((await ctx.app.inject({ method: "PUT", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto), payload: { accountIds: [theirs.id] } })).statusCode).toBe(403);
// The editor points the photographer's login at the press conference.
res = await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [mine[0]!.id], until } });
expect(res.json()).toMatchObject({ ftpTargets: [{ login: "foto.r1", until }] });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(foto) })).json() as { accounts: { elsewhere: { id: string } | null }[] }).accounts[0]!.elsewhere).toMatchObject({ id: press.id });
// Taken during the game, but sent while the login points at the press conference: it goes there.
expect(await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#123456" })))).toMatchObject({ status: "ingested", eventId: press.id });
// Switched off: by the time again.
await ctx.app.inject({ method: "PUT", url: `/v1/events/${press.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: [] } });
expect(await service.ingestFile(await drop("foto.r1", "b.jpg", await jpeg({ color: "#654321" })))).toMatchObject({ status: "ingested", eventId: event.id });
// A time gone by: back by the time too.
await ctx.db.ftpAccount.updateMany({ data: { targetEventId: press.id, targetUntil: new Date(Date.now() - 1000) } });
expect(await service.ingestFile(await drop("foto.r1", "c.jpg", await jpeg({ color: "#665544" })))).toMatchObject({ status: "ingested", eventId: event.id });
});
it("deletes an event: its photos go back to Sem evento; put-away events are listed apart", async () => {
const { orgId, admin, foto, event } = await setup();
const outcome = await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg()));
expect(outcome).toMatchObject({ eventId: event.id });
await ctx.app.inject({ method: "PUT", url: `/v1/events/${event.id}/ftp-target`, headers: bearer(admin), payload: { accountIds: (await ctx.db.ftpAccount.findMany()).map((a) => a.id), until: new Date(Date.now() + 3600_000).toISOString() } });
expect((await ctx.app.inject({ method: "DELETE", url: `/v1/events/${event.id}`, headers: bearer(foto) })).statusCode).toBe(403);
const del = await ctx.app.inject({ method: "DELETE", url: `/v1/events/${event.id}`, headers: bearer(admin) });
expect(del.json()).toMatchObject({ deleted: event.id, photos: 1 });
expect(await ctx.db.photo.findFirst({ where: { id: (outcome as { photoId: string }).photoId } })).toMatchObject({ eventId: null });
expect(await ctx.db.ftpAccount.findFirst()).toMatchObject({ targetEventId: null });
// Put away by hand: out of the list, in the "archived" one; the archive's own games never are.
const other = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin), payload: { home: "Gala", startsAt: "2026-10-01T20:00:00Z" } })).json() as { id: string };
await ctx.app.inject({ method: "PATCH", url: `/v1/events/${other.id}`, headers: bearer(admin), payload: { archived: true } });
expect(((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events`, headers: bearer(admin) })).json() as { events: unknown[] }).events).toHaveLength(0);
const archived = (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/events?archived=true`, headers: bearer(admin) })).json() as { events: { id: string }[] };
expect(archived.events.map((e) => e.id)).toEqual([other.id]);
});
it("drops duplicates, sets aside unknown logins and RAW files, and sends unmatched photos to the inbox", async () => {
const { orgId, admin } = await setup();
const data = await jpeg();
+94
View File
@@ -0,0 +1,94 @@
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import { createDb } from "../src/db.js";
import { numberContext, numbersIn } from "../src/faces/numbers.js";
import { resetDb, seedUser } from "./helpers.js";
/** Shirt numbers hold within a season and competition: another season, a cup or the national team may differ. */
describe("shirt numbers by season and competition", () => {
const db = createDb(process.env.DATABASE_URL_TEST ?? "");
afterAll(() => db.$disconnect());
beforeEach(() => resetDb(db));
async function setup() {
const { org, user } = await seedUser(db, "[email protected]", { org: "fpa", role: "OWNER" });
const orgId = org!.id;
const team = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "t1", sport: "andebol", name: "Sporting CP", slug: "sporting-cp" } });
const other = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "t2", sport: "andebol", name: "ABC de Braga", slug: "abc" } });
// Ana wore 23 five seasons ago and wears 7 now; the person was made from today's squad entry.
await db.sportsPlayer.create({ data: { teamId: team.id, season: "20212022", externalId: "p1", name: "Ana Seabra", number: "23" } });
const now = await db.sportsPlayer.create({ data: { teamId: team.id, season: "20262027", externalId: "p1", name: "Ana Seabra", number: "7" } });
const ana = await db.person.create({ data: { organizationId: orgId, name: "Ana Seabra", club: "Sporting CP", number: "7", sportsPlayerId: now.id } });
// Rui has no squad entry: only the number typed on him.
const rui = await db.person.create({ data: { organizationId: orgId, name: "Rui Silva", club: "Sporting CP", number: "14" } });
const event = (data: { home: string; away: string; startsAt: string; competition?: string; linked?: boolean }) =>
db.event.create({
data: {
organizationId: orgId,
home: data.home,
away: data.away,
competition: data.competition ?? null,
startsAt: new Date(data.startsAt),
ingestFrom: new Date(data.startsAt),
ingestUntil: new Date(data.startsAt),
iptcTemplate: {},
createdById: user.id,
...(data.linked && { homeTeamId: team.id, awayTeamId: other.id }),
},
});
let n = 0;
/** Ana confirmed in a game, her shirt clearly read as `number` in three photos. */
const seen = async (eventId: string, number: string) => {
const group = await db.faceGroup.create({ data: { organizationId: orgId, eventId, centroid: [1, 0], model: "auraface-v1", size: 3, personId: ana.id } });
for (let i = 0; i < 3; i++) {
n++;
const photo = await db.photo.create({ data: { organizationId: orgId, eventId, source: "UPLOAD", originalName: `P_${n}.jpg`, sha256: String(n).padStart(64, "0"), byteSize: 1, storageKey: `k${n}`, status: "READY" } });
await db.face.create({ data: { organizationId: orgId, photoId: photo.id, groupId: group.id, x0: 0.4, y0: 0.2, x1: 0.5, y1: 0.35, score: 0.9, embedding: [1, 0], model: "auraface-v1", jerseyNumber: number, jerseyScore: 0.95 } });
}
};
return { ana, rui, event, seen };
}
const today = new Date("2026-10-15T12:00:00Z");
const numbers = async (eventId: string, ids: string[]) => {
const ctx = (await numberContext(db, eventId, today))!;
return Object.fromEntries(await numbersIn(db, ctx, ids));
};
it("reads no numbers at an event that is not a game (a gala, a session): faces only", async () => {
const { event } = await setup();
const gala = await event({ home: "Gala do Andebol 2026", away: "", startsAt: "2026-07-10T20:00:00Z" });
expect(await numberContext(db, gala.id, today)).toBeNull();
});
it("takes the squad of the game's season, not today's", async () => {
const { ana, rui, event } = await setup();
const league = await event({ home: "Sporting CP", away: "ABC de Braga", startsAt: "2026-10-04T18:00:00Z", competition: "Andebol 1", linked: true });
const old = await event({ home: "Sporting CP", away: "ABC de Braga", startsAt: "2021-11-20T18:00:00Z", competition: "Andebol 1", linked: true });
expect(await numbers(league.id, [ana.id, rui.id])).toEqual({ [ana.id]: "7", [rui.id]: "14" });
// Five seasons ago: her number then, and Rui's typed number (no season of its own) says nothing.
expect(await numbers(old.id, [ana.id, rui.id])).toEqual({ [ana.id]: "23" });
});
it("never gives a club number to a national team's shirt, and learns the one worn there", async () => {
const { ana, rui, event, seen } = await setup();
const game = await event({ home: "Portugal", away: "França", startsAt: "2026-10-10T18:00:00Z" });
expect(await numbers(game.id, [ana.id, rui.id])).toEqual({});
// Confirmed in another national game this season, wearing 13: that is her number for Portugal.
const before = await event({ home: "Portugal", away: "Espanha", startsAt: "2026-10-08T18:00:00Z" });
await seen(before.id, "13");
expect(await numbers(game.id, [ana.id])).toEqual({ [ana.id]: "13" });
// Her club games are not affected.
const league = await event({ home: "Sporting CP", away: "ABC de Braga", startsAt: "2026-10-04T18:00:00Z", competition: "Andebol 1", linked: true });
expect(await numbers(league.id, [ana.id])).toEqual({ [ana.id]: "7" });
});
it("uses the number worn in a competition with its own numbering", async () => {
const { ana, event, seen } = await setup();
const cup1 = await event({ home: "Sporting CP", away: "ABC de Braga", startsAt: "2026-10-01T18:00:00Z", competition: "Taça EHF" });
const cup2 = await event({ home: "ABC de Braga", away: "Sporting CP", startsAt: "2026-10-12T18:00:00Z", competition: "Taça EHF" });
// Before anything is known of that cup: the season's squad.
expect(await numbers(cup2.id, [ana.id])).toEqual({ [ana.id]: "7" });
await seen(cup1.id, "70");
expect(await numbers(cup2.id, [ana.id])).toEqual({ [ana.id]: "70" });
});
});
+10
View File
@@ -84,3 +84,13 @@ describe("rename on arrival", () => {
expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } })).fileName).toBe("PS_ABC Braga x CDE Gil Eanes_19310700");
});
});
describe("Photo Mechanic rename templates", () => {
it("accepts its variables in any case, with its modifiers", async () => {
const { renameExample } = await import("../src/library/ftp.js");
expect(renameExample("PS_{Event:0:lc:tr: /_}_{filenamebase:-4}_{IPTCDATE}")).toBe("PS_abc_braga_x_cde_gil_eanes_1234_20261011.jpg");
expect(renameExample("{model:0:UC}_{serialnum}_{timesort}")).toBe("CANON EOS R3_123_19310745.jpg");
expect(() => renameExample("{event:shout}")).toThrow(/invalid modifiers/);
expect(() => renameExample("{nope}")).toThrow(/unknown variables/);
});
});
+22 -1
View File
@@ -1,6 +1,6 @@
import pino from "pino";
import { Writable } from "node:stream";
import { afterAll, describe, expect, it } from "vitest";
import { afterAll, describe, expect, it, vi } from "vitest";
import { buildApp } from "../src/app.js";
import { loadConfig } from "../src/config.js";
import { createDb } from "../src/db.js";
@@ -42,6 +42,27 @@ describe("errors to errors.bitreport.pt", () => {
expect(other!.fingerprint).not.toBe(first!.fingerprint);
});
it("survives the known undici socket-end assertion (nodejs/undici#5360) instead of exiting", async () => {
const hub = fakeHub();
const reporter = reporterWith(hub.fetchImpl);
const exitSpy = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);
const before = process.listeners("uncaughtException");
reporter.watchProcess("worker");
try {
const err = new Error("false == true");
err.name = "AssertionError";
(err as { code?: string }).code = "ERR_ASSERTION";
err.stack = `AssertionError [ERR_ASSERTION]: false == true\n at Parser.finish (node:internal/deps/undici/undici:6165:9)\n at TLSSocket.<anonymous> (node:internal/deps/undici/undici:6499:36)`;
process.emit("uncaughtException", err);
await reporter.flush();
expect(exitSpy).not.toHaveBeenCalled();
expect(hub.sent.flatMap((s) => s.events)).toMatchObject([{ level: "warning", context: { undici_known_bug: "nodejs/undici#5360" } }]);
} finally {
for (const l of process.listeners("uncaughtException")) if (!before.includes(l)) process.removeListener("uncaughtException", l);
exitSpy.mockRestore();
}
});
it("does nothing without a key", async () => {
const hub = fakeHub();
const reporter = reporterWith(hub.fetchImpl, "");
+32 -1
View File
@@ -80,7 +80,14 @@ describe("federation data", () => {
]);
expect(parseFpaBoletim("<html><body><table><tr><td>Equipa A :: X</td></tr></table></body></html>").available).toBe(false);
expect(fpaShortName("Ana Lima")).toBe("Ana Lima");
expect(parseFpaClubTerms(CLUB_PAGE)).toEqual({ season: "374", levels: [{ id: "59", name: "Seniores M - ACR" }, { id: "4", name: "Seniores M" }, { id: "11", name: "Seniores F" }] });
expect(parseFpaClubTerms(CLUB_PAGE)).toEqual({
season: "374",
seasons: [
{ id: "374", season: "20262027" },
{ id: "373", season: "20252026" },
],
levels: [{ id: "59", name: "Seniores M - ACR" }, { id: "4", name: "Seniores M" }, { id: "11", name: "Seniores F" }],
});
expect(parseFpaReferees("<body><a>Cursos Árbitros</a><table><tr><td>Árbitros</td>\n<td>Ana Lima, Bruno Costa</td></tr><tr><td>Delegados</td><td>Mário Silva</td></tr><tr><td>Oficiais de Mesa</td><td>Rita Sá, Luís Mota</td></tr></table></body>")).toEqual([
{ name: "Ana Lima", role: "REFEREE" },
{ name: "Bruno Costa", role: "REFEREE" },
@@ -545,6 +552,30 @@ describe("sports data service", () => {
expect(photosOf("Tiago Ferreira")).toEqual({ confirmed: 0, likely: 1 });
});
it("FPA: a past season, club by club, following every club met (national games only)", async () => {
const calls: string[] = [];
const json = (body: unknown) => ({ ok: true, status: 200, json: async () => body, text: async () => JSON.stringify(body), arrayBuffer: async () => new ArrayBuffer(0) });
const page = (b: string) => ({ ok: true, status: 200, json: async () => ({}), text: async () => b, arrayBuffer: async () => new TextEncoder().encode(b).buffer as ArrayBuffer });
const GIL: [string, string, string] = ["50001", "142", "CDE GIL EANES"];
const regional = { ...fpaGame("900003", "2025-11-01", AGUAS, GIL, [20, 20]), ID_ASSOCIACAO: "3" };
const fetcher: Fetch = async (url) => {
calls.push(url);
const u = new URL(url);
if (u.pathname.includes("getAgendaJogosFAP")) return json([{ ...fpaGame("990001", "2026-10-30", VITORIA, VITORIA, null), ID_ASSOCIACAO: "8" }]) as never;
if (u.host === "portal.fpa.pt") return page(CLUB_PAGE) as never;
if (u.pathname.endsWith("/140/373/4")) return json([{ ...fpaGame("900001", "2025-10-04", VITORIA, AGUAS, [30, 28]), ID_ASSOCIACAO: "8" }]) as never;
if (u.pathname.endsWith("/141/373/4")) return json([{ ...fpaGame("900002", "2026-03-07", AGUAS, GIL, [25, 27]), ID_ASSOCIACAO: "8" }, regional]) as never;
return json([]) as never;
};
const service = new SportsService({ db: ctx.db, storage: new LocalStorage(ctx.config.STORAGE_ROOT), log: quiet, fetch: fetcher, fpfDelayMs: 0, uefaDelayMs: 0, fpaDelayMs: 0 });
expect(await service.importFpaSeason("20252026")).toBe(2);
const saved = await ctx.db.sportsFixture.findMany({ where: { season: "20252026", externalId: { in: ["900001", "900002", "900003"] } }, select: { externalId: true } });
expect(saved.map((f) => f.externalId).sort()).toEqual(["900001", "900002"]);
// Águas Santas (met in Vitória's games) and Gil Eanes (met in Águas Santas') were read too.
expect(calls.some((c) => c.includes("/clube/id/141/"))).toBe(true);
expect(calls.some((c) => c.includes("/clube/id/142/"))).toBe(true);
});
it("UEFA: matches with the referee team, squads from match sheets, and the referees as people of the event", async () => {
const { org, user } = await seedUser(ctx.db, "[email protected]", { org: "torreense", role: "OWNER" });
await sports.refreshDue(now);
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vitest";
import { fetchFailure } from "../src/delivery/zerozero.js";
describe("zerozero fetch errors", () => {
it("keeps the socket code that fetch hides on cause", () => {
const err = new TypeError("fetch failed");
(err as { cause?: unknown }).cause = { code: "ETIMEDOUT", message: "connect ETIMEDOUT" };
expect(fetchFailure(err)).toBe("fetch failed (ETIMEDOUT)");
});
it("joins every address error when happy eyeballs fails them all", () => {
const err = new TypeError("fetch failed");
(err as { cause?: unknown }).cause = { errors: [{ code: "ENETUNREACH" }, { code: "ECONNREFUSED" }] };
expect(fetchFailure(err)).toBe("fetch failed (ENETUNREACH, ECONNREFUSED)");
});
});
+57 -3
View File
@@ -186,6 +186,7 @@ export const t = {
queued: (n: number) => (n ? `${n} fotos em fila para análise` : "Não há fotos por analisar"),
disabled: "O reconhecimento de caras está desligado nesta organização.",
working: "A analisar as fotos…",
unavailable: (n: number) => (n > 0 ? `Análise de caras indisponível (${n} ${n === 1 ? "foto por analisar" : "fotos por analisar"}).` : "Análise de caras indisponível."),
showSingles: (n: number) => `Mostrar ${n} ${n === 1 ? "cara que aparece" : "caras que aparecem"} só numa foto`,
hideSingles: "Esconder caras que aparecem só numa foto",
unclear: (n: number) => `${n} ${n === 1 ? "cara desfocada ficou" : "caras desfocadas ficaram"} de fora (público, fundo)`,
@@ -206,6 +207,7 @@ export const t = {
iptcIssue: {
missing_variable: (d: string) => (d === "players" ? "Sem jogadores identificados" : `Falta {${d}} nos dados do evento`),
unknown_code: (d: string) => `Código \\${d}\\ não existe`,
bad_modifier: (d: string) => `Modificador inválido (${d})`,
} as Record<string, (d: string) => string>,
camera: "Câmara",
exposure: "Exposição",
@@ -241,6 +243,50 @@ export const t = {
auto: "Procurar pelas equipas e hora",
use: "Usar",
},
eventSettings: {
button: "Evento",
receivingTitle: (logins: string) => `A receber o FTP de ${logins}`,
ftpTitle: "Receber FTP aqui",
ftpHelp: "As fotos destes logins FTP vêm todas para este evento, seja qual for a hora da câmara. Os outros continuam a ir para o evento da hora em que a foto foi tirada.",
noLogins: "Sem logins FTP.",
hereUntil: (when: string) => `A receber aqui até ${when}`,
hereForever: "A receber aqui até desligares",
elsewhere: (title: string) => `Agora a enviar para ${title}`,
until: "Até:",
untilEvent: "o fim do evento",
untilOff: "eu desligar",
timesTitle: "Horário e fotógrafos",
timesHelp: "Sem \"Receber FTP aqui\", cada foto vai para o evento em cuja janela de receção foi tirada, dos fotógrafos atribuídos (sem nenhum: de todos).",
startsAt: "Início",
from: "Recebe fotos de",
to: "até",
photographers: "Fotógrafos",
anyone: "Sem fotógrafos escolhidos: recebe de todos.",
save: "Guardar",
archive: "Arquivar",
archiveHelp: "Sai da lista e deixa de receber fotos. Fica em \"Arquivados\".",
unarchive: "Tirar do arquivo",
unarchiveHelp: "Volta à lista e a receber fotos.",
delete: "Apagar evento",
deleteConfirm: (n: number) => (n ? `Apagar o evento? As ${n} fotos voltam para \"Sem evento\" (não se perdem).` : "Apagar o evento?"),
deleteYes: "Apagar",
cancel: "Cancelar",
errors: {
archive_event: "É um jogo do arquivo da cloud: não se apaga daqui.",
until_in_the_past: "Essa hora já passou.",
event_archived: "O evento está arquivado.",
ftp_account_not_yours: "Só podes escolher os teus logins.",
invalid_ingest_window: "A receção tem de acabar depois de começar.",
} as Record<string, string>,
},
eventsList: {
older: (n: number) => `Anteriores (${n})`,
hideOlder: "Esconder anteriores",
archived: "Arquivados",
hideArchived: "Esconder arquivados",
noArchived: "Nada arquivado.",
ftp: "FTP",
},
autopilot: {
button: "Piloto automático",
enable: "Ligar o piloto automático neste evento",
@@ -372,6 +418,8 @@ export const t = {
reauthorise: "Autorizar de novo",
scanNow: "Analisar agora",
pause: "Pausar",
look: "Aspeto do site",
looks: { none: "PhotoReport", liga: "Liga Portugal", fpa: "Federação de Andebol" } as Record<string, string>,
resume: "Retomar",
remove: "Desligar",
removeConfirm: "Desligar esta cloud? As fotos já indexadas ficam na biblioteca.",
@@ -380,7 +428,13 @@ export const t = {
never: "ainda não",
progress: (done: number, total: number) => `${done.toLocaleString("pt-PT")} de ${total.toLocaleString("pt-PT")} fotos indexadas`,
failed: (n: number) => `${n} com erro`,
galleriesLine: (g: number, games: number, named: number, other: number) => `${g} galerias · ${games} jogos encontrados · ${named} pelo nome · ${other} outras pastas`,
pace: (perHour: number, left: number) => {
if (!perHour) return left ? "à espera do worker" : "";
const hours = left / perHour;
const eta = hours < 1 ? `${Math.max(1, Math.round(hours * 60))} min` : hours < 48 ? `${Math.round(hours)} h` : `${Math.round(hours / 24)} dias`;
return `${perHour.toLocaleString("pt-PT")} fotos/hora${left ? ` · faltam ~${eta}` : ""}`;
},
galleriesLine: (g: number, games: number, named: number, other: number) => `${g} galerias · ${games} jogos oficiais · ${named} jogos por confirmar · ${other} eventos`,
status: { LOGIN: "Por autorizar", READY: "Ligada", SCANNING: "A analisar", ERROR: "Erro", PAUSED: "Em pausa" } as Record<string, string>,
errors: {
login_expired: "A autorização expirou. Autoriza de novo.",
@@ -393,10 +447,10 @@ export const t = {
secrets_not_configured: "O servidor não tem a chave de segredos configurada.",
} as Record<string, string>,
galleries: "Galerias",
tabs: { unmatched: "Por confirmar", games: "Jogos", all: "Todas" },
tabs: { games: "Jogos oficiais", named: "Jogos por confirmar", events: "Eventos", all: "Todas" },
search: "Procurar pasta…",
noGalleries: "Sem galerias aqui.",
matched: { FIXTURE: "jogo oficial", MANUAL: "escolhido", NAME: "pelo nome", FOLDER: "pasta" } as Record<string, string>,
matched: { FIXTURE: "jogo oficial", MANUAL: "jogo escolhido", NAME: "jogo · pelo nome", FOLDER: "evento" } as Record<string, string>,
choose: "Escolher jogo",
cancel: "Cancelar",
searchGame: "Equipa, competição…",
+317
View File
@@ -0,0 +1,317 @@
import {
ApiError,
type ApiClient,
type EventSummary,
type FtpTargetAccount,
} from "@photoreport/sdk";
import { useEffect, useState } from "react";
import { t } from "../i18n.js";
import { isoToLisbonLocal, lisbonLocalToIso } from "./EventForm.js";
const hm = new Intl.DateTimeFormat("pt-PT", {
day: "2-digit",
month: "short",
hour: "2-digit",
minute: "2-digit",
timeZone: "Europe/Lisbon",
});
/**
* The open event's settings: where the FTP logins send their photos ("Receber FTP aqui"), its times and
* photographers (which decide where photos go by the time they were taken), and putting it away or deleting it.
*/
export function EventSettingsButton(props: {
api: ApiClient;
orgId: string;
event: EventSummary;
canEdit: boolean;
onSaved: (e: EventSummary) => void;
onRemoved: (eventId: string) => void;
}) {
const L = t.eventSettings;
const { api, event } = props;
const [open, setOpen] = useState(false);
const [accounts, setAccounts] = useState<FtpTargetAccount[] | null>(null);
const [until, setUntil] = useState<"event" | "off">("event");
const [startsAt, setStartsAt] = useState(isoToLisbonLocal(event.startsAt));
const [from, setFrom] = useState(isoToLisbonLocal(event.ingestFrom));
const [to, setTo] = useState(isoToLisbonLocal(event.ingestUntil));
const [people, setPeople] = useState<
{ id: string; name: string; role: string }[]
>([]);
const [chosen, setChosen] = useState<Set<string>>(
new Set(event.photographers.map((p) => p.id)),
);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [confirm, setConfirm] = useState(false);
useEffect(() => {
setStartsAt(isoToLisbonLocal(event.startsAt));
setFrom(isoToLisbonLocal(event.ingestFrom));
setTo(isoToLisbonLocal(event.ingestUntil));
setChosen(new Set(event.photographers.map((p) => p.id)));
setConfirm(false);
}, [event]);
useEffect(() => {
if (!open) return;
setError(null);
api.ftpTargets(event.id).then(
(r) => setAccounts(r.accounts),
() => setAccounts([]),
);
if (props.canEdit)
api.listPeople(props.orgId).then(
(r) => setPeople(r.people),
() => setPeople([]),
);
}, [open, api, event.id, props.orgId, props.canEdit]);
const run = async (fn: () => Promise<void>) => {
setBusy(true);
setError(null);
try {
await fn();
} catch (err) {
setError(
err instanceof ApiError
? (L.errors[err.code] ?? err.code)
: t.unexpectedError,
);
} finally {
setBusy(false);
}
};
const toggleFtp = (id: string, on: boolean) =>
run(async () => {
const ids = (accounts ?? [])
.filter((a) => (a.id === id ? on : a.here))
.map((a) => a.id);
const saved = await api.setFtpTarget(event.id, {
accountIds: ids,
...(until === "off" && { until: null }),
});
props.onSaved(saved);
setAccounts((await api.ftpTargets(event.id)).accounts);
});
const save = () =>
run(async () => {
props.onSaved(
await api.updateEvent(event.id, {
startsAt: lisbonLocalToIso(startsAt),
ingestFrom: lisbonLocalToIso(from),
ingestUntil: lisbonLocalToIso(to),
photographerIds: [...chosen],
}),
);
});
const receiving = event.ftpTargets?.length ?? 0;
const input =
"h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none";
return (
<div className="relative">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className={`flex h-6 items-center gap-1.5 border border-black px-2.5 text-[12px] ${receiving ? "bg-accent text-white" : "bg-cell text-ink hover:bg-cell-on"}`}
title={
receiving
? L.receivingTitle(event.ftpTargets!.map((a) => a.login).join(", "))
: L.button
}
>
{L.button}
{receiving > 0 && <span className="font-mono text-[10px]">· FTP</span>}
</button>
{open && (
<div
className="absolute right-0 top-7 z-30 max-h-[80vh] w-[380px] space-y-4 overflow-y-auto border border-black bg-panel p-3 text-[12px] shadow-xl"
role="dialog"
aria-label={L.button}
>
<section className="space-y-2">
<h3 className="font-semibold uppercase tracking-wide text-ink">
{L.ftpTitle}
</h3>
<p className="text-faint">{L.ftpHelp}</p>
{accounts === null && <p className="text-faint" aria-busy="true" />}
{accounts?.length === 0 && (
<p className="text-faint">{L.noLogins}</p>
)}
{accounts?.map((a) => (
<label key={a.id} className="flex items-start gap-2">
<input
type="checkbox"
disabled={busy || !!event.archivedAt}
checked={a.here}
onChange={(e) => void toggleFtp(a.id, e.target.checked)}
className="mt-0.5"
/>
<span className="min-w-0">
<span className="font-mono text-ink">{a.login}</span>{" "}
<span className="text-muted">· {a.user.name}</span>
{a.here && (
<span className="block text-accent">
{a.until
? L.hereUntil(hm.format(new Date(a.until)))
: L.hereForever}
</span>
)}
{!a.here && a.elsewhere && (
<span className="block text-faint">
{L.elsewhere(a.elsewhere.title)}
</span>
)}
</span>
</label>
))}
{!!accounts?.length && (
<label className="flex items-center gap-2 text-muted">
{L.until}
<select
value={until}
onChange={(e) => setUntil(e.target.value as "event" | "off")}
className="h-6 border border-black bg-cell px-1 text-[12px] text-ink"
>
<option value="event">{L.untilEvent}</option>
<option value="off">{L.untilOff}</option>
</select>
</label>
)}
</section>
{props.canEdit && (
<section className="space-y-2 border-t border-line pt-3">
<h3 className="font-semibold uppercase tracking-wide text-ink">
{L.timesTitle}
</h3>
<p className="text-faint">{L.timesHelp}</p>
<label className="block">
<span className="text-faint">{L.startsAt}</span>
<input
type="datetime-local"
value={startsAt}
onChange={(e) => setStartsAt(e.target.value)}
className={input}
/>
</label>
<div className="grid grid-cols-2 gap-2">
<label className="block">
<span className="text-faint">{L.from}</span>
<input
type="datetime-local"
value={from}
onChange={(e) => setFrom(e.target.value)}
className={input}
/>
</label>
<label className="block">
<span className="text-faint">{L.to}</span>
<input
type="datetime-local"
value={to}
onChange={(e) => setTo(e.target.value)}
className={input}
/>
</label>
</div>
<fieldset className="space-y-1">
<legend className="text-faint">{L.photographers}</legend>
{people.map((p) => (
<label key={p.id} className="flex items-center gap-2">
<input
type="checkbox"
checked={chosen.has(p.id)}
onChange={(e) => {
const next = new Set(chosen);
if (e.target.checked) next.add(p.id);
else next.delete(p.id);
setChosen(next);
}}
/>
<span>{p.name}</span>
</label>
))}
{chosen.size === 0 && <p className="text-faint">{L.anyone}</p>}
</fieldset>
<button
type="button"
disabled={busy}
onClick={() => void save()}
className="h-7 border border-black bg-accent px-3 text-[12px] text-white disabled:opacity-40"
>
{L.save}
</button>
</section>
)}
{props.canEdit && (
<section className="flex flex-wrap items-center gap-2 border-t border-line pt-3">
<button
type="button"
disabled={busy}
onClick={() =>
void run(async () => {
const saved = await api.updateEvent(event.id, {
archived: !event.archivedAt,
});
if (saved.archivedAt) props.onRemoved(event.id);
else props.onSaved(saved);
setOpen(false);
})
}
className="h-7 border border-black bg-cell px-3 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40"
title={event.archivedAt ? L.unarchiveHelp : L.archiveHelp}
>
{event.archivedAt ? L.unarchive : L.archive}
</button>
{!event.fromArchive &&
(confirm ? (
<>
<span className="w-full text-[#f0c27a]">
{L.deleteConfirm(event.photoCount)}
</span>
<button
type="button"
disabled={busy}
onClick={() =>
void run(async () => {
await api.deleteEvent(event.id);
setOpen(false);
props.onRemoved(event.id);
})
}
className="h-7 border border-black bg-[#8a2a20] px-3 text-[12px] text-white disabled:opacity-40"
>
{L.deleteYes}
</button>
<button
type="button"
onClick={() => setConfirm(false)}
className="h-7 px-2 text-[12px] text-muted underline"
>
{L.cancel}
</button>
</>
) : (
<button
type="button"
disabled={busy}
onClick={() => setConfirm(true)}
className="h-7 border border-black bg-cell px-3 text-[12px] text-[#e8857a] hover:bg-cell-on disabled:opacity-40"
>
{L.delete}
</button>
))}
</section>
)}
{error && <p className="text-[#e8857a]">{error}</p>}
</div>
)}
</div>
);
}
+97 -18
View File
@@ -1,9 +1,20 @@
import type { EventSummary } from "@photoreport/sdk";
import { useState } from "react";
import { t } from "../i18n.js";
import { LookupButton } from "./PhotoLookup.js";
const day = new Intl.DateTimeFormat("pt-PT", { day: "2-digit", month: "short", timeZone: "Europe/Lisbon" });
const time = new Intl.DateTimeFormat("pt-PT", { hour: "2-digit", minute: "2-digit", timeZone: "Europe/Lisbon" });
const day = new Intl.DateTimeFormat("pt-PT", {
day: "2-digit",
month: "short",
timeZone: "Europe/Lisbon",
});
/** Events older than this go under "Anteriores" (unless receiving FTP, or open). */
const RECENT_DAYS = 4;
const time = new Intl.DateTimeFormat("pt-PT", {
hour: "2-digit",
minute: "2-digit",
timeZone: "Europe/Lisbon",
});
export function EventsPanel(props: {
events: EventSummary[];
@@ -15,15 +26,64 @@ export function EventsPanel(props: {
onCreate: () => void;
/** Search by a photo (with face recognition on). */
onLookup?: (file: File) => void;
/** Events put away by hand (loaded when asked for); null: not shown. */
archived?: EventSummary[] | null;
onToggleArchived?: () => void;
}) {
const [older, setOlder] = useState(false);
const L = t.eventsList;
// What is in use: today, the next ones and the last few days, and anything receiving FTP or open now.
const since = Date.now() - RECENT_DAYS * 86_400_000;
const recent = props.events.filter(
(e) =>
Date.parse(e.startsAt) >= since ||
!!e.ftpTargets?.length ||
props.scope === e.id,
);
const past = props.events.filter((e) => !recent.includes(e));
const row = (active: boolean) =>
`flex w-full items-baseline justify-between gap-2 px-3 py-1.5 text-left text-[13px] ${active ? "bg-cell-on text-ink" : "text-muted hover:bg-raised"}`;
const item = (e: EventSummary, archived = false) => (
<button
key={e.id}
className={row(props.scope === e.id)}
onClick={() => props.onOpen(e.id)}
>
<span className="min-w-0">
<span className={`block truncate ${archived ? "text-faint" : ""}`}>
{e.title}
</span>
<span className="block font-mono text-[10px] text-faint">
{day.format(new Date(e.startsAt))} ·{" "}
{time.format(new Date(e.startsAt))}
{e.competitionCode && ` · ${e.competitionCode}`}
{!!e.ftpTargets?.length && (
<span
className="ml-1 text-accent"
title={e.ftpTargets.map((a) => a.login).join(", ")}
>
· {L.ftp}
</span>
)}
</span>
</span>
<span className="font-mono text-[11px]">{e.photoCount}</span>
</button>
);
return (
<aside aria-label={t.events} className="flex w-60 shrink-0 flex-col border-r border-line bg-panel max-lg:w-full max-lg:border-r-0 max-lg:border-b">
<aside
aria-label={t.events}
className="flex w-60 shrink-0 flex-col border-r border-line bg-panel max-lg:w-full max-lg:border-r-0 max-lg:border-b"
>
<div className="panel-head">
<span>{t.events}</span>
{props.canCreate && (
<button className="text-base leading-none text-muted hover:text-ink" onClick={props.onCreate} aria-label={t.newEvent} title={t.newEvent}>
<button
className="text-base leading-none text-muted hover:text-ink"
onClick={props.onCreate}
aria-label={t.newEvent}
title={t.newEvent}
>
+
</button>
)}
@@ -42,31 +102,50 @@ export function EventsPanel(props: {
type="search"
placeholder={t.searchPlaceholder}
aria-label={t.searchPlaceholder}
defaultValue={props.scope?.startsWith("search:") ? props.scope.slice(7) : ""}
defaultValue={
props.scope?.startsWith("search:") ? props.scope.slice(7) : ""
}
className="h-7 w-full min-w-0 border border-black bg-[#161617] px-2 text-[12px] text-ink placeholder:text-faint focus:border-accent focus:outline-none"
/>
{props.onLookup && <LookupButton onFile={props.onLookup} />}
</form>
<nav className="min-h-0 flex-1 overflow-y-auto py-1 max-lg:max-h-48">
{props.canSeeInbox && (
<button className={row(props.scope === "inbox")} onClick={() => props.onOpen("inbox")}>
<button
className={row(props.scope === "inbox")}
onClick={() => props.onOpen("inbox")}
>
<span className="italic">{t.inbox}</span>
<span className="font-mono text-[11px]">{props.inboxCount}</span>
</button>
)}
{props.events.length === 0 && <p className="px-3 py-4 text-xs text-faint">{t.noEvents}</p>}
{props.events.map((e) => (
<button key={e.id} className={row(props.scope === e.id)} onClick={() => props.onOpen(e.id)}>
<span className="min-w-0">
<span className="block truncate">{e.title}</span>
<span className="block font-mono text-[10px] text-faint">
{day.format(new Date(e.startsAt))} · {time.format(new Date(e.startsAt))}
{e.competitionCode && ` · ${e.competitionCode}`}
</span>
</span>
<span className="font-mono text-[11px]">{e.photoCount}</span>
{props.events.length === 0 && (
<p className="px-3 py-4 text-xs text-faint">{t.noEvents}</p>
)}
{recent.map((e) => item(e))}
{past.length > 0 && (
<button
className="w-full px-3 py-1.5 text-left text-[11px] uppercase tracking-wide text-faint hover:text-ink"
onClick={() => setOlder((o) => !o)}
aria-expanded={older}
>
{older ? L.hideOlder : L.older(past.length)}
</button>
))}
)}
{older && past.map((e) => item(e))}
{props.onToggleArchived && (
<button
className="w-full px-3 py-1.5 text-left text-[11px] uppercase tracking-wide text-faint hover:text-ink"
onClick={props.onToggleArchived}
aria-expanded={!!props.archived}
>
{props.archived ? L.hideArchived : L.archived}
</button>
)}
{props.archived?.length === 0 && (
<p className="px-3 py-1 text-[11px] text-faint">{L.noArchived}</p>
)}
{props.archived?.map((e) => item(e, true))}
</nav>
</aside>
);
+8 -2
View File
@@ -204,6 +204,7 @@ function GroupCard(props: {
export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api: ApiClient; orgId: string; eventId: string; canAnalyse: boolean; refreshKey: number }) {
const [groups, setGroups] = useState<FaceGroupSummary[] | null>(null);
const [pending, setPending] = useState(0);
const [engineOn, setEngineOn] = useState(true);
const [unclear, setUnclear] = useState(0);
const [showSingles, setShowSingles] = useState(false);
const [people, setPeople] = useState<SquadPerson[]>([]);
@@ -217,6 +218,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
setGroups(r.groups);
setPending(r.pending);
setUnclear(r.unclear ?? 0);
setEngineOn(r.available !== false);
},
() => setGroups([]),
);
@@ -243,12 +245,16 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
const isSingle = (g: FaceGroupSummary) => g.size === 1 && !g.person && !g.suggestion;
const singles = (groups ?? []).filter(isSingle).length;
const shown = (groups ?? []).filter((g) => showSingles || !isSingle(g));
let empty: string = t.faces.none;
if (!engineOn) empty = t.faces.unavailable(pending);
else if (pending > 0) empty = t.faces.working;
return (
<section aria-label={t.faces.title} className="p-3">
<div className="mb-3 flex flex-wrap items-center gap-3 text-[12px] text-muted">
<span>{t.faces.summary(groups?.length ?? 0, open)}</span>
{pending > 0 && <span className="font-mono text-[11px] text-[#7fb0ff]">{t.faces.pending(pending)}</span>}
{pending > 0 && engineOn && <span className="font-mono text-[11px] text-[#7fb0ff]">{t.faces.pending(pending)}</span>}
{!engineOn && <span className="text-[11px] text-danger">{t.faces.unavailable(pending)}</span>}
{unclear > 0 && <span className="text-[11px] text-faint">{t.faces.unclear(unclear)}</span>}
<Link to="/numbers" className="text-[11px] text-muted underline hover:text-ink">
{t.numbers.title}
@@ -293,7 +299,7 @@ export function FacesView({ api, orgId, eventId, canAnalyse, refreshKey }: { api
{groups === null ? (
<p className="p-6 text-center text-[13px] text-faint">…</p>
) : groups.length === 0 ? (
<p className="p-8 text-center text-[13px] text-faint">{pending ? t.faces.working : t.faces.none}</p>
<p className="p-8 text-center text-[13px] text-faint">{empty}</p>
) : (
<div className="grid gap-2" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(232px, 1fr))" }}>
{shown.map((g) => (
+29 -10
View File
@@ -5,15 +5,20 @@ import { t } from "../i18n.js";
type Values = Record<string, string>;
/** The pad's sections; the last four (the rest of Photo Mechanic's pad) start folded unless they have values. */
const SECTIONS = [
{ id: "newsroom", title: "Informação jornal" },
{ id: "generic", title: "Info genérica" },
{ id: "newsroom", title: "Informação jornal", folded: false },
{ id: "generic", title: "Info genérica", folded: false },
{ id: "contact", title: "Contacto do autor", folded: true },
{ id: "location", title: "Localização (mostrada e de captura)", folded: true },
{ id: "status", title: "Estado, instruções e direitos", folded: true },
{ id: "models", title: "Fornecedor e modelos", folded: true },
] as const;
/** Multi-line fields, as in the Photo Mechanic pad. */
const TALL = new Set(["caption", "extendedDescription", "headline", "altText"]);
export const VARIABLES = ["home", "away", "venue", "city", "competition", "competitionCode", "round", "date", "season", "players", "photographer", "sport:upper"];
export const VARIABLES = ["home", "away", "event", "venue", "city", "competition", "competitionCode", "round", "date", "iptcdate", "season", "players", "photographer", "sport:upper", "model", "lens", "serialnum", "caption", "headline"];
function toForm(template: EventSummary["iptcTemplate"]): Values {
const out: Values = {};
@@ -133,12 +138,11 @@ export function IptcTemplateEditor({ api, events, canEdit, onSaved }: { api: Api
</div>
</div>
</div>
{SECTIONS.map((section) => (
<fieldset key={section.id} className="border-b border-line px-4 py-3">
<legend className="sr-only">{section.title}</legend>
<p className="mb-2 text-[11px] font-semibold uppercase tracking-wider text-[#d0d0d0]">{section.title}</p>
{SECTIONS.map((section) => {
const fields = IPTC_FIELDS.filter((f) => f.section === section.id);
const grid = (
<div className="grid grid-cols-[150px_1fr] items-start gap-x-3 gap-y-2 max-sm:grid-cols-1">
{IPTC_FIELDS.filter((f) => f.section === section.id).map((f) => (
{fields.map((f) => (
<label key={f.key} className="contents">
<span className="pt-1.5 text-right text-[12px] text-faint max-sm:text-left">
{f.label}
@@ -152,8 +156,23 @@ export function IptcTemplateEditor({ api, events, canEdit, onSaved }: { api: Api
</label>
))}
</div>
</fieldset>
))}
);
const title = <span className="text-[11px] font-semibold uppercase tracking-wider text-[#d0d0d0]">{section.title}</span>;
if (section.folded)
return (
<details key={`${section.id}:${event?.id ?? ""}`} open={fields.some((f) => values[f.key])} className="border-b border-line px-4 py-3">
<summary className="cursor-pointer select-none">{title}</summary>
<div className="mt-2">{grid}</div>
</details>
);
return (
<fieldset key={section.id} className="border-b border-line px-4 py-3">
<legend className="sr-only">{section.title}</legend>
<p className="mb-2">{title}</p>
{grid}
</fieldset>
);
})}
{canEdit && (
<div className="sticky bottom-0 flex items-center justify-end gap-3 border-t border-line bg-panel px-4 py-3">
{status && <span className="text-[12px] text-muted">{status}</span>}
+8 -1
View File
@@ -1,7 +1,10 @@
import { ApiError, type ApiClient, type FtpAccount } from "@photoreport/sdk";
import { useEffect, useState } from "react";
/** The variables most used in names, as in Photo Mechanic (clicking one adds it to the template). */
/**
* The variables most used in names (clicking one adds it to the template). Every Photo Mechanic variable and its
* modifiers work (`{filenamebase:-4}`, `{event:0:UC}`, `{caption:0:lc:tr: /_}`).
*/
export const RENAME_VARIABLES = [
["{event}", "Casa x Fora"],
["{home}", "Casa"],
@@ -16,6 +19,10 @@ export const RENAME_VARIABLES = [
["{competitionCode}", "PO01"],
["{round}", "jornada"],
["{originalName}", "nome da câmara"],
["{filenamebase:-4}", "nº do ficheiro (4 últimos)"],
["{model}", "câmara"],
["{serialnum}", "nº de série"],
["{event:0:lc:tr: /_}", "minúsculas, _ em vez de espaço"],
] as const;
const input = "h-8 w-full border border-black bg-[#161617] px-2 font-mono text-[12px] text-ink focus:border-accent focus:outline-none";
+391 -95
View File
@@ -1,6 +1,12 @@
import { DESTINATION_EXAMPLES } from "@photoreport/metadata";
import { ApiError, type ApiClient, type DeliveryKind, type DeliveryTarget } from "@photoreport/sdk";
import { useState } from "react";
import {
ApiError,
type ApiClient,
type DeliveryKind,
type DeliveryTarget,
type FtpAccount,
} from "@photoreport/sdk";
import { useEffect, useState } from "react";
import { desktopDeliveryShell } from "../desktop/localDeliveries.js";
import { t } from "../i18n.js";
import { isDesktop } from "../platform.js";
@@ -8,7 +14,18 @@ import { isDesktop } from "../platform.js";
const SIZES = [12000, 6000, 4000, 3500, 3000, 2000];
/** Where each kind connects, and what its user and secret fields mean. */
const KINDS: Record<DeliveryKind, { label: string; address: string; placeholder: string; user: string; secret: string; help: string; multiline?: boolean }> = {
const KINDS: Record<
DeliveryKind,
{
label: string;
address: string;
placeholder: string;
user: string;
secret: string;
help: string;
multiline?: boolean;
}
> = {
NEXTCLOUD: {
label: "Nextcloud",
address: "Endereço da Nextcloud",
@@ -71,17 +88,56 @@ const PRESETS = {
jpegQuality: 80,
sharpen: true,
},
abola: { label: "A Bola (SFTP)", kind: "SFTP", baseUrl: "sftp://transfer.ringier.ch", longEdge: 12000, ...DESTINATION_EXAMPLES.abola },
fpa: { label: "Estrutura FPA", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.fpa },
liga: { label: "Estrutura Liga", kind: "NEXTCLOUD", baseUrl: "https://cloud.photoreport.pt", longEdge: 4000, ...DESTINATION_EXAMPLES.liga },
zerozero: { label: "ZeroZero", kind: "ZEROZERO", baseUrl: "https://fotos.zerozero.pt", longEdge: 3000, folder: "zerozero", fileName: "{originalName}", jpegQuality: 90, sharpen: false },
abola: {
label: "A Bola (SFTP)",
kind: "SFTP",
baseUrl: "sftp://transfer.ringier.ch",
longEdge: 12000,
...DESTINATION_EXAMPLES.abola,
},
fpa: {
label: "Estrutura FPA",
kind: "NEXTCLOUD",
baseUrl: "https://cloud.photoreport.pt",
longEdge: 4000,
...DESTINATION_EXAMPLES.fpa,
},
liga: {
label: "Estrutura Liga",
kind: "NEXTCLOUD",
baseUrl: "https://cloud.photoreport.pt",
longEdge: 4000,
...DESTINATION_EXAMPLES.liga,
},
zerozero: {
label: "ZeroZero",
kind: "ZEROZERO",
baseUrl: "https://fotos.zerozero.pt",
longEdge: 3000,
folder: "zerozero",
fileName: "{originalName}",
jpegQuality: 90,
sharpen: false,
},
} as const;
/**
* New (or edited) delivery destination, with Photo Mechanic's uploader options. Secrets are write-only: encrypted
* on the server and never shown again (leave the field empty when editing to keep the saved one).
*/
export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: ApiClient; orgId: string; target?: DeliveryTarget; onClose: () => void; onCreated: (t: DeliveryTarget) => void }) {
export function TargetForm({
api,
orgId,
target,
onClose,
onCreated,
}: {
api: ApiClient;
orgId: string;
target?: DeliveryTarget;
onClose: () => void;
onCreated: (t: DeliveryTarget) => void;
}) {
const [v, setV] = useState({
name: target?.name ?? "",
kind: (target?.kind ?? "NEXTCLOUD") as DeliveryKind,
@@ -89,19 +145,38 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
username: target?.username ?? "",
password: "",
folderTemplate: target?.folderTemplate ?? (PRESETS.fpa.folder as string),
fileNameTemplate: target?.fileNameTemplate ?? (PRESETS.fpa.fileName as string),
fileNameTemplate:
target?.fileNameTemplate ?? (PRESETS.fpa.fileName as string),
longEdge: target?.longEdge ?? 4000,
jpegQuality: target?.jpegQuality ?? 100,
sharpen: target?.sharpen ?? false,
dpi: target?.dpi ?? 300,
keepExif: target?.keepExif ?? true,
srgb: target?.srgb ?? false,
originals: target?.originals ?? false,
onArrival: target?.onArrival ?? false,
arrivalLogins: target?.arrivalLogins ?? ([] as string[]),
untouched: target?.untouched ?? false,
});
// The FTP logins whose arrivals this destination can take (a relay to one's computer).
const [logins, setLogins] = useState<FtpAccount[]>([]);
useEffect(() => {
api.listFtpAccounts(orgId).then(
(r) => setLogins(r.accounts),
() => setLogins([]),
);
}, [api, orgId]);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const k = KINDS[v.kind];
const input = "h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink focus:border-accent focus:outline-none";
const field = (key: "name" | "baseUrl" | "username" | "folderTemplate" | "fileNameTemplate", label: string, extra: React.InputHTMLAttributes<HTMLInputElement> = {}) => (
const input =
"h-8 w-full border border-black bg-[#161617] px-2 text-[13px] text-ink focus:border-accent focus:outline-none";
const field = (
key:
"name" | "baseUrl" | "username" | "folderTemplate" | "fileNameTemplate",
label: string,
extra: React.InputHTMLAttributes<HTMLInputElement> = {},
) => (
<label className="block">
<span className="mb-1 block text-[11px] text-faint">{label}</span>
<input
@@ -115,7 +190,12 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
);
return (
<div role="dialog" aria-modal="true" aria-label="Novo destino" className="fixed inset-0 z-30 flex items-center justify-center bg-black/60 p-4">
<div
role="dialog"
aria-modal="true"
aria-label="Novo destino"
className="fixed inset-0 z-30 flex items-center justify-center bg-black/60 p-4"
>
<form
className="max-h-full w-full max-w-xl overflow-y-auto border border-line bg-panel shadow-2xl"
onSubmit={(e) => {
@@ -128,11 +208,19 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
setError("Escolhe a pasta.");
return;
}
(target ? api.updateDeliveryTarget(orgId, target.id, password ? v : rest) : api.createDeliveryTarget(orgId, v.kind === "LOCAL" ? rest : v)).then(
(target
? api.updateDeliveryTarget(orgId, target.id, password ? v : rest)
: api.createDeliveryTarget(orgId, v.kind === "LOCAL" ? rest : v)
).then(
(target) => onCreated(target),
(err) => {
setBusy(false);
setError(err instanceof ApiError ? ((err.body as { message?: string } | null)?.message ?? err.code) : t.unexpectedError);
setError(
err instanceof ApiError
? ((err.body as { message?: string } | null)?.message ??
err.code)
: t.unexpectedError,
);
},
);
}}
@@ -150,7 +238,10 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
setV({
...v,
kind: p.kind,
baseUrl: v.kind === p.kind && v.baseUrl && v.baseUrl !== "ftp://" ? v.baseUrl : p.baseUrl,
baseUrl:
v.kind === p.kind && v.baseUrl && v.baseUrl !== "ftp://"
? v.baseUrl
: p.baseUrl,
folderTemplate: p.folder,
fileNameTemplate: p.fileName,
longEdge: p.longEdge,
@@ -173,33 +264,70 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
value={v.kind}
onChange={(e) => {
const kind = e.target.value as DeliveryKind;
setV({ ...v, kind, baseUrl: KINDS[kind].placeholder, ...(kind === "ZEROZERO" && { folderTemplate: "zerozero", fileNameTemplate: "{originalName}", longEdge: 3000, jpegQuality: 90 }), ...(kind === "LOCAL" && { folderTemplate: "/{event}/", username: "" }) });
setV({
...v,
kind,
baseUrl: KINDS[kind].placeholder,
...(kind === "ZEROZERO" && {
folderTemplate: "zerozero",
fileNameTemplate: "{originalName}",
longEdge: 3000,
jpegQuality: 90,
}),
...(kind === "LOCAL" && {
folderTemplate: "/{event}/",
username: "",
}),
});
}}
>
{(Object.keys(KINDS) as DeliveryKind[])
.filter((kind) => kind !== "LOCAL" || isDesktop() || v.kind === "LOCAL")
.filter(
(kind) =>
kind !== "LOCAL" || isDesktop() || v.kind === "LOCAL",
)
.map((kind) => (
<option key={kind} value={kind}>
{KINDS[kind].label}
</option>
))}
<option key={kind} value={kind}>
{KINDS[kind].label}
</option>
))}
</select>
</label>
{field("name", "Nome (ex.: A Bola, FPA, Liga)")}
</div>
{v.kind === "LOCAL" && (
<div>
<span className="mb-1 block text-[11px] text-faint">{k.address}</span>
<span className="mb-1 block text-[11px] text-faint">
{k.address}
</span>
<div className="flex gap-2">
<span className={`${input} flex items-center truncate font-mono text-[12px]`}>{v.baseUrl.startsWith("/") || /^[A-Za-z]:/.test(v.baseUrl) ? v.baseUrl : "—"}</span>
<span
className={`${input} flex items-center truncate font-mono text-[12px]`}
>
{v.baseUrl.startsWith("/") || /^[A-Za-z]:/.test(v.baseUrl)
? v.baseUrl
: "—"}
</span>
{isDesktop() && (
<button
type="button"
className="h-8 shrink-0 border border-black bg-cell px-3 text-[12px] hover:bg-cell-on"
onClick={() =>
void Promise.all([desktopDeliveryShell.pick(), desktopDeliveryShell.machine()]).then(
([folder, machine]) => folder && setV((cur) => ({ ...cur, baseUrl: folder, username: machine })),
() => setError("Esta versão da app ainda não sabe guardar em pastas: atualiza a app."),
void Promise.all([
desktopDeliveryShell.pick(),
desktopDeliveryShell.machine(),
]).then(
([folder, machine]) =>
folder &&
setV((cur) => ({
...cur,
baseUrl: folder,
username: machine,
})),
() =>
setError(
"Esta versão da app ainda não sabe guardar em pastas: atualiza a app.",
),
)
}
>
@@ -207,85 +335,253 @@ export function TargetForm({ api, orgId, target, onClose, onCreated }: { api: Ap
</button>
)}
</div>
<p className="mt-1 text-[11px] leading-snug text-faint">{k.help}</p>
<p className="mt-1 text-[11px] leading-snug text-faint">
{k.help}
</p>
</div>
)}
{v.kind !== "DROPBOX" && v.kind !== "ZEROZERO" && v.kind !== "LOCAL" && field("baseUrl", k.address, { placeholder: k.placeholder, spellCheck: false })}
{v.kind !== "DROPBOX" &&
v.kind !== "ZEROZERO" &&
v.kind !== "LOCAL" &&
field("baseUrl", k.address, {
placeholder: k.placeholder,
spellCheck: false,
})}
{v.kind !== "LOCAL" && (
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
{field("username", k.user, { autoComplete: "off", spellCheck: false })}
<label className="block">
<span className="mb-1 block text-[11px] text-faint">{k.secret}</span>
{k.multiline && v.password.includes("\n") ? (
<textarea required={!target} rows={4} className={`${input} h-auto font-mono text-[11px]`} value={v.password} onChange={(e) => setV({ ...v, password: e.target.value })} spellCheck={false} />
) : (
<input
required={!target}
placeholder={target ? "(manter a guardada)" : undefined}
type="password"
autoComplete="new-password"
className={input}
value={v.password}
onChange={(e) => setV({ ...v, password: e.target.value })}
onPaste={(e) => {
// A pasted private key keeps its line breaks.
const text = e.clipboardData.getData("text");
if (k.multiline && text.includes("\n")) {
e.preventDefault();
setV({ ...v, password: text });
}
}}
/>
)}
</label>
</div>
)}
{v.kind !== "LOCAL" && <p className="text-[11px] leading-snug text-faint">{k.help} Fica guardada encriptada e nunca volta a ser mostrada.</p>}
{v.kind !== "ZEROZERO" && field("folderTemplate", v.kind === "LOCAL" ? "Subpasta ({event} = Casa x Fora)" : "Pasta ({event} = Casa x Fora)")}
{field("fileNameTemplate", "Nome do ficheiro ({originalName} mantém o da câmara, {n:pad3} numera 001, 002…)")}
<fieldset className="grid grid-cols-2 gap-3 border border-line p-3 max-sm:grid-cols-1">
<legend className="px-1 text-[11px] text-faint">Saída (como no uploader do Photo Mechanic)</legend>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Tamanho (lado maior)</span>
<select className={input} value={SIZES.includes(v.longEdge) ? v.longEdge : "custom"} onChange={(e) => e.target.value !== "custom" && setV({ ...v, longEdge: Number(e.target.value) })}>
{SIZES.map((s) => (
<option key={s} value={s}>
{s >= 12000 ? "Original (sem redimensionar)" : `${s} px`}
</option>
))}
<option value="custom">Outro…</option>
</select>
{!SIZES.includes(v.longEdge) && (
<input type="number" min={800} max={12000} className={`${input} mt-1`} value={v.longEdge} onChange={(e) => setV({ ...v, longEdge: Number(e.target.value) })} />
)}
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Qualidade JPEG: {v.jpegQuality}</span>
<input type="range" min={40} max={100} className="w-full accent-[var(--color-accent,#e5484d)]" value={v.jpegQuality} onChange={(e) => setV({ ...v, jpegQuality: Number(e.target.value) })} />
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Resolução (ppi)</span>
<input type="number" min={72} max={1200} className={input} value={v.dpi} onChange={(e) => setV({ ...v, dpi: Number(e.target.value) })} />
</label>
<div className="space-y-1 pt-4 text-[12px] text-muted">
<label className="flex items-center gap-2">
<input type="checkbox" checked={v.sharpen} onChange={(e) => setV({ ...v, sharpen: e.target.checked })} /> Nitidez (sharpen)
</label>
<label className="flex items-center gap-2">
<input type="checkbox" checked={v.keepExif} onChange={(e) => setV({ ...v, keepExif: e.target.checked })} /> Manter EXIF da câmara
</label>
<label className="flex items-center gap-2">
<input type="checkbox" checked={v.srgb} onChange={(e) => setV({ ...v, srgb: e.target.checked })} /> Converter para sRGB
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
{field("username", k.user, {
autoComplete: "off",
spellCheck: false,
})}
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
{k.secret}
</span>
{k.multiline && v.password.includes("\n") ? (
<textarea
required={!target}
rows={4}
className={`${input} h-auto font-mono text-[11px]`}
value={v.password}
onChange={(e) => setV({ ...v, password: e.target.value })}
spellCheck={false}
/>
) : (
<input
required={!target}
placeholder={target ? "(manter a guardada)" : undefined}
type="password"
autoComplete="new-password"
className={input}
value={v.password}
onChange={(e) => setV({ ...v, password: e.target.value })}
onPaste={(e) => {
// A pasted private key keeps its line breaks.
const text = e.clipboardData.getData("text");
if (k.multiline && text.includes("\n")) {
e.preventDefault();
setV({ ...v, password: text });
}
}}
/>
)}
</label>
</div>
</fieldset>
)}
{v.kind !== "LOCAL" && (
<p className="text-[11px] leading-snug text-faint">
{k.help} Fica guardada encriptada e nunca volta a ser mostrada.
</p>
)}
{v.kind !== "ZEROZERO" &&
field(
"folderTemplate",
v.kind === "LOCAL"
? "Subpasta ({event} = Casa x Fora, {iptcdate} = 20261009)"
: "Pasta ({event} = Casa x Fora)",
)}
{field(
"fileNameTemplate",
"Nome do ficheiro ({originalName} mantém o da câmara, {n:pad3} numera 001, 002…, {timesort} hora do disparo)",
)}
<div className="space-y-1 border border-line p-3 text-[12px] text-muted">
<label className="flex items-start gap-2">
<input
type="checkbox"
className="mt-0.5"
checked={v.originals}
onChange={(e) => setV({ ...v, originals: e.target.checked })}
/>
<span>
<span className="text-ink">Originais</span> — o ficheiro tal
como chegou da câmara (sem redimensionar nem recomprimir), com o
IPTC escrito e o nome acima. Para o teu backup, como o destino
do Live Ingest do Photo Mechanic.
</span>
</label>
{v.originals && (
<label className="ml-6 flex items-start gap-2">
<input
type="checkbox"
className="mt-0.5"
checked={v.untouched}
onChange={(e) => setV({ ...v, untouched: e.target.checked })}
/>
<span>
<span className="text-ink">Tal como chegou</span> — sem
IPTC escrito e com o nome da câmara (use{" "}
<code className="font-mono">{"{originalName}"}</code> no nome),
para o Live Ingest do Photo Mechanic no teu computador o
apanhar como se tivesse chegado ao teu FTP local.
</span>
</label>
)}
<label className="flex items-start gap-2">
<input
type="checkbox"
className="mt-0.5"
checked={v.onArrival}
onChange={(e) => setV({ ...v, onArrival: e.target.checked })}
/>
<span>
<span className="text-ink">Tudo o que chegar</span> — cada foto
que entra (FTP, app de computador, envio pelo browser) vem para
aqui sozinha, assim que está num evento.
</span>
</label>
{v.onArrival && logins.length > 0 && (
<fieldset className="ml-6 space-y-1">
<legend className="text-faint">
Só destes logins FTP (nenhum marcado: de todos)
</legend>
{logins.map((a) => (
<label key={a.id} className="flex items-center gap-2">
<input
type="checkbox"
checked={v.arrivalLogins.includes(a.id)}
onChange={(e) =>
setV({
...v,
arrivalLogins: e.target.checked
? [...v.arrivalLogins, a.id]
: v.arrivalLogins.filter((id) => id !== a.id),
})
}
/>
<span className="font-mono text-ink">{a.login}</span>
<span>· {a.user.name}</span>
</label>
))}
</fieldset>
)}
</div>
{!v.originals && (
<fieldset className="grid grid-cols-2 gap-3 border border-line p-3 max-sm:grid-cols-1">
<legend className="px-1 text-[11px] text-faint">
Saída (como no uploader do Photo Mechanic)
</legend>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
Tamanho (lado maior)
</span>
<select
className={input}
value={SIZES.includes(v.longEdge) ? v.longEdge : "custom"}
onChange={(e) =>
e.target.value !== "custom" &&
setV({ ...v, longEdge: Number(e.target.value) })
}
>
{SIZES.map((s) => (
<option key={s} value={s}>
{s >= 12000 ? "Original (sem redimensionar)" : `${s} px`}
</option>
))}
<option value="custom">Outro…</option>
</select>
{!SIZES.includes(v.longEdge) && (
<input
type="number"
min={800}
max={12000}
className={`${input} mt-1`}
value={v.longEdge}
onChange={(e) =>
setV({ ...v, longEdge: Number(e.target.value) })
}
/>
)}
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
Qualidade JPEG: {v.jpegQuality}
</span>
<input
type="range"
min={40}
max={100}
className="w-full accent-[var(--color-accent,#e5484d)]"
value={v.jpegQuality}
onChange={(e) =>
setV({ ...v, jpegQuality: Number(e.target.value) })
}
/>
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">
Resolução (ppi)
</span>
<input
type="number"
min={72}
max={1200}
className={input}
value={v.dpi}
onChange={(e) => setV({ ...v, dpi: Number(e.target.value) })}
/>
</label>
<div className="space-y-1 pt-4 text-[12px] text-muted">
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={v.sharpen}
onChange={(e) => setV({ ...v, sharpen: e.target.checked })}
/>{" "}
Nitidez (sharpen)
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={v.keepExif}
onChange={(e) => setV({ ...v, keepExif: e.target.checked })}
/>{" "}
Manter EXIF da câmara
</label>
<label className="flex items-center gap-2">
<input
type="checkbox"
checked={v.srgb}
onChange={(e) => setV({ ...v, srgb: e.target.checked })}
/>{" "}
Converter para sRGB
</label>
</div>
</fieldset>
)}
</div>
{error && <p className="px-4 pb-2 text-[12px] text-danger">{error}</p>}
<div className="flex justify-end gap-2 border-t border-line px-4 py-3">
<button type="button" onClick={onClose} className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on">
<button
type="button"
onClick={onClose}
className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on"
>
{t.cancel}
</button>
<button disabled={busy} className="h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50">
<button
disabled={busy}
className="h-8 bg-accent px-4 font-display text-[15px] font-semibold uppercase tracking-wide text-white hover:bg-accent-strong disabled:opacity-50"
>
{target ? t.save : t.create}
</button>
</div>
+61 -18
View File
@@ -39,34 +39,77 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
);
}
/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */
const ORIGINAL_IPC_MS = 45_000;
/** A few at a time: one is slow, all of them freeze the bar. */
const MAX_PARALLEL_ORIGINALS = 3;
function withTimeout<T>(work: Promise<T>, ms: number): Promise<T | "timeout" | null> {
return new Promise((resolve) => {
let settled = false;
const finish = (value: T | "timeout" | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const timer = setTimeout(() => finish("timeout"), ms);
work.then(
(value) => finish(value),
() => finish(null),
);
});
}
/**
* Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export
* made on the server), the server asks over the live channel and this sends it in the background.
* made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it.
* Up to three at a time, so the webview stays responsive and the next ask can run.
*/
function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"]; add: ReturnType<typeof useUploadQueue>["add"] }) {
const sending = useRef(new Set<string>());
const queue = useRef<{ sha256: string; photoId: string }[]>([]);
const active = useRef(0);
const pump = useCallback(() => {
while (active.current < MAX_PARALLEL_ORIGINALS) {
const next = queue.current.shift();
if (!next) return;
active.current += 1;
const release = () => {
sending.current.delete(next.sha256);
active.current -= 1;
pump();
};
void (async () => {
const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS);
if (bytes && bytes !== "timeout") {
add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release());
return;
}
if (bytes !== "timeout") {
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
// photo's original, which the server checks is the same photo.
try {
const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS);
if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
}
}
release();
})();
}
}, [add, api]);
const onMessage = useCallback(
(m: LibraryMessage) => {
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
sending.current.add(m.sha256);
void localOriginal(m.sha256).then(async (bytes) => {
if (bytes) {
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
return;
}
// The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this
// photo's original, which the server checks is the same photo.
try {
const changed = await localOriginalChanged(m.sha256);
if (changed) await api.sendOriginal(m.photoId, new Blob([changed], { type: "image/jpeg" }), `${m.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
} finally {
sending.current.delete(m.sha256);
}
});
queue.current.push({ sha256: m.sha256, photoId: m.photoId });
pump();
},
[add, api],
[pump],
);
useLibraryLive(api, onMessage);
return null;
+71 -4
View File
@@ -171,6 +171,7 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
<span>
{A.progress(c.done, total)}
{c.failed > 0 && <span className="text-danger"> · {A.failed(c.failed)}</span>}
{(c.pending > 0 || (c.perHour ?? 0) > 0) && <span className="text-faint"> · {A.pace(c.perHour ?? 0, c.pending)}</span>}
</span>
<span>{A.galleriesLine(c.galleries, c.games, c.named, c.unmatched)}</span>
</div>
@@ -191,6 +192,24 @@ function SourceCard({ api, source, isAdmin, active, onSelect, onChange, onRemove
{copied ? A.copied : A.copy}
</button>
<span className="w-full text-faint">{A.viewerHelp}</span>
{isAdmin && (
<label className="flex items-center gap-2">
<span className="text-muted">{A.look}:</span>
<select
value={source.look ?? ""}
disabled={busy}
onChange={(e) => {
const look = (e.target.value || null) as "liga" | "fpa" | null;
void run(() => api.updateCloudSource(source.id, { look }));
}}
className="h-6 border border-black bg-cell px-1 text-[11px] text-ink"
>
<option value="">{A.looks.none}</option>
<option value="liga">{A.looks.liga}</option>
<option value="fpa">{A.looks.fpa}</option>
</select>
</label>
)}
</div>
)}
@@ -307,13 +326,26 @@ function ConnectForm({ api, orgId, onConnected }: { api: ApiClient; orgId: strin
);
}
type Tab = "unmatched" | "games" | "all";
/** Games (official, or known only by their folder) apart from events (galas, sessions): they are matched differently. */
type Tab = "games" | "named" | "events" | "all";
function Galleries({ api, source }: { api: ApiClient; source: CloudSource }) {
const [tab, setTab] = useState<Tab>("unmatched");
const [tab, setTab] = useState<Tab>("named");
const [q, setQ] = useState("");
const [folders, setFolders] = useState<CloudFolderSummary[] | null>(null);
const [choosing, setChoosing] = useState<string | null>(null);
const [check, setCheck] = useState<{ busy: boolean; result?: Awaited<ReturnType<ApiClient["rematchCloudSource"]>>; error?: string } | null>(null);
const [reload, setReload] = useState(0);
const runCheck = (all: boolean) => {
setCheck({ busy: true });
api.rematchCloudSource(source.id, all).then(
(result) => {
setCheck({ busy: false, result });
setReload((n) => n + 1);
},
(err) => setCheck({ busy: false, error: errorOf(err) }),
);
};
useEffect(() => {
let live = true;
@@ -327,7 +359,7 @@ function Galleries({ api, source }: { api: ApiClient; source: CloudSource }) {
live = false;
clearTimeout(timer);
};
}, [api, source.id, tab, q, source.counts.done, source.counts.galleries]);
}, [api, source.id, tab, q, source.counts.done, source.counts.galleries, reload]);
return (
<section className="border border-line bg-panel">
@@ -335,9 +367,44 @@ function Galleries({ api, source }: { api: ApiClient; source: CloudSource }) {
<span>
{A.galleries} · {source.name}
</span>
<span className="flex gap-2 normal-case tracking-normal">
<button type="button" disabled={check?.busy} onClick={() => runCheck(false)} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on disabled:opacity-40" title="Volta a ligar já cada galeria de jogo oficial ao seu jogo, com as regras de hoje">
{check?.busy ? "A rever…" : "Rever jogos"}
</button>
<button type="button" disabled={check?.busy} onClick={() => runCheck(true)} className="h-6 border border-black bg-cell px-2 text-[12px] text-muted hover:bg-cell-on disabled:opacity-40" title="Revê todas as galerias (pode demorar)">
Rever tudo
</button>
</span>
</div>
{check && !check.busy && (
<div className="border-b border-line px-4 py-2 text-[12px]">
{check.error ? (
<p className="text-danger">{check.error}</p>
) : (
check.result && (
<details>
<summary className="cursor-pointer text-muted">
{check.result.checked} galerias revistas · {check.result.moved} alteradas · {check.result.errors.length} com erro
</summary>
<ul className="mt-1 max-h-64 space-y-0.5 overflow-y-auto font-mono text-[11px]">
{check.result.changes.map((c) => (
<li key={`c${c.path}`} className="text-muted">
{c.path} <span className="text-faint">{A.matched[c.from ?? ""] ?? "—"} → {A.matched[c.to ?? ""] ?? "—"}</span>
</li>
))}
{check.result.errors.map((e) => (
<li key={`e${e.path}`} className="text-danger">
{e.path}: {e.error}
</li>
))}
</ul>
</details>
)
)}
</div>
)}
<div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2">
{(["unmatched", "games", "all"] as const).map((k) => (
{(["games", "named", "events", "all"] as const).map((k) => (
<button key={k} type="button" onClick={() => setTab(k)} aria-pressed={tab === k} className={`h-7 px-3 text-[12px] ${tab === k ? "bg-cell-on text-ink" : "text-muted hover:text-ink"}`}>
{A.tabs[k]}
</button>
+28 -1
View File
@@ -7,6 +7,7 @@ import { pasteCommand } from "./DevelopPage.js";
import { t } from "../i18n.js";
import { EventForm } from "../library/EventForm.js";
import { EventsPanel } from "../library/EventsPanel.js";
import { EventSettingsButton } from "../library/EventSettings.js";
import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
@@ -40,6 +41,7 @@ export function LibraryPage() {
const canCull = role !== null && hasRole(role, "INGESTER");
const canCreate = role !== null && hasRole(role, "EDITOR");
const [events, setEvents] = useState<EventSummary[]>([]);
const [archivedEvents, setArchivedEvents] = useState<EventSummary[] | null>(null);
const [inboxCount, setInboxCount] = useState(0);
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false);
@@ -205,7 +207,7 @@ export function LibraryPage() {
const fileInput = useRef<HTMLInputElement>(null);
const [dragging, setDragging] = useState(false);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const openEvent = events.find((e) => e.id === uploadInto);
const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto);
const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading");
const failed = uploads.items.filter((i) => i.status === "failed");
const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length;
@@ -328,6 +330,13 @@ export function LibraryPage() {
onOpen={(scope) => void open(scope)}
onCreate={() => setCreating(true)}
onLookup={(file) => void runLookup(file)}
archived={archivedEvents}
{...(canCreate && {
onToggleArchived: () => {
if (archivedEvents) setArchivedEvents(null);
else api.listEvents(orgId, { archived: true }).then((r) => setArchivedEvents(r.events), () => setArchivedEvents([]));
},
})}
/>
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
@@ -346,6 +355,24 @@ export function LibraryPage() {
{t.importPhotos}
</button>
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
{openEvent && (
<EventSettingsButton
api={api}
orgId={orgId}
event={openEvent}
canEdit={canCreate}
onSaved={(e) => {
setEvents((list) => (e.archivedAt ? list : list.some((x) => x.id === e.id) ? list.map((x) => (x.id === e.id ? e : x)) : [e, ...list]));
setArchivedEvents((list) => (list ? (e.archivedAt ? list.map((x) => (x.id === e.id ? e : x)) : list.filter((x) => x.id !== e.id)) : list));
}}
onRemoved={(id) => {
setEvents((list) => list.filter((x) => x.id !== id));
setArchivedEvents(null);
void loadEvents();
void open("inbox");
}}
/>
)}
{canCull && openEvent && (
<SquadsButton api={api} event={openEvent} canEdit={canCreate} onSaved={(e) => setEvents((list) => list.map((x) => (x.id === e.id ? e : x)))} />
)}
+3
View File
@@ -13,6 +13,9 @@
"dependencies": {
"@fontsource/barlow": "^5.3.0",
"@fontsource/barlow-condensed": "^5.3.0",
"@fontsource/bebas-neue": "^5.3.0",
"@fontsource/open-sans": "^5.3.0",
"@fontsource/source-sans-3": "^5.3.1",
"@fontsource/space-mono": "^5.3.0",
"@photoreport/contracts": "workspace:*",
"next": "15.5.27",
+116 -21
View File
@@ -79,6 +79,9 @@ interface Directory {
const PAGE = 48;
const day = new Intl.DateTimeFormat("pt-PT", { timeZone: "Europe/Lisbon", day: "numeric", month: "long", year: "numeric" });
const storageKey = (id: string) => `arquivo_${id}`;
/** Whose archive it is, in the band on top, when it wears its owner's look. */
const OWNER: Record<"liga" | "fpa", string> = { liga: "Liga Portugal", fpa: "Federação de Andebol de Portugal" };
const read = (k: string) => {
try {
return window.sessionStorage.getItem(k);
@@ -121,21 +124,43 @@ export function ArchiveView({ info }: { info: ArchiveInfo }) {
setToken(null);
}, [info.id]);
if (!ready) return <main className="wrap" aria-busy="true" />;
const owner = info.look ? OWNER[info.look] : null;
const session = token && (
<span className="meta">
{viewer ? <span className="who">{`Sessão de ${viewer} · `}</span> : ""}
<button type="button" className="linkish" onClick={signOut}>
Sair
</button>
</span>
);
if (!ready)
return (
<main className="wrap">
<Loading />
</main>
);
return (
<>
{owner && (
<div className="look-band">
<div className="wrap look-band-in">
<strong>{owner}</strong>
{session}
</div>
</div>
)}
<main className="wrap">
<header className="gallery-head">
<span className="kicker">Arquivo · {info.organization}</span>
<h1 className="title h1">{info.name}</h1>
{token && (
<span className="meta">
{viewer ? `Sessão de ${viewer} · ` : ""}
<button type="button" className="linkish" onClick={signOut}>
Sair
</button>
</span>
)}
</header>
{owner ? (
<header className="gallery-head">
<h1 className="title h1">Arquivo fotográfico</h1>
</header>
) : (
<header className="gallery-head">
<span className="kicker">Arquivo · {info.organization}</span>
<h1 className="title h1">{info.name}</h1>
{session}
</header>
)}
{token ? (
<Browse info={info} token={token} onExpired={signOut} />
) : (
@@ -150,6 +175,7 @@ export function ArchiveView({ info }: { info: ArchiveInfo }) {
/>
)}
</main>
</>
);
}
@@ -228,6 +254,38 @@ function SignIn({ info, onDone }: { info: ArchiveInfo; onDone: (token: string, n
type Tab = "galleries" | "people" | "teams";
/**
* What is shown while something loads: never a blank page. After a while it says so and offers to try again (a
* big gallery, a busy server), with the way back always there.
*/
function Loading({ onBack, backLabel = "← Voltar", onRetry }: { onBack?: () => void; backLabel?: string; onRetry?: () => void }) {
const [slow, setSlow] = useState(false);
useEffect(() => {
const timer = setTimeout(() => setSlow(true), 8000);
return () => clearTimeout(timer);
}, []);
return (
<>
{onBack && (
<div className="toolbar">
<button type="button" className="chip" onClick={onBack}>
{backLabel}
</button>
</div>
)}
<div className="loading" role="status" aria-live="polite">
<span className="spinner" aria-hidden="true" />
<span>{slow ? "Está a demorar mais do que o costume…" : "A carregar…"}</span>
{slow && onRetry && (
<button type="button" className="linkish" onClick={onRetry}>
Tentar outra vez
</button>
)}
</div>
</>
);
}
/** Where the viewer is: browsing, in a gallery, on a person's photos, or on "more of this face". */
type View = { kind: "browse" } | { kind: "gallery"; id: string } | { kind: "person"; id: string } | { kind: "face"; id: string };
@@ -363,6 +421,7 @@ function Browse({ info, token, onExpired }: { info: ArchiveInfo; token: string;
)}
</div>
)}
{list === null && <Loading />}
{list?.length === 0 && <p className="empty">Nenhuma galeria partilhada contigo{q || team || player ? " com estes filtros" : ""}.</p>}
<div className="cards">
{list?.map((g) => (
@@ -398,7 +457,7 @@ function Browse({ info, token, onExpired }: { info: ArchiveInfo; token: string;
))}
</div>
)}
{!people && <p className="empty" aria-busy="true" />}
{!people && <Loading />}
{people && shownPeople.length === 0 && <p className="empty">{people.people.length ? "Ninguém com esse nome." : "Ainda não há pessoas identificadas nestas galerias. Abre uma foto e clica numa cara para encontrar mais fotos dela."}</p>}
<ul className="people-grid">
{shownPeople.map((p) => (
@@ -419,7 +478,11 @@ function Browse({ info, token, onExpired }: { info: ArchiveInfo; token: string;
{tab === "teams" && (
<ul className="archive-names">
{!directory && <li className="empty" aria-busy="true" />}
{!directory && (
<li>
<Loading />
</li>
)}
{directory?.teams
.filter((t) => fold(t.name).includes(fold(q.trim())))
.map((t) => (
@@ -505,13 +568,14 @@ function PhotosOf({
const [index, setIndex] = useState<number | null>(null);
const [error, setError] = useState(false);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
const url = view.kind === "person" ? `/v1/archive/${info.id}/people/${view.id}` : `/v1/archive/${info.id}/faces/${view.id}/similar`;
call<PhotosOfResult>(url, token).then(
({ body }) => setData(body),
(err) => (err instanceof Unauthorised ? onExpired() : setError(true)),
);
}, [info.id, view.kind, view.id, token, onExpired]);
}, [info.id, view.kind, view.id, token, onExpired, attempt]);
const photos = useMemo(() => (data ? (only ? data.photos.filter((p) => p.level === only) : data.photos) : []), [data, only]);
const counts = useMemo(() => {
@@ -520,8 +584,23 @@ function PhotosOf({
return c;
}, [data]);
if (error) return <p className="empty">Não foi possível abrir esta pesquisa.</p>;
if (!data) return <p className="empty" aria-busy="true" />;
if (error)
return (
<>
<div className="toolbar">
<button type="button" className="chip" onClick={onBack}>
← Voltar
</button>
</div>
<p className="empty">
Não foi possível abrir esta pesquisa.{" "}
<button type="button" className="linkish" onClick={() => (setError(false), setAttempt((n) => n + 1))}>
Tentar outra vez
</button>
</p>
</>
);
if (!data) return <Loading onBack={onBack} onRetry={() => setAttempt((n) => n + 1)} />;
const first = data.photos[0];
const who = data.person;
return (
@@ -727,12 +806,13 @@ function Gallery({
const [index, setIndex] = useState<number | null>(null);
const [error, setError] = useState(false);
const [attempt, setAttempt] = useState(0);
useEffect(() => {
call<GalleryDetail>(`/v1/archive/galleries/${id}`, token).then(
({ body }) => setG(body),
(err) => (err instanceof Unauthorised ? onExpired() : setError(true)),
);
}, [id, token, onExpired]);
}, [id, token, onExpired, attempt]);
// Who is in this gallery: named faces first (with a face to show), then names written on the photos.
const people = useMemo(() => {
@@ -748,8 +828,23 @@ function Gallery({
}, [g]);
const photos = useMemo(() => (g ? (only ? g.photos.filter((p) => (p.faces ?? []).some((f) => f.person?.id === only && f.level === "confirmed")) : g.photos) : []), [g, only]);
if (error) return <p className="empty">Esta galeria não está disponível para ti.</p>;
if (!g) return <p className="empty" aria-busy="true" />;
if (error)
return (
<>
<div className="toolbar">
<button type="button" className="chip" onClick={onBack}>
← Galerias
</button>
</div>
<p className="empty">
Não foi possível abrir esta galeria.{" "}
<button type="button" className="linkish" onClick={() => (setError(false), setAttempt((n) => n + 1))}>
Tentar outra vez
</button>
</p>
</>
);
if (!g) return <Loading onBack={onBack} backLabel="← Galerias" onRetry={() => setAttempt((n) => n + 1)} />;
return (
<>
<div className="toolbar">
+16 -1
View File
@@ -1,5 +1,13 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import "@fontsource/bebas-neue/400.css";
import "@fontsource/source-sans-3/400.css";
import "@fontsource/source-sans-3/600.css";
import "@fontsource/source-sans-3/700.css";
import "@fontsource/open-sans/400.css";
import "@fontsource/open-sans/600.css";
import "@fontsource/open-sans/700.css";
import "@fontsource/open-sans/800.css";
import { ArchiveView } from "./ArchiveView";
export const dynamic = "force-dynamic";
@@ -13,6 +21,8 @@ export interface ArchiveInfo {
name: string;
cloud: string;
organization: string;
/** The owner's colours and type (Liga Portugal, FPA), or PhotoReport's. */
look?: "liga" | "fpa" | null;
}
async function load(id: string): Promise<ArchiveInfo> {
@@ -34,5 +44,10 @@ export async function generateMetadata({ params }: Params): Promise<Metadata> {
*/
export default async function ArchivePage({ params }: Params) {
const info = await load((await params).id);
return <ArchiveView info={info} />;
if (!info.look) return <ArchiveView info={info} />;
return (
<div className="archive-look" data-look={info.look}>
<ArchiveView info={info} />
</div>
);
}
+340
View File
@@ -347,6 +347,31 @@ select {
padding: 64px 0;
color: var(--muted);
}
.loading {
display: flex;
align-items: center;
gap: 12px;
padding: 64px 0;
color: var(--muted);
}
.spinner {
width: 18px;
height: 18px;
border-radius: 50%;
border: 2px solid currentColor;
border-right-color: transparent;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
.spinner {
animation: none;
}
}
/* Gallery */
.gallery-head {
@@ -973,3 +998,318 @@ button.chip {
.face-list button:hover span {
color: var(--accent);
}
/*
* Archives in their owner's look (cloud_sources.look), over the same structure: Liga Portugal (night blue, orange,
* condensed capitals) and the Federação de Andebol (light grey, red bar, Open Sans capitals). Colours and type only:
* no marks or logos of theirs.
*/
[data-look="liga"] {
--bg: #001941;
--surface: #00235a;
--ink: #ffffff;
--muted: rgba(255, 255, 255, 0.74);
--faint: rgba(255, 255, 255, 0.5);
--line: rgba(255, 255, 255, 0.14);
--accent: #ff8000;
--accent-ink: #001941;
--bar: #00235a;
--bar-ink: #ffffff;
--display: "Bebas Neue", "Barlow Condensed", "Arial Narrow", sans-serif;
--text: "Source Sans 3", "Barlow", system-ui, sans-serif;
--radius: 6px;
color-scheme: dark;
}
[data-look="fpa"] {
--bg: #e4e4e4;
--surface: #ffffff;
--ink: #111111;
--muted: #444444;
--faint: #808080;
--line: #d2d2d2;
--accent: #c61624;
--accent-ink: #ffffff;
--bar: #c61624;
--bar-ink: #ffffff;
--display: "Open Sans", system-ui, sans-serif;
--text: "Open Sans", system-ui, sans-serif;
--radius: 0px;
color-scheme: light;
}
.archive-look {
min-height: 100vh;
background: var(--bg);
color: var(--ink);
font-family: var(--text);
}
.archive-look .look-band {
background: var(--bar);
color: var(--bar-ink);
}
.archive-look .look-band-in {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px;
min-height: 52px;
text-transform: uppercase;
letter-spacing: 0.06em;
font-size: 13px;
}
.archive-look .look-band-in strong {
font-family: var(--display);
font-weight: 700;
font-size: 18px;
}
.archive-look .kicker {
font-family: var(--text);
font-weight: 700;
font-size: 13px;
}
/* Liga: a deep blue band with an orange rule, big condensed titles, cards on a lighter blue. */
[data-look="liga"] .look-band {
background: linear-gradient(90deg, #00235a 0%, #002ac0 100%);
border-bottom: 3px solid var(--accent);
}
[data-look="liga"] .look-band-in strong {
font-weight: 400;
font-size: 24px;
letter-spacing: 0.04em;
}
[data-look="liga"] .title {
font-weight: 400;
letter-spacing: 0.02em;
}
[data-look="liga"] .gallery-head {
border-bottom-color: var(--line);
}
[data-look="liga"] .chip {
font-weight: 400;
font-size: 17px;
}
[data-look="liga"] .chip.on,
[data-look="liga"] .chip:hover {
border-color: var(--accent);
color: var(--accent);
}
[data-look="liga"] .card .frame,
[data-look="liga"] .face-crop {
border-radius: var(--radius);
}
[data-look="liga"] input,
[data-look="liga"] select {
background: var(--surface);
color: var(--ink);
border-color: var(--line);
}
/* FPA: white header band, red bar under it, dark red uppercase headings, white cards. */
[data-look="fpa"] .look-band {
background: var(--surface);
color: var(--ink);
border-bottom: 6px solid var(--bar);
}
[data-look="fpa"] .look-band-in strong {
font-weight: 600;
font-size: 17px;
letter-spacing: 0.02em;
}
[data-look="fpa"] .look-band-in span {
color: var(--muted);
}
[data-look="fpa"] .title {
font-weight: 800;
letter-spacing: -0.01em;
line-height: 1.05;
}
[data-look="fpa"] .h1 {
font-size: clamp(30px, 4.6vw, 56px);
}
[data-look="fpa"] .archive-card .title,
[data-look="fpa"] .card .title {
color: #9e000e;
font-weight: 700;
}
[data-look="fpa"] .chip {
font-weight: 600;
font-size: 13px;
border-radius: 0;
background: var(--surface);
}
[data-look="fpa"] .chip.on,
[data-look="fpa"] .chip:hover {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-ink);
}
[data-look="fpa"] .button {
font-weight: 600;
font-size: 15px;
}
.archive-look .meta {
font-family: var(--text);
}
/* Cards as panels, like the owners' own news cards. */
.archive-look .archive-card {
background: var(--surface);
padding-bottom: 14px;
border-radius: var(--radius);
overflow: hidden;
}
.archive-look .archive-card > span {
padding: 0 14px;
}
.archive-look .archive-card .frame {
margin-bottom: 10px;
border-radius: 0;
}
[data-look="fpa"] .archive-card .title {
font-size: 21px;
}
[data-look="fpa"] .archive-card:hover .title {
color: var(--accent);
}
[data-look="liga"] .archive-card .title {
font-size: 26px;
}
[data-look="liga"] .archive-card:hover {
box-shadow: inset 0 -3px 0 var(--accent);
}
.archive-look .cards .archive-card {
align-self: stretch;
}
.archive-look .look-band-in .meta {
text-transform: none;
letter-spacing: 0;
color: inherit;
opacity: 0.85;
}
.archive-look .gallery-head {
padding-top: 32px;
}
/* The photo large, in the archive's colours. */
[data-look="liga"] .lightbox {
background: rgba(0, 14, 38, 0.97);
color: #fff;
}
[data-look="liga"] .lightbox .side {
background: var(--surface);
border-left-color: var(--line);
}
[data-look="liga"] .lightbox .close,
[data-look="liga"] .lightbox .arrow {
background: rgba(0, 35, 90, 0.8);
border-radius: 50%;
}
[data-look="liga"] .lightbox .close:hover,
[data-look="liga"] .lightbox .arrow:hover {
background: var(--accent);
color: var(--accent-ink);
}
[data-look="fpa"] .lightbox {
background: rgba(17, 17, 17, 0.97);
}
[data-look="fpa"] .lightbox .side {
background: var(--surface);
color: var(--ink);
border-left: 6px solid var(--bar);
}
[data-look="fpa"] .lightbox .side .meta {
color: var(--muted);
}
[data-look="fpa"] .lightbox .close:hover,
[data-look="fpa"] .lightbox .arrow:hover {
background: var(--accent);
}
.archive-look .gallery-people button.on,
.archive-look .gallery-people button:hover {
background: var(--surface);
box-shadow: inset 0 -2px 0 var(--accent);
}
[data-look="fpa"] .person-head .title,
[data-look="fpa"] .archive-names strong {
color: #9e000e;
}
[data-look="fpa"] .archive-names button:hover strong {
color: var(--accent);
}
[data-look="liga"] .archive-names strong {
font-family: var(--display);
font-weight: 400;
font-size: 21px;
letter-spacing: 0.02em;
}
[data-look="liga"] .people-grid strong {
font-family: var(--display);
font-weight: 400;
font-size: 20px;
letter-spacing: 0.02em;
}
[data-look="fpa"] .people-grid strong {
text-transform: uppercase;
font-size: 14px;
}
/* Phones: the band on one line, the search under the tabs, titles that fit. */
@media (max-width: 640px) {
.archive-look .look-band-in {
min-height: 44px;
font-size: 12px;
}
.archive-look .look-band-in strong {
font-size: 15px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-look="liga"] .look-band-in strong {
font-size: 20px;
}
.archive-look .gallery-head {
padding: 22px 0 16px;
}
[data-look="fpa"] .h1 {
font-size: 30px;
}
.archive-look .toolbar .search,
.archive-look .toolbar .search input {
width: 100%;
}
.archive-look .cards {
grid-template-columns: 1fr;
gap: 16px;
}
}
.archive-look .look-band .linkish {
color: inherit;
}
.archive-look .archive-card {
display: flex;
flex-direction: column;
justify-content: flex-start;
gap: 2px;
}
.archive-look .h1 {
font-size: clamp(34px, 5vw, 64px);
}
[data-look="fpa"] .h1 {
font-size: clamp(28px, 4vw, 48px);
}
.archive-look .h2 .meta {
font-family: var(--text);
font-size: 0.42em;
font-weight: 700;
color: var(--accent);
vertical-align: middle;
letter-spacing: 0.04em;
}
@media (max-width: 640px) {
.archive-look .look-band .who {
display: none;
}
.archive-look .look-band-in .meta {
flex-shrink: 0;
}
}
+55 -4
View File
@@ -221,6 +221,22 @@ Face and number are used together:
Suggestions still never name anyone on their own.
A number holds within a season and competition, not for life (`apps/api/src/faces/numbers.ts`): a player may
wear another one five seasons later, in a cup with its own numbering, or for the national team. Wherever a
person's number is used (the comparisons above, the squad suggestion, the training samples' labels) it is the
number for that event's context:
- **Season:** the official match's, or the event's day (July to June). The squad read is that season's, so an
old game gets the number worn then, even for players who have since left.
- **Official match (linked to its teams):** that season's squad first; then what the shirts clearly read (three
or more clear readings) in the person's confirmed photos of the same season and competition.
- **Not linked (a cup, a friendly, a tournament):** those readings in that competition first, then the season's
squad.
- **National team** (a country on either side, or a "Seleção" folder): club squads and club numbers never apply,
only what was read in national games of that season.
- **The number typed on the person** has no season: used only in the current season and never for a national
team. Training samples never take the model's own readings as labels.
Next: back-of-shirt numbers. These are players with no face visible, and they need a box detector trained on
hand-drawn boxes.
@@ -321,6 +337,24 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
with the templates' subfolders and name. It only writes inside folders chosen there with the system's folder
picker (`src-tauri/src/deliver.rs`), never a path a page passes. For testing a destination's rules, or keeping
the finished files to choose from later.
- **Originals** (`delivery_targets.originals`, any kind): the original as it arrived, byte for byte in its image
(no resizing, no recompression, the camera's EXIF and profile kept), with the IPTC written by exiftool and the
name from the templates, like Photo Mechanic's Live Ingest destination (`{iptcdate} - {event}`,
`PS_{event}_{timesort}`). With **every arrival** (`on_arrival`), each photo that is ready in an event (FTP, the
desktop app, uploads; not the archive's) is queued there on its own (`IngestService.arrivals` →
`DeliveryService.queueArrival`). Together on a `LOCAL` destination: one's own backup of the originals in a
folder on the computer (where e.g. Amazon Photos backs it up).
- **Edited again after delivery** (`delivery_items.delivered_seq`, `replaces_path`): a delivered photo whose edits
change later (a crop put right after the autopilot sent it) is sent again to every destination it went to, once
its edits have paused for a minute (`DeliveryService.queueEdited`, checked every half minute with the queue). The
same item goes again with the same number, so the same name: a file is replaced; on ZeroZero (which keeps every
upload) the new image goes up and the previous one is taken back (`DELETE /api/images/<id>`). Originals' backups
carry no edits and are not sent again. Deliveries made before this count as showing the photo as it is.
- **The central FTP as a relay** (`arrival_logins`, `untouched`): an every-arrival `LOCAL` destination can take only
some FTP logins' photos, and with `untouched` the original goes byte for byte as the camera sent it (no metadata
written, the camera's name with `{originalName}`), into the folder a local Photo Mechanic Live Ingest watches. The
photo still enters PhotoReport as any FTP arrival (event, IPTC, deliveries); the photographer's computer gets it as
if the camera had sent to the FTP there.
- **Importing destinations** (desktop, "Importar…" in Destinos): Photo Mechanic's upload accounts
(`fileupload/templates/builtin/<kind>-conn.yml`) and templates (`fileupload/snapshot/builtin/<kind>/*.snap`), and
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places. The desktop takes the saved
@@ -343,10 +377,27 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
(`DELETE /api/images/<id>` takes it back).
Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Templates accept Photo Mechanic's variable
names (`{iptcyear4}`, `{iptcmonth0}`, `{iptcday0}`, `{datesort}`, `{timesort}`, `{event}`), so a Cofina path such
as `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}` works as typed there. Targets can be duplicated
(same server and credentials, another name and folder).
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Targets can be duplicated (same server and
credentials, another name and folder).
**Photo Mechanic compatibility (templates and IPTC).** Every template (IPTC pad, folders, file names, rename on
arrival) takes every variable of Photo Mechanic's list, under its names and short names, in any case
(`packages/metadata/src/pmvars.ts`), and its modifiers: substrings `{var:index,count}` (negative index from the
end, negative count trims the end), `lc`/`UC`/`PC`, and `tr:find/repl` (`{caption:0:lc:tr: /_}`). So a Cofina path
such as `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}` or Live Ingest's `{iptcdate} - {event}` /
`PS_{event}_{timesort}` work as typed there. As in Photo Mechanic, the IPTC variables (`{event}`, `{caption}`,
`{headline}`, `{city}`...) are the photo's IPTC: in folders and names, the pad applied to it; inside the pad, the
IPTC the file arrived with. `{event}`, `{city}` and `{location}` fall back to the event's ("Home x Away", its city,
its venue); `{date}` and the IPTC dates are the capture's (the event's day without a capture time). Camera
variables come from the photo's columns plus `photos.exif` (exposure compensation, flash, metering, program, white
balance, 35 mm focal length, lens range, firmware, owner, artist, GPS), read at ingest; photos from before are read
from the file at delivery. Variables PhotoReport has no data for (Getty fields, Nikon Picture Control, ICC
primaries, client/user extras, shutter count) exist and are empty, as in Photo Mechanic. The IPTC pad has every
Photo Mechanic field, written to the same IIM and XMP tags (contact info, state, country and code, location taken,
instructions, transmission reference, category, urgency, edit status, genre, scene, subject code, usage terms,
copyright URL, image supplier, model release), and the same fields are read from incoming files. PhotoReport's own
variables (`{home}`, `{away}`, `{competition}`, `{season}`, `{round}`, `{players}`, `{photographer}`, `{n}`...)
stay.
Rename on arrival (Live Ingest "Rename as"): photos arriving by FTP or the desktop app get a name from a
template. The template is the organisation's, or the FTP login's own (`""` keeps camera names). Names are made
+72 -4
View File
@@ -23,6 +23,13 @@ never reaches PhotoReport. A revoked app password puts the source back to LOGIN
`lib/capacity.ts`), newest season first: download to a temp file, sha256, 2048 px
preview with metadata, then the normal ingest as source `CLOUD` (`originalStored = false`, no autopilot, no
rename). The same picture already in the library is linked, not duplicated. Faces run as for any photo.
- Each claim is shared between the clouds with pending images, so a big newer archive (Liga) never starves
another (FPA); inside a cloud, newest season first.
- WebDAV through Nextcloud's PHP is the slow part of a big first import (the CPUs sit idle). With the cloud's
data folder mounted read-only on the worker, `ARCHIVE_LOCAL_DIRS` reads the files from disk instead:
`https://cloud.photoreport.pt/FPA=/mnt/nextcloud/<owner>/files/FPA` (comma-separated; the folder as the
connected account sees it = where it is on disk). A file not there, or of another size than the walk saw, is
downloaded as before; deliveries and the 100% view read from the mount too.
- The editor's 100% view (`GET /v1/photos/:id/original`) and deliveries read the original from the cloud.
## Matching galleries to games
@@ -47,13 +54,74 @@ never reaches PhotoReport. A revoked app password puts the source back to LOGIN
Teams match by abbreviation, slug, name or close name (`sameTeam`); a game not found among the fixtures is named
with the clubs' names when its initials name exactly one known club (`SLB` → SL Benfica). Every walk reads the
galleries matched by name again (`rematch`) and puts right what is now understood better. One fixture found → the game's event
(an existing one, or a new **archived** event with both squads: archived events stay out of the day's list and
never catch FTP photos). Otherwise an event from the name (NAME) or named after the folder (FOLDER). Arquivo →
"Por confirmar" lists those; "Escolher jogo" picks the official game and moves the photos.
galleries matched by name again (`rematch`) and puts right what is now understood better. One fixture found → the
game's **archived** event (the archive's own, with both squads: archived events stay out of the day's list and never
catch FTP photos).
The archive never adds to an event of the library (one photographed live), not even for the same official game:
a wrong match must never put photos in an event someone is working on. Safeguards, because a wrong game is worse
than none:
- Only a dated folder, or one placed in its competition, season and matchday (`LPBetclic 26-27/Jornada 5`), is
matched to an official game; a season, month or matchday alone is not (one club's month folder only when that
month's game against the club above is the only one).
- A reserve, youth or women's side in the name or the path (`B`, `Sub-23`, `Feminino`, `Juniores`, `Revelação`)
never matches the first team's game.
- Name events join only other archive events of the same day (never by the folder's date in the cloud, never an
official game's).
- Never a day still to come: fixtures not yet played are never candidates; a folder date in the future is read the
other way when that makes sense (`23.09.28` → 28 Sep 2023) or ignored; a name event is never dated ahead.
- The photos' own day (`captureDay`: the Lisbon day of the camera time of most indexed photos, 3+ and 60%+) dates a
folder whose name has no day, both to find its game and to date its event. A date in the folder's name always
wins over the cameras (their clocks can be wrong).
- Every walk, and on the worker's start for all clouds (`verifyAll`), each FIXTURE gallery is checked: an event
still to come, or (the folder's name giving no day) another day than its photos were taken, takes it off that
game for good, to an event of the photos' own day.
- Before a photo of a FIXTURE folder is added, its capture day is checked against the game: more than 36 h apart
and the folder is taken off the game for good (`fixture_rejected`), its photos moving to an event of its own.
- On start, the worker takes out of live events every folder put there before (`leaveLiveEvents`): their photos
move to the archive's own events, faces found again there; photos that were already in the live event (the same
picture sent live) stay, and so do folders placed there by hand. Otherwise an event from the name (NAME) or named after the folder (FOLDER).
- Both teams must be recognised: a game with one side guessed (a nickname, a sponsor's name) is not matched. A first
team is never its B side ("SL Benfica" is not "SL Benfica B").
- Legends', veterans', charity, exhibition and tribute games, galas (`isExhibition`: "Liga Portugal Legends 2025-26")
are games in no championship: never an official fixture; the tournament's folder is the event's competition.
- Every check (on start, then every six hours, and after a season's calendar is read) makes every match but a manual
one again with today's rules: a folder that no longer fits its official game moves to the right one or to an event
of its own; a NAME event keeps its folder but takes the better names ("01.23 Leixões SC" → "Leixões SC", known
teams by their official name). One folder failing never stops the rest.
**Teams in the viewer.** The directory and the team filter show each team once: without the date or number a folder
put before it (`teamLabel`), and as the known team when exactly one fits (`canonicalTeam`: "SCP", "Sporting",
"06_Sporting CP" → Sporting CP); filtering by it finds the galleries under every name it was written as.
**Faces keep to the sport.** A person known from a squad has that team's sport; a face is never suggested as someone
of another sport than the event's (its own, its official game's, or its cloud's: Liga football, FPA handball).
Suggestions made before that are taken away on the worker's start (`dropCrossSportSuggestions`); names confirmed by
a person stay.
**Games and events are kept apart.** A game (FIXTURE/MANUAL: official; NAME: known only by its folder) is matched
on competition, season, matchday, day and teams; an event (FOLDER: a gala, a session, a presentation, a training)
is never given a game and reads no shirt numbers (`numberContext` is null for an event without an away side): its
people are known by their face only. Arquivo → galleries: "Jogos oficiais", "Jogos por confirmar" (NAME), "Eventos"
(FOLDER), "Todas"; "Escolher jogo" picks the official game and moves the photos.
**Past seasons' calendars.** The live refresh only keeps the current season. When the archive meets a folder of
another season it reads that season's calendar once: Liga Portugal's month by month (`importLigaSeason`, awaited),
the FPA's national games club by club (`importFpaSeason`: the portal's `getJogosClubeEpocaEscalao` for every level of
each club, starting from today's agenda and following every club met, regional associations' games left out). The
FPA's is slow on purpose (one portal page at a time), so it runs in the background, one season at a time, in the
worker only; when it brings games, every gallery is matched again (`verifyAll`). A season counts as read with 300+
played games.
## Viewers (site)
- Each archive can wear its owner's look (`cloud_sources.look`): `liga` (Liga Portugal: night blue, orange,
condensed capitals) or `fpa` (Federação de Andebol: light grey, red bar, Open Sans capitals); none is
PhotoReport's. Set from the source's name or folder when connected, changed in the app (Arquivo → "Aspeto do
site"). Colours and type only, no marks or logos of theirs (`globals.css`, `[data-look]`).
`https://events.photoreport.pt/arquivo/<source id>` (any site domain works; `VITE_ARCHIVE_URL` in the app sets
the link it shows). The viewer signs in with **their own** account on that cloud (login flow v2 again). The API
reads what is shared with them (OCS `shared_with_me`, user and group shares), revokes that app password at once,
+5 -2
View File
@@ -35,8 +35,11 @@ module.exports = {
node_args: "--env-file=.env",
instances: 1,
exec_mode: "fork",
max_memory_restart: "2G",
kill_timeout: 30000,
// Archive burst (many downloads + face processes) on 48-vCPU hosts routinely exceeds 2G; a too-low
// cap caused SIGINT restart loops and Prisma "pool after end" noise during unclean disconnect (BIT-31189).
max_memory_restart: "6G",
// Must exceed worker drain window (25s) so in-flight jobs finish before PM2 SIGKILLs.
kill_timeout: 45000,
// Keep retrying with a growing pause (up to 15 s) instead of giving up after 15 quick crashes, e.g. while
// the database container is still starting after a host reboot.
exp_backoff_restart_delay: 200,
+1
View File
@@ -1,5 +1,6 @@
export * from "./codes.js";
export * from "./iptc.js";
export * from "./paths.js";
export * from "./pmvars.js";
export * from "./template.js";
export * from "./vars.js";
+83 -4
View File
@@ -1,6 +1,6 @@
import { z } from "zod";
import { type CodeList, expandCodes } from "./codes.js";
import { render, type TemplateVars } from "./template.js";
import { lookup, render, type TemplateVars } from "./template.js";
/**
* The IPTC fields PhotoReport fills, in the order and grouping of the Photo Mechanic pad used today.
@@ -27,6 +27,43 @@ export const IPTC_FIELDS = [
{ key: "creatorIdentity", label: "Creator's Identity", section: "generic", list: false, tags: [] },
{ key: "personsShown", label: "Persons shown", section: "generic", list: true, tags: ["XMP-iptcExt:PersonInImage"] },
{ key: "licensors", label: "Licensors", section: "generic", list: true, tags: ["XMP-plus:LicensorName"] },
// The rest of Photo Mechanic's pad, with the tags it writes (IIM and XMP, as above).
{ key: "jobTitle", label: "Creator's Job Title", section: "contact", list: false, tags: ["IPTC:By-lineTitle", "XMP-photoshop:AuthorsPosition"] },
{ key: "creatorAddress", label: "Contact Address", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorAddress"] },
{ key: "creatorCity", label: "Contact City", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorCity"] },
{ key: "creatorRegion", label: "Contact State/Province", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorRegion"] },
{ key: "creatorPostalCode", label: "Contact Postal Code", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorPostalCode"] },
{ key: "creatorCountry", label: "Contact Country", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorCountry"] },
{ key: "creatorPhone", label: "Contact Phone", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkTelephone"] },
{ key: "creatorEmail", label: "Contact Email", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkEmail"] },
{ key: "creatorUrl", label: "Contact Web URL", section: "contact", list: false, tags: ["XMP-iptcCore:CreatorWorkURL"] },
{ key: "captionWriter", label: "Caption Writer", section: "contact", list: false, tags: ["IPTC:Writer-Editor", "XMP-photoshop:CaptionWriter"] },
{ key: "state", label: "State/Province", section: "location", list: false, tags: ["IPTC:Province-State", "XMP-photoshop:State"] },
{ key: "country", label: "Country", section: "location", list: false, tags: ["IPTC:Country-PrimaryLocationName", "XMP-photoshop:Country"] },
{ key: "countryCode", label: "Country Code", section: "location", list: false, tags: ["IPTC:Country-PrimaryLocationCode", "XMP-iptcCore:CountryCode"] },
{ key: "locationTaken", label: "Location (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedSublocation"] },
{ key: "cityTaken", label: "City (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCity"] },
{ key: "stateTaken", label: "State/Province (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedProvinceState"] },
{ key: "countryTaken", label: "Country (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCountryName"] },
{ key: "countryCodeTaken", label: "Country Code (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedCountryCode"] },
{ key: "worldRegionTaken", label: "World Region (Taken)", section: "location", list: false, tags: ["XMP-iptcExt:LocationCreatedWorldRegion"] },
{ key: "transmissionReference", label: "Job ID/Transmission Reference", section: "status", list: false, tags: ["IPTC:OriginalTransmissionReference", "XMP-photoshop:TransmissionReference"] },
{ key: "instructions", label: "Instructions", section: "status", list: false, tags: ["IPTC:SpecialInstructions", "XMP-photoshop:Instructions"] },
{ key: "category", label: "Category", section: "status", list: false, tags: ["IPTC:Category", "XMP-photoshop:Category"] },
{ key: "urgency", label: "Urgency", section: "status", list: false, tags: ["IPTC:Urgency", "XMP-photoshop:Urgency"] },
{ key: "editStatus", label: "Edit Status", section: "status", list: false, tags: ["IPTC:EditStatus"] },
{ key: "genre", label: "Intellectual Genre", section: "status", list: false, tags: ["IPTC:ObjectAttributeReference", "XMP-iptcCore:IntellectualGenre"] },
{ key: "scene", label: "Scene", section: "status", list: false, tags: ["XMP-iptcCore:Scene"] },
{ key: "subjectCode", label: "Subject Code", section: "status", list: false, tags: ["IPTC:SubjectReference", "XMP-iptcCore:SubjectCode"] },
{ key: "usageTerms", label: "Rights Usage Terms", section: "status", list: false, tags: ["XMP-xmpRights:UsageTerms"] },
{ key: "copyrightUrl", label: "Copyright Info URL", section: "status", list: false, tags: ["XMP-xmpRights:WebStatement"] },
{ key: "digitalSourceType", label: "Digital Source Type", section: "status", list: false, tags: ["XMP-iptcExt:DigitalSourceType"] },
{ key: "imageSupplierName", label: "Image Supplier", section: "models", list: false, tags: ["XMP-plus:ImageSupplierName"] },
{ key: "imageSupplierId", label: "Image Supplier ID", section: "models", list: false, tags: ["XMP-plus:ImageSupplierID"] },
{ key: "imageSupplierImageId", label: "Image Supplier Image ID", section: "models", list: false, tags: ["XMP-plus:ImageSupplierImageID"] },
{ key: "modelReleaseId", label: "Model Release ID", section: "models", list: false, tags: ["XMP-plus:ModelReleaseID"] },
{ key: "modelAges", label: "Model Age", section: "models", list: false, tags: ["XMP-iptcExt:ModelAge"] },
{ key: "modelInfo", label: "Additional Model Info", section: "models", list: false, tags: ["XMP-iptcExt:AdditionalModelInformation"] },
] as const;
export type IptcFieldKey = (typeof IPTC_FIELDS)[number]["key"];
@@ -62,6 +99,42 @@ export const IptcTemplate = z.object({
creatorIdentity: text.optional(),
personsShown: list.optional(),
licensors: list.optional(),
jobTitle: text.optional(),
creatorAddress: text.optional(),
creatorCity: text.optional(),
creatorRegion: text.optional(),
creatorPostalCode: text.optional(),
creatorCountry: text.optional(),
creatorPhone: text.optional(),
creatorEmail: text.optional(),
creatorUrl: text.optional(),
captionWriter: text.optional(),
state: text.optional(),
country: text.optional(),
countryCode: text.optional(),
locationTaken: text.optional(),
cityTaken: text.optional(),
stateTaken: text.optional(),
countryTaken: text.optional(),
countryCodeTaken: text.optional(),
worldRegionTaken: text.optional(),
transmissionReference: text.optional(),
instructions: text.optional(),
category: text.optional(),
urgency: text.optional(),
editStatus: text.optional(),
genre: text.optional(),
scene: text.optional(),
subjectCode: text.optional(),
usageTerms: text.optional(),
copyrightUrl: text.optional(),
digitalSourceType: text.optional(),
imageSupplierName: text.optional(),
imageSupplierId: text.optional(),
imageSupplierImageId: text.optional(),
modelReleaseId: text.optional(),
modelAges: text.optional(),
modelInfo: text.optional(),
});
export type IptcTemplate = z.infer<typeof IptcTemplate>;
@@ -100,7 +173,7 @@ export const GENERAL_TEMPLATE: IptcTemplate = {
export interface IptcIssue {
field: IptcFieldKey;
kind: "missing_variable" | "unknown_code";
kind: "missing_variable" | "unknown_code" | "bad_modifier";
detail: string;
}
@@ -110,7 +183,13 @@ export interface ApplyResult {
}
function fill(template: string, vars: TemplateVars, codes: CodeList | undefined, field: IptcFieldKey, issues: IptcIssue[]): string {
const rendered = render(template, vars, { missing: "drop" });
let rendered;
try {
rendered = render(template, vars, { missing: "drop" });
} catch (err) {
issues.push({ field, kind: "bad_modifier", detail: err instanceof Error ? err.message : String(err) });
return template;
}
for (const name of rendered.missing) issues.push({ field, kind: "missing_variable", detail: name });
if (!codes) return rendered.text;
const expanded = expandCodes(rendered.text, codes);
@@ -141,7 +220,7 @@ export function applyTemplate(template: IptcTemplate, vars: TemplateVars, codes?
const items: string[] = [];
for (const entry of source as string[]) {
const whole = /^\{([a-zA-Z][a-zA-Z0-9_]*)\}$/.exec(entry);
const listVar = whole?.[1] ? vars[whole[1]] : undefined;
const listVar = whole?.[1] ? lookup(vars, whole[1]) : undefined;
if (Array.isArray(listVar)) {
items.push(...listVar.map((v) => fill(v, {}, codes, field.key, issues)));
continue;
+11 -2
View File
@@ -32,9 +32,18 @@ export class PathTemplateError extends Error {
}
}
/** Renders, turning a bad modifier (`{event:xyz}`) into a template error. */
function renderPath(template: string, vars: TemplateVars) {
try {
return render(template, vars);
} catch (err) {
throw new PathTemplateError(err instanceof Error ? err.message : String(err));
}
}
/** Renders a folder template into a normalised absolute path ending in `/`. Missing variables are an error. */
export function renderFolder(template: string, vars: TemplateVars): string {
const { text, missing } = render(template, safeVars(vars));
const { text, missing } = renderPath(template, safeVars(vars));
if (missing.length) throw new PathTemplateError(`missing variables: ${missing.join(", ")}`, missing);
const segments = text.split("/").map((s) => s.trim()).filter(Boolean);
if (segments.some((s) => s === "." || s === "..")) throw new PathTemplateError("path cannot contain . or ..");
@@ -49,7 +58,7 @@ export function renderFileName(template: string, vars: TemplateVars, originalFil
const dot = originalFileName.lastIndexOf(".");
const base = dot > 0 ? originalFileName.slice(0, dot) : originalFileName;
const ext = dot > 0 ? originalFileName.slice(dot).toLowerCase() : "";
const { text, missing } = render(template, safeVars({ ...vars, originalName: base }));
const { text, missing } = renderPath(template, safeVars({ ...vars, originalName: base }));
if (missing.length) throw new PathTemplateError(`missing variables: ${missing.join(", ")}`, missing);
const name = safeSegment(text);
if (!name) throw new PathTemplateError("file name is empty");
+100 -1
View File
@@ -1,5 +1,8 @@
import { describe, expect, it } from "vitest";
import { renderFileName, renderFolder } from "./paths.js";
import { applyTemplate, toExiftoolArgs } from "./iptc.js";
import { PathTemplateError, renderFileName, renderFolder } from "./paths.js";
import { PM_VARIABLE_NAMES } from "./pmvars.js";
import { badModifiers, render } from "./template.js";
import { buildVars } from "./vars.js";
describe("Photo Mechanic variables", () => {
@@ -19,3 +22,99 @@ describe("Photo Mechanic variables", () => {
expect(v.timesort).toBeUndefined();
});
});
describe("Photo Mechanic syntax", () => {
const v = { filenamebase: "DSC_1234", filename: "DSC_1234.JPG", caption: "Golo de RUI silva" };
const r = (t: string) => render(t, v).text;
it("extracts substrings as in its documentation", () => {
expect(r("{filenamebase:0,3}")).toBe("DSC");
expect(r("{filenamebase:-4,4}")).toBe("1234");
expect(r("{filenamebase:-4}")).toBe("1234");
expect(r("{filenamebase:2,3}")).toBe("C_1");
expect(r("{filename:0,-4}")).toBe("DSC_1234");
});
it("converts case and translates", () => {
expect(r("{filenamebase:0:lc}")).toBe("dsc_1234");
expect(r("{filenamebase:0:PC}")).toBe("Dsc_1234");
expect(r("{caption:0:UC}")).toBe("GOLO DE RUI SILVA");
expect(r("{caption:0:lc:tr: /_}")).toBe("golo_de_rui_silva");
expect(r("{filename:0:tr:\\//-}")).toBe("DSC_1234.JPG");
expect(render("{a:tr:\\//-}", { a: "x/y" }).text).toBe("x-y");
});
it("matches names in any case and refuses bad modifiers", () => {
expect(r("{FileNameBase}")).toBe("DSC_1234");
expect(badModifiers("{a:0,3} {b:zz} {c:0:lc:tr:a/b}")).toEqual(["{b:zz}"]);
});
});
describe("every Photo Mechanic variable", () => {
const event = { home: "SC Braga", away: "Sporting CP", venue: "Estádio Municipal de Braga", city: "Braga", startsAt: new Date("2026-10-11T19:30:00Z") };
const photo = {
capturedAt: new Date("2026-10-11T20:05:09.120Z"),
fileName: "IMG_0042.CR3",
fileSize: 24_500_000,
width: 6000,
height: 4000,
make: "Canon",
model: "Canon EOS R3",
serial: "123456",
lensModel: "RF400mm F2.8 L IS USM",
lensRange: [400, 400] as const,
focalLength: 400,
aperture: 2.8,
exposureTime: 1 / 1600,
iso: 3200,
exposureCompensation: -0.3,
flashFired: false,
exposureProgram: "Manual",
rating: 3,
sequence: 7,
};
const vars = buildVars(event, photo, "Peter Spark", { iptc: { caption: "Golo", headline: "Braga vence", event: "SC Braga x Sporting CP", city: "Braga" }, now: new Date("2026-10-12T09:00:00Z") });
it("knows every name and short name of the list", () => {
for (const name of ["byline", "phtg", "iptcdate", "idat", "timesort", "tims", "filenamebase", "fbas", "serialnum", "snum", "num*", "lenstype", "wiredate", "usercompany", "gcfi", "pcnm", "prrx", "seqn", "rand4"])
expect(PM_VARIABLE_NAMES.has(name), name).toBe(true);
});
it("fills the camera's details", () => {
const r = (t: string) => render(t, vars).text;
expect(r("{make} {model} #{serialnum} {lens} {lenstype}")).toBe("Canon Canon EOS R3 #123456 400mm RF400mm F2.8 L IS USM");
expect(r("f/{aperture} {shutter} ISO {iso} {comp} {flash} {program}")).toBe("f/2.8 1/1600 ISO 3200 -0.3 No Manual");
expect(r("{width}x{height} {aspect} {filesize} {frame4} {type} {rating} {num*}")).toBe("6000x4000 3:2 24.5MB 0042 CR3 *** 3");
});
it("fills the dates and the pad", () => {
const r = (t: string) => render(t, vars).text;
expect(r("{iptcdate} - {event}")).toBe("20261011 - SC Braga x Sporting CP");
expect(r("PS_{event}_{timesort}")).toBe("PS_SC Braga x Sporting CP_21050912");
expect(r("{date} {time} {dow} {monthname} {iptcmonthnameap}")).toBe("11/10/2026 21:05:09 Sunday October Oct.");
expect(r("{wiredate}")).toBe("20261011T210509+0100");
expect(r("{todaysort} {yesterday}")).toBe("20261012 11/10/2026");
expect(r("{caption} | {headline} | {byline} | {seqn} | {location}")).toBe("Golo | Braga vence | Peter Spark | 7 | Estádio Municipal de Braga");
});
it("leaves the ones without data empty", () => {
expect(vars.gpsdir).toBe("");
expect(vars.clientname).toBe("");
expect(render("{clientname}", vars, { missing: "drop" }).text).toBe("");
});
});
describe("Photo Mechanic's IPTC pad", () => {
it("writes the rest of its fields where it writes them", () => {
const { values } = applyTemplate({ jobTitle: "Fotojornalista", instructions: "Embargo até às 22h", state: "Braga", country: "Portugal", countryCode: "PRT", creatorEmail: "[email protected]", cityTaken: "Braga" }, {});
const args = toExiftoolArgs(values);
for (const a of ["-IPTC:By-lineTitle=Fotojornalista", "-XMP-photoshop:AuthorsPosition=Fotojornalista", "-IPTC:SpecialInstructions=Embargo até às 22h", "-IPTC:Province-State=Braga", "-IPTC:Country-PrimaryLocationName=Portugal", "-IPTC:Country-PrimaryLocationCode=PRT", "-XMP-iptcCore:[email protected]", "-XMP-iptcExt:LocationCreatedCity=Braga"])
expect(args).toContain(a);
});
it("reports a bad modifier instead of failing", () => {
const { issues } = applyTemplate({ caption: "{home:zz}" }, { home: "x" });
expect(issues).toEqual([{ field: "caption", kind: "bad_modifier", detail: "unknown template modifier: zz" }]);
expect(() => renderFolder("/{home:zz}/", { home: "x" })).toThrow(PathTemplateError);
});
});
+585
View File
@@ -0,0 +1,585 @@
/**
* Photo Mechanic's variables, with the names and short names of its list
* (docs.camerabits.com, "List of Photo Mechanic Variables"), so a template typed in Photo Mechanic (a Live Ingest
* folder, a rename, an IPTC pad, an upload path) works here as it is. Every name in that list exists here: the ones
* PhotoReport has no data for (a Getty field, a Nikon Picture Control, the ICC primaries) are empty, as Photo
* Mechanic leaves a variable with no value.
*
* Times are Lisbon wall-clock time, as the cameras of our coverage are set and as Photo Mechanic shows them.
*/
/** What is known of a photo: the camera's EXIF, the file, the IPTC written into it, its place in a batch. */
export interface PmPhoto {
capturedAt?: Date | undefined;
/** The name the file came with ("IMG_1234.JPG"). */
fileName?: string | undefined;
fileSize?: number | undefined;
/** When the file arrived (Photo Mechanic's modification date). */
modifiedAt?: Date | undefined;
width?: number | undefined;
height?: number | undefined;
make?: string | undefined;
model?: string | undefined;
serial?: string | undefined;
/** The lens's name ("RF100-500mm F4.5-7.1 L IS USM"). */
lensModel?: string | undefined;
/** The lens's focal range in mm ([100, 500]). */
lensRange?: readonly [number, number] | undefined;
focalLength?: number | undefined;
focalLength35?: number | undefined;
aperture?: number | undefined;
/** Seconds (1/400 → 0.0025). */
exposureTime?: number | undefined;
iso?: number | undefined;
exposureCompensation?: number | undefined;
flashFired?: boolean | undefined;
meteringMode?: string | undefined;
exposureProgram?: string | undefined;
whiteBalance?: string | undefined;
focusMode?: string | undefined;
software?: string | undefined;
firmware?: string | undefined;
owner?: string | undefined;
artist?: string | undefined;
tiffCopyright?: string | undefined;
imageDescription?: string | undefined;
userComment?: string | undefined;
colorSpace?: string | undefined;
iccProfile?: string | undefined;
shutterCount?: number | undefined;
/** Pixels per inch. */
resolution?: number | undefined;
latitude?: number | undefined;
longitude?: number | undefined;
altitude?: number | undefined;
/** 0-5 stars. */
rating?: number | undefined;
/** Colour class: its number (0-8) and name. */
colorClass?: number | undefined;
colorClassName?: string | undefined;
tagged?: boolean | undefined;
/** Position in the batch (a delivery, an ingest), from 1, and its size. */
sequence?: number | undefined;
total?: number | undefined;
}
/** The IPTC values of the photo (filled pad), by Photo Mechanic's variable names. */
export type PmIptc = Partial<Record<string, string | readonly string[] | undefined>>;
const TIME_ZONE = "Europe/Lisbon";
const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/** AP style: March to July in full, the others abbreviated (and "Sept."). */
const MONTHS_AP = ["Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."];
const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
interface Wall {
y: string;
m: string;
d: string;
hh: string;
mm: string;
ss: string;
cs: string;
ms: string;
dow: number;
/** "+0100" */
offset: string;
}
const WALL = new Intl.DateTimeFormat("en-GB", { timeZone: TIME_ZONE, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", weekday: "short" });
function wall(date: Date): Wall {
const p = Object.fromEntries(
WALL.formatToParts(date)
.map((x) => [x.type, x.value]),
) as Record<string, string>;
const asUtc = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second));
const minutes = Math.round((asUtc - Math.floor(date.getTime() / 1000) * 1000) / 60000);
const abs = Math.abs(minutes);
const ms = date.getUTCMilliseconds();
return {
y: p.year!,
m: p.month!,
d: p.day!,
hh: p.hour!,
mm: p.minute!,
ss: p.second!,
cs: String(Math.floor(ms / 10)).padStart(2, "0"),
ms: String(ms).padStart(3, "0"),
dow: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(p.weekday!),
offset: `${minutes < 0 ? "-" : "+"}${String(Math.floor(abs / 60)).padStart(2, "0")}${String(abs % 60).padStart(2, "0")}`,
};
}
const h12 = (hh: string) => String(Number(hh) % 12 || 12);
const shortDate = (w: Wall) => `${w.d}/${w.m}/${w.y}`;
/** Capture (or any) date and time in every way Photo Mechanic writes it; `prefix` "iptc" for its IPTC names. */
function dateVars(w: Wall | undefined): Record<string, string | undefined> {
if (!w) return {};
return {
ampm: Number(w.hh) < 12 ? "AM" : "PM",
date: shortDate(w),
datemil: `${w.d} ${MONTHS[Number(w.m) - 1]!.slice(0, 3)} ${w.y}`,
datesort: `${w.y}${w.m}${w.d}`,
datesortdash: `${w.y}-${w.m}-${w.d}`,
day: String(Number(w.d)),
day0: w.d,
dow: DAYS[w.dow],
dow3: DAYS[w.dow]?.slice(0, 3),
hour: h12(w.hh),
hour0: h12(w.hh).padStart(2, "0"),
hour24: w.hh,
minute: w.mm,
month: String(Number(w.m)),
month0: w.m,
monthname: MONTHS[Number(w.m) - 1],
monthname3: MONTHS[Number(w.m) - 1]?.slice(0, 3),
monthnameap: MONTHS_AP[Number(w.m) - 1],
second: w.ss,
subsecond: w.cs,
time: `${w.hh}:${w.mm}:${w.ss}`,
/** hhmmss plus hundredths: sorts in shooting order and tells burst frames apart. */
timesort: `${w.hh}${w.mm}${w.ss}${w.cs}`,
timesortdash: `${w.hh}-${w.mm}-${w.ss}`,
timesortlong: `${w.hh}${w.mm}${w.ss}${w.ms}`,
year2: w.y.slice(2),
year4: w.y,
};
}
/** Photo Mechanic's IPTC date names: the IPTC Date/Time Created, which PhotoReport writes from the capture time. */
function iptcDateVars(w: Wall | undefined): Record<string, string | undefined> {
if (!w) return {};
return {
iptcampm: Number(w.hh) < 12 ? "AM" : "PM",
iptcdate: `${w.y}${w.m}${w.d}`,
iptcday: String(Number(w.d)),
iptcday0: w.d,
iptcdow: DAYS[w.dow],
iptcdow3: DAYS[w.dow]?.slice(0, 3),
iptchour: h12(w.hh),
iptchour0: h12(w.hh).padStart(2, "0"),
iptchour24: w.hh,
iptcminute: w.mm,
iptcmonth: String(Number(w.m)),
iptcmonth0: w.m,
iptcmonthname: MONTHS[Number(w.m) - 1],
iptcmonthname3: MONTHS[Number(w.m) - 1]?.slice(0, 3),
iptcmonthnameap: MONTHS_AP[Number(w.m) - 1],
iptcsecond: w.ss,
iptctime: `${w.hh}${w.mm}${w.ss}${w.offset}`,
iptcyear2: w.y.slice(2),
iptcyear4: w.y,
wiredate: `${w.y}${w.m}${w.d}T${w.hh}${w.mm}${w.ss}${w.offset}`,
};
}
function nowVars(now: Date): Record<string, string | undefined> {
const w = wall(now);
const day = (offsetDays: number) => shortDate(wall(new Date(now.getTime() + offsetDays * 86_400_000)));
return {
now: `${w.hh}:${w.mm}:${w.ss}`,
nowampm: Number(w.hh) < 12 ? "AM" : "PM",
nowhour: h12(w.hh),
nowhour0: h12(w.hh).padStart(2, "0"),
nowhour24: w.hh,
nowminute: w.mm,
nowsecond: w.ss,
nowsort: `${w.hh}${w.mm}${w.ss}`,
nowsortlong: `${w.hh}${w.mm}${w.ss}${w.cs}`,
nowsubsecond: w.cs,
today: shortDate(w),
todayday: String(Number(w.d)),
todayday0: w.d,
todaydow: DAYS[w.dow],
todaydow3: DAYS[w.dow]?.slice(0, 3),
todaymil: `${w.d} ${MONTHS[Number(w.m) - 1]!.slice(0, 3)} ${w.y}`,
todaymonth: String(Number(w.m)),
todaymonth0: w.m,
todaymonthname: MONTHS[Number(w.m) - 1],
todaymonthname3: MONTHS[Number(w.m) - 1]?.slice(0, 3),
todaymonthnameap: MONTHS_AP[Number(w.m) - 1],
todaysort: `${w.y}${w.m}${w.d}`,
todayyear2: w.y.slice(2),
todayyear4: w.y,
tomorrow: day(1),
yesterday: day(-1),
};
}
const trim = (n: number) => String(Math.round(n * 10) / 10);
function shutter(seconds: number | undefined): string | undefined {
if (!seconds || seconds <= 0) return undefined;
if (seconds >= 0.3) return trim(seconds);
return `1/${Math.round(1 / seconds)}`;
}
function aspect(w: number | undefined, h: number | undefined): string | undefined {
if (!w || !h) return undefined;
const [a, b] = w >= h ? [w, h] : [h, w];
const r = a / b;
for (const [x, y] of [[1, 1], [5, 4], [4, 3], [3, 2], [16, 9], [2, 1], [3, 1]] as const) if (Math.abs(r - x / y) < 0.01) return w >= h ? `${x}:${y}` : `${y}:${x}`;
return (w / h).toFixed(2);
}
function bytes(n: number | undefined): string | undefined {
if (n === undefined) return undefined;
if (n >= 1e6) return `${(n / 1e6).toFixed(1)}MB`;
if (n >= 1e3) return `${Math.round(n / 1e3)}KB`;
return `${n}B`;
}
const ev = (v: number | undefined) => (v === undefined ? undefined : `${v > 0 ? "+" : ""}${trim(v)}`);
const log2 = (x: number) => Math.log(x) / Math.LN2;
/** Every Photo Mechanic variable for a photo, under each of its names and short names. */
export function pmVars(photo: PmPhoto = {}, iptc: PmIptc = {}, opts: { now?: Date | undefined; fallbackDay?: Date | undefined; user?: string | undefined } = {}): Record<string, string | readonly string[] | undefined> {
const now = opts.now ?? new Date();
const shot = photo.capturedAt ?? opts.fallbackDay;
const w = shot ? wall(shot) : undefined;
const capture = photo.capturedAt ? wall(photo.capturedAt) : undefined;
const mod = photo.modifiedAt ? wall(photo.modifiedAt) : undefined;
const file = photo.fileName ?? "";
const dot = file.lastIndexOf(".");
const base = dot > 0 ? file.slice(0, dot) : file;
const frame = /(\d+)(?!.*\d)/.exec(base)?.[1];
const s = (v: string | number | undefined | null) => (v === undefined || v === null || v === "" ? "" : String(v));
const iptcText = (k: string) => {
const v = iptc[k];
return Array.isArray(v) ? v.join(", ") : s(v as string | undefined);
};
const av = photo.aperture ? 2 * log2(photo.aperture) : undefined;
const tv = photo.exposureTime ? -log2(photo.exposureTime) : undefined;
const sv = photo.iso ? log2(photo.iso / 3.125) : undefined;
const evApex = av !== undefined && tv !== undefined ? av + tv : undefined;
const lens = photo.lensRange ? (photo.lensRange[0] === photo.lensRange[1] ? `${photo.lensRange[0]}mm` : `${photo.lensRange[0]}-${photo.lensRange[1]}mm`) : photo.focalLength ? `${trim(photo.focalLength)}mm` : undefined;
const maxdim = photo.width && photo.height ? Math.max(photo.width, photo.height) : undefined;
const pixels = photo.width && photo.height ? `${(photo.width * photo.height / 1e6).toFixed(1)}M` : undefined;
const ppi = photo.resolution;
// name → [value, ...aliases]
const table: [string, string | readonly string[] | undefined, ...string[]][] = [
// Camera or image-specific
["actuations", s(photo.shutterCount), "act"],
["aperture", s(photo.aperture ? trim(photo.aperture) : undefined), "f"],
["artist", s(photo.artist)],
["aspect", s(aspect(photo.width, photo.height)), "aspt"],
["aspectcrop", s(aspect(photo.width, photo.height)), "aspc"],
["av", s(av === undefined ? undefined : trim(av))],
["brightness", "", "brit", "bv"],
["bytes", s(photo.width && photo.height ? photo.width * photo.height * 3 : undefined), "byte"],
["colormode", s(photo.colorSpace), "cmod"],
["colorclass", s(photo.colorClassName), "color", "colr"],
["colorclasscolor", "", "clrc"],
["colorclassval", s(photo.colorClass), "colorval", "clrv"],
["comment", s(photo.userComment), "cmnt"],
["comp", s(ev(photo.exposureCompensation))],
["corrupt", "", "crpt"],
["cropheight", s(photo.height), "yc"],
["cropwidth", s(photo.width), "xc"],
["description", s(photo.imageDescription)],
["ev", s(evApex === undefined ? undefined : trim(evApex))],
["ev100", s(evApex !== undefined && sv !== undefined ? trim(evApex - (sv - 5)) : undefined)],
["filename", file, "file"],
["filenamebase", base, "fbas"],
["filesize", s(bytes(photo.fileSize)), "size"],
["firmware", s(photo.firmware), "firm"],
["flash", photo.flashFired === undefined ? "" : photo.flashFired ? "Yes" : "No", "flsh"],
["flashcomp", "", "fcmp"],
["focallength", s(photo.focalLength ? trim(photo.focalLength) : undefined)],
["focusmode", s(photo.focusMode), "focus", "fmod"],
["folder", "", "fldr"],
["foldernum", "", "fldn"],
["folderpath", "", "fpth"],
["fps", ""],
["frame", s(frame), "fnum"],
["frame4", s(frame?.slice(-4).padStart(4, "0")), "fnm4"],
["gps", photo.latitude !== undefined && photo.longitude !== undefined ? "1" : "0"],
["hascrop", "False", "hc"],
["height", s(photo.height), "h", "y"],
["id", s(photo.owner)],
["iso", s(photo.iso)],
["isox", ""],
["kelvin", "", "ktmp"],
["label", s(photo.colorClassName), "labl"],
["lens", s(lens)],
["lens35", s(photo.focalLength35 ? trim(photo.focalLength35) : undefined), "35mm"],
["lenstype", s(photo.lensModel), "lt"],
["lenstypenum", "", "ltnm"],
["lightsource", "", "lsrc"],
["lock", "0"],
["make", s(photo.make)],
["maxdim", s(maxdim), "maxd"],
["mediatype", "still", "mtyp"],
["meteringmode", s(photo.meteringMode), "mmod"],
["model", s(photo.model), "modl"],
["numstars", s(photo.rating ?? 0), "num*"],
["owner", s(photo.owner), "ownr"],
["parentfolderpath", "", "pfpt"],
["path", file],
["pixels", s(pixels), "pxls"],
["prefix", base.slice(0, 3), "prfx"],
["printsize", s(ppi && photo.width && photo.height ? `${trim(photo.width / ppi)}x${trim(photo.height / ppi)}in` : undefined), "psiz"],
["printsizecms", s(ppi && photo.width && photo.height ? `${trim((photo.width / ppi) * 2.54)}x${trim((photo.height / ppi) * 2.54)}cm` : undefined), "pscm"],
["printsizeinches", s(ppi && photo.width && photo.height ? `${trim(photo.width / ppi)}x${trim(photo.height / ppi)}in` : undefined), "psin"],
["program", s(photo.exposureProgram), "mode", "prgm"],
["quality", "", "qlty"],
["rating", "*".repeat(photo.rating ?? 0), "stars", "rate"],
["resolution", s(ppi), "resolutioninches", "rsin"],
["resolutioncms", s(ppi ? trim(ppi / 2.54) : undefined), "rscm"],
["rotation", "0", "rot"],
["serialnum", s(photo.serial), "serial", "snum"],
["sharpness", "", "shrp"],
["shutter", s(shutter(photo.exposureTime)), "ss"],
["software", s(photo.software), "soft"],
["sound", "0", "snd"],
["sv", s(sv === undefined ? undefined : trim(sv))],
["tag", photo.tagged ? "1" : "0"],
["tiffcopyright", s(photo.tiffCopyright), "tifc"],
["tonecomp", "", "tone"],
["tv", s(tv === undefined ? undefined : trim(tv))],
["type", file ? file.slice(dot + 1).toUpperCase() : "", ],
["uniqueid", "", "uniq"],
["user", s(photo.owner)],
["width", s(photo.width), "w", "x"],
["whitebalance", s(photo.whiteBalance), "white", "baln"],
["whitemode", s(photo.whiteBalance ? (/auto/i.test(photo.whiteBalance) ? "AUTO" : "MANUAL") : undefined), "whim"],
// Standard IPTC fields (the photo's pad)
["alttext", iptcText("altText"), "alt"],
["alttextalt", iptcText("altText") || iptcText("headline"), "alta"],
["byline", iptcText("creator") || s(opts.user), "name", "photog", "phtg"],
["caption", iptcText("caption"), "capt"],
["captionwriter", iptcText("captionWriter"), "cwrt"],
["category", iptcText("category"), "cat"],
["city", iptcText("city")],
["citytaken", iptcText("cityTaken"), "cttk"],
["contactaddress", iptcText("creatorAddress"), "ciad"],
["contactcity", iptcText("creatorCity"), "cicy"],
["contactstate", iptcText("creatorRegion"), "cist"],
["contactzip", iptcText("creatorPostalCode"), "cizp"],
["contactcountry", iptcText("creatorCountry"), "cicn"],
["contactemail", iptcText("creatorEmail"), "ciem"],
["contactphone", iptcText("creatorPhone"), "ciph"],
["contactweb", iptcText("creatorUrl"), "ciwb"],
["copyright", iptcText("copyright"), "copy"],
["copyrighturl", iptcText("copyrightUrl"), "curl"],
["country", iptcText("country"), "cnty"],
["countrytaken", iptcText("countryTaken"), "cntk"],
["countrycode", iptcText("countryCode"), "ccod"],
["countrycodetaken", iptcText("countryCodeTaken"), "cctk"],
["credit", iptcText("credit"), "cred"],
["editstatus", iptcText("editStatus"), "edit"],
["event", iptcText("event"), "evnt"],
["extendeddesc", iptcText("extendedDescription"), "extd"],
["genre", iptcText("genre"), "gene"],
["headline", iptcText("headline"), "head"],
["identity", iptcText("creatorIdentity"), "idn"],
["instructions", iptcText("instructions"), "inst"],
["imagesupplierid", iptcText("imageSupplierId"), "isid"],
["imagesupplierimageid", iptcText("imageSupplierImageId"), "isii"],
["imagesuppliername", iptcText("imageSupplierName"), "isnm"],
["keywords", iptcText("keywords"), "keyw"],
["location", iptcText("location"), "loc"],
["locationtaken", iptcText("locationTaken"), "lctk"],
["locationidtaken", "", "litk"],
["mining", ""],
["modelages", iptcText("modelAges"), "moda"],
["modelinfo", iptcText("modelInfo"), "modi"],
["modelreleaseid", iptcText("modelReleaseId"), "mrid"],
["object", iptcText("title"), "objt", "slug"],
["persons", iptcText("personsShown"), "prsn"],
["province", iptcText("state"), "prov", "state", "stat"],
["scene", iptcText("scene"), "scen"],
["source", iptcText("source"), "srce"],
["sourcetype", iptcText("digitalSourceType"), "srct"],
["statetaken", iptcText("stateTaken"), "sttk"],
["subject", iptcText("subjectCode"), "subj"],
["suppcat1", s((iptc.supplementalCategories as readonly string[] | undefined)?.[0]), "sup1"],
["suppcat2", s((iptc.supplementalCategories as readonly string[] | undefined)?.[1]), "sup2"],
["suppcat3", s((iptc.supplementalCategories as readonly string[] | undefined)?.[2]), "sup3"],
["title", iptcText("jobTitle"), "titl"],
["transref", iptcText("transmissionReference"), "tref"],
["urgency", iptcText("urgency"), "urgc"],
["usage", iptcText("usageTerms"), "usag"],
["worldregiontaken", iptcText("worldRegionTaken"), "wrtk"],
// ICC profile
["gamma", "", "gama"],
["icc", s(photo.iccProfile)],
...(["prrx", "prry", "prgx", "prgy", "prbx", "prby", "wpx", "wpy"].map((k) => [k, ""] as [string, string])),
// Special
["index", s(photo.sequence), "indx"],
["ingestseq", s(photo.sequence), "iseq"],
["nl", "\n"],
["page", "1"],
["pagecount", "1"],
["rand3", String(Math.floor(Math.random() * 1000)).padStart(3, "0")],
["rand4", String(Math.floor(Math.random() * 10000)).padStart(4, "0")],
["rand10", String(1 + Math.floor(Math.random() * 10)).padStart(2, "0")],
["rand100", String(1 + Math.floor(Math.random() * 100)).padStart(3, "0")],
["rand1000", String(1 + Math.floor(Math.random() * 1000)).padStart(4, "0")],
["sequence", s(photo.sequence), "seqn", "auto"],
["tab", "\t"],
["total", s(photo.total), "totl"],
// GPS
["altitude", s(photo.altitude === undefined ? undefined : trim(photo.altitude)), "galt"],
["bearingfrom", "", "bfrm"],
["bearingto", "", "brto"],
["distance", "", "dist"],
["gpsdate", "", "gdat"],
["gpsdatum", "", "gdtm"],
["gpsdif", "", "gdif"],
["gpsdir", "", "gdir"],
["gpddirref", "", "gdrf"],
["gpsdop", "", "gdop"],
["gpsmode", "", "gmod"],
["gpsstatus", "", "gsta"],
["gpstime", "", "gtim"],
["gpsversion", "", "gver"],
["latitude", s(photo.latitude === undefined ? undefined : photo.latitude.toFixed(6)), "glat"],
["longitude", s(photo.longitude === undefined ? undefined : photo.longitude.toFixed(6)), "glon"],
["satellites", "", "gsat"],
["speed", "", "gspd"],
["track", "", "gtrk"],
["trackref", "", "gtrf"],
// User and client
["jobname", "", "job"],
["username", s(opts.user), "urna"],
...(
[
["usercompany", "urco"],
["useraddress", "ura1"],
["useraddress2", "ura2"],
["usercity", "urcy"],
["userstate", "urst"],
["userzip", "urzip"],
["usercountry", "urcn"],
["userphone", "urph"],
["usermobile", "urmb"],
["userweb", "urwb"],
["useremail", "urem"],
["usercustom1", "urc1"],
["usercustom2", "urc2"],
["usercustom3", "urc3"],
["clientname", "clna"],
["clientcompany", "clco"],
["clientaddress", "cla1"],
["clientaddress2", "cla2"],
["clientcity", "clcy"],
["clientstate", "clst"],
["clientzip", "clzip"],
["clientcountry", "uscn"],
["clientphone", "clph"],
["clientmobile", "clmb"],
["clientweb", "clwb"],
["clientemail", "clem"],
["clientcustom1", "clc1"],
["clientcustom2", "clc2"],
["clientcustom3", "clc3"],
// Nikon Picture Control, Getty
["pcnm"],
["pcad"],
["pcqa"],
["pcsh"],
["pccn"],
["pcbr"],
["pcsa"],
["pchu"],
["pcfe"],
["pcte"],
["pcts"],
["callforimage", "gcfi"],
["composition", "gcmp"],
["exclusivecov", "gexc"],
["imagerank", "grnk"],
["personality", "gprs"],
["routingdest", "grtd"],
["routingexcl", "gexl"],
] as string[][]
).map(([k, ...aliases]) => [k!, "", ...aliases] as [string, string, ...string[]]),
];
const out: Record<string, string | readonly string[] | undefined> = {};
for (const [name, value, ...aliases] of table) for (const key of [name, ...aliases]) out[key] = value;
// Dates: the capture (or, without one, the given day), the IPTC Date Created, now, and the file's arrival.
const d = dateVars(w);
const aliases: Record<string, string[]> = {
date: ["shot"],
datemil: ["datm"],
datesort: ["dats"],
datesortdash: ["dtsd"],
hour0: ["hr0"],
hour24: ["h24"],
minute: ["min"],
month: ["mn"],
month0: ["mn0"],
monthname: ["mnn"],
monthname3: ["mnn3"],
monthnameap: ["mnap"],
second: ["sec"],
subsecond: ["ssec"],
timesort: ["tims"],
timesortdash: ["tmsd"],
timesortlong: ["tmsl"],
year2: ["yr2"],
year4: ["yr4"],
};
for (const [k, v] of Object.entries(d)) for (const key of [k, ...(aliases[k] ?? [])]) out[key] = v ?? "";
if (!capture) for (const k of ["time", "timesort", "timesortdash", "timesortlong", "hour", "hour0", "hour24", "minute", "second", "subsecond", "ampm", "tims", "tmsd", "tmsl", "hr0", "h24", "min", "sec", "ssec"]) out[k] = undefined;
const id = iptcDateVars(w);
const iptcAliases: Record<string, string[]> = {
iptcampm: ["iap"],
iptcdate: ["idat"],
iptcday: ["iday"],
iptcday0: ["idy0"],
iptcdow: ["idow"],
iptcdow3: ["idw3"],
iptchour: ["ihr"],
iptchour0: ["ihr0"],
iptchour24: ["ih24"],
iptcminute: ["imin"],
iptcmonth: ["imn"],
iptcmonth0: ["imn0"],
iptcmonthname: ["imnn"],
iptcsecond: ["isec"],
iptctime: ["itim"],
iptcyear2: ["iyr2"],
iptcyear4: ["iyr4"],
wiredate: ["wdat"],
};
for (const [k, v] of Object.entries(id)) for (const key of [k, ...(iptcAliases[k] ?? [])]) out[key] = v ?? "";
const n = nowVars(now);
const nowAliases: Record<string, string[]> = {
nowampm: ["nap"],
nowhour: ["nhr"],
nowhour0: ["nhr0"],
nowhour24: ["nh24"],
nowminute: ["nmin"],
nowsecond: ["nsec"],
nowsort: ["nows"],
nowsortlong: ["nwsl"],
nowsubsecond: ["nsub"],
today: ["tday"],
todayday: ["tdy"],
todayday0: ["tdy0"],
todaydow: ["tdow"],
todaydow3: ["tdw3"],
todaymil: ["tdym"],
todaymonth: ["tmn"],
todaymonth0: ["tmn0"],
todaymonthname: ["tmnn"],
todaymonthname3: ["tmn3"],
todaymonthnameap: ["tmap"],
todaysort: ["tdys"],
todayyear2: ["tyr2"],
todayyear4: ["tyr4"],
tomorrow: ["tmrw"],
yesterday: ["ystd"],
};
for (const [k, v] of Object.entries(n)) for (const key of [k, ...(nowAliases[k] ?? [])]) out[key] = v ?? "";
const m = mod ? { moddate: shortDate(mod), modtime: `${mod.hh}:${mod.mm}:${mod.ss}`, moddatesort: `${mod.y}${mod.m}${mod.d}`, modtimesort: `${mod.hh}${mod.mm}${mod.ss}` } : { moddate: "", modtime: "", moddatesort: "", modtimesort: "" };
const modAliases: Record<string, string> = { moddate: "mdat", modtime: "mtim", moddatesort: "mdts", modtimesort: "mtms" };
for (const [k, v] of Object.entries(m)) out[k] = out[modAliases[k]!] = v;
return out;
}
/** Every Photo Mechanic variable name (and short name) this module knows. */
export const PM_VARIABLE_NAMES: ReadonlySet<string> = new Set(Object.keys(pmVars({ capturedAt: new Date(0) })));
+96 -19
View File
@@ -1,12 +1,17 @@
/**
* `{variable}` templates, in the spirit of Photo Mechanic variables.
* `{variable}` templates, with Photo Mechanic's syntax, so a template typed there works here as it is.
*
* Syntax: `{name}` or `{name:modifier}`; modifiers chain with `:` (`{home:upper}`).
* - `upper`, `lower`: change case (pt-PT rules).
* - `pad3` (any digit count): left-pad a number with zeros.
* - `first`: first word only.
* `{{` and `}}` produce literal braces. Unknown variables are left in place and reported,
* so a typo is visible in the output instead of silently disappearing (or dropped, with `missing: "drop"`).
* Syntax: `{name}` or `{name:modifiers}`. Names are matched without regard to case (`{IptcDate}` is `{iptcdate}`).
* Photo Mechanic's modifiers (docs.camerabits.com, "Variable Substring Extraction"):
* - `{name:index,count}` / `{name:index}`: a substring. Index 0 keeps everything, 1 skips the first character, a
* negative index counts from the end; a negative count trims that many characters from the end
* (`{filenamebase:-4}` → "1234", `{filename:0,-4}` → "DSC_1234").
* - `lc`, `UC`, `PC`: lower, upper, Proper case (`{caption:0:lc}`).
* - `tr:find/repl`: replace every `find` with `repl`, last in the chain (`{caption:0:lc:tr: /\_}`); `\/` is a
* slash and `\\` a backslash.
* PhotoReport's own, kept: `upper`, `lower`, `first` (first word), `padN` (left-pad with zeros: `{n:pad3}`).
* `{{` and `}}` produce literal braces. Unknown or empty variables are left in place and reported, so a typo is
* visible in the output instead of silently disappearing (or dropped, with `missing: "drop"`).
*/
export type TemplateVars = Readonly<Record<string, string | number | readonly string[] | undefined>>;
@@ -17,20 +22,80 @@ export interface RenderResult {
missing: string[];
}
const TOKEN = /\{\{|\}\}|\{([a-zA-Z][a-zA-Z0-9_]*)((?::[a-zA-Z0-9]+)*)\}/g;
const TOKEN = /\{\{|\}\}|\{([a-zA-Z][a-zA-Z0-9_*]*)((?::[^{}]*)?)\}/g;
function stringify(value: string | number | readonly string[]): string {
if (Array.isArray(value)) return value.join(", ");
return String(value);
}
function applyModifier(value: string, modifier: string): string {
if (modifier === "upper") return value.toLocaleUpperCase("pt-PT");
if (modifier === "lower") return value.toLocaleLowerCase("pt-PT");
if (modifier === "first") return value.trim().split(/\s+/)[0] ?? "";
const pad = /^pad(\d)$/.exec(modifier);
if (pad) return value.padStart(Number(pad[1]), "0");
throw new Error(`unknown template modifier: ${modifier}`);
const properCase = (value: string) =>
value.toLocaleLowerCase("pt-PT").replace(/(^|\s)(\S)/gu, (_, space: string, c: string) => space + c.toLocaleUpperCase("pt-PT"));
/** Photo Mechanic's substring: index (negative from the end), count (negative trims the end). */
function substring(value: string, index: number, count: number | undefined): string {
const chars = [...value];
const start = index < 0 ? Math.max(0, chars.length + index) : Math.min(index, chars.length);
const end = count === undefined ? chars.length : count < 0 ? Math.max(start, chars.length + count) : Math.min(chars.length, start + count);
return chars.slice(start, end).join("");
}
/** `find/repl` with `\/` and `\\` escapes. */
function translate(value: string, spec: string): string {
let find = "";
let repl = "";
let into: "find" | "repl" = "find";
for (let i = 0; i < spec.length; i++) {
let c = spec[i]!;
if (c === "\\" && (spec[i + 1] === "/" || spec[i + 1] === "\\")) c = spec[++i]!;
else if (c === "/" && into === "find") {
into = "repl";
continue;
}
if (into === "find") find += c;
else repl += c;
}
return find ? value.split(find).join(repl) : value;
}
function applyModifiers(value: string, mods: string): string {
if (!mods) return value;
const parts = mods.slice(1).split(":");
for (let i = 0; i < parts.length; i++) {
const mod = parts[i]!;
if (mod === "tr") return translate(value, parts.slice(i + 1).join(":"));
const sub = /^(-?\d+)(?:,(-?\d+))?$/.exec(mod.trim());
if (sub) value = substring(value, Number(sub[1]), sub[2] === undefined ? undefined : Number(sub[2]));
else if (mod === "UC" || mod === "upper") value = value.toLocaleUpperCase("pt-PT");
else if (mod === "lc" || mod === "lower") value = value.toLocaleLowerCase("pt-PT");
else if (mod === "PC") value = properCase(value);
else if (mod === "first") value = value.trim().split(/\s+/)[0] ?? "";
else if (/^pad\d$/.test(mod)) value = value.padStart(Number(mod.slice(3)), "0");
else throw new Error(`unknown template modifier: ${mod}`);
}
return value;
}
const lowered = new WeakMap<object, Map<string, string>>();
/** A variable's value; the name's case does not matter (Photo Mechanic's are lower case, ours camelCase). */
export function lookup(vars: TemplateVars, name: string): TemplateVars[string] {
if (name in vars) return vars[name];
let index = lowered.get(vars);
if (!index) {
index = new Map();
for (const key of Object.keys(vars)) if (!index.has(key.toLowerCase())) index.set(key.toLowerCase(), key);
lowered.set(vars, index);
}
const key = index.get(name.toLowerCase());
return key === undefined ? undefined : vars[key];
}
/** Whether a template names a variable that exists (with any case). */
export function hasVariable(vars: TemplateVars, name: string): boolean {
if (name in vars) return true;
const lower = name.toLowerCase();
return Object.keys(vars).some((k) => k.toLowerCase() === lower);
}
export interface RenderOptions {
@@ -43,14 +108,12 @@ export function render(template: string, vars: TemplateVars, options: RenderOpti
const text = template.replace(TOKEN, (match, name: string | undefined, mods: string | undefined) => {
if (match === "{{") return "{";
if (match === "}}") return "}";
const raw = name === undefined ? undefined : vars[name];
const raw = name === undefined ? undefined : lookup(vars, name);
if (raw === undefined || (Array.isArray(raw) && raw.length === 0) || raw === "") {
missing.add(name ?? "");
return options.missing === "drop" ? "" : match;
}
let value = stringify(raw);
for (const mod of (mods ?? "").split(":").filter(Boolean)) value = applyModifier(value, mod);
return value;
return applyModifiers(stringify(raw), mods ?? "");
});
return { text, missing: [...missing] };
}
@@ -61,3 +124,17 @@ export function variablesIn(template: string): string[] {
for (const m of template.matchAll(TOKEN)) if (m[1]) out.add(m[1]);
return [...out];
}
/** Modifiers a template uses that are not valid (reported when a template is saved). */
export function badModifiers(template: string): string[] {
const bad: string[] = [];
for (const m of template.matchAll(TOKEN)) {
if (!m[1] || !m[2]) continue;
try {
applyModifiers("x", m[2]);
} catch {
bad.push(m[0]);
}
}
return bad;
}
+40 -53
View File
@@ -1,3 +1,4 @@
import { type PmIptc, type PmPhoto, pmVars } from "./pmvars.js";
import type { TemplateVars } from "./template.js";
/** What an event knows about itself; filled by an admin or editor when the event is created. */
@@ -18,16 +19,22 @@ export interface EventInfo {
startsAt: Date;
}
export interface PhotoInfo {
capturedAt?: Date | undefined;
/** The photo: its camera's EXIF and file (Photo Mechanic's camera variables), the people in it, its place in a batch. */
export interface PhotoInfo extends PmPhoto {
/** Names of the people in the photo, from identification or typed by an editor. */
players?: readonly string[] | undefined;
/** Position in the delivery, starting at 1. */
sequence?: number | undefined;
/** Same as `model` and `serial` (older callers). */
cameraModel?: string | undefined;
cameraSerial?: string | undefined;
}
export interface VarsOptions {
/** The IPTC of the photo, by IptcValues keys: Photo Mechanic's {caption}, {headline}, {event}... */
iptc?: PmIptc | undefined;
/** "Now" for {today}, {now}... (tests). */
now?: Date | undefined;
}
const TIME_ZONE = "Europe/Lisbon";
function parts(date: Date): { y: string; m: string; d: string; hh: string; mm: string; ss: string; cs: string } {
@@ -60,40 +67,58 @@ export function eventName(event: { home: string; away: string | null }): string
return event.away ? `${event.home} x ${event.away}` : event.home;
}
/** The variables available to every template (IPTC, folders, file names). */
export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?: string): TemplateVars {
/**
* The variables available to every template (IPTC, folders, file names): every Photo Mechanic variable (see
* pmvars.ts) plus PhotoReport's own (the event's teams, competition, season, the photographer). Where both name
* the same thing Photo Mechanic's meaning wins: {event}, {city} and {location} are the photo's IPTC when it has
* them, else the event's ("Home x Away", its city, its venue); {date} is the capture's day (the event's without
* a capture time), as Photo Mechanic's.
*/
export function buildVars(event: EventInfo, photo: PhotoInfo = {}, photographer?: string, options: VarsOptions = {}): TemplateVars {
const day = parts(event.startsAt);
const season = seasonOf(event.startsAt);
const shot = photo.capturedAt ? parts(photo.capturedAt) : undefined;
return {
const iptc = options.iptc ?? {};
const pm = pmVars(
{ ...photo, model: photo.model ?? photo.cameraModel, serial: photo.serial ?? photo.cameraSerial },
iptc,
{ now: options.now, fallbackDay: event.startsAt, user: photographer },
);
const text = (k: string) => {
const v = iptc[k];
return typeof v === "string" && v.trim() ? v : undefined;
};
const own: Record<string, string | number | readonly string[] | undefined> = {
home: event.home,
away: event.away,
/** "Home x Away", like the Event field in Photo Mechanic's templates; the name alone when it is not a match. */
event: eventName(event),
event: text("event") ?? eventName(event),
city: text("city") ?? event.city,
location: text("location") ?? event.venue,
homeShort: event.homeShort ?? event.home,
awayShort: event.awayShort ?? event.away,
venue: event.venue,
city: event.city,
competition: event.competition,
competitionCode: event.competitionCode,
round: event.round,
matchNumber: event.matchNumber,
sport: event.sport,
date: `${day.d}/${day.m}/${day.y}`,
dateIso: `${day.y}-${day.m}-${day.d}`,
dateCompact: `${day.y}${day.m}${day.d}`,
season: `${season.start}_${season.end}`,
seasonSlash: `${season.start}/${season.end}`,
seasonShort: `${String(season.start).slice(2)}-${String(season.end).slice(2)}`,
time: shot ? `${shot.hh}:${shot.mm}:${shot.ss}` : undefined,
players: photo.players && photo.players.length ? photo.players : undefined,
n: photo.sequence,
photographer,
initials: photographer ? initialsOf(photographer) : undefined,
camera: photo.cameraModel,
serial: photo.cameraSerial,
...photoMechanicDates(photo.capturedAt ?? event.startsAt, photo.capturedAt),
camera: photo.model ?? photo.cameraModel,
};
const out: Record<string, string | number | readonly string[] | undefined> = { ...pm };
for (const [k, v] of Object.entries(own)) if (v !== undefined && v !== "") out[k] = v;
else if (!(k in out) || out[k] === "") out[k] = v;
// Photo Mechanic's {persons} from the identified players when the IPTC has none yet.
if (!out.persons && own.players) out.persons = out.prsn = own.players;
return out;
}
/** Capture time in Lisbon wall-clock time with its offset, for IPTC DateCreated/TimeCreated. */
@@ -113,41 +138,3 @@ const initialsOf = (name: string) =>
.filter(Boolean)
.map((w) => w[0]!.toUpperCase())
.join("");
/**
* Photo Mechanic's names for the capture date and time, so its upload paths and rename templates work as typed
* there: `/fotografia/{iptcyear4}.{iptcmonth0}.{iptcday0} {event}`, `PS_{event}_{timesort}`. The date is the
* capture's (IPTC Date Created), in Lisbon time; without a capture time, the event's day.
*/
function photoMechanicDates(day: Date, shot: Date | undefined): Record<string, string | undefined> {
const p = parts(day);
const t = shot ? parts(shot) : undefined;
const date = {
year4: p.y,
year2: p.y.slice(2),
month0: p.m,
month: String(Number(p.m)),
day0: p.d,
day: String(Number(p.d)),
datesort: `${p.y}${p.m}${p.d}`,
};
return {
...date,
iptcyear4: date.year4,
iptcyear2: date.year2,
iptcmonth0: date.month0,
iptcmonth: date.month,
iptcday0: date.day0,
iptcday: date.day,
hour: t?.hh,
minute: t?.mm,
second: t?.ss,
/** hhmmss plus hundredths: sorts in shooting order and tells burst frames apart. */
timesort: t ? `${t.hh}${t.mm}${t.ss}${t.cs}` : undefined,
/** The day it is sent (Lisbon), as Photo Mechanic's {todaysort}. */
todaysort: (() => {
const n = parts(new Date());
return `${n.y}${n.m}${n.d}`;
})(),
};
}
+29 -6
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, CloudFolderSummary, CloudSource, InvoiceSummary, AutopilotStyle, DeliveryTarget, DeliveryTargetInput, JerseySample, JerseyStats, PersonSummary, PhotoFace, PhotoLookup, ShopSettings, SquadPerson, DeviceGrant, FtpAccount, FtpPlan, EventInput, EventSquads, EventSummary, IptcIssue, SportsCompetition, SportsFixture, SportsPlayer, SportsTeam, Me, Member, PhotoQuery, Role, ZerozeroGame } from "./types.js";
import type { AgendaEntry, ArchiveStorage, 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";
/**
* Where the refresh token lives. The web app leaves it in an httpOnly cookie (no store); the desktop app keeps it
@@ -247,8 +247,8 @@ export class ApiClient {
// ---- library ---------------------------------------------------------------------------------------
listEvents(orgId: string, opts: { includeArchived?: boolean } = {}) {
const q = opts.includeArchived ? "?includeArchived=true" : "";
listEvents(orgId: string, opts: { includeArchived?: boolean; archived?: boolean } = {}) {
const q = opts.archived ? "?archived=true" : opts.includeArchived ? "?includeArchived=true" : "";
return this.request<{ events: EventSummary[]; inboxCount: number }>("GET", `/v1/orgs/${orgId}/events${q}`);
}
@@ -260,6 +260,21 @@ export class ApiClient {
return this.request<EventSummary>("PATCH", `/v1/events/${eventId}`, input);
}
/** Deletes the event; its photos go back to "Sem evento". */
deleteEvent(eventId: string) {
return this.request<{ deleted: string; photos: number }>("DELETE", `/v1/events/${eventId}`);
}
/** The FTP logins one may point at this event, and where each sends its photos now. */
ftpTargets(eventId: string) {
return this.request<{ accounts: FtpTargetAccount[] }>("GET", `/v1/events/${eventId}/ftp-target`);
}
/** "Receber FTP aqui": these logins send everything to this event until `until` (null: until switched off). */
setFtpTarget(eventId: string, input: { accountIds: string[]; until?: string | null }) {
return this.request<EventSummary>("PUT", `/v1/events/${eventId}/ftp-target`, input);
}
// ---- sports data ----------------------------------------------------------------------------------------
sportsCompetitions() {
@@ -670,7 +685,7 @@ export class ApiClient {
// ---- faces ------------------------------------------------------------------------------------------
faceGroups(eventId: string) {
return this.request<{ groups: FaceGroupSummary[]; pending: number; unclear: number }>("GET", `/v1/events/${eventId}/face-groups`);
return this.request<{ groups: FaceGroupSummary[]; pending: number; unclear: number; available?: boolean }>("GET", `/v1/events/${eventId}/face-groups`);
}
confirmFaceGroup(groupId: string, who: ConfirmFaceGroup) {
@@ -752,7 +767,7 @@ export class ApiClient {
return this.request<CloudSource>("POST", `/v1/cloud-sources/${sourceId}/login`);
}
updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean }) {
updateCloudSource(sourceId: string, input: { name?: string; rootPath?: string; paused?: boolean; look?: "liga" | "fpa" | null }) {
return this.request<CloudSource>("PATCH", `/v1/cloud-sources/${sourceId}`, input);
}
@@ -760,11 +775,19 @@ export class ApiClient {
return this.request<CloudSource>("POST", `/v1/cloud-sources/${sourceId}/scan`);
}
/** Checks the cloud's galleries again now (official games by default, everything with `all`) and says what changed. */
rematchCloudSource(sourceId: string, all = false) {
return this.request<{ checked: number; moved: number; changes: { path: string; from: string | null; to: string | null }[]; errors: { path: string; error: string }[] }>(
"POST",
`/v1/cloud-sources/${sourceId}/rematch${all ? "?all=1" : ""}`,
);
}
deleteCloudSource(sourceId: string) {
return this.request<void>("DELETE", `/v1/cloud-sources/${sourceId}`);
}
listCloudFolders(sourceId: string, query: { state?: "all" | "games" | "unmatched" | "folders"; q?: string; limit?: number } = {}) {
listCloudFolders(sourceId: string, query: { state?: "all" | "games" | "named" | "events" | "unmatched" | "folders"; q?: string; limit?: number } = {}) {
const qs = new URLSearchParams(Object.entries(query).filter(([, v]) => v !== undefined && v !== "").map(([k, v]) => [k, String(v)]));
return this.request<{ folders: CloudFolderSummary[] }>("GET", `/v1/cloud-sources/${sourceId}/folders${qs.size ? `?${qs}` : ""}`);
}
+32
View File
@@ -72,6 +72,22 @@ export interface EventSummary {
fixtureId?: string | null;
homeTeamId?: string | null;
awayTeamId?: string | null;
/** A game the archive made from a cloud folder (cannot be deleted from the library). */
fromArchive?: boolean;
/** FTP logins sending everything here now ("Receber FTP aqui"). */
ftpTargets?: { accountId: string; login: string; user: { id: string; name: string }; until: string | null }[];
}
/** An FTP login, as the "Receber FTP aqui" choice shows it. */
export interface FtpTargetAccount {
id: string;
login: string;
user: { id: string; name: string };
/** Sending to this event now. */
here: boolean;
/** Sending to another event now. */
elsewhere: { id: string; title: string } | null;
until: string | null;
}
/** An entry of the person's own agenda (their calendar), with what the new-event form fills from it. */
@@ -225,6 +241,14 @@ export interface DeliveryTarget {
dpi?: number;
keepExif?: boolean;
srgb?: boolean;
/** The originals as they arrived (metadata written in, renamed), not resized JPEGs: one's own backup. */
originals?: boolean;
/** Everything that arrives is sent here on its own. */
onArrival?: boolean;
/** With onArrival: only these FTP logins' photos (ids; empty: everyone's). */
arrivalLogins?: string[];
/** With originals: the file exactly as it arrived (no metadata written, the camera's name). */
untouched?: boolean;
username: string;
folderTemplate: string;
fileNameTemplate: string;
@@ -284,6 +308,10 @@ export interface DeliveryTargetInput {
dpi?: number;
keepExif?: boolean;
srgb?: boolean;
originals?: boolean;
onArrival?: boolean;
arrivalLogins?: string[];
untouched?: boolean;
}
export interface PersonSummary {
@@ -376,6 +404,8 @@ export interface CloudSourceCounts {
named: number;
/** Folders that are not games (events, ceremonies…). */
unmatched: number;
/** Images indexed per hour lately (the last 15 minutes); 0 when none. */
perHour?: number;
}
/** A Nextcloud folder indexed into the archive. */
@@ -384,6 +414,8 @@ export interface CloudSource {
name: string;
baseUrl: string;
rootPath: string;
/** How the archive's site looks: Liga Portugal's or FPA's colours and type, or PhotoReport's (null). */
look?: "liga" | "fpa" | null;
/** The cloud account (once authorised). */
account: string | null;
status: "LOGIN" | "READY" | "SCANNING" | "ERROR" | "PAUSED";
+24
View File
@@ -223,6 +223,15 @@ importers:
'@fontsource/barlow-condensed':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/bebas-neue':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/open-sans':
specifier: ^5.3.0
version: 5.3.0
'@fontsource/source-sans-3':
specifier: ^5.3.1
version: 5.3.1
'@fontsource/space-mono':
specifier: ^5.3.0
version: 5.3.0
@@ -627,6 +636,15 @@ packages:
'@fontsource/[email protected]':
resolution: {integrity: sha512-tGR0y6QObRtKv71MOth44222+mdNFM/ZWFWDV1VLzNbG4oK9PNRlyJzmkck4vHAi9ibHBXgt4SlY51amFP55CA==}
'@fontsource/[email protected]':
resolution: {integrity: sha512-nCxMEb9Bg9sjNWm9TIOsvHKDMLRUfEZPWpLgYu6m9KavZZVSA/WoHzI5wROwqA+eNwEi/PNBAcB5Co7HA3S0Cw==}
'@fontsource/[email protected]':
resolution: {integrity: sha512-V1bdMlGNyZrJwzrdusshMOw2YR0aqYDL7kOo9dkxUEKl8dFv66A9HLckOOXl572sG/7ohhDQrCrTFGSn9LZcSw==}
'@fontsource/[email protected]':
resolution: {integrity: sha512-O3YxvbotUOgYI2Zx0bBcEMNjnwitRf9P2+9pd54sMoux1NHrdXnMwZusw2P78lFhEzOPN4glOEQmX0ASaS68uA==}
'@fontsource/[email protected]':
resolution: {integrity: sha512-FrpBMOVWn3PRdRHlrZWC55X3kZG/2BTH7SM5ZyS/bky3iKya2BturI5lk+t0RoDQL2JyHzURsVq/EisCsxpI5A==}
@@ -3429,6 +3447,12 @@ snapshots:
'@fontsource/[email protected]': {}
'@fontsource/[email protected]': {}
'@fontsource/[email protected]': {}
'@fontsource/[email protected]': {}
'@fontsource/[email protected]': {}
'@img/[email protected]': {}