Compare commits

...
Author SHA1 Message Date
spark 10004452b4 Folder search: read faces on this computer and remember them.
ci / rust (pull_request) Failing after 39s
ci / typescript (pull_request) Failing after 7m37s
The desktop app reads the folder locally and only asks the server for a name. A photo already read is not read again. While a folder is still read on the server, face processes keep being added until the CPU is full.
2026-10-17 19:45:44 +01:00
spark 63d600f6fb Folder search: try the game first, then everyone else, on every core
ci / rust (push) Successful in 7m32s
ci / typescript (push) Failing after 9m20s
A face is named from the match when one of them matches, and only then from the rest of the organization. The scan runs one face process per spare core.
2026-10-17 19:12:34 +01:00
spark 96deacd7b6 Folder search: try the game first, then everyone else, on every core.
ci / rust (pull_request) Successful in 7m42s
ci / typescript (pull_request) Failing after 9m6s
A face is named from the match (players and officials) when one of them matches, and only then from the rest of the organization. The scan runs one face process per spare core so a full folder is read in parallel.
2026-10-17 19:11:32 +01:00
spark ad06967bdb Folder search: limit face names to the chosen game
ci / rust (push) Successful in 8m12s
ci / typescript (push) Failing after 10m43s
Name a face only among the chosen game's squad.
2026-10-17 18:53:47 +01:00
spark 404ef90a3e Folder search: name a face only from the chosen game's squad
ci / rust (pull_request) Successful in 8m5s
ci / typescript (pull_request) Failing after 10m29s
The game was already shown, but each face was compared with every person in the organization. The picker now limits that comparison to the two teams' squad for the season, which is who can be named and a much smaller search.
2026-10-17 18:53:24 +01:00
spark 333652caba Folder search, newest faces, official siglas, archive season, desktop card ingest
ci / rust (push) Successful in 7m34s
ci / typescript (push) Failing after 9m23s
Search a folder for faces and numbers, then import the selection. Also newest-first face analysis, official FPA short codes, archive season dating, and desktop card offload.
2026-10-17 18:39:07 +01:00
spark 3791af12c0 Merge branches 'task/faces-newest-first', 'task/event-official-siglas', 'task/archive-season-dating', 'task/desktop-card-ingest' and 'task/card-scan' into task/_integrate
ci / rust (pull_request) Successful in 7m39s
ci / typescript (pull_request) Failing after 9m21s
2026-10-17 18:36:02 +01:00
spark 2741de223a Faces: date the newest-first index after migrations already in production
The folder name sorted before the archive viewer migration, which is already applied. Deploy applies pending folders in name order and refuses one that lands behind a later applied migration.
2026-10-17 18:35:42 +01:00
spark 378730429d Library: search a folder for faces and shirt numbers, then import the pick
A photographer can point at any folder, read the clear faces and jersey numbers without copying the files in, filter by name, club or number, and import only the photos they choose into the open event.
2026-10-17 18:35:31 +01:00
spark 3acffbd9f6 Desktop card ingest: date by EXIF capture time, not just the file's mtime
The folder date now comes from EXIF DateTimeOriginal when it can be read — a
JPEG's own EXIF, or a RAW's paired JPEG (RAW+JPEG shooting) — so a card offloaded
days after the shoot still lands in the day it was shot. It falls back to the
file's modification time when there is no EXIF (RAW-only formats with no reader
yet, e.g. CR3), so it is never worse than before.

exif_date() added to preview.rs (follows the ExifIFD pointer to DateTimeOriginal,
same byte-walking as exif_orientation); card.rs reads it for JPEGs and for a RAW's
sibling JPEG. Still needs CI to build.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 17:28:09 +00:00
spark 128a561e1c Desktop: import a memory card into a dated folder (Photo Mechanic Cmd+Y)
A new "Cartão…" button in the library offers Photo Mechanic's card offload: it
copies (default) or moves the photos from a card/folder into a dated folder on
this computer, with a folder template ({iptcyear4}/{iptcyear4}{iptcmonth0}{iptcday0}/{type}),
RAW+JPEG handling, overwrite, and WAV/XMP sidecars. The last settings used are
remembered. Pure filesystem — nothing is sent to the server.

Safety: the default is copy. "Move" copies, verifies the copy (size and SHA-256),
and only then deletes the original; on any mismatch or error it never deletes, so
a card is never emptied of a file that did not arrive whole.

The capture day comes from the file's modification time (on a card straight from
the camera that is when the frame was shot). Exact EXIF/RAW capture time — the CR3
case — is a later refinement; the shell has no RAW decoder yet (that is the
exiv2-FFI work on the engine roadmap).

New: card.rs (card_scan/card_ingest/card_settings/card_save_settings), wired in
lib.rs, build.rs and capabilities; CardIngest.tsx dialog; chrono added for the
local date. NOT built/typechecked here (no toolchain) — needs CI. chrono is new,
so Cargo.lock must be regenerated (cargo build) if CI runs --locked.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 17:23:49 +00:00
spark f04e38c821 Archive: date a gallery by the season in its path, not the cloud's modified time
A gallery whose folder name has no date (e.g. "J6 - ALA x ASSO") was dated from
the Nextcloud folder's modified time — when it was copied to the cloud, not when
the game was played — so 2018/19 games showed as 2026. A wrong season also
misidentifies faces (it matches against the wrong season's squads).

Date priority is now: the folder name's date, then the photos' capture day (both
already tried), then the season from the path (".../FPA/Fotos/2018_2019/..." ->
a date in that season), and only as a last resort the cloud's modified time. The
"current event still fits" check also rejects an event whose season no longer
matches the path, so the next scan re-dates the galleries already mis-catalogued.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 17:07:53 +00:00
spark d337fa122d Events: one-off script to backfill short codes on existing events
Fills homeShort/awayShort on events created before the automatic fill, from the
same official FPA club list. Dry-run by default; --apply writes. Uses pg and
DATABASE_URL so it needs no build.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:58:25 +00:00
spark 411989e9a3 Events: fill team short codes from the official FPA club list
Handball fixtures carry no team abbreviations, so homeShort/awayShort were empty
and the delivery folder fell back to the full team name ("CDE Gil Eanes x CD
Feirense" instead of "GIL x CDF"). Add the federation's official "Cores, Siglas
e Nomes" short codes (Campeonato Betclic, men and women) and, when creating an
event, fill homeShort/awayShort from the club name whenever the fixture gave none.

Matching is by a normalised name (case, accents, punctuation and sponsor dashes
ignored); a club not on the list simply keeps the full name, so the fallback is
never worse than today. The list lives in one file to update once a season.

Only new events are filled here; existing events keep their current values (set
them by hand in the event settings, or ask for a one-off backfill).

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:58:25 +00:00
spark ef7be320f8 Faces: analyse the most recently shot photos first
The analysis queue was ordered oldest-first (created_at ascending), so a newly
shot or just-imported game went to the back, behind any older backlog of pending
photos, and seemed not to start until the event was boosted by hand ("Analisar
caras do jogo"). A photographer wants the game they just shot analysed now.

Order non-boosted photos newest-first (created_at DESC); a manually boosted event
still jumps ahead. The partial index is recreated to match the new order so the
claim stays index-ordered.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:56:28 +00:00
spark a1e1f69713 Archive: open each gallery by the page (#13)
ci / rust (push) Successful in 7m22s
ci / typescript (push) Failing after 9m3s
The public archive was loading every indexed photo on each click. Pages now come from the database.
2026-10-17 17:47:19 +01:00
spark 11282efa1a Archive: open each gallery by the page, with a link that survives refresh.
ci / rust (pull_request) Successful in 7m25s
ci / typescript (pull_request) Failing after 8m57s
The public archive was loading every indexed photo on each click. Pages now come from the database, and Nextcloud is only asked when someone signs in.
2026-10-17 17:46:24 +01:00
spark 2f4ef6170b Merge pull request 'Delivery: label a taken-back photo in the queue' (#12) from task/delivery-retracted-label into main
ci / rust (push) Successful in 7m58s
ci / typescript (push) Failing after 9m39s
2026-10-17 17:21:09 +01:00
spark 7968302ccc Delivery: label a taken-back photo in the queue.
ci / typescript (pull_request) Failing after 11m34s
ci / rust (pull_request) Successful in 8m23s
The new RETRACTED status has to be named in the app or the build that ships the take-back fails typecheck.
2026-10-17 17:19:01 +01:00
spark b6abdaf6a6 Merge pull request 'Autopilot: also edit and pick hand-uploaded photos' (#11) from task/autopilot-hand-uploads into main
ci / typescript (push) Failing after 5m8s
ci / rust (push) Successful in 11m53s
Autopilot: also edit and pick hand-uploaded photos
2026-10-17 17:15:10 +01:00
spark 99e43ad482 Merge pull request 'Delivery: take a photo back when it is rejected or un-picked' (#10) from task/delivery-retract-unwanted into main
ci / typescript (push) Failing after 5m15s
ci / rust (push) Successful in 13m42s
2026-10-17 17:14:54 +01:00
spark 174277868d Autopilot: also edit and pick hand-uploaded photos
ci / rust (pull_request) Successful in 13m38s
ci / typescript (pull_request) Failing after 14m8s
Autopilot skipped hand uploads (source UPLOAD) and only ran on photos that
arrived by FTP or the desktop app's ingest. A second photographer often adds
their photos by hand, and those should go through the event's autopilot too.

Now autopilot runs for every source but archive re-imports (CLOUD) when the
event has it switched on, both on arrival (ingest) and when photos join an event
(adopt). The arrival rename is unchanged — hand uploads keep their own names.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:11:40 +00:00
spark 7c67a23cb9 Delivery: take a photo back from its destinations when it is rejected or un-picked
ci / typescript (pull_request) Failing after 4m28s
ci / rust (pull_request) Successful in 13m17s
A photo could be pulled off a destination only on ZeroZero, and only when an edit
replaced it. Now a delivered photo that is rejected, or un-picked (PICK -> none),
is taken back from every destination, and an edit that moves the file to a new
folder or name removes the old one on every transport (not just ZeroZero), so no
orphan is left behind.

- Transport gains remove(remotePath); implemented for Nextcloud (WebDAV DELETE),
  SFTP, FTP and Dropbox (ZeroZero already had it). Missing-file is never an error.
- delivery_items gains a `retract` flag and a RETRACTED terminal status. A rejected
  or un-picked photo's deliveries are queued for removal (DONE/WAITING) or cancelled
  outright (QUEUED, never uploaded); the worker removes them and marks them RETRACTED.
- The flag PATCH triggers the retraction (REJECT for any, or the photos still PICK
  when they go to none, i.e. un-pick), reading the old flags first.
- deliveryState() ignores RETRACTED, so a taken-back photo reads as not delivered.

Destructive on the client's live destinations (it deletes delivered files, agency
FTP included, by request). Not run locally — no toolchain/space on this machine;
needs CI to compile and a throwaway target to try before production.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 15:15:40 +00:00
spark 3d407f5524 Merge pull request 'Ship pending library, delivery and FTP fixes' (#9) from task/ship-pending into main
ci / rust (push) Successful in 7m59s
ci / typescript (push) Successful in 10m14s
2026-10-17 16:07:24 +01:00
spark 1e2a5b482e Delivery: send the selected photos to several destinations at once
ci / rust (pull_request) Successful in 7m59s
ci / typescript (pull_request) Successful in 10m1s
The send button chose a single destination. You can now pick several (a checklist
appears when there is more than one destination) and one send queues the photos to
all of them — the same photos to the agency FTP, a ZeroZero desk and a cloud
folder in one go. "Melhores" and "Enviar de novo" follow the same set.

Each destination still goes through the existing per-target deliver() path (queued
offline when there is no network), looped over the chosen set and the results
merged, so the server and the delivery queue are unchanged.

The chosen set is remembered on every change (not only on send), so it survives
switching tabs — which also fixes the earlier "forgets the destination" bug, so
this supersedes task/library-remember-target. Older saved single-id values are
still read.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:06:47 +01:00
spark 8d12e7c995 Events: let the photographer set the short team codes used in delivery folders
Delivery folders/filenames use {homeShort}/{awayShort}, which fall back to the
full team name when the event has no short code. Short codes are only filled in
when an event is created from a fixture that carries abbreviations; an event made
by hand, or from a fixture without them, has none, so its folder gets the full
names ("CDE GIL Eanes x CD Feirense -Movit" instead of "CDE x CDF").

Add "Sigla casa"/"Sigla visitante" fields to the event settings (match events
only) so the codes can be set or corrected on any existing event; the folder
picks them up on the next delivery. The API and SDK already accept homeShort/
awayShort on updateEvent — this only wires the UI. Labels are inline for now to
avoid touching i18n.ts, which another branch is editing.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:06:47 +01:00
spark 1702c290de Local FTP: stop a stopped server's shutdown from flagging the running one as errored
On the libunftp version in use, server.listen() returns Err when the server is
shut down gracefully, and the listen task writes that into the shared last_error
asynchronously. ftp_save_settings restarts the server (stop -> sleep -> start):
start() clears last_error and brings up a new server, but the *old* listen task
then returns its expected "shutdown error" and writes it into the same shared
slot — so a perfectly running server reports `server error: shutdown error`.

Give each server instance an epoch. The listen task records its error only while
it is still the current server; stop() moves the epoch on (so the server's own
shutdown is ignored) and clears last_error, since a server stopped on purpose is
not a server in error.

No command signatures change. cargo build/clippy/test to run in CI (no Rust
toolchain on this machine).

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:06:47 +01:00
spark 03df893e34 Library: keep the grid loading reliably and never show a silent blank tile
Two causes of the "half-loaded" grid where some READY photos stay grey:

1. cachedImage fetched thumbnails with no timeout, inside a 6-slot concurrency
   limiter. A single stalled request (busy server, dropped connection) held its
   slot forever and starved every queued tile, so the rest of the grid never
   loaded. Download now runs through an AbortController that aborts after 20s,
   freeing the slot so the queue keeps moving; the stalled photo falls back to
   loading its URL directly instead of blocking the others.

2. The grid cell rendered `shown && <img>` with no onError and no fallback, so a
   pending or failed image was an indistinguishable grey blank. A READY photo
   now shows "…" while its thumbnail is still resolving and "erro" if the image
   fails to load (onError), mirroring the loupe's resilience.

UI/cache only; no API or data changes.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:06:47 +01:00
spark d756d13d69 Delivery (FPA): use short team codes in Nextcloud folder and file names
The FPA destination preset built the game folder and file name from the full
team names ({home} x {away}), e.g. "Vitória SC x AA Águas Santas". FPA expects
the short codes ("VSC x AAAS"). Switch the FPA folder and fileName templates to
{homeShort} x {awayShort}.

Safe by construction: buildVars sets homeShort/awayShort with a `?? home`
fallback, so when an event has no short code the segment is the full name (never
empty, never a missing-variable error). Liga keeps full names on purpose
("1. Casa Pia x Sporting"), so its preset is unchanged.

Test: the FPA fixture now uses distinct full names + short codes, proving the
template renders the short code rather than the full name.

Claude-Session: https://claude.ai/code/session_01RAkmwWv6L5KmpX4h9JPD2i
2026-10-17 16:06:47 +01:00
spark 53d8194cd5 Merge pull request 'Faces: a requested event jumps the analysis queue' (#8) from task/face-queue-boost into main
ci / rust (push) Successful in 7m49s
ci / typescript (push) Successful in 10m1s
Faces: a requested event jumps the analysis queue
2026-10-17 15:40:31 +01:00
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
145 changed files with 8862 additions and 928 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';
@@ -0,0 +1,5 @@
-- A delivered photo that is rejected or un-picked is taken back from the destination.
-- PostgreSQL 12+ allows ADD VALUE inside a transaction as long as the new value is not used in the same one.
ALTER TYPE "DeliveryStatus" ADD VALUE IF NOT EXISTS 'RETRACTED';
ALTER TABLE "delivery_items" ADD COLUMN "retract" BOOLEAN NOT NULL DEFAULT false;
@@ -0,0 +1,31 @@
-- Gallery pages read one folder at a time, in path order. The walk looks up children by parent.
CREATE INDEX "cloud_files_folder_id_status_path_idx" ON "cloud_files"("folder_id", "status", "path");
CREATE INDEX "cloud_folders_parent_id_idx" ON "cloud_folders"("parent_id");
-- The gallery list is "this source, folders that have photos".
CREATE INDEX "cloud_folders_source_galleries_idx" ON "cloud_folders"("source_id") WHERE "photo_count" > 0;
-- One row per sign-in. The session token carries this id, not the folder list.
CREATE TABLE "archive_grants" (
"id" UUID NOT NULL,
"source_id" UUID NOT NULL,
"viewer_name" TEXT NOT NULL,
"sees_all" BOOLEAN NOT NULL DEFAULT false,
"expires_at" TIMESTAMP(3) NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "archive_grants_pkey" PRIMARY KEY ("id")
);
CREATE TABLE "archive_grant_folders" (
"grant_id" UUID NOT NULL,
"folder_id" UUID NOT NULL,
CONSTRAINT "archive_grant_folders_pkey" PRIMARY KEY ("grant_id","folder_id")
);
CREATE INDEX "archive_grants_source_id_expires_at_idx" ON "archive_grants"("source_id", "expires_at");
CREATE INDEX "archive_grant_folders_folder_id_idx" ON "archive_grant_folders"("folder_id");
ALTER TABLE "archive_grants" ADD CONSTRAINT "archive_grants_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "archive_grant_folders" ADD CONSTRAINT "archive_grant_folders_grant_id_fkey" FOREIGN KEY ("grant_id") REFERENCES "archive_grants"("id") ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE "archive_grant_folders" ADD CONSTRAINT "archive_grant_folders_folder_id_fkey" FOREIGN KEY ("folder_id") REFERENCES "cloud_folders"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,4 @@
-- Analyse the most recently shot photos first (a just-finished game no longer waits behind an old backlog).
-- Match the claim's ORDER BY faces_boosted_at DESC NULLS LAST, created_at DESC.
DROP INDEX IF EXISTS "photos_faces_pending_idx";
CREATE INDEX "photos_faces_pending_idx" ON "photos" ("faces_boosted_at" DESC NULLS LAST, "created_at" DESC) WHERE "faces_status" = 'PENDING';
+69
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.
@@ -504,6 +518,8 @@ enum DeliveryStatus {
WAITING
DONE
FAILED
/// Taken back from the destination after the photo was rejected, un-picked, or cancelled before upload.
RETRACTED
}
/// Where a client's photos go, and how folders and files are named there (each client has its own rules).
@@ -532,6 +548,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 +582,12 @@ 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 (the old file is removed once the new one lands).
replacesPath String? @map("replaces_path")
/// Queued to be taken back from the destination (the photo was rejected or un-picked): the worker removes it.
retract Boolean @default(false)
byteSize Int? @map("byte_size")
requestedById String? @map("requested_by_id") @db.Uuid
nextAttemptAt DateTime @default(now()) @map("next_attempt_at")
@@ -1562,6 +1594,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")
@@ -1574,6 +1608,7 @@ model CloudSource {
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
folders CloudFolder[]
files CloudFile[]
grants ArchiveGrant[]
@@index([organizationId])
@@map("cloud_sources")
@@ -1594,15 +1629,19 @@ 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")
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
files CloudFile[]
grants ArchiveGrantFolder[]
@@unique([sourceId, fileId])
@@index([sourceId, path])
@@index([parentId])
@@map("cloud_folders")
}
@@ -1631,5 +1670,35 @@ model CloudFile {
@@unique([sourceId, fileId])
@@index([status, sourceId])
@@index([photoId])
@@index([folderId, status, path])
@@map("cloud_files")
}
/// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again.
/// Shares stay as they were at sign-in until the session ends.
model ArchiveGrant {
id String @id @default(uuid()) @db.Uuid
sourceId String @map("source_id") @db.Uuid
viewerName String @map("viewer_name")
seesAll Boolean @default(false) @map("sees_all")
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade)
folders ArchiveGrantFolder[]
@@index([sourceId, expiresAt])
@@map("archive_grants")
}
model ArchiveGrantFolder {
grantId String @map("grant_id") @db.Uuid
folderId String @map("folder_id") @db.Uuid
grant ArchiveGrant @relation(fields: [grantId], references: [id], onDelete: Cascade)
folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade)
@@id([grantId, folderId])
@@index([folderId])
@@map("archive_grant_folders")
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env node
/**
* One-off: fill homeShort/awayShort on existing events from the official FPA club list, for events created before
* the automatic fill (apps/api/src/sports/fpa-siglas.ts). Safe: only fills when a short code is missing; never
* overwrites one that is set, and a club not on the list is left alone.
*
* Run from apps/api where DATABASE_URL is available (dry-run first):
* node scripts/backfill-siglas.mjs # shows what it would change
* node scripts/backfill-siglas.mjs --apply # writes the changes
*
* Keep the list below in sync with src/sports/fpa-siglas.ts.
*/
import pg from "pg";
const CLUBS = [
["ABC", ["ABC de Braga", "ABC Braga"]],
["ADC", ["AD Carvalhos Sernox", "AD Carvalhos"]],
["AAAS", ["Águas Santas Milaneza", "Águas Santas", "AA Águas Santas"]],
["AAA", ["Avanca Bioria Bondalti", "Avanca"]],
["CFB", ["CF Os Belenenses", "Os Belenenses"]],
["FCP", ["FC Porto"]],
["GCST", ["GC Santo Tirso Retrotarget", "GC Santo Tirso"]],
["CSM", ["Marítimo Madeira Andebol SAD", "Marítimo Madeira"]],
["PAC", ["Póvoa AC Bodegão CCR Proteu", "Póvoa AC"]],
["SLB", ["SL Benfica"]],
["SCP", ["Sporting CP"]],
["VSC", ["Vitória SC"]],
["SPS", ["ADA São Pedro do Sul Multisac", "ADA São Pedro do Sul"]],
["ALA", ["Alavarium"]],
["CALE", ["CA Leça"]],
["CDF", ["CD Feirense Movit", "CD Feirense"]],
["GIL", ["CDE Gil Eanes"]],
["CJAG", ["CJ Almeida Garrett Gesti Douro UAE", "CJ Almeida Garrett"]],
["JUVE", ["Juve Lis"]],
["MAD", ["Madeira SAD"]],
];
const norm = (s) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
const BY_NAME = new Map();
for (const [sigla, names] of CLUBS) for (const n of names) BY_NAME.set(norm(n), sigla);
const siglaFor = (name) => (name ? BY_NAME.get(norm(name)) : undefined);
const apply = process.argv.includes("--apply");
if (!process.env.DATABASE_URL) {
console.error("DATABASE_URL não definido. Corre a partir de apps/api (ou faz `source .env`).");
process.exit(1);
}
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
try {
const { rows } = await client.query(
`SELECT id, home, away, home_short, away_short FROM events WHERE away <> '' AND (home_short IS NULL OR away_short IS NULL)`,
);
let n = 0;
for (const r of rows) {
const hs = r.home_short ?? siglaFor(r.home);
const as = r.away_short ?? siglaFor(r.away);
const changes = (!r.home_short && hs) || (!r.away_short && as);
if (!changes) continue;
n++;
console.log(`${r.home} x ${r.away} -> ${hs ?? r.home_short ?? "—"} x ${as ?? r.away_short ?? "—"}`);
if (apply) {
await client.query(`UPDATE events SET home_short = COALESCE(home_short, $1), away_short = COALESCE(away_short, $2) WHERE id = $3`, [hs ?? null, as ?? null, r.id]);
}
}
console.log(`\n${apply ? "Atualizados" : "A atualizar (dry-run)"}: ${n} evento(s).`);
} finally {
await client.end();
}
+42 -6
View File
@@ -31,8 +31,12 @@ import { DevelopService } from "./develop/service.js";
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 { faceEnginePaths } from "./lib/engines.js";
import { type FaceEngine, FaceProcess, GrowingFacePool } from "./faces/process.js";
import { faceWorkerLive } from "./faces/heartbeat.js";
import { faceEnginePaths, jerseyModelDir, scanSlots } from "./lib/engines.js";
import { modelsDir } from "./lib/models.js";
import { JerseyModel, JerseyPool } from "./jersey/model.js";
import type { JerseyReader } from "./faces/lookup.js";
import { registerJerseyRoutes } from "./jersey/routes.js";
import { JerseyService } from "./jersey/service.js";
import { registerSearchRoutes } from "./library/search.js";
@@ -73,13 +77,17 @@ 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;
/** Shirt numbers on a card scan. Tests pass a fake; otherwise the model is loaded on the first scan. */
jersey?: JerseyReader | null;
/** 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, jersey }: 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,18 +147,46 @@ 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 slots = scanSlots();
const lookupEngine = new IdleEngine(
faceEngine ? () => faceEngine : facePaths && config.NODE_ENV !== "test" ? () => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER }) : null,
faceEngine
? () => faceEngine
: facePaths && config.NODE_ENV !== "test"
? () => new GrowingFacePool(() => new FaceProcess({ bin: facePaths.bin, modelsDir: facePaths.modelsDir, embedder: config.FACES_EMBEDDER }), slots)
: null,
);
app.addHook("onClose", async () => (faceEngine ? undefined : lookupEngine.close()));
const lookup = new FaceLookup({ db, engine: () => lookupEngine.get() });
await registerLookupRoutes(app, { db, sessions, lookup, signer });
let jerseyOnce: Promise<JerseyReader | null> | null = null;
const jerseyOf = (): Promise<JerseyReader | null> => {
if (jersey !== undefined) return Promise.resolve(jersey);
if (config.NODE_ENV === "test") return Promise.resolve(null);
jerseyOnce ??= (async () => {
const dir = jerseyModelDir(config);
if (!dir) return null;
const first = await JerseyModel.load(dir).catch((err: unknown) => {
app.log.warn({ err }, "jersey model not loaded for card scan");
return null;
});
if (!first) return null;
const copies = Math.min(slots, 8);
if (copies === 1) return first;
const rest = await Promise.all(Array.from({ length: copies - 1 }, () => JerseyModel.load(dir).catch(() => null)));
const models = [first, ...rest.filter((model): model is JerseyModel => !!model)];
return models.length === 1 ? models[0]! : new JerseyPool(models);
})();
return jerseyOnce;
};
await registerLookupRoutes(app, { db, sessions, lookup, signer, jersey: jerseyOf, models: modelsDir(config.STORAGE_ROOT) });
await registerDeliveryRoutes(app, { db, sessions, secrets, delivery });
// Edits are stored and fanned out here; the worker replays and renders them.
// Corrections to the autopilot's edits teach it (autopilot/learning.ts).
+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;
}
+88 -54
View File
@@ -1,6 +1,7 @@
import type { FastifyInstance, FastifyRequest } from "fastify";
import { eventName } from "@photoreport/metadata";
import { z } from "zod";
import { Prisma } from "../generated/prisma/client.js";
import type { Db } from "../db.js";
import { boxInCrop, cropOfSettings } from "../faces/frame.js";
import { cosine, inFocus, THRESHOLDS } from "../faces/math.js";
@@ -41,14 +42,15 @@ export function faceBox(
export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: Deps) {
const { db, signer, viewerOf, visibleFolders } = deps;
/** Photos of the source the viewer may see (indexed, in a visible gallery), with their gallery. */
const visiblePhotos = async (v: Viewer): Promise<Map<string, string>> => {
/**
* Indexed files of this source the viewer may see, as a join condition on `cf`. Empty access is null, so callers
* skip the query instead of building a list of every photo id.
*/
const scopeOf = async (v: Viewer): Promise<Prisma.Sql | null> => {
const visible = await visibleFolders(v);
const rows = await db.cloudFile.findMany({
where: { sourceId: v.s, status: "DONE", photoId: { not: null }, ...(visible !== "all" && { folderId: { in: visible } }) },
select: { photoId: true, folderId: true },
});
return new Map(rows.map((r) => [r.photoId!, r.folderId]));
if (visible !== "all" && !visible.length) return null;
if (visible === "all") return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
return Prisma.sql`cf.source_id = ${v.s}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
};
const galleryInfo = async (folderIds: string[]) => {
@@ -56,19 +58,26 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
return new Map(folders.map((f) => [f.id, { id: f.id, title: f.event ? eventName(f.event) : (f.path.split("/").pop() ?? ""), startsAt: f.event?.startsAt ?? null, competition: f.event?.competition ?? null }]));
};
/** Photos (with the face found) as the pages show them, newest game first. */
const photoCards = async (hits: { photoId: string; faceId: string; level: Level; score: number | null }[], where: Map<string, string>) => {
/** Photos (with the face found) as the pages show them, newest game first. Faces of the photo load when it is opened. */
const photoCards = async (hits: { photoId: string; faceId: string; level: Level; score: number | null }[], scope: Prisma.Sql) => {
if (!hits.length) return [];
const ids = hits.map((h) => h.photoId);
const links = await db.$queryRaw<{ photo_id: string; folder_id: string }[]>`
SELECT DISTINCT ON (cf.photo_id) cf.photo_id, cf.folder_id
FROM cloud_files cf
WHERE cf.photo_id = ANY(${ids}::uuid[]) AND ${scope}
ORDER BY cf.photo_id, cf.path`;
const folderOf = new Map(links.map((r) => [r.photo_id, r.folder_id]));
const photos = await db.photo.findMany({
where: { id: { in: hits.map((h) => h.photoId) } },
where: { id: { in: ids } },
select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true, originalName: true },
});
const byId = new Map(photos.map((p) => [p.id, p]));
const faces = await db.face.findMany({ where: { id: { in: hits.map((h) => h.faceId) } }, select: { id: true, x0: true, y0: true, x1: true, y1: true } });
const faceById = new Map(faces.map((f) => [f.id, f]));
const galleries = await galleryInfo(hits.map((h) => where.get(h.photoId)!).filter(Boolean));
const facesIn = await facesOfPhotos(db, photos);
const galleries = await galleryInfo([...folderOf.values()]);
return hits
.filter((h) => byId.has(h.photoId))
.filter((h) => byId.has(h.photoId) && folderOf.has(h.photoId))
.map((h) => {
const p = byId.get(h.photoId)!;
const f = faceById.get(h.faceId);
@@ -84,8 +93,7 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
level: h.level,
score: h.score,
face: f ? faceBox(f, p) : null,
faces: facesIn.get(p.id) ?? [],
gallery: galleries.get(where.get(h.photoId)!) ?? null,
gallery: galleries.get(folderOf.get(h.photoId)!) ?? null,
};
})
.sort((a, b) => (b.gallery?.startsAt?.getTime() ?? 0) - (a.gallery?.startsAt?.getTime() ?? 0) || (a.capturedAt?.getTime() ?? 0) - (b.capturedAt?.getTime() ?? 0));
@@ -112,17 +120,17 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
const { sourceId } = SourceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const query = PeopleQuery.parse(req.query);
const where = await visiblePhotos(v);
if (!where.size) return { people: [], clubs: [] };
const photoIds = [...where.keys()];
const scope = await scopeOf(v);
if (!scope) return { people: [], clubs: [] };
const rows = await db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; reference: boolean; confirmed: bigint; probable: bigint }[]>`
SELECT p.id, p.name, p.club, p.number, p.reference_key IS NOT NULL AS reference,
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id = p.id) AS confirmed,
count(DISTINCT f.photo_id) FILTER (WHERE g.person_id IS NULL) AS probable
FROM face_groups g
JOIN faces f ON f.group_id = g.id
JOIN cloud_files cf ON cf.photo_id = f.photo_id
JOIN people p ON p.id = coalesce(g.person_id, g.suggested_person_id)
WHERE g.ignored_at IS NULL AND f.photo_id = ANY(${photoIds}::uuid[])
WHERE g.ignored_at IS NULL AND ${scope}
GROUP BY p.id`;
const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
const words = fold(query.q ?? "").split(/\s+/).filter(Boolean);
@@ -132,8 +140,10 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
const faces = noRef.length
? await db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>`
SELECT DISTINCT ON (coalesce(g.person_id, g.suggested_person_id)) coalesce(g.person_id, g.suggested_person_id) AS person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1
FROM faces f JOIN face_groups g ON g.id = f.group_id
WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND f.photo_id = ANY(${photoIds}::uuid[])
FROM faces f
JOIN face_groups g ON g.id = f.group_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id
WHERE coalesce(g.person_id, g.suggested_person_id) = ANY(${noRef}::uuid[]) AND g.ignored_at IS NULL AND ${scope}
ORDER BY coalesce(g.person_id, g.suggested_person_id), (g.person_id IS NOT NULL) DESC, f.sharpness DESC NULLS LAST, f.score DESC`
: [];
const facePhotos = await db.photo.findMany({ where: { id: { in: faces.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } });
@@ -171,28 +181,32 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
const { sourceId, personId } = PersonParams.parse(req.params);
const v = viewerOf(req, sourceId);
const query = PhotosQuery.parse(req.query);
const where = await visiblePhotos(v);
const scope = await scopeOf(v);
const person = await db.person.findFirst({ where: { id: personId, organization: { cloudSources: { some: { id: sourceId } } } } });
if (!person) throw notFound("person_not_found");
const photoIds = [...where.keys()];
const named = await db.face.findMany({
where: { photoId: { in: photoIds }, group: { ignoredAt: null, OR: [{ personId }, ...(query.level === "all" ? [{ personId: null, suggestedPersonId: personId }] : [])] } },
select: { id: true, photoId: true, sharpness: true, group: { select: { personId: true, suggestionScore: true } } },
});
const named = scope
? await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null; person_id: string | null; suggestion_score: number | null }[]>`
SELECT f.id, f.photo_id, f.sharpness, g.person_id, g.suggestion_score
FROM faces f
JOIN face_groups g ON g.id = f.group_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id
WHERE g.ignored_at IS NULL AND ${scope}
AND (g.person_id = ${personId}::uuid OR (${query.level === "all"} AND g.person_id IS NULL AND g.suggested_person_id = ${personId}::uuid))`
: [];
const hits: { photoId: string; faceId: string; level: Level; score: number | null; sharpness: number | null }[] = named.map((f) => ({
photoId: f.photoId,
photoId: f.photo_id,
faceId: f.id,
level: f.group?.personId === personId ? "confirmed" : "probable",
score: f.group?.personId === personId ? null : (f.group?.suggestionScore ?? null),
level: f.person_id === personId ? "confirmed" : "probable",
score: f.person_id === personId ? null : f.suggestion_score,
sharpness: f.sharpness,
}));
if (query.level === "all" && person.centroid.length && person.model) {
const similar = await similarGroups(person.centroid, person.model, photoIds, new Set());
if (scope && query.level === "all" && person.centroid.length && person.model) {
const similar = await similarGroups(person.centroid, person.model, scope, new Set());
const seen = new Set(hits.map((h) => h.photoId));
for (const s of similar) if (!s.personId && !seen.has(s.photoId)) hits.push({ photoId: s.photoId, faceId: s.faceId, level: "similar", score: s.score, sharpness: s.sharpness });
}
const chosen = onePerPhoto(hits).slice(0, query.limit);
const photos = await photoCards(chosen, where);
const photos = scope ? await photoCards(chosen, scope) : [];
return {
person: { id: person.id, name: person.name, club: person.club, number: person.number, reference: person.referenceKey ? signer.personUrl(person.id) : null },
counts: { confirmed: photos.filter((p) => p.level === "confirmed").length, probable: photos.filter((p) => p.level === "probable").length, similar: photos.filter((p) => p.level === "similar").length },
@@ -200,23 +214,34 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
};
});
/** Face groups (in the given photos) like a face: their faces, with how alike, most alike first. */
const similarGroups = async (embedding: number[], model: string, photoIds: string[], exclude: Set<string>) => {
/** Face groups in the viewer's galleries like a face: their faces, with how alike, most alike first. */
const similarGroups = async (embedding: number[], model: string, scope: Prisma.Sql, exclude: Set<string>) => {
const t = THRESHOLDS[model] ?? { match: 0.5 };
const eventIds = await db.photo.findMany({ where: { id: { in: photoIds } }, select: { eventId: true }, distinct: ["eventId"] });
const groups = await db.faceGroup.findMany({
where: { eventId: { in: eventIds.map((e) => e.eventId!).filter(Boolean) }, model, ignoredAt: null },
select: { id: true, centroid: true, personId: true },
});
const groups = await db.$queryRaw<{ id: string; centroid: unknown; person_id: string | null }[]>`
SELECT g.id, g.centroid, g.person_id
FROM face_groups g
WHERE g.ignored_at IS NULL AND g.model = ${model} AND cardinality(g.centroid) > 0
AND g.event_id IN (
SELECT ph.event_id FROM photos ph
JOIN cloud_files cf ON cf.photo_id = ph.id
WHERE ${scope} AND ph.event_id IS NOT NULL
)`;
const asVector = (v: unknown): number[] => (Array.isArray(v) ? v.map(Number) : typeof v === "string" ? v.replace(/[{}]/g, "").split(",").filter(Boolean).map(Number) : []);
const near = groups
.filter((g) => !exclude.has(g.id) && g.centroid.length)
.map((g) => ({ g, score: cosine(embedding, g.centroid) }))
.filter((g) => !exclude.has(g.id))
.map((g) => ({ g, vector: asVector(g.centroid) }))
.filter((x) => x.vector.length)
.map((x) => ({ g: x.g, score: cosine(embedding, x.vector) }))
.filter((x) => x.score >= t.match);
if (!near.length) return [];
const score = new Map(near.map((x) => [x.g.id, x]));
const faces = await db.face.findMany({ where: { groupId: { in: [...score.keys()] }, photoId: { in: photoIds } }, select: { id: true, photoId: true, groupId: true, sharpness: true } });
const faces = await db.$queryRaw<{ id: string; photo_id: string; group_id: string; sharpness: number | null }[]>`
SELECT f.id, f.photo_id, f.group_id, f.sharpness
FROM faces f
JOIN cloud_files cf ON cf.photo_id = f.photo_id
WHERE f.group_id = ANY(${[...score.keys()]}::uuid[]) AND ${scope}`;
return faces
.map((f) => ({ faceId: f.id, photoId: f.photoId, sharpness: f.sharpness, score: score.get(f.groupId!)!.score, personId: score.get(f.groupId!)!.g.personId }))
.map((f) => ({ faceId: f.id, photoId: f.photo_id, sharpness: f.sharpness, score: score.get(f.group_id)!.score, personId: score.get(f.group_id)!.g.person_id }))
.sort((a, b) => b.score - a.score);
};
@@ -227,32 +252,41 @@ export async function registerArchivePeopleRoutes(app: FastifyInstance, deps: De
app.get("/v1/archive/:sourceId/faces/:faceId/similar", async (req) => {
const { sourceId, faceId } = FaceParams.parse(req.params);
const v = viewerOf(req, sourceId);
const where = await visiblePhotos(v);
const scope = await scopeOf(v);
const face = await db.face.findUnique({ where: { id: faceId }, include: { group: { include: { person: true, suggested: true } } } });
if (!face || !where.has(face.photoId)) throw notFound("face_not_found");
const seen = face && scope
? await db.$queryRaw<{ ok: number }[]>`SELECT 1 AS ok FROM cloud_files cf WHERE cf.photo_id = ${face.photoId}::uuid AND ${scope} LIMIT 1`
: [];
if (!face || !scope || !seen.length) throw notFound("face_not_found");
const named = face.group?.person ?? null;
const probe = face.group?.centroid.length ? face.group.centroid : face.embedding;
const photoIds = [...where.keys()];
const hits: { photoId: string; faceId: string; level: Level; score: number | null; sharpness: number | null }[] = [];
// Its own group: the same person in the same game (certain as the grouping is).
if (face.groupId) {
const own = await db.face.findMany({ where: { groupId: face.groupId, photoId: { in: photoIds } }, select: { id: true, photoId: true, sharpness: true } });
for (const f of own) hits.push({ photoId: f.photoId, faceId: f.id, level: named ? "confirmed" : "similar", score: named ? null : 1, sharpness: f.sharpness });
const own = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null }[]>`
SELECT f.id, f.photo_id, f.sharpness FROM faces f
JOIN cloud_files cf ON cf.photo_id = f.photo_id
WHERE f.group_id = ${face.groupId}::uuid AND ${scope!}`;
for (const f of own) hits.push({ photoId: f.photo_id, faceId: f.id, level: named ? "confirmed" : "similar", score: named ? null : 1, sharpness: f.sharpness });
} else hits.push({ photoId: face.photoId, faceId: face.id, level: "similar", score: 1, sharpness: face.sharpness });
// The same named person elsewhere.
if (named) {
const more = await db.face.findMany({ where: { photoId: { in: photoIds }, group: { personId: named.id, ignoredAt: null } }, select: { id: true, photoId: true, sharpness: true } });
for (const f of more) hits.push({ photoId: f.photoId, faceId: f.id, level: "confirmed", score: null, sharpness: f.sharpness });
const more = await db.$queryRaw<{ id: string; photo_id: string; sharpness: number | null }[]>`
SELECT f.id, f.photo_id, f.sharpness FROM faces f
JOIN face_groups g ON g.id = f.group_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id
WHERE g.person_id = ${named.id}::uuid AND g.ignored_at IS NULL AND ${scope!}`;
for (const f of more) hits.push({ photoId: f.photo_id, faceId: f.id, level: "confirmed", score: null, sharpness: f.sharpness });
}
if (probe.length) {
for (const s of await similarGroups(probe, face.model, photoIds, new Set(face.groupId ? [face.groupId] : []))) {
if (probe.length && scope) {
for (const s of await similarGroups(probe, face.model, scope, new Set(face.groupId ? [face.groupId] : []))) {
if (named && s.personId === named.id) continue;
// Faces named as someone else are someone else.
if (s.personId && named) continue;
hits.push({ photoId: s.photoId, faceId: s.faceId, level: s.personId ? "confirmed" : "similar", score: s.score, sharpness: s.sharpness });
}
}
const photos = await photoCards(onePerPhoto(hits).slice(0, 400), where);
const photos = await photoCards(onePerPhoto(hits).slice(0, 400), scope!);
const suggested = !named && face.group?.suggested ? face.group.suggested : null;
return {
person: named ? { id: named.id, name: named.name, club: named.club } : 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 },
+454 -66
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, seasonOf } 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, season: game.season }, 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; season?: string | null },
day: string | null,
modified: Date | null,
current: string | null = null,
@@ -450,14 +687,29 @@ 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 && (!g.season || seasonOf(lisbonDay(e.startsAt)) === g.season) && (!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;
}
}
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 (day && !pastOrToday(day)) day = null;
// The day from the folder name, else (tried earlier) the photos' capture day; then the season from the path so
// at least the year/season is right (wrong season misidentifies faces). The cloud's modified time is only a
// last resort — it is when the folder was copied there, not when the game was played.
const startsAt = day
? new Date(`${day}T12:00:00Z`)
: g.season
? new Date(`${g.season.slice(0, 4)}-10-01T12:00:00Z`)
: (modified ?? new Date());
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 +723,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 +756,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 +852,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 +907,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 +979,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 +1051,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 +1068,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 +1129,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");
}
}
+154 -31
View File
@@ -2,14 +2,15 @@ import { createHmac, timingSafeEqual } from "node:crypto";
import type { FastifyInstance, FastifyRequest } from "fastify";
import { eventName } from "@photoreport/metadata";
import { z } from "zod";
import { Prisma } from "../generated/prisma/client.js";
import type { Db } from "../db.js";
import { NextcloudError } from "../delivery/nextcloud.js";
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 { facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import { canonicalTeam, describeFolder } from "./match.js";
import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js";
import type { ArchiveService } from "./service.js";
/**
@@ -25,10 +26,12 @@ export interface Viewer {
s: string;
/** Display name on the cloud. */
n: string;
/** Grant written at sign-in. Sessions signed before grants existed carry `all` and `f` instead. */
g?: string;
/** Sees the whole source (the account that indexes it, or a share of its root or above). */
all: boolean;
all?: boolean;
/** Archive folder ids shared with them (each with everything below). */
f: string[];
f?: string[];
exp: number;
}
@@ -58,6 +61,13 @@ export class ViewerTokens {
const SourceParams = z.object({ sourceId: z.uuid() });
const FolderParams = z.object({ folderId: z.uuid() });
const PhotoParams = z.object({ photoId: z.uuid() });
const GalleryQuery = z.object({
offset: z.coerce.number().int().min(0).default(0),
limit: z.coerce.number().int().min(1).max(60).default(48),
player: z.string().trim().max(120).optional(),
person: z.uuid().optional(),
});
const Poll = z.object({ state: z.string().min(10).max(4000) });
const ListQuery = z.object({
q: z.string().trim().max(120).optional(),
@@ -86,13 +96,24 @@ export async function registerArchiveViewerRoutes(
return v;
};
/** Ids of the gallery folders a viewer may open in a source. */
/**
* Ids of the gallery folders a viewer may open in a source. A grant is one row ("sees everything", or the shared
* folder ids); a session from before grants still carries that list in the token.
*/
const visibleFolders = async (v: Viewer): Promise<string[] | "all"> => {
if (v.all) return "all";
if (!v.f.length) return [];
let all = !!v.all;
let roots = v.f ?? [];
if (v.g) {
const grant = await db.archiveGrant.findUnique({ where: { id: v.g }, include: { folders: { select: { folderId: true } } } });
if (!grant || grant.sourceId !== v.s || grant.expiresAt.getTime() <= Date.now()) throw unauthorized("archive_login_required");
all = grant.seesAll;
roots = grant.folders.map((f) => f.folderId);
}
if (all) return "all";
if (!roots.length) return [];
const rows = await db.$queryRaw<{ id: string }[]>`
WITH RECURSIVE tree AS (
SELECT id FROM cloud_folders WHERE source_id = ${v.s}::uuid AND id = ANY(${v.f}::uuid[])
SELECT id FROM cloud_folders WHERE source_id = ${v.s}::uuid AND id = ANY(${roots}::uuid[])
UNION
SELECT c.id FROM cloud_folders c JOIN tree t ON c.parent_id = t.id
)
@@ -100,6 +121,12 @@ export async function registerArchiveViewerRoutes(
return rows.map((r) => r.id);
};
/** Indexed files of this source the viewer may see. Joined in later queries; never a list of photo ids. */
const fileScope = (sourceId: string, visible: string[] | "all"): Prisma.Sql => {
if (visible === "all") return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL`;
return Prisma.sql`cf.source_id = ${sourceId}::uuid AND cf.status = 'DONE' AND cf.photo_id IS NOT NULL AND cf.folder_id = ANY(${visible}::uuid[])`;
};
const folderWhere = (v: Viewer, visible: string[] | "all") => ({
sourceId: v.s,
photoCount: { gt: 0 },
@@ -112,7 +139,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`. */
@@ -159,7 +186,17 @@ export async function registerArchiveViewerRoutes(
folders = rows.map((r) => r.id);
}
}
return { token: tokens.sign({ s: source.id, n: me.displayName, all, f: folders }), viewer: { name: me.displayName, all, folders: folders.length } };
await db.archiveGrant.deleteMany({ where: { sourceId: source.id, expiresAt: { lt: new Date() } } });
const grant = await db.archiveGrant.create({
data: {
sourceId: source.id,
viewerName: me.displayName,
seesAll: all,
expiresAt: new Date(Date.now() + VIEWER_TTL_SEC * 1000),
...(!all && folders.length ? { folders: { create: folders.map((folderId) => ({ folderId })) } } : {}),
},
});
return { token: tokens.sign({ s: source.id, n: me.displayName, g: grant.id }), viewer: { name: me.displayName, all, folders: folders.length } };
} catch (err) {
if (err instanceof NextcloudError) throw new AppError(502, "cloud_error", err.message);
throw err;
@@ -169,6 +206,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 +240,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,41 +286,77 @@ 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 eventIds = [...new Set(folders.map((f) => f.eventId!))];
const players = eventIds.length
? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>`
SELECT p.name, count(*) AS photos, max(pe.club) AS club
FROM (SELECT unnest(ph.players) AS name FROM photos ph JOIN cloud_files cf ON cf.photo_id = ph.id
WHERE ph.event_id = ANY(${eventIds}::uuid[]) AND cf.source_id = ${sourceId}::uuid) p
LEFT JOIN people pe ON pe.name = p.name AND pe.organization_id = (SELECT organization_id FROM cloud_sources WHERE id = ${sourceId}::uuid)
GROUP BY p.name ORDER BY count(*) DESC, p.name LIMIT 2000`
: [];
const teams = new Map([...(await teamGroups(sourceId, games.values()))].map(([name, g]) => [name, g.galleries]));
const players =
visible === "all" || visible.length
? await db.$queryRaw<{ name: string; photos: bigint; club: string | null }[]>`
SELECT p.name, count(*) AS photos, max(pe.club) AS club
FROM (SELECT unnest(ph.players) AS name FROM photos ph JOIN cloud_files cf ON cf.photo_id = ph.id
WHERE ${fileScope(sourceId, visible)} AND cardinality(ph.players) > 0) p
LEFT JOIN people pe ON pe.name = p.name AND pe.organization_id = (SELECT organization_id FROM cloud_sources WHERE id = ${sourceId}::uuid)
WHERE p.name <> ''
GROUP BY p.name ORDER BY count(*) DESC, p.name LIMIT 2000`
: [];
return {
teams: [...teams].map(([name, galleries]) => ({ name, galleries })).sort((a, b) => b.galleries - a.galleries || a.name.localeCompare(b.name)),
players: players.map((p) => ({ name: p.name, club: p.club, photos: Number(p.photos) })),
};
});
/** One gallery's photos (the viewer must see its folder). */
/** One page of a gallery (the viewer must see its folder). Faces are not in the page; a photo asks for its own. */
app.get("/v1/archive/galleries/:folderId", async (req) => {
const { folderId } = FolderParams.parse(req.params);
const query = GalleryQuery.parse(req.query);
const v = viewerOf(req);
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.includes(folderId)) throw notFound("gallery_not_found");
const folder = await db.cloudFolder.findFirst({ where: { id: folderId, sourceId: v.s }, include: { event: true, source: { select: { baseUrl: true } } } });
if (!folder) throw notFound("gallery_not_found");
const player = typeof (req.query as { player?: unknown }).player === "string" ? (req.query as { player: string }).player : undefined;
const files = await db.cloudFile.findMany({
where: { folderId, status: "DONE", photoId: { not: null }, ...(player && { photo: { players: { has: player } } }) },
include: { photo: { select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true, developSnapshot: true } } },
orderBy: { path: "asc" },
const where = {
folderId,
status: "DONE" as const,
photoId: { not: null },
...(query.player && { photo: { players: { has: query.player } } }),
...(query.person && { photo: { faces: { some: { group: { personId: query.person, ignoredAt: null } } } } }),
};
const [total, files, named, sharpest] = await Promise.all([
db.cloudFile.count({ where }),
db.cloudFile.findMany({
where,
include: { photo: { select: { id: true, width: true, height: true, players: true, capturedAt: true, renderedSeq: true } } },
orderBy: { path: "asc" },
skip: query.offset,
take: query.limit,
}),
db.$queryRaw<{ id: string; name: string; count: number }[]>`
SELECT p.id, p.name, count(DISTINCT f.photo_id)::int AS count
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN people p ON p.id = g.person_id
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
GROUP BY p.id
ORDER BY count(DISTINCT f.photo_id) DESC, p.name`,
db.$queryRaw<{ person_id: string; photo_id: string; x0: number; y0: number; x1: number; y1: number }[]>`
SELECT DISTINCT ON (g.person_id) g.person_id, f.photo_id, f.x0, f.y0, f.x1, f.y1
FROM faces f
JOIN face_groups g ON g.id = f.group_id AND g.person_id IS NOT NULL AND g.ignored_at IS NULL
JOIN cloud_files cf ON cf.photo_id = f.photo_id AND cf.folder_id = ${folderId}::uuid AND cf.status = 'DONE'
ORDER BY g.person_id, f.sharpness DESC NULLS LAST, f.score DESC`,
]);
const facePhotos = await db.photo.findMany({
where: { id: { in: sharpest.map((f) => f.photo_id) } },
select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true },
});
// The faces in each photo: a click finds more photos of that face.
const faces = await facesOfPhotos(db, files.map((f) => f.photo!));
const photoById = new Map(facePhotos.map((p) => [p.id, p]));
const faceOf = new Map(
sharpest.flatMap((f) => {
const p = photoById.get(f.photo_id);
if (!p) return [];
return [[f.person_id, { src: signer.url(f.photo_id, "preview", p.renderedSeq), box: faceBox(f, p), aspect: p.width && p.height ? p.width / p.height : 1.5 }] as const];
}),
);
const base = folder.source.baseUrl.replace(/\/+$/, "");
return {
id: folder.id,
@@ -259,6 +366,8 @@ export async function registerArchiveViewerRoutes(
startsAt: folder.event?.startsAt ?? null,
/** The folder on the cloud (opens for those it is shared with). */
cloudUrl: `${base}/f/${folder.fileId}`,
total,
people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })),
photos: files.map((f) => ({
id: f.photo!.id,
name: f.path.split("/").pop(),
@@ -269,11 +378,25 @@ export async function registerArchiveViewerRoutes(
thumb: signer.url(f.photo!.id, "thumb", f.photo!.renderedSeq),
preview: signer.url(f.photo!.id, "preview", f.photo!.renderedSeq),
cloudUrl: `${base}/f/${f.fileId}`,
faces: faces.get(f.photo!.id) ?? [],
})),
};
});
/** The faces of one photo, when it is opened. The grid does not carry them. */
app.get("/v1/archive/photos/:photoId", async (req) => {
const { photoId } = PhotoParams.parse(req.params);
const v = viewerOf(req);
const file = await db.cloudFile.findFirst({
where: { photoId, sourceId: v.s, status: "DONE" },
include: { photo: { select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true } } },
});
if (!file?.photo) throw notFound("photo_not_found");
const visible = await visibleFolders(v);
if (visible !== "all" && !visible.includes(file.folderId)) throw notFound("photo_not_found");
const faces = await facesOfPhotos(db, [file.photo]);
return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] };
});
await registerArchivePeopleRoutes(app, { db, signer, viewerOf, visibleFolders });
}
+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). */
+7
View File
@@ -78,6 +78,13 @@ export class NextcloudClient {
if (res.status !== 201 && res.status !== 204) throw new NextcloudError(`PUT ${remoteFile} failed: ${res.status}`, res.status);
}
/** Removes a file (idempotent: a missing file is not an error). */
async remove(remoteFile: string): Promise<void> {
const res = await this.call("DELETE", this.davUrl(remoteFile));
// 204/200 removed, 404 already gone, 423 locked (worth a retry).
if (res.status !== 204 && res.status !== 200 && res.status !== 404) throw new NextcloudError(`DELETE ${remoteFile} failed: ${res.status}`, res.status);
}
/** Public, read-only link to a folder; reuses an existing link when there is one. */
async shareLink(folder: string): Promise<string> {
const base = this.auth.baseUrl.replace(/\/+$/, "");
+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: {
+138 -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);
@@ -52,6 +58,26 @@ export function deliveredName(photo: { originalName: string; fileName: string |
/** Where a file rendered for a computer's folder waits on the server. */
export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`;
/**
* Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination
* (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED):
* cancelled outright. Returns how many are queued for removal.
*/
export async function retractPhotos(db: Db, organizationId: string, photoIds: string[]): Promise<number> {
if (!photoIds.length) return 0;
// Not uploaded yet: cancel, there is nothing on the destination to remove.
await db.deliveryItem.updateMany({
where: { organizationId, photoId: { in: photoIds }, status: "QUEUED", retract: false },
data: { status: "RETRACTED", finishedAt: new Date() },
});
// Already delivered, or waiting for a computer to take it: the worker takes it back.
const r = await db.deliveryItem.updateMany({
where: { organizationId, photoId: { in: photoIds }, status: { in: ["DONE", "WAITING"] }, retract: false },
data: { status: "QUEUED", retract: true, attempts: 0, nextAttemptAt: new Date(), lastError: null, finishedAt: null },
});
return r.count;
}
export class DeliveryRejected extends Error {
constructor(readonly code: string) {
super(code);
@@ -92,7 +118,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 +191,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);
@@ -222,6 +299,28 @@ export class DeliveryService {
async process(itemId: string): Promise<DeliveryItem> {
const { db, storage, log } = this.deps;
const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } });
// Taking a delivery back: the photo was rejected or un-picked. Remove it from the destination (or drop the
// copy still waiting on the server for a computer), never an upload.
if (item.retract) {
let retractUpdate: Partial<DeliveryItem>;
try {
if (item.target.kind === "LOCAL") await storage.remove(localKey(item.organizationId, item.id)).catch(() => {});
else if (item.remotePath) await this.client(item.target).remove(item.remotePath);
retractUpdate = { status: "RETRACTED", retract: false, remotePath: null, lastError: null, finishedAt: new Date() };
log.info({ itemId, remotePath: item.remotePath }, "delivery: taken back from the destination");
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
const retry = !(err instanceof DeliveryRejected) && isTransient(err);
retractUpdate =
retry && item.attempts < MAX_ATTEMPTS
? { status: "QUEUED", lastError: message, nextAttemptAt: new Date(Date.now() + backoffMs(item.attempts)) }
: { status: "FAILED", retract: false, lastError: `retract: ${message}`, finishedAt: new Date() };
log.warn({ itemId, attempt: item.attempts, error: message, final: retractUpdate.status === "FAILED" }, "delivery: retract failed");
}
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: retractUpdate });
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
let update: Partial<DeliveryItem>;
// An archive photo: its original is read from the cloud it lives on.
let cloud: { file: string; done: () => Promise<void> } | null = null;
@@ -244,24 +343,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 +378,16 @@ 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-");
// When the file lands at a new path (an edit changed the folder or name), remove the old one so no orphan is
// left behind; on ZeroZero `alreadyThere` means the desk already had it, so there is nothing to take back.
if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath) {
await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous file not removed"));
}
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 +521,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 +531,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 +554,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");
}
}
+73 -15
View File
@@ -25,6 +25,8 @@ export interface Transport {
ensureFolder(folder: string): Promise<void>;
/** Returns where the photo ended up when the service names it (an id), else nothing. */
upload(remoteFile: string, data: Buffer, meta?: UploadMeta): Promise<void | string>;
/** Takes a delivered file back (retraction, or replacing one at a changed path). Missing file is not an error. */
remove(remotePath: string): Promise<void>;
/** Public read-only link to a folder; undefined when the service has none. */
shareLink?(folder: string): Promise<string>;
/** Connects and checks the credentials; SFTP also reports the host key fingerprint. */
@@ -80,24 +82,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() {}
}
@@ -110,6 +130,9 @@ class NextcloudTransport implements Transport {
upload(remoteFile: string, data: Buffer) {
return this.client.upload(remoteFile, data);
}
remove(remoteFile: string) {
return this.client.remove(remoteFile);
}
shareLink(folder: string) {
return this.client.shareLink(folder);
}
@@ -233,6 +256,18 @@ export class SftpTransport implements Transport {
});
}
remove(remoteFile: string): Promise<void> {
return this.serial.run(async () => {
const client = await this.connect();
try {
// noErrorOK: a file already gone is fine.
await client.delete(remoteFile, true);
} catch (err) {
this.fail(err, `delete ${remoteFile}`);
}
});
}
test(): Promise<{ fingerprint?: string }> {
return this.serial.run(async () => {
const client = await this.connect();
@@ -311,6 +346,19 @@ export class FtpTransport implements Transport {
});
}
remove(remoteFile: string): Promise<void> {
return this.serial.run(async () => {
const client = await this.connect();
try {
await client.remove(remoteFile);
} catch (err) {
// 550: no such file — already gone, not an error.
if ((err as { code?: number }).code === 550) return;
this.fail(err, `delete ${remoteFile}`);
}
});
}
test(): Promise<{ account?: string }> {
return this.serial.run(async () => {
const client = await this.connect();
@@ -394,6 +442,16 @@ export class DropboxTransport implements Transport {
});
}
async remove(remoteFile: string): Promise<void> {
try {
await this.rpc("files/delete_v2", { path: remoteFile });
} catch (err) {
// Already gone is not an error.
if (err instanceof TransportError && /not_found/.test(err.message)) return;
throw err;
}
}
async shareLink(folder: string): Promise<string> {
const path = folder.replace(/\/+$/, "");
try {
+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;
}
}
+75 -7
View File
@@ -3,7 +3,10 @@ import { tmpdir } from "node:os";
import path from "node:path";
import sharp from "sharp";
import type { Db } from "../db.js";
import { MIN_SHARPNESS, THRESHOLDS } from "./math.js";
import type { JerseyReading } from "../jersey/model.js";
import { numberBoxes } from "../jersey/crop.js";
import { JERSEY_MIN_SCORE } from "./votes.js";
import { MIN_SHARPNESS, THRESHOLDS, inFocus } from "./math.js";
import type { FaceEngine } from "./process.js";
/** A face found in the photo someone searched with (box in fractions of the photo). */
@@ -11,6 +14,8 @@ export interface QueryFace {
box: { x0: number; y0: number; x1: number; y1: number };
embedding: number[];
sharp: boolean;
/** Engine measurement, when it has one. `inFocus` uses it to drop a blurred crowd. */
sharpness?: number | null;
}
export type MatchLevel = "strong" | "possible";
@@ -23,6 +28,19 @@ export class LookupRejected extends Error {
/** How far below the "same person" threshold a face still shows, as "possible". */
const POSSIBLE_BELOW = 0.06;
/** A face smaller than this (fraction of the long side) is not someone to name. */
const MIN_FACE_SIDE = 0.012;
/** Reads a shirt number from a photo on disk. Absent when the model is not installed. */
export interface JerseyReader {
read(path: string, box: { x0: number; y0: number; x1: number; y1: number }): Promise<JerseyReading>;
}
/** One clear face in a card photo: who it looks like is decided by the caller; the number is read here. */
export interface InspectedFace extends QueryFace {
number: string | null;
numberScore: number | null;
}
const levelOf = (score: number, match: number): MatchLevel | null => (score >= match ? "strong" : score >= match - POSSIBLE_BELOW ? "possible" : null);
@@ -42,8 +60,11 @@ export class FaceLookup {
return !!this.deps.engine();
}
/** The faces in the photo, largest first. */
async facesIn(image: Buffer): Promise<{ model: string; faces: QueryFace[] }> {
/**
* The photo, resized, on disk for the engine, then deleted. Nothing is stored.
* `faces` is every detected face, largest first, in fractions of the resized photo.
*/
private async withPhoto<T>(image: Buffer, run: (file: string, width: number, height: number, faces: QueryFace[], model: string) => Promise<T>): Promise<T> {
const engine = this.deps.engine();
if (!engine) throw new LookupRejected("engine_unavailable");
let jpeg: Buffer;
@@ -67,15 +88,49 @@ export class FaceLookup {
box: { x0: frac(f.x0, w), y0: frac(f.y0, h), x1: frac(f.x1, w), y1: frac(f.y1, h) },
embedding: f.embedding!,
sharp: f.sharpness == null || f.sharpness >= MIN_SHARPNESS,
...(f.sharpness != null ? { sharpness: f.sharpness } : {}),
}))
.sort((a, b) => (b.box.x1 - b.box.x0) * (b.box.y1 - b.box.y0) - (a.box.x1 - a.box.x0) * (a.box.y1 - a.box.y0));
if (!faces.length) throw new LookupRejected("no_face");
return { model: engine.model, faces };
return await run(file, w, h, faces, engine.model);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
/** The faces in the photo, largest first. */
async facesIn(image: Buffer): Promise<{ model: string; faces: QueryFace[] }> {
return this.withPhoto(image, async (_file, _w, _h, faces, model) => {
if (!faces.length) throw new LookupRejected("no_face");
return { model, faces };
});
}
/**
* Faces and shirt numbers in one photo from a card. Clear faces only (a blurred crowd is not who the photo is
* about). The photo is not kept. An empty list means nothing readable, which is a normal photo of the court.
*/
async inspect(image: Buffer, jersey: JerseyReader | null): Promise<{ model: string; faces: InspectedFace[] }> {
return this.withPhoto(image, async (file, width, height, detected, model) => {
const clear = inFocus(detected.filter((f) => Math.max(f.box.x1 - f.box.x0, f.box.y1 - f.box.y0) >= MIN_FACE_SIDE));
const faces: InspectedFace[] = [];
for (const f of clear) {
let number: string | null = null;
let numberScore: number | null = null;
if (jersey && f.sharp) {
for (const { box } of numberBoxes(f.box, width, height)) {
const reading = await jersey.read(file, box).catch(() => null);
if (reading?.number && reading.score >= JERSEY_MIN_SCORE && (numberScore == null || reading.score > numberScore)) {
number = reading.number;
numberScore = reading.score;
}
}
}
faces.push({ box: f.box, embedding: f.embedding, sharp: f.sharp, number, numberScore });
}
return { model, faces };
});
}
private threshold(model: string): number {
return (THRESHOLDS[model] ?? { match: 0.5 }).match;
}
@@ -104,8 +159,20 @@ export class FaceLookup {
return rows.map((r) => ({ groupId: r.id, eventId: r.event_id, personId: r.person_id, size: r.size, score: Number(r.score), level: levelOf(Number(r.score), match)! }));
}
/** Named people like the face (their centroid: confirmed faces and reference photo). */
async people(orgId: string, embedding: number[], model: string, limit = 5) {
/**
* Named people like the face (their centroid: confirmed faces and reference photo).
* `prefer`, when set, is the whole search when anyone there matches: the game's players and officials.
* Only a face none of them match is compared with the rest of the organization.
*/
async people(orgId: string, embedding: number[], model: string, limit = 5, prefer: string[] | null = null) {
if (prefer?.length) {
const inGame = await this.matchPeople(orgId, embedding, model, limit, prefer);
if (inGame.length) return inGame;
}
return this.matchPeople(orgId, embedding, model, limit, null);
}
private async matchPeople(orgId: string, embedding: number[], model: string, limit: number, only: string[] | null) {
const match = this.threshold(model);
const rows = await this.deps.db.$queryRaw<{ id: string; name: string; club: string | null; number: string | null; score: number }[]>`
SELECT id, name, club, number, score FROM (
@@ -114,6 +181,7 @@ export class FaceLookup {
/ NULLIF(sqrt((SELECT sum(a * a) FROM unnest(p.centroid) AS u(a))), 0) AS score
FROM people p
WHERE p.organization_id = ${orgId}::uuid AND p.model = ${model} AND cardinality(p.centroid) = ${embedding.length}
AND (${only}::uuid[] IS NULL OR p.id = ANY(${only}::uuid[]))
) s
WHERE score >= ${match - POSSIBLE_BELOW}
ORDER BY score DESC
+99 -2
View File
@@ -1,3 +1,6 @@
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { join } from "node:path";
import type { FastifyInstance, FastifyRequest } from "fastify";
import { z } from "zod";
import { ROLE_RANK, requireAuth, requireMembership } from "../auth/guard.js";
@@ -6,7 +9,9 @@ import type { Db } from "../db.js";
import { AppError, badRequest, conflict } from "../lib/errors.js";
import { photoInclude, toSummary } from "../library/serialize.js";
import type { UrlSigner } from "../storage/storage.js";
import { type FaceLookup, LookupRejected, type MatchLevel, type QueryFace } from "./lookup.js";
import { scanSlots } from "../lib/engines.js";
import { numberContext, numbersIn, rosterOf } from "./numbers.js";
import { type FaceLookup, type JerseyReader, LookupRejected, type MatchLevel, type QueryFace } from "./lookup.js";
const OrgParams = z.object({ orgId: z.uuid() });
export const LookupQuery = z.object({
@@ -39,7 +44,12 @@ export const facesOut = (faces: QueryFace[]) => faces.map((f) => ({ box: f.box,
* Search the library by a photo: who is it (named people like that face) and every photo with that face, across
* all events or one. Only with biometrics on for the organization; the photo is not kept.
*/
export async function registerLookupRoutes(app: FastifyInstance, deps: { db: Db; sessions: SessionService; lookup: FaceLookup; signer: UrlSigner }) {
const MODEL_FILES = ["face_detection_yunet_2023mar.onnx", "glintr100.onnx"] as const;
export async function registerLookupRoutes(
app: FastifyInstance,
deps: { db: Db; sessions: SessionService; lookup: FaceLookup; signer: UrlSigner; jersey?: () => Promise<JerseyReader | null>; models?: string | null },
) {
const { db, lookup, signer } = deps;
const authenticate = requireAuth(deps.sessions);
@@ -100,4 +110,91 @@ export async function registerLookupRoutes(app: FastifyInstance, deps: { db: Db;
matches: shown.map((p) => ({ photoId: p.id, ...best.get(p.id)! })),
};
});
// A folder is thousands of photos of one game. The squad does not change between them, so it is read once.
const rosters = new Map<string, { at: number; ids: string[] | null }>();
const rosterFor = 10 * 60_000;
const roster = async (eventId: string): Promise<string[] | null> => {
const hit = rosters.get(eventId);
if (hit && Date.now() - hit.at < rosterFor) return hit.ids;
const ids = await rosterOf(db, eventId);
rosters.set(eventId, { at: Date.now(), ids });
return ids;
};
/**
* One photo from a folder, not imported: the clear faces, the shirt number under each, and the known person.
* A game is asked first (its players and officials). Anyone it does not know is looked up in the whole
* organization. The file is read and thrown away. Nothing is written to the library.
*/
app.post("/v1/orgs/:orgId/faces/scan", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
const eventId = z.object({ eventId: z.uuid().optional() }).parse(req.query).eventId;
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org.biometricsEnabled) throw conflict("biometrics_disabled");
const image = await lookupImage(req);
const jersey = (await deps.jersey?.()) ?? null;
const read = await lookup.inspect(image, jersey).catch(lookupFailed);
const ctx = eventId ? await numberContext(db, eventId) : null;
const ids = eventId ? await roster(eventId) : null;
const hits = await Promise.all(
read.faces.map(async (f) => (f.sharp ? ((await lookup.people(orgId, f.embedding, read.model, 1, ids && ids.length ? ids : null))[0] ?? null) : null)),
);
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return {
slots: scanSlots(),
roster: ids ? ids.length : ids,
faces: read.faces.map((f, i) => {
const hit = hits[i];
return {
box: f.box,
number: f.number,
person: hit ? { id: hit.id, name: hit.name, club: hit.club, number: worn.get(hit.id) ?? hit.number, level: hit.level } : null,
};
}),
};
});
/**
* Names for faces already read on the photographer's computer. The photo stays there; only the embeddings
* (and nothing else) are compared, first with the game and then with everyone else.
*/
app.post("/v1/orgs/:orgId/faces/identify", { preHandler: authenticate, config: { rateLimit: { max: 25000, timeWindow: "10 minutes" } } }, async (req) => {
const { orgId } = OrgParams.parse(req.params);
const body = z
.object({
eventId: z.uuid().optional(),
model: z.string().min(1).max(64).default("auraface-v1"),
faces: z.array(z.object({ embedding: z.array(z.number().finite()).min(8).max(1024) })).max(32),
})
.parse(req.body);
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org.biometricsEnabled) throw conflict("biometrics_disabled");
const ctx = body.eventId ? await numberContext(db, body.eventId) : null;
const ids = body.eventId ? await roster(body.eventId) : null;
const prefer = ids && ids.length ? ids : null;
const hits = await Promise.all(body.faces.map(async (f) => (await lookup.people(orgId, f.embedding, body.model, 1, prefer))[0] ?? null));
const worn = ctx ? await numbersIn(db, ctx, hits.flatMap((h) => (h ? [h.id] : []))) : new Map<string, string>();
return {
roster: ids ? ids.length : ids,
people: hits.map((hit) => (hit ? { id: hit.id, name: hit.name, club: hit.club, number: worn.get(hit.id) ?? hit.number, level: hit.level } : null)),
};
});
/** The face models, so the desktop app can read a folder itself. Checked by hash when they are loaded. */
app.get("/v1/orgs/:orgId/faces/models/:file", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params);
const { file } = z.object({ file: z.enum(MODEL_FILES) }).parse(req.params);
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { biometricsEnabled: true } });
if (!org.biometricsEnabled) throw conflict("biometrics_disabled");
const dir = deps.models;
if (!dir) throw new AppError(404, "models_missing");
const path = join(dir, file);
const info = await stat(path).catch(() => null);
if (!info?.isFile()) throw new AppError(404, "models_missing");
return reply.header("content-type", "application/octet-stream").header("content-length", String(info.size)).header("cache-control", "private, max-age=86400").send(createReadStream(path));
});
}
+234
View File
@@ -0,0 +1,234 @@
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;
}
/** A match official as stored on the fixture (`{ name, fullName, externalId, role }`). */
interface FixtureOfficial {
name?: string;
fullName?: string | null;
externalId?: string | null;
}
/**
* Who this game should be asked first: the season's squad of the two teams (the same player, even when their
* person row points at another season) and the match officials who already have a face (referees, table).
* Null when nothing of the game is known, so the caller compares with everyone straight away. An empty list
* means the squad is known and none of them have a face on file yet.
*/
export async function rosterOf(db: Db, eventId: string): Promise<string[] | null> {
const ctx = await numberContext(db, eventId);
if (!ctx) return null;
const ids = new Set<string>();
let squad = 0;
if (ctx.teamIds.length) {
squad = await db.sportsPlayer.count({ where: { teamId: { in: ctx.teamIds }, season: ctx.season } });
if (squad > 0) {
const rows = await db.$queryRaw<{ id: string }[]>`
SELECT DISTINCT p.id
FROM people p
JOIN sports_players mine ON mine.id = p.sports_player_id
WHERE p.organization_id = ${ctx.organizationId}::uuid
AND cardinality(p.centroid) > 0
AND EXISTS (
SELECT 1 FROM sports_players squad
WHERE squad.team_id = ANY(${ctx.teamIds}::uuid[])
AND squad.season = ${ctx.season}
AND (
squad.id = mine.id
OR (squad.external_id IS NOT NULL AND squad.external_id = mine.external_id)
OR (squad.team_id = mine.team_id AND squad.name = mine.name)
)
)`;
for (const row of rows) ids.add(row.id);
}
}
for (const id of await officialsOf(db, eventId, ctx.organizationId)) ids.add(id);
if (ids.size) return [...ids];
if (squad > 0) return [];
// No official squad: people typed against these clubs, and only when that set is small enough to be the game.
const event = await db.event.findUnique({ where: { id: eventId }, select: { home: true, away: true, homeShort: true, awayShort: true } });
if (!event) return null;
const teams = [event.home, event.away, event.homeShort, event.awayShort].filter((t): t is string => !!t).map(fold);
const people = await db.person.findMany({
where: { organizationId: ctx.organizationId, club: { not: null }, NOT: { centroid: { isEmpty: true } } },
select: { id: true, club: true },
});
const clubIds = people
.filter((p) => {
const club = fold(p.club ?? "");
return club.length > 2 && teams.some((t) => t.length > 2 && (t.includes(club) || club.includes(t)));
})
.map((p) => p.id);
if (!clubIds.length || clubIds.length > 400) return null;
return clubIds;
}
/** Referees and table officials of this match who already have a face. */
async function officialsOf(db: Db, eventId: string, organizationId: string): Promise<string[]> {
const event = await db.event.findUnique({ where: { id: eventId }, select: { fixture: { select: { officials: true } } } });
const list = Array.isArray(event?.fixture?.officials) ? (event.fixture.officials as FixtureOfficial[]) : [];
const names = [...new Set(list.flatMap((o) => [o.name, o.fullName].filter((n): n is string => !!n)))];
const externalIds = [...new Set(list.map((o) => o.externalId).filter((id): id is string => !!id))];
const ids = new Set<string>();
if (names.length) {
const byName = await db.person.findMany({
where: { organizationId, name: { in: names }, NOT: { centroid: { isEmpty: true } } },
select: { id: true },
});
for (const person of byName) ids.add(person.id);
}
if (externalIds.length) {
const players = await db.sportsPlayer.findMany({ where: { externalId: { in: externalIds } }, select: { id: true } });
if (players.length) {
const byLicence = await db.person.findMany({
where: { organizationId, sportsPlayerId: { in: players.map((p) => p.id) }, NOT: { centroid: { isEmpty: true } } },
select: { id: true },
});
for (const person of byLicence) ids.add(person.id);
}
}
return [...ids];
}
+92
View File
@@ -1,5 +1,25 @@
import { cpus } from "node:os";
import { LeastBusy, LineProcess } from "../lib/line-process.js";
/** Stop adding face processes once the machine is this full. */
const CPU_TARGET = 0.97;
interface CpuTimes {
idle: number;
total: number;
}
function cpuTimes(): CpuTimes {
let idle = 0;
let total = 0;
for (const cpu of cpus()) {
const t = cpu.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total };
}
export interface DetectedFace {
x0: number;
y0: number;
@@ -73,3 +93,75 @@ export class FacePool implements FaceEngine {
await Promise.all(this.engines.map((e) => e.close()));
}
}
/**
* Face processes that start a few at a time and keep being added while the CPU is under {@link CPU_TARGET}.
* Each process is one core. `cap` is the most this machine should run.
*/
export class GrowingFacePool implements FaceEngine {
readonly model: string;
private readonly engines: FaceEngine[] = [];
private readonly busy: number[] = [];
private last: CpuTimes = cpuTimes();
private lastGrow = 0;
constructor(
private readonly make: () => FaceEngine,
private readonly cap: number,
) {
const first = make();
this.model = first.model;
this.engines.push(first);
this.busy.push(0);
this.add(Math.min(3, Math.max(0, cap - 1)));
}
get size(): number {
return this.engines.length;
}
private add(count: number): void {
const room = Math.max(0, this.cap - this.engines.length);
const n = Math.min(count, room);
for (let i = 0; i < n; i++) {
this.engines.push(this.make());
this.busy.push(0);
}
}
/** Add more processes when every current one is busy and the CPU is not full yet. */
private grow(): void {
if (this.engines.length >= this.cap) return;
const now = Date.now();
if (now - this.lastGrow < 1500) return;
const allBusy = this.busy.every((n) => n > 0);
if (!allBusy && this.engines.length >= 4) return;
const sample = cpuTimes();
const idle = sample.idle - this.last.idle;
const total = sample.total - this.last.total;
this.last = sample;
const used = total > 0 ? 1 - idle / total : 0;
if (used >= CPU_TARGET) return;
const step = Math.max(2, Math.floor(this.engines.length / 2));
this.add(step);
this.lastGrow = now;
}
async analyse(path: string): Promise<FaceAnalysis> {
this.grow();
let index = 0;
for (let i = 1; i < this.busy.length; i++) {
if (this.busy[i]! < this.busy[index]!) index = i;
}
this.busy[index]!++;
try {
return await this.engines[index]!.analyse(path);
} finally {
this.busy[index]!--;
}
}
async close(): Promise<void> {
await Promise.all(this.engines.map((e) => e.close()));
}
}
+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 DESC 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> {
+30 -6
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 }),
},
});
@@ -181,17 +192,27 @@ export class IngestService {
const made = await this.makeDerivatives(orgId, sha256, storageKey);
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 autopilot = origin.source !== "UPLOAD" && origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
// The event's autopilot edits what arrives by FTP, the desktop app, or a hand upload (a second photographer's
// photos added by hand count too); only archive re-imports (CLOUD) are left as they were.
const event = eventId ? await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, faceBoostedAt: true } }) : null;
const autopilot = origin.source !== "CLOUD" && (event?.autopilot as { enabled?: boolean } | null)?.enabled === true;
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 +268,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 };
}
+16 -2
View File
@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";
import path from "node:path";
import * as ort from "onnxruntime-node";
import sharp from "sharp";
import { LeastBusy } from "../lib/line-process.js";
import type { Box } from "./crop.js";
interface Meta {
@@ -37,7 +38,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 +46,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 } })
@@ -63,3 +64,16 @@ export class JerseyModel {
return { number: label === "illegible" ? null : label, score: probs[best]! };
}
}
/** Several copies of the shirt-number model, so a folder scan can read numbers on many cores at once. */
export class JerseyPool {
private readonly pool: LeastBusy<JerseyModel>;
constructor(models: JerseyModel[]) {
this.pool = new LeastBusy(models);
}
read(original: string, box: Box): Promise<JerseyReading> {
return this.pool.use((model) => model.read(original, box));
}
}
+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),
};
+22
View File
@@ -1,8 +1,30 @@
import { existsSync } from "node:fs";
import { availableParallelism, totalmem } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { modelsDir } from "./models.js";
/**
* How many face processes a folder scan runs at once. Each process is one core (the engine is single-threaded),
* so this is what fills the machine. A few cores stay for the API and the library worker when the box is large.
*/
export function scanSlots(machine: { cpus: number; memoryBytes: number } = { cpus: availableParallelism(), memoryBytes: totalmem() }): number {
const cpus = Math.max(1, machine.cpus);
const spareGb = Math.max(1, machine.memoryBytes / 1e9 - 6);
const byMemory = Math.max(1, Math.floor(spareGb / 0.6));
// One core stays for the window and the API. The pool grows up to this until the machine is full.
const leave = cpus > 2 ? 1 : 0;
return Math.max(1, Math.min(cpus - leave, byMemory));
}
/** The shirt-number model, when it was downloaded next to the face models or pointed at by the env. */
export function jerseyModelDir(config: { JERSEY_MODEL_DIR?: string | undefined; STORAGE_ROOT: string }): string | null {
if (config.JERSEY_MODEL_DIR && existsSync(join(config.JERSEY_MODEL_DIR, "jersey.onnx"))) return config.JERSEY_MODEL_DIR;
const models = modelsDir(config.STORAGE_ROOT);
const dir = models ? join(models, "jersey") : null;
return dir && existsSync(join(dir, "jersey.onnx")) ? dir : null;
}
/**
* Where the face engine is: what apps/api/.env says, or what the deploy built (target/release) and downloaded
* (models next to the storage). Shared by the worker (library analysis) and the API (search by photo).
+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 },
+7 -4
View File
@@ -4,17 +4,20 @@ import { applyRename } from "./rename.js";
/**
* Photos that just joined an event (moved by hand, or claimed from "Sem evento" when the event was created or its
* window changed) get what arriving in it would have given them: the event's arrival name, faces analysed again so
* they group with the event's people, and the event's autopilot edit (FTP and desktop photos only, as on arrival).
* they group with the event's people, and the event's autopilot edit (everything but archive re-imports, as on arrival).
*/
export async function joinedEvent(db: Db, eventId: string, ids: string[]): Promise<void> {
if (!ids.length) return;
const event = await db.event.findUnique({ where: { id: eventId }, select: { autopilot: true, organization: { select: { biometricsEnabled: true } } } });
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" } });
await db.photo.updateMany({ where: { id: { in: ids }, status: "READY", source: { not: "CLOUD" }, autopilotStatus: "NONE" }, data: { autopilotStatus: "PENDING" } });
}
for (const id of ids) await applyRename(db, id);
}
+81 -5
View File
@@ -7,9 +7,10 @@ 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 { officialSigla } from "../sports/fpa-siglas.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
@@ -51,24 +52,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 +157,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 } } } : {}),
};
@@ -153,6 +173,9 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
if (body.photographerIds?.length) await assertMembers(orgId, body.photographerIds);
const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, autopilot, fixtureId, homeTeamId, awayTeamId, ...fields } = body;
const match = await resolveMatch({ fixtureId, homeTeamId, awayTeamId });
// Fall back to the federation's official short codes when the fixture carried none (handball has no abbreviations).
const homeShort = fields.homeShort ?? officialSigla(fields.home);
const awayShort = fields.awayShort ?? (fields.away ? officialSigla(fields.away) : undefined);
const event = await db.event.create({
data: {
...compact(fields),
@@ -160,6 +183,8 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
...(autopilot && { autopilot }),
home: fields.home,
away: fields.away ?? "",
...(homeShort != null && { homeShort }),
...(awayShort != null && { awayShort }),
startsAt: fields.startsAt,
organizationId: orgId,
createdById: currentUserId(req),
@@ -218,4 +243,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
View File
@@ -14,6 +14,7 @@ import type { Broadcaster } from "../realtime.js";
import type { LocalStorage, UrlSigner, Variant } from "../storage/storage.js";
import { DEFAULT_CODE_LIST, iptcForPhoto } from "./iptc.js";
import { photoInclude, toSummary } from "./serialize.js";
import { retractPhotos } from "../delivery/service.js";
const OrgParams = z.object({ orgId: z.uuid() });
const PhotoParams = z.object({ photoId: z.uuid() });
@@ -102,8 +103,17 @@ export async function registerPhotoRoutes(
if (patch.colorLabel !== undefined) data.colorLabel = patch.colorLabel;
if (patch.players !== undefined) data.players = patch.players;
if (patch.eventId !== undefined) data.eventId = patch.eventId;
// A rejected or un-picked photo that was already delivered is taken back from its destinations. Un-pick is a
// PICK -> NONE change, so the photos that are still PICK right now are the ones being un-picked (read first).
const retractIds =
patch.flag === "REJECT"
? ids
: patch.flag === "NONE"
? (await db.photo.findMany({ where: { id: { in: ids }, organizationId: orgId, flag: "PICK" }, select: { id: true } })).map((p) => p.id)
: [];
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
if (result.count !== ids.length) throw notFound("photo_not_found");
if (retractIds.length) await retractPhotos(db, orgId, retractIds);
// Moved to another event: arrival names, faces and the autopilot follow it.
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
+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");
}
}
+55
View File
@@ -0,0 +1,55 @@
/**
* Official FPA Campeonato Betclic club short codes (the federation's "Cores, Siglas e Nomes" list).
*
* The sports data provider does not carry team abbreviations for these competitions, so without this the delivery
* folder falls back to the full team name ("CDE Gil Eanes x CD Feirense" instead of "GIL x CDF"). This fills an
* event's homeShort/awayShort from the club name when they are not set. Matching is by a normalised name, so case,
* accents, punctuation and sponsor dashes do not matter; a club not listed simply keeps the full name (no harm).
*
* Update once per season when the federation changes club names or sponsors.
*/
/** Each short code with the club-name forms it may appear as (official name first, then safe variants). */
const CLUBS: ReadonlyArray<readonly [string, readonly string[]]> = [
// Andebol 1 (masculino)
["ABC", ["ABC de Braga", "ABC Braga"]],
["ADC", ["AD Carvalhos Sernox", "AD Carvalhos"]],
["AAAS", ["Águas Santas Milaneza", "Águas Santas", "AA Águas Santas"]],
["AAA", ["Avanca Bioria Bondalti", "Avanca"]],
["CFB", ["CF Os Belenenses", "Os Belenenses"]],
["FCP", ["FC Porto"]],
["GCST", ["GC Santo Tirso Retrotarget", "GC Santo Tirso"]],
["CSM", ["Marítimo Madeira Andebol SAD", "Marítimo Madeira"]],
["PAC", ["Póvoa AC Bodegão CCR Proteu", "Póvoa AC"]],
["SLB", ["SL Benfica"]],
["SCP", ["Sporting CP"]],
["VSC", ["Vitória SC"]],
// Campeonato Betclic (feminino)
["SPS", ["ADA São Pedro do Sul Multisac", "ADA São Pedro do Sul"]],
["ALA", ["Alavarium"]],
["CALE", ["CA Leça"]],
["CDF", ["CD Feirense Movit", "CD Feirense"]],
["GIL", ["CDE Gil Eanes"]],
["CJAG", ["CJ Almeida Garrett Gesti Douro UAE", "CJ Almeida Garrett"]],
["JUVE", ["Juve Lis"]],
["MAD", ["Madeira SAD"]],
];
/** Lower-case, accent-free, non-alphanumerics collapsed to single spaces: "CD Feirense -Movit" -> "cd feirense movit". */
function normalise(name: string): string {
return name
.normalize("NFD")
.replace(/\p{Diacritic}/gu, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.trim();
}
const BY_NAME = new Map<string, string>();
for (const [sigla, names] of CLUBS) for (const name of names) BY_NAME.set(normalise(name), sigla);
/** The official short code for a club name, or undefined when it is not in the list (then keep the full name). */
export function officialSigla(name: string | null | undefined): string | undefined {
if (!name) return undefined;
return BY_NAME.get(normalise(name));
}
+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();
+240 -8
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", () => {
@@ -628,12 +681,18 @@ describe("archive from a Nextcloud", () => {
// The gallery says where the faces are.
const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "SCP x ABC" } } });
res = await get(owner, `/v1/archive/galleries/${folder.id}`);
const withFaces = (res.json().photos as { id: string; faces: { person: { name: string } | null; level: string | null }[] }[]).find((p) => p.id === p2.id)!;
expect(withFaces.faces.map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort());
res = await get(owner, `/v1/archive/galleries/${folder.id}?limit=1`);
expect(res.json().photos).toHaveLength(1);
expect(res.json().total).toBe(2);
expect(res.json().photos[0].faces).toBeUndefined();
expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]);
res = await get(owner, `/v1/archive/photos/${p2.id}`);
expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort());
// The club sees the game but not the gala: no look-alike from there.
// The club sees the game but not the gala: no look-alike from there, and not that photo.
const club = await signIn("abc");
res = await get(club, `/v1/archive/photos/${gala.id}`);
expect(res.statusCode).toBe(404);
res = await get(club, `/v1/archive/${source.id}/people/${martim.id}`);
expect(res.json().counts).toEqual({ confirmed: 2, probable: 0, similar: 0 });
res = await get(club, `/v1/archive/${source.id}/faces/${f1.id}/similar`);
@@ -651,4 +710,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();
+85 -1
View File
@@ -48,7 +48,7 @@ describe("search by photo", () => {
STORAGE_ROOT: path.join(dir, "storage"),
});
db = createDb(config.DATABASE_URL);
app = await buildApp({ config, db, faceEngine: engine });
app = await buildApp({ config, db, faceEngine: engine, jersey: { async read() { return { number: "5", score: 0.95 }; } } });
jpeg = await sharp({ create: { width: 800, height: 1000, channels: 3, background: "#777" } }).jpeg().toBuffer();
});
afterAll(async () => {
@@ -137,6 +137,90 @@ describe("search by photo", () => {
expect(res.json()).toMatchObject({ error: "biometrics_disabled" });
});
it("reads a card photo without keeping it: the shirt number and the person, or nothing", async () => {
const { orgId, token, events, rui } = await setup();
// High in the frame and small enough that the chest crop stays inside the photo.
engine.next = { width: 800, height: 1000, faces: [found(1, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
const mp = multipart(jpeg);
const post = (id = orgId) => app.inject({ method: "POST", url: `/v1/orgs/${id}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
let res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, faces: [{ number: "5", person: { id: rui.id, name: "Rui Silva", number: "14", level: "strong" } }] });
expect(JSON.stringify(res.json())).not.toContain("embedding");
engine.next = { width: 800, height: 1000, faces: [] };
res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, faces: [] });
await db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: false } });
res = await post();
expect(res.statusCode).toBe(409);
expect(res.json()).toMatchObject({ error: "biometrics_disabled" });
});
it("names only a player of the chosen game, not someone else with the same face", async () => {
const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf", sport: "andebol", name: "Feirense", slug: "feirense" } });
const player = await db.sportsPlayer.create({ data: { teamId: home.id, season: "20262027", name: "Rui Silva", externalId: "rui" } });
await db.person.update({ where: { id: rui.id }, data: { sportsPlayerId: player.id } });
await db.person.create({ data: { organizationId: orgId, name: "Outra Pessoa", club: "Outro Clube", centroid: face(1), model: "auraface-v1" } });
await db.event.update({ where: { id: events.a }, data: { homeTeamId: home.id, awayTeamId: away.id } });
engine.next = { width: 800, height: 1000, faces: [found(1, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
const mp = multipart(jpeg);
const res = await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: 1, faces: [{ person: { id: rui.id, name: "Rui Silva" } }] });
});
it("asks the game first, including a referee, and the rest of the organization only when the game has no match", async () => {
const { orgId, token, events, rui } = await setup();
const home = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "gil2", sport: "andebol", name: "Gil Eanes", slug: "gil-eanes-2" } });
const away = await db.sportsTeam.create({ data: { provider: "FPA", externalId: "cdf2", sport: "andebol", name: "Feirense", slug: "feirense-2" } });
const player = await db.sportsPlayer.create({ data: { teamId: home.id, season: "20262027", name: "Rui Silva", externalId: "rui2" } });
await db.person.update({ where: { id: rui.id }, data: { sportsPlayerId: player.id } });
const comp = await db.sportsCompetition.create({ data: { provider: "FPA", externalId: "scan-ref", sport: "andebol", name: "PO", season: "20262027" } });
const fixture = await db.sportsFixture.create({
data: {
competitionId: comp.id,
season: "20262027",
externalId: "165",
homeTeamId: home.id,
awayTeamId: away.id,
startsAt: new Date("2026-09-20T18:00:00Z"),
officials: [{ name: "Carlos Reis", role: "REFEREE" }],
},
});
await db.event.update({ where: { id: events.a }, data: { homeTeamId: home.id, awayTeamId: away.id, fixtureId: fixture.id } });
const referee = await db.person.create({ data: { organizationId: orgId, name: "Carlos Reis", club: "Arbitragem", centroid: face(3), model: "auraface-v1" } });
await db.person.create({ data: { organizationId: orgId, name: "Fora do jogo", club: "Outro", centroid: face(3), model: "auraface-v1" } });
const outsider = await db.person.create({ data: { organizationId: orgId, name: "Só lá fora", club: "Outro", centroid: face(4), model: "auraface-v1" } });
const mp = multipart(jpeg);
const post = () => app.inject({ method: "POST", url: `/v1/orgs/${orgId}/faces/scan?eventId=${events.a}`, headers: { ...bearer(token), "content-type": mp.type }, payload: mp.payload });
engine.next = { width: 800, height: 1000, faces: [found(3, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
let res = await post();
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: 2, faces: [{ person: { id: referee.id, name: "Carlos Reis" } }] });
engine.next = { width: 800, height: 1000, faces: [found(4, { x0: 0.4, y0: 0.05, x1: 0.5, y1: 0.15 })] };
res = await post();
expect(res.json()).toMatchObject({ faces: [{ person: { id: outsider.id, name: "Só lá fora" } }] });
});
it("names an embedding read on the photographer's computer, without the photo", async () => {
const { orgId, token, rui } = await setup();
const res = await app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/faces/identify`,
headers: { ...bearer(token), "content-type": "application/json" },
payload: { faces: [{ embedding: face(1) }, { embedding: face(9) }] },
});
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ roster: null, people: [{ id: rui.id, name: "Rui Silva" }, null] });
});
it("finds a visitor's face in a public gallery's photos only", async () => {
const { orgId, token, photos } = await setup();
expect((await app.inject({ method: "POST", url: `/v1/orgs/${orgId}/sites`, headers: bearer(token), payload: { domain: "fotos.test", skin: "photoreport", name: "PhotoReport" } })).statusCode).toBe(201);
+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)");
});
});
+88 -4
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",
@@ -301,7 +347,7 @@ export const t = {
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
original_not_here: "O original nunca chegou do computador do fotógrafo",
},
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou" },
deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou", RETRACTED: "Retirada" },
codeList: "Substituição de códigos",
codeListHelp: "Uma linha por código: código, tab, texto. Escreve \\v7\\ numa legenda e é trocado pelo texto. Listas do Photo Mechanic servem tal como estão.",
save: "Guardar",
@@ -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…",
@@ -562,6 +616,36 @@ export const t = {
engine_unavailable: "O reconhecimento de caras não está disponível neste servidor.",
} as Record<string, string>,
},
cardScan: {
button: "Procurar numa pasta",
title: "Procurar numa pasta",
help: "Escolhe uma pasta. As fotos ficam onde estão. Só entram no jogo as que selecionares.",
local: "A ler neste computador. As fotos não são enviadas. O que já foi lido fica guardado.",
preparing: "A preparar o reconhecimento neste computador. Da primeira vez demora um pouco.",
game: "Jogo",
roster: (n: number) =>
n === 1
? "Primeiro 1 pessoa deste jogo (jogadores e árbitros). Se não der, o resto."
: `Primeiro as ${n} pessoas deste jogo (jogadores e árbitros). Se não der, o resto.`,
rosterNone: "Este jogo tem plantel, mas ainda nenhuma cara conhecida. Compara com toda a gente.",
rosterOpen: "Este jogo não tem plantel: compara com toda a gente.",
jpeg: "Só lê JPEG. Os outros ficheiros da pasta ficam de fora.",
pick: "Escolher pasta",
search: "Nome, clube ou número",
scanning: (done: number, total: number) => `A ver ${done} de ${total}`,
cancel: "Parar",
close: "Fechar",
none: "Nenhuma foto corresponde a essa pesquisa.",
empty: "Nenhuma cara nem número nestas fotos.",
unread: (n: number) => (n === 1 ? "1 foto sem cara nem número ficou de fora." : `${n} fotos sem cara nem número ficaram de fora.`),
selectShown: "Selecionar estas",
clear: "Limpar seleção",
import: (n: number) => (n === 1 ? "Importar 1" : `Importar ${n}`),
sent: (n: number) => (n === 1 ? "1 foto a entrar no jogo." : `${n} fotos a entrar no jogo.`),
probable: "provável",
number: (n: string) => `#${n}`,
failed: "Não foi possível ler algumas fotos.",
},
searchSuggested: (n: number) => `${n} ${n === 1 ? "foto em que o reconhecimento facial sugere" : "fotos em que o reconhecimento facial sugere"} esta pessoa (confirma em Caras)`,
numbers: {
title: "Números das camisolas",
+242
View File
@@ -0,0 +1,242 @@
import { useEffect, useState } from "react";
import { desktopInvoke } from "../platform.js";
/**
* "Importar cartão": copies (or moves) photos from a memory card into a dated folder on this computer, like Photo
* Mechanic's Ingest (Cmd+Y). Desktop only. Pure filesystem — it does not send anything to the server. The last
* settings used are remembered. Labels are inline (desktop-only dialog); they can move to i18n later.
*/
type RawJpeg = "both" | "raw" | "jpeg";
interface CardSettings {
destination: string;
folderTemplate: string;
rawJpeg: RawJpeg;
mv: boolean;
overwrite: boolean;
sidecars: boolean;
}
interface CardScan {
raw: number;
jpeg: number;
other: number;
bytes: number;
}
interface CardResult {
copied: number;
moved: number;
skipped: number;
failed: number;
notes: string[];
destination: string;
}
const DEFAULTS: CardSettings = {
destination: "~/Pictures",
folderTemplate: "{iptcyear4}/{iptcyear4}{iptcmonth0}{iptcday0}/{type}",
rawJpeg: "both",
mv: false,
overwrite: false,
sidecars: true,
};
const human = (bytes: number): string => {
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`;
return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
};
export function CardIngestButton() {
const [open, setOpen] = useState(false);
return (
<>
<button
onClick={() => setOpen(true)}
title="Descarregar um cartão para uma pasta datada (copiar ou mover)"
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
Cartão…
</button>
{open && <CardDialog onClose={() => setOpen(false)} />}
</>
);
}
function CardDialog({ onClose }: { onClose: () => void }) {
const [s, setS] = useState<CardSettings>(DEFAULTS);
const [source, setSource] = useState("");
const [scan, setScan] = useState<CardScan | null>(null);
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState<{ done: number; total: number; name: string } | null>(null);
const [result, setResult] = useState<CardResult | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {});
}, []);
useEffect(() => {
let alive = true;
let stop: (() => void) | undefined;
void import("@tauri-apps/api/event").then(({ listen }) =>
listen<{ done: number; total: number; name: string }>("card-progress", (e) => setProgress(e.payload)).then(
(un) => (alive ? (stop = un) : un()),
),
);
return () => {
alive = false;
stop?.();
};
}, []);
const total = scan ? scan.raw + scan.jpeg + scan.other : 0;
const pickSource = async () => {
setError(null);
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (!p) return;
setSource(p);
setScan(null);
setResult(null);
try {
setScan(await desktopInvoke<CardScan>("card_scan", { source: p }));
} catch (e) {
setError(String(e));
}
};
const pickDest = async () => {
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (p) setS({ ...s, destination: p });
};
const run = async () => {
if (!source) {
setError("Escolhe primeiro o cartão/pasta de origem.");
return;
}
setBusy(true);
setError(null);
setResult(null);
setProgress({ done: 0, total, name: "" });
try {
await desktopInvoke("card_save_settings", { settings: s }); // remember the last settings used
setResult(await desktopInvoke<CardResult>("card_ingest", { source, settings: s }));
} catch (e) {
setError(String(e));
} finally {
setBusy(false);
setProgress(null);
}
};
const field = "h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none";
const row = "flex items-center gap-2 text-[12px]";
return (
<div role="dialog" aria-modal="true" aria-label="Importar cartão" className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4">
<div className="max-h-full w-full max-w-lg space-y-3 overflow-y-auto border border-line bg-panel p-4 shadow-2xl">
<div className="flex items-center justify-between">
<h2 className="font-semibold uppercase tracking-wide text-ink">Importar cartão</h2>
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
Fechar
</button>
</div>
<p className="text-[11px] text-faint">Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.</p>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Origem (cartão/pasta)</span>
<div className="flex gap-2">
<input readOnly value={source} placeholder="Escolhe o cartão…" className={field} />
<button onClick={() => void pickSource()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
…
</button>
</div>
{scan && (
<span className="mt-1 block text-[11px] text-muted">
{scan.raw} RAW · {scan.jpeg} JPEG{scan.other ? ` · ${scan.other} outras` : ""} · {human(scan.bytes)}
</span>
)}
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Destino</span>
<div className="flex gap-2">
<input value={s.destination} onChange={(e) => setS({ ...s, destination: e.target.value })} className={field} />
<button onClick={() => void pickDest()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
…
</button>
</div>
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Subpastas (template)</span>
<input value={s.folderTemplate} onChange={(e) => setS({ ...s, folderTemplate: e.target.value })} className={`${field} font-mono`} />
<span className="mt-1 block text-[11px] text-faint">{"Variáveis: {iptcyear4} {iptcmonth0} {iptcday0} {type} {ext} — data pela hora do ficheiro."}</span>
</label>
<div className="grid grid-cols-2 gap-2">
<label className="block">
<span className="mb-1 block text-[11px] text-faint">RAW + JPEG</span>
<select value={s.rawJpeg} onChange={(e) => setS({ ...s, rawJpeg: e.target.value as RawJpeg })} className={field}>
<option value="both">RAW e JPEG</option>
<option value="raw">Só RAW</option>
<option value="jpeg">Só JPEG</option>
</select>
</label>
<div className="flex flex-col justify-end gap-1">
<label className={row}>
<input type="checkbox" checked={s.mv} onChange={(e) => setS({ ...s, mv: e.target.checked })} />
Mover (apaga do cartão depois de verificar)
</label>
<label className={row}>
<input type="checkbox" checked={s.overwrite} onChange={(e) => setS({ ...s, overwrite: e.target.checked })} />
Sobrescrever existentes
</label>
<label className={row}>
<input type="checkbox" checked={s.sidecars} onChange={(e) => setS({ ...s, sidecars: e.target.checked })} />
Levar WAV/XMP
</label>
</div>
</div>
{s.mv && <p className="text-[11px] text-[#f0c27a]">Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).</p>}
{error && <p className="text-[11px] text-danger">{error}</p>}
{progress && busy && (
<p className="text-[11px] text-muted">
A processar {progress.done}/{progress.total}… {progress.name}
</p>
)}
{result && (
<div className="border border-line bg-cell p-2 text-[11px] text-ink">
<p>
{result.moved ? `${result.moved} movidas · ` : ""}
{result.copied ? `${result.copied} copiadas · ` : ""}
{result.skipped ? `${result.skipped} ignoradas · ` : ""}
{result.failed ? `${result.failed} falhadas` : ""}
{!result.moved && !result.copied && !result.skipped && !result.failed ? "Nada a fazer." : ""}
</p>
<p className="mt-1 break-all text-faint">{result.destination}</p>
{result.notes.length > 0 && (
<ul className="mt-1 list-inside list-disc text-faint">
{result.notes.slice(0, 8).map((n, i) => (
<li key={i}>{n}</li>
))}
</ul>
)}
</div>
)}
<div className="flex justify-end gap-2 pt-1">
<button
onClick={() => void run()}
disabled={busy || !source}
className="h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
>
{s.mv ? "Mover" : "Copiar"}
</button>
</div>
</div>
</div>
);
}
+110
View File
@@ -0,0 +1,110 @@
import { fireEvent, render, screen } from "@testing-library/react";
import type { ApiClient, EventSummary } from "@photoreport/sdk";
import { describe, expect, it, vi } from "vitest";
import { CardScan, cardMatches } from "./CardScan.js";
const face = (over: { number?: string | null; name?: string; club?: string | null; personNumber?: string | null } = {}) => ({
box: { x0: 0, y0: 0, x1: 0.1, y1: 0.1 },
number: over.number ?? null,
person: over.name
? { id: "p", name: over.name, club: over.club ?? null, number: over.personNumber ?? null, level: "strong" as const }
: null,
});
describe("searching a card", () => {
it("matches a shirt number only as that number", () => {
const faces = [face({ number: "5", name: "Ana" }), face({ number: "15" })];
expect(cardMatches(faces, "5")).toBe(true);
expect(cardMatches(faces, "15")).toBe(true);
expect(cardMatches(faces, "1")).toBe(false);
});
it("matches a name or a club, ignoring accents", () => {
const faces = [face({ name: "Inês", club: "Gil Eanes", personNumber: "5" })];
expect(cardMatches(faces, "ines")).toBe(true);
expect(cardMatches(faces, "gil 5")).toBe(true);
expect(cardMatches(faces, "feirense")).toBe(false);
});
it("keeps a photo with a face when the search is empty, and drops one with none", () => {
expect(cardMatches([face()], "")).toBe(true);
expect(cardMatches([], "")).toBe(false);
});
});
describe("card folder dialog", () => {
it("reads the JPEGs, filters by name and number, and imports only the selected originals", async () => {
vi.stubGlobal(
"createImageBitmap",
async () => ({ width: 4000, height: 3000, close() {} }),
);
let thumbs = 0;
vi.spyOn(URL, "createObjectURL").mockImplementation(() => `blob:thumb-${thumbs++}`);
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
HTMLCanvasElement.prototype.getContext = (() => ({ drawImage() {} })) as unknown as typeof HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.toBlob = function (cb) {
cb(new Blob([new Uint8Array([1])], { type: "image/jpeg" }));
};
const scanCard = vi.fn()
.mockResolvedValueOnce({ slots: 4, roster: 2, faces: [face({ number: "5", name: "Inês", club: "Gil Eanes", personNumber: "5" })] })
.mockResolvedValueOnce({ slots: 4, roster: 2, faces: [] });
const onImport = vi.fn();
const { container } = render(
<CardScan
api={{ scanCard } as unknown as ApiClient}
orgId="org"
eventId="game"
games={[{ id: "game", home: "CDE GIL Eanes", away: "CD Feirense", homeShort: "GIL", awayShort: "CDF", startsAt: "2026-10-17T15:00:00.000Z" } as EventSummary]}
onImport={onImport}
onClose={() => {}}
/>,
);
const picker = container.querySelector("input[type=file]") as HTMLInputElement;
expect(picker.webkitdirectory).toBe(true);
const chosen = [
new File(["a"], "a.jpg", { type: "image/jpeg" }),
new File(["raw"], "b.CR2"),
new File(["c"], "c.jpg", { type: "image/jpeg" }),
];
fireEvent.change(picker, { target: { files: chosen } });
expect(await screen.findByRole("button", { name: /Inês #5/ })).toBeTruthy();
expect(screen.getByText(/1 foto sem cara nem número ficou de fora/)).toBeTruthy();
expect(scanCard).toHaveBeenCalledTimes(2);
expect(scanCard).toHaveBeenCalledWith("org", expect.anything(), "game");
expect(screen.getByText(/Primeiro as 2 pessoas deste jogo/)).toBeTruthy();
fireEvent.change(screen.getByLabelText("Nome, clube ou número"), { target: { value: "ines 5" } });
fireEvent.click(screen.getByRole("button", { name: /Inês #5/ }));
fireEvent.click(screen.getByRole("button", { name: "Importar 1" }));
expect(onImport).toHaveBeenCalledTimes(1);
const sent = onImport.mock.calls[0]![0] as File[];
expect(sent.map((f) => f.name)).toEqual(["a.jpg"]);
expect(onImport.mock.calls[0]![1]).toBe("game");
expect(screen.getByText("1 foto a entrar no jogo.")).toBeTruthy();
});
it("does not send a photo again when the same file was already read", async () => {
vi.stubGlobal("createImageBitmap", async () => ({ width: 800, height: 600, close() {} }));
vi.spyOn(URL, "createObjectURL").mockImplementation(() => "blob:again");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
HTMLCanvasElement.prototype.getContext = (() => ({ drawImage() {} })) as unknown as typeof HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.toBlob = function (cb) {
cb(new Blob([new Uint8Array([1])], { type: "image/jpeg" }));
};
const scanCard = vi.fn().mockResolvedValue({ slots: 4, roster: null, faces: [face({ name: "Rui" })] });
const file = new File(["same"], "again.jpg", { type: "image/jpeg" });
const { container } = render(
<CardScan api={{ scanCard } as unknown as ApiClient} orgId="org" eventId="game" games={[{ id: "game", home: "A", away: "B", startsAt: "2026-10-17T15:00:00.000Z" } as EventSummary]} onImport={() => {}} onClose={() => {}} />,
);
const picker = container.querySelector("input[type=file]") as HTMLInputElement;
fireEvent.change(picker, { target: { files: [file] } });
expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy();
expect(scanCard).toHaveBeenCalledTimes(1);
fireEvent.change(picker, { target: { files: [file] } });
expect(await screen.findByRole("button", { name: /Rui/ })).toBeTruthy();
expect(scanCard).toHaveBeenCalledTimes(1);
});
});
+465
View File
@@ -0,0 +1,465 @@
import type { ApiClient, CardScan as CardReading, EventSummary } from "@photoreport/sdk";
import { ApiError } from "@photoreport/sdk";
import { useEffect, useMemo, useRef, useState } from "react";
import { t } from "../i18n.js";
import { kv } from "../offline/kv.js";
import { asArrayBuffer, desktopInvoke, isDesktop } from "../platform.js";
type Face = CardReading["faces"][number];
interface Item {
file: File | null;
/** Set when the desktop app read the photo itself. */
path: string;
name: string;
thumb: string;
faces: Face[] | null;
error: boolean;
}
interface CachedScan {
roster: number | null;
faces: Face[];
}
interface LocalFace extends Face {
embedding?: number[];
}
interface LocalPhoto {
done: number;
total: number;
path: string;
name: string;
cached: boolean;
needsName: boolean;
error: boolean;
roster: number | null;
thumb: string;
faces: LocalFace[];
}
const JPEG = /\.jpe?g$/i;
const fold = (s: string) => s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase();
function cacheKey(orgId: string, eventId: string, file: File): string {
const rel = "webkitRelativePath" in file && typeof file.webkitRelativePath === "string" && file.webkitRelativePath ? file.webkitRelativePath : file.name;
return `card-scan:${orgId}:${eventId}:${rel}:${file.size}:${file.lastModified}`;
}
/** A photo matches when every word is in a face: a number must be that shirt or that player's number. */
export function cardMatches(faces: Face[], query: string): boolean {
if (!faces.length) return false;
const words = fold(query).split(/\s+/).filter(Boolean);
if (!words.length) return true;
return faces.some((f) => {
const text = fold([f.person?.name, f.person?.club].filter(Boolean).join(" "));
const numbers = new Set([f.number, f.person?.number].filter((n): n is string => !!n));
return words.every((w) => (/^\d+$/.test(w) ? numbers.has(w) : text.includes(w)));
});
}
function labelOf(faces: Face[]): string {
const bits: string[] = [];
for (const f of faces) {
if (f.person) {
const who = f.person.level === "possible" ? `${f.person.name} (${t.cardScan.probable})` : f.person.name;
bits.push([who, f.person.number ? t.cardScan.number(f.person.number) : f.number ? t.cardScan.number(f.number) : null].filter(Boolean).join(" "));
} else if (f.number) bits.push(t.cardScan.number(f.number));
}
return [...new Set(bits)].join(" · ");
}
/** A small JPEG for the engine. The original file stays for the import. */
async function previewOf(file: File): Promise<Blob> {
const bmp = await createImageBitmap(file);
try {
const max = 1600;
const scale = Math.min(1, max / Math.max(bmp.width, bmp.height));
const canvas = document.createElement("canvas");
canvas.width = Math.max(1, Math.round(bmp.width * scale));
canvas.height = Math.max(1, Math.round(bmp.height * scale));
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("canvas");
ctx.drawImage(bmp, 0, 0, canvas.width, canvas.height);
const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, "image/jpeg", 0.85));
if (!blob) throw new Error("encode");
return blob;
} finally {
bmp.close();
}
}
/**
* Look through a folder on this computer for faces and shirt numbers, without importing it.
* The photographer then sends only the photos they pick into the event.
*/
const gameLabel = (e: EventSummary) => {
const day = e.startsAt.slice(0, 10).split("-").reverse().join("/");
const teams = [e.homeShort || e.home, e.away ? e.awayShort || e.away : ""].filter(Boolean).join(" × ");
return `${day} ${teams}`;
};
export function CardScan({
api,
orgId,
eventId,
games,
onImport,
onClose,
}: {
api: ApiClient;
orgId: string;
eventId: string;
games: EventSummary[];
onImport: (files: File[], eventId: string) => void;
onClose: () => void;
}) {
const input = useRef<HTMLInputElement>(null);
const stop = useRef(false);
const [items, setItems] = useState<Item[]>([]);
const [done, setDone] = useState(0);
const [total, setTotal] = useState(0);
const [running, setRunning] = useState(false);
const [query, setQuery] = useState("");
const [selected, setSelected] = useState<Set<number>>(new Set());
const [note, setNote] = useState<string | null>(null);
const [sent, setSent] = useState<string | null>(null);
const [gameId, setGameId] = useState(eventId);
const [roster, setRoster] = useState<number | null | undefined>(undefined);
const [localMode, setLocalMode] = useState(false);
const folderRef = useRef("");
const gameRef = useRef(gameId);
gameRef.current = gameId;
const choices = useMemo(() => [...games].sort((a, b) => b.startsAt.localeCompare(a.startsAt)), [games]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const live = useRef<Item[]>([]);
live.current = items;
useEffect(() => {
return () => {
stop.current = true;
for (const item of live.current) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb);
};
}, []);
const shown = useMemo(() => items.map((item, index) => ({ item, index })).filter(({ item }) => item.faces && cardMatches(item.faces, query)), [items, query]);
const unread = items.filter((item) => item.faces && item.faces.length === 0 && !item.error).length;
const run = async (list: FileList) => {
stop.current = false;
setNote(null);
setSent(null);
setSelected(new Set());
const files = [...list].filter((f) => JPEG.test(f.name));
setTotal(files.length);
setDone(0);
if (!files.length) {
setRunning(false);
setItems((prev) => {
for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb);
return [];
});
setNote(t.cardScan.jpeg);
return;
}
setRunning(true);
const next: Item[] = files.map((file) => ({ file, path: "", name: file.name, thumb: "", faces: null, error: false }));
setItems((prev) => {
for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb);
return next;
});
// A handful at first; the server says how many it can read at once, and the rest start then.
let width = Math.min(8, next.length);
let running = 0;
let cursor = 0;
await new Promise<void>((resolve) => {
const launch = () => {
while (!stop.current && running < width && cursor < next.length) {
const item = next[cursor++]!;
const file = item.file;
if (!file) continue;
running++;
void (async () => {
try {
const saved = await kv.get<CachedScan>(cacheKey(orgId, gameRef.current, file));
if (saved) {
item.faces = saved.faces;
setRoster(saved.roster);
if (saved.faces.length) item.thumb = URL.createObjectURL(await previewOf(file));
} else {
const small = await previewOf(file);
const read = await api.scanCard(orgId, small, gameRef.current);
item.faces = read.faces;
setRoster(read.roster);
if (read.slots > width) width = read.slots;
if (read.faces.length) item.thumb = URL.createObjectURL(small);
await kv.set(cacheKey(orgId, gameRef.current, file), { roster: read.roster, faces: read.faces });
}
} catch (err) {
item.error = true;
item.faces = [];
if (err instanceof ApiError && (err.code === "biometrics_disabled" || err.code === "engine_unavailable")) {
stop.current = true;
setNote(t.lookup.errors[err.code] ?? t.unexpectedError);
}
} finally {
running--;
setDone((n) => n + 1);
setItems(next.slice());
launch();
if (running === 0 && (stop.current || cursor >= next.length)) resolve();
}
})();
}
if (running === 0 && (stop.current || cursor >= next.length)) resolve();
};
launch();
});
setRunning(false);
if (next.some((item) => item.error) && !stop.current) setNote(t.cardScan.failed);
};
const runLocal = async (folder: string) => {
stop.current = false;
folderRef.current = folder;
setLocalMode(true);
setNote(t.cardScan.preparing);
setSent(null);
setSelected(new Set());
setDone(0);
setTotal(0);
setRunning(true);
const next: Item[] = [];
const byPath = new Map<string, Item>();
setItems((prev) => {
for (const item of prev) if (item.thumb.startsWith("blob:")) URL.revokeObjectURL(item.thumb);
return [];
});
const pending: { item: Item; embeddings: number[][] }[] = [];
let naming = Promise.resolve();
const nameBatch = async (batch: { item: Item; embeddings: number[][] }[]) => {
if (!batch.length) return;
const named = await api.identifyFaces(orgId, { eventId: gameRef.current, faces: batch.flatMap((row) => row.embeddings.map((embedding) => ({ embedding }))) });
setRoster(named.roster);
let at = 0;
for (const row of batch) {
const people = named.people.slice(at, at + row.embeddings.length);
at += row.embeddings.length;
row.item.faces = (row.item.faces ?? []).map((face, i) => ({ ...face, person: people[i] ?? null }));
void desktopInvoke("faces_remember", {
folder,
path: row.item.path,
orgId,
eventId: gameRef.current,
roster: named.roster,
faces: row.item.faces,
}).catch(() => {});
}
setItems(next.slice());
};
const schedule = () => {
if (pending.length < 16) return;
const batch = pending.splice(0, 24);
naming = naming.then(() => nameBatch(batch)).catch(() => {});
};
let unlisten = () => {};
try {
const { listen } = await import("@tauri-apps/api/event");
unlisten = await listen<LocalPhoto>("faces-photo", (e) => {
const ev = e.payload;
if (stop.current) return;
setTotal(ev.total);
setDone(ev.done);
setNote(null);
let item = byPath.get(ev.path);
if (!item) {
item = { file: null, path: ev.path, name: ev.name, thumb: "", faces: null, error: false };
byPath.set(ev.path, item);
next.push(item);
}
item.error = ev.error;
if (ev.thumb) item.thumb = `data:image/jpeg;base64,${ev.thumb}`;
if (ev.roster != null) setRoster(ev.roster);
item.faces = ev.faces.map((face) => ({ box: face.box, number: face.number, person: face.person }));
if (ev.needsName && !ev.error) {
const embeddings = ev.faces.flatMap((face) => (face.embedding && face.embedding.length ? [face.embedding] : []));
if (embeddings.length && item.faces) pending.push({ item, embeddings });
schedule();
}
setItems(next.slice());
});
const token = await api.realtimeToken();
await desktopInvoke("faces_scan", { folder, orgId, eventId: gameRef.current, api: api.baseUrl, token });
if (pending.length) {
const batch = pending.splice(0, pending.length);
naming = naming.then(() => nameBatch(batch)).catch(() => {});
}
await naming;
} catch (err) {
setNote(err instanceof ApiError ? (t.lookup.errors[err.code] ?? t.unexpectedError) : t.cardScan.failed);
} finally {
unlisten();
setRunning(false);
}
};
const pick = async () => {
if (isDesktop()) {
const local = await desktopInvoke<boolean>("faces_local").then((ok) => ok).catch(() => false);
if (local) {
const folder = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (folder) await runLocal(folder);
return;
}
}
input.current?.click();
};
const toggle = (index: number) => {
setSelected((cur) => {
const n = new Set(cur);
if (n.has(index)) n.delete(index);
else n.add(index);
return n;
});
};
return (
<div role="dialog" aria-modal="true" aria-label={t.cardScan.title} className="fixed inset-0 z-30 flex flex-col bg-black/80 p-4">
<div className="mx-auto flex min-h-0 w-full max-w-6xl flex-1 flex-col border border-black bg-panel">
<div className="flex flex-wrap items-center gap-3 border-b border-line px-3 py-2">
<div className="text-[13px] text-ink">{t.cardScan.title}</div>
<select
aria-label={t.cardScan.game}
value={gameId}
onChange={(e) => {
setGameId(e.target.value);
setRoster(undefined);
}}
className="h-7 max-w-[280px] border border-black bg-cell px-1.5 text-[12px] text-ink"
>
{choices.map((game) => (
<option key={game.id} value={game.id}>
{gameLabel(game)}
</option>
))}
</select>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t.cardScan.search}
aria-label={t.cardScan.search}
className="h-7 min-w-[220px] flex-1 border border-black bg-cell px-2 text-[13px] text-ink"
/>
<button type="button" onClick={() => void pick()} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.pick}
</button>
<input
ref={(node) => {
input.current = node;
// A folder picker, not a file picker: the card stays where it is.
if (node) node.webkitdirectory = true;
}}
type="file"
accept="image/jpeg,.jpg,.jpeg"
multiple
hidden
onChange={(e) => {
if (e.target.files?.length) void run(e.target.files);
e.target.value = "";
}}
/>
{running && (
<button
type="button"
onClick={() => {
stop.current = true;
if (localMode) void desktopInvoke("faces_cancel").catch(() => {});
}}
className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
{t.cardScan.cancel}
</button>
)}
<button type="button" onClick={onClose} className="h-7 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.close}
</button>
</div>
<p className="px-3 py-2 text-[12px] text-muted">
{localMode ? t.cardScan.local : t.cardScan.help} {t.cardScan.jpeg}
{roster === null && <span className="ml-2 text-ink">{t.cardScan.rosterOpen}</span>}
{roster === 0 && <span className="ml-2 text-ink">{t.cardScan.rosterNone}</span>}
{typeof roster === "number" && roster > 0 && <span className="ml-2 text-ink">{t.cardScan.roster(roster)}</span>}
{running && <span className="ml-2 font-mono text-ink">{t.cardScan.scanning(done, total)}</span>}
</p>
{note && <p className="px-3 pb-2 text-[12px] text-danger">{note}</p>}
{sent && <p className="px-3 pb-2 text-[12px] text-ink">{sent}</p>}
<div className="min-h-0 flex-1 overflow-y-auto px-3 pb-3">
{!running && items.length > 0 && shown.length === 0 && !note && <p className="py-8 text-center text-[13px] text-muted">{query.trim() ? t.cardScan.none : t.cardScan.empty}</p>}
<div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-2">
{shown.map(({ item, index }) => (
<button
key={item.path || item.thumb || item.name}
type="button"
onClick={() => toggle(index)}
aria-pressed={selected.has(index)}
className={`border text-left ${selected.has(index) ? "border-accent" : "border-black"}`}
>
<img src={item.thumb} alt="" className="aspect-[3/2] w-full bg-black object-contain" />
<span className="block truncate px-1.5 py-1 text-[11px] text-ink">{item.faces ? labelOf(item.faces) : item.name}</span>
</button>
))}
</div>
{unread > 0 && !query.trim() && <p className="py-3 text-[12px] text-faint">{t.cardScan.unread(unread)}</p>}
</div>
<div className="flex items-center justify-end gap-2 border-t border-line px-3 py-2">
<button
type="button"
onClick={() => setSelected(new Set(shown.map(({ index }) => index)))}
className="h-7 px-2 text-[12px] text-faint underline hover:text-ink"
>
{t.cardScan.selectShown}
</button>
<button type="button" onClick={() => setSelected(new Set())} className="h-7 px-2 text-[12px] text-faint underline hover:text-ink">
{t.cardScan.clear}
</button>
<button
type="button"
disabled={selected.size === 0}
onClick={() => {
void (async () => {
const files: File[] = [];
for (const index of selected) {
const item = items[index];
if (!item) continue;
if (item.file) {
files.push(item.file);
continue;
}
if (!item.path) continue;
const data = asArrayBuffer(await desktopInvoke("faces_read", { path: item.path }));
files.push(new File([data], item.name, { type: "image/jpeg" }));
}
if (!files.length) return;
onImport(files, gameId);
setSent(t.cardScan.sent(files.length));
setSelected(new Set());
})();
}}
className="h-8 bg-accent px-3 text-[13px] text-white disabled:opacity-40"
>
{t.cardScan.import(selected.size)}
</button>
</div>
</div>
</div>
);
}
+347
View File
@@ -0,0 +1,347 @@
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 [homeShort, setHomeShort] = useState(event.homeShort ?? "");
const [awayShort, setAwayShort] = useState(event.awayShort ?? "");
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)));
setHomeShort(event.homeShort ?? "");
setAwayShort(event.awayShort ?? "");
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],
...(event.away ? { homeShort: homeShort.trim() || null, awayShort: awayShort.trim() || null } : {}),
}),
);
});
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>
{event.away && (
/* Siglas curtas para as pastas de entrega (ex.: CDE x CDF); vazio usa o nome completo. Labels inline: i18n.ts por agora noutra branch. */
<div className="grid grid-cols-2 gap-2">
<label className="block">
<span className="text-faint">Sigla casa</span>
<input
value={homeShort}
onChange={(e) => setHomeShort(e.target.value)}
placeholder={event.home}
maxLength={20}
className={input}
/>
</label>
<label className="block">
<span className="text-faint">Sigla visitante</span>
<input
value={awayShort}
onChange={(e) => setAwayShort(e.target.value)}
placeholder={event.away}
maxLength={20}
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) => (
+9 -1
View File
@@ -31,6 +31,8 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
const label = LABEL_COLOR[photo.colorLabel];
// Desktop app: thumbnails are kept on the computer, so the grid shows without a network.
const shown = useCachedImage(src, isDesktop());
const [imgFailed, setImgFailed] = useState(false);
useEffect(() => setImgFailed(false), [shown]);
return (
<button
ref={ref}
@@ -49,7 +51,13 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
</span>
<span className="flex min-h-0 w-full flex-1 items-center justify-center">
{photo.status === "READY" ? (
shown && <img src={shown} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
imgFailed ? (
<span className="font-mono text-[10px] uppercase text-faint">erro</span>
) : shown ? (
<img src={shown} onError={() => setImgFailed(true)} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
) : (
<span className="font-mono text-[10px] uppercase text-faint">…</span>
)
) : (
<span className="font-mono text-[10px] uppercase text-faint">{photo.status === "FAILED" ? "erro" : "…"}</span>
)}
+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";
+87 -32
View File
@@ -10,25 +10,51 @@ import { ZerozeroGamePicker } from "./ZerozeroGame.js";
const LAST_TARGET = "deliver.target";
const BEST_COUNT = "deliver.bestCount";
/** The saved destinations: a list now, but older versions saved one id, so both are read. */
function savedTargets(): string[] {
const raw = prefs.get(LAST_TARGET) ?? "";
if (!raw) return [];
try {
const v = JSON.parse(raw);
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string");
} catch {
/* an older single-id value */
}
return [raw];
}
/**
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to a
* destination. With no destination yet it leads to where one is set up.
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to one or
* more destinations at once. With no destination yet it leads to where one is set up.
*/
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; eventId?: string | null; onQueued: (items: DeliveryItemSummary[]) => void }) {
const { api, orgId, selection, targets, eventId } = props;
const [bestOpen, setBestOpen] = useState(false);
const [bestCount, setBestCount] = useState(() => Number(prefs.get(BEST_COUNT)) || 30);
const [bestAgain, setBestAgain] = useState(false);
/** Photos the last send skipped because this destination already has them: offered to send again. */
/** Photos the last send skipped because a destination already has them: offered to send again. */
const [already, setAlready] = useState<string[]>([]);
const navigate = useNavigate();
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
const [chosenTargets, setChosenTargets] = useState<string[]>(savedTargets);
const [pickOpen, setPickOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [note, setNote] = useState<string | null>(null);
/** Remember the chosen destinations across tabs and restarts (persisted on every change, not only on send). */
const remember = (ids: string[]) => {
setChosenTargets(ids);
prefs.set(LAST_TARGET, JSON.stringify(ids));
};
// Drop destinations that no longer exist; with none left, start on the first available one.
useEffect(() => {
if (targets.length && !targets.some((x) => x.id === targetId)) setTargetId(targets[0]!.id);
}, [targets, targetId]);
useEffect(() => setAlready([]), [targetId, eventId]);
if (!targets.length) return;
const valid = chosenTargets.filter((id) => targets.some((x) => x.id === id));
if (valid.length !== chosenTargets.length || valid.length === 0) remember(valid.length ? valid : [targets[0]!.id]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [targets]);
useEffect(() => setAlready([]), [chosenTargets, eventId]);
useEffect(() => {
if (!note) return;
const timer = setTimeout(() => setNote(null), 5000);
@@ -43,16 +69,28 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
);
}
const selected = targets.filter((x) => chosenTargets.includes(x.id));
const selectedLabel = selected.map((x) => x.name).join(", ");
const photos = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY");
const toggle = (id: string) => {
const next = chosenTargets.includes(id) ? chosenTargets.filter((x) => x !== id) : [...chosenTargets, id];
remember(next.length ? next : [id]); // keep at least one chosen
};
const send = async (ids = photos.map((p) => p.id), again = false) => {
if (!selected.length) return;
setBusy(true);
try {
// Without a network (or photos still uploading) the request waits on this computer and goes when it can.
const r = await deliver(api, orgId, targetId, ids, again);
prefs.set(LAST_TARGET, targetId);
props.onQueued(r.queued);
setAlready(r.skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId));
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
// Without a network (or photos still uploading) each request waits on this computer and goes when it can.
const results: Awaited<ReturnType<typeof deliver>>[] = [];
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again));
const queued = results.flatMap((r) => r.queued);
const skipped = results.flatMap((r) => r.skipped);
const waiting = results.some((r) => r.waiting);
props.onQueued(queued);
setAlready([...new Set(skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId))]);
setNote(waiting ? t.offline.queuedDelivery : t.delivered(queued.length, skipped.length));
} catch (err) {
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
} finally {
@@ -60,19 +98,21 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
}
};
const target = targets.find((x) => x.id === targetId);
// Only the best of the open event: a short gallery of game moments, spread over the match.
const sendBest = async () => {
if (!eventId) return;
if (!eventId || !selected.length) return;
setBusy(true);
try {
const r = await api.deliverBest(orgId, { targetId, eventId, count: bestCount, again: bestAgain });
prefs.set(LAST_TARGET, targetId);
const results: Awaited<ReturnType<ApiClient["deliverBest"]>>[] = [];
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain }));
prefs.set(BEST_COUNT, String(bestCount));
props.onQueued(r.queued);
setAlready(r.skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId));
const queued = results.flatMap((r) => r.queued);
const skipped = results.flatMap((r) => r.skipped);
const chosen = results[0]?.chosen ?? [];
props.onQueued(queued);
setAlready([...new Set(skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId))]);
setBestOpen(false);
setNote(r.chosen.length ? t.bestSent(r.queued.length, r.chosen.length) : t.bestNone);
setNote(chosen.length ? t.bestSent(queued.length, chosen.length) : t.bestNone);
} catch (err) {
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
} finally {
@@ -82,20 +122,35 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
return (
<span className="relative flex items-center gap-1">
{target?.kind === "ZEROZERO" && eventId && <ZerozeroGamePicker api={api} orgId={orgId} targetId={targetId} eventId={eventId} compact />}
{eventId && selected.filter((x) => x.kind === "ZEROZERO").map((x) => <ZerozeroGamePicker key={x.id} api={api} orgId={orgId} targetId={x.id} eventId={eventId} compact />)}
{targets.length > 1 && (
<select aria-label={t.deliverTo} value={targetId} onChange={(e) => setTargetId(e.target.value)} className="h-6 max-w-[140px] border border-black bg-cell px-1 text-[12px] text-ink">
{targets.map((x) => (
<option key={x.id} value={x.id}>
{x.name}
</option>
))}
</select>
<span className="relative">
<button
type="button"
onClick={() => setPickOpen((o) => !o)}
aria-expanded={pickOpen}
aria-label={t.deliverTo}
title={selectedLabel}
className="h-6 max-w-[180px] truncate border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
>
{selected.length ? selectedLabel : t.deliverTo}
</button>
{pickOpen && (
<div className="absolute left-0 top-7 z-30 max-h-[60vh] w-[220px] space-y-1 overflow-y-auto border border-black bg-panel p-2 text-[12px] shadow-xl" role="group" aria-label={t.deliverTo}>
{targets.map((x) => (
<label key={x.id} className="flex items-center gap-2">
<input type="checkbox" checked={chosenTargets.includes(x.id)} onChange={() => toggle(x.id)} />
<span className="min-w-0 truncate text-ink">{x.name}</span>
</label>
))}
</div>
)}
</span>
)}
<button
onClick={() => void send()}
disabled={busy || !photos.length || !targetId}
title={photos.length ? `${t.sendTo} ${targets.find((x) => x.id === targetId)?.name ?? ""}` : t.selectToSend}
disabled={busy || !photos.length || !selected.length}
title={photos.length ? `${t.sendTo} ${selectedLabel}` : t.selectToSend}
className="h-6 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
>
{t.sendN(photos.length)}
@@ -122,8 +177,8 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
<input type="checkbox" checked={bestAgain} onChange={(e) => setBestAgain(e.target.checked)} />
{t.bestAgain}
</label>
<button disabled={busy || !targetId} className="h-7 w-full bg-accent font-semibold text-white disabled:opacity-40">
{t.bestSend(target?.name ?? "")}
<button disabled={busy || !selected.length} className="h-7 w-full bg-accent font-semibold text-white disabled:opacity-40">
{t.bestSend(selectedLabel)}
</button>
</form>
)}
+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;
+15 -1
View File
@@ -48,6 +48,20 @@ async function slot<T>(fn: () => Promise<T>): Promise<T> {
}
}
/** How long to wait for a single image download before giving up its slot. */
const FETCH_TIMEOUT_MS = 20000;
/** fetch that aborts if it stalls, so one hung request can't hold a concurrency slot forever and starve the grid. */
async function fetchWithTimeout(url: string): Promise<Response> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
try {
return await fetch(url, { signal: ctrl.signal });
} finally {
clearTimeout(timer);
}
}
/**
* The image as a blob URL: from this computer when it was seen before, else downloaded once and kept. Null when it
* can't be had (offline and never seen). The caller revokes the URL when done.
@@ -59,7 +73,7 @@ export async function cachedImage(url: string): Promise<string | null> {
if (kept) return URL.createObjectURL(kept);
try {
const blob = await slot(async () => {
const res = await fetch(url);
const res = await fetchWithTimeout(url);
if (!res.ok) throw new Error(`http_${res.status}`);
return res.blob();
});
+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>
+1
View File
@@ -15,6 +15,7 @@ const STATUS_COLOR: Record<DeliveryItemSummary["status"], string> = {
WAITING: "text-[#7fb0ff]",
DONE: "text-ok",
FAILED: "text-[#f0a35a]",
RETRACTED: "text-faint",
};
/** Delivery queue per destination, live, with retry and the public link of an event's folder. */
+47 -1
View File
@@ -7,6 +7,8 @@ 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 { CardScan } from "../library/CardScan.js";
import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { Grid, Loupe, type LoupeFace } from "../library/Grid.js";
@@ -15,6 +17,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { CardIngestButton } from "../library/CardIngest.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "../library/store.js";
@@ -40,9 +43,11 @@ 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);
const [cardOpen, setCardOpen] = useState(false);
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
useEffect(() => setFilterState(savedFilter(orgId)), [orgId]);
@@ -205,7 +210,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 +333,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">
@@ -345,7 +357,31 @@ export function LibraryPage() {
<button onClick={() => fileInput.current?.click()} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.importPhotos}
</button>
{uploadInto && (
<button onClick={() => setCardOpen(true)} className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
{t.cardScan.button}
</button>
)}
{desktop && <LocalFtpButton ftp={localFtp} events={events} openEventId={uploadInto} />}
{desktop && <CardIngestButton />}
{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)))} />
)}
@@ -545,6 +581,16 @@ export function LibraryPage() {
onPlayers={(ids, players) => patch(ids, { players })}
/>
{cardOpen && uploadInto && openEvent && (
<CardScan
api={api}
orgId={orgId}
eventId={uploadInto}
games={events.some((e) => e.id === openEvent.id) ? events : [openEvent, ...events]}
onImport={(files, id) => uploads.add(files, id)}
onClose={() => setCardOpen(false)}
/>
)}
{iptcOpen && <IptcInfo api={api} orgId={orgId} photos={selection} targets={targets} canDeliver={canCull} onClose={() => setIptcOpen(false)} />}
{creating && (
<EventForm
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.12",
"version": "0.3.13",
"private": true,
"type": "module",
"scripts": {
+4 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.12"
version = "0.3.13"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
@@ -20,6 +20,7 @@ serde = { version = "1", features = ["derive"] }
rand = "0.8"
local-ip-address = "0.6"
dirs = "6"
chrono = { version = "0.4", default-features = false, features = ["clock"] }
libunftp = { version = "0.23.1", default-features = false, features = ["ring"] }
unftp-sbe-fs = "0.4.0"
async-trait = "0.1"
@@ -27,7 +28,9 @@ tokio = { version = "1", features = ["sync", "time", "fs", "net", "io-util"] }
unftp-core = "0.1.0"
serde_json = "1"
sha2 = "0.10"
libc = "0.2"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
photoreport-faces = { path = "../../../workers/faces" }
tauri-plugin-dialog = "2"
tauri-plugin-updater = "2"
# New versions of the interface (see src/ui.rs). Already built for the updater: same versions, no new crates.
+9
View File
@@ -26,6 +26,15 @@ fn main() {
"catalog_scan",
"catalog_status",
"catalog_cancel",
"card_scan",
"card_ingest",
"card_settings",
"card_save_settings",
"faces_local",
"faces_scan",
"faces_cancel",
"faces_remember",
"faces_read",
"update_check",
"update_install",
"ui_status",
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more